From e7a043dc7bf764be385929265ca9c9358c6c5ee8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandro=20Gonz=C3=A1lez?= Date: Sat, 10 Feb 2024 22:28:38 +0100 Subject: [PATCH] Implement `ConstInstantiable` for arrays and slices It can be useful to have maps where values are slices or arrays. Given that Rust stabilized the basic const generics we need on Rust 1.51 and the project has a MSRV of 1.56, there is no reason I can see for not implementing this required trait for arrays and slices. These changes implement such trait for the described types, as long as the contained type implements `ConstInstantiable` itself. --- quickphf_codegen/src/const_instantiable.rs | 35 +++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/quickphf_codegen/src/const_instantiable.rs b/quickphf_codegen/src/const_instantiable.rs index b36701e..abe4983 100644 --- a/quickphf_codegen/src/const_instantiable.rs +++ b/quickphf_codegen/src/const_instantiable.rs @@ -10,7 +10,7 @@ pub trait ConstInstantiable { /// Provides blanket implementation of [`ConstInstantiable`] which defers to /// [`Debug`](core::fmt::Debug) representation of type. -pub trait DebugInstantiable: std::fmt::Debug {} +pub trait DebugInstantiable: fmt::Debug {} impl ConstInstantiable for T { fn fmt_const_new(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { @@ -119,3 +119,36 @@ where } } } + +impl ConstInstantiable for [T; N] { + fn fmt_const_new(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt_const_slice_inner(self, f) + } +} + +impl ConstInstantiable for &[T; N] { + fn fmt_const_new(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + (&self[..]).fmt_const_new(f) + } +} + +impl ConstInstantiable for &[T] { + fn fmt_const_new(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "&")?; + fmt_const_slice_inner(self, f) + } +} + +fn fmt_const_slice_inner( + slice: &[T], + f: &mut fmt::Formatter<'_>, +) -> fmt::Result { + write!(f, "[")?; + for (i, value) in slice.iter().enumerate() { + value.fmt_const_new(f)?; + if i < slice.len() - 1 { + write!(f, ", ")?; + } + } + write!(f, "]") +}