1/*!
2Small shared utilities used by Jiff.
3*/
45#[cfg(feature = "alloc")]
6pub(crate) mod crc32;
78/// A slice that is either `'static` or on the heap.
9///
10/// This is useful for representing a sequence of data that can be either
11/// created at runtime and put on the heap (when dynamic memory allocation is
12/// needed), or when it needs to be constructed at compile time. For example,
13/// this is used to represent time zone transitions inside this crate's TZif
14/// representation.
15///
16/// The downside of this type is that `T` cannot contain any borrows.
17///
18/// This is similar to `SmallStr`, but there is no array-only variant. As such,
19/// this isn't intended for small data. (Indeed, time zone transitions can get
20/// pretty long.) This also makes the API simpler: all constructors are
21/// infallible.
22#[derive(#[automatically_derived]impl<T: ::core::clone::Clone + 'static>
::core::clone::Clone for MaybeStaticSlice<T> {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
MaybeStaticSlice { kind: ::core::clone::Clone::clone(&self.kind) }
}
}Clone, #[automatically_derived]impl<T: ::core::fmt::Debug + 'static>
::core::fmt::Debug for MaybeStaticSlice<T> {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field1_finish(f,
"MaybeStaticSlice kind", &&self.kind)
}
}Debug, #[automatically_derived]impl<T: ::core::cmp::Eq + 'static> ::core::cmp::Eq for
MaybeStaticSlice<T> {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<MaybeStaticSliceKind<T>>;
}
}Eq, #[automatically_derived]impl<T: ::core::cmp::PartialEq + 'static>
::core::marker::StructuralPartialEq for MaybeStaticSlice<T> {
}
#[automatically_derived]impl<T: ::core::cmp::PartialEq + 'static>
::core::cmp::PartialEq for MaybeStaticSlice<T> {
#[inline]
fn eq(&self, other: &Self) -> bool { self.kind == other.kind }
}PartialEq)]
23pub struct MaybeStaticSlice<T: 'static> {
24 kind: MaybeStaticSliceKind<T>,
25}
2627#[derive(#[automatically_derived]impl<T: ::core::clone::Clone + 'static>
::core::clone::Clone for MaybeStaticSliceKind<T> {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
match self {
Self::Static(__self_0) =>
MaybeStaticSliceKind::Static(::core::clone::Clone::clone(__self_0)),
Self::Heap(__self_0) =>
MaybeStaticSliceKind::Heap(::core::clone::Clone::clone(__self_0)),
}
}
}Clone, #[automatically_derived]impl<T: ::core::fmt::Debug + 'static>
::core::fmt::Debug for MaybeStaticSliceKind<T> {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::Static(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Static", &__self_0),
Self::Heap(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f, "Heap",
&__self_0),
}
}
}Debug, #[automatically_derived]impl<T: ::core::cmp::Eq + 'static> ::core::cmp::Eq for
MaybeStaticSliceKind<T> {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<&'static [T]>;
let _: ::core::cmp::AssertParamIsEq<alloc::boxed::Box<[T]>>;
}
}Eq, #[automatically_derived]impl<T: ::core::cmp::PartialEq + 'static>
::core::marker::StructuralPartialEq for MaybeStaticSliceKind<T> {
}
#[automatically_derived]impl<T: ::core::cmp::PartialEq + 'static>
::core::cmp::PartialEq for MaybeStaticSliceKind<T> {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other) &&
match (self, other) {
(Self::Static(__self_0), Self::Static(__arg1_0)) =>
__self_0 == __arg1_0,
(Self::Heap(__self_0), Self::Heap(__arg1_0)) =>
__self_0 == __arg1_0,
_ => unsafe { ::core::intrinsics::unreachable() }
}
}
}PartialEq)]
28enum MaybeStaticSliceKind<T: 'static> {
29 Static(&'static [T]),
30#[cfg(feature = "alloc")]
31Heap(alloc::boxed::Box<[T]>),
32}
3334impl<T: 'static> MaybeStaticSlice<T> {
35/// Creates a new static slice from the data provided.
36#[inline]
37pub const fn statik(data: &'static [T]) -> MaybeStaticSlice<T> {
38let kind = MaybeStaticSliceKind::Static(data);
39MaybeStaticSlice { kind }
40 }
4142/// Creates a new slice on the heap from the data provided.
43#[cfg(feature = "alloc")]
44 #[inline]
45pub const fn heap(data: alloc::boxed::Box<[T]>) -> MaybeStaticSlice<T> {
46let kind = MaybeStaticSliceKind::Heap(data);
47MaybeStaticSlice { kind }
48 }
4950/// Returns the underlying data as a slice.
51#[inline]
52pub const fn as_slice(&self) -> &[T] {
53match self.kind {
54 MaybeStaticSliceKind::Static(slice) => slice,
55#[cfg(feature = "alloc")]
56MaybeStaticSliceKind::Heap(ref slice) => slice,
57 }
58 }
59}
6061impl<T: 'static> From<&'static [T]> for MaybeStaticSlice<T> {
62#[inline]
63fn from(data: &'static [T]) -> MaybeStaticSlice<T> {
64MaybeStaticSlice::statik(data)
65 }
66}
6768#[cfg(feature = "alloc")]
69impl<T: 'static> From<alloc::boxed::Box<[T]>> for MaybeStaticSlice<T> {
70#[inline]
71fn from(data: alloc::boxed::Box<[T]>) -> MaybeStaticSlice<T> {
72MaybeStaticSlice::heap(data)
73 }
74}
7576impl<T: 'static> core::ops::Dereffor MaybeStaticSlice<T> {
77type Target = [T];
7879#[inline]
80fn deref(&self) -> &[T] {
81self.as_slice()
82 }
83}
8485/// A "small" string that usually lives in an array.
86///
87/// When the string is too big, it spills over into the heap. Generally
88/// speaking, this should only be used when spilling into the heap is
89/// exceptionally rare. For example, for representing pathological user data
90/// (like very long time zone abbreviations).
91///
92/// The `ARRAY_CAPACITY_MAX` parameter defines the maximum length of a string
93/// that will fit in an array backed storage. This number cannot be any
94/// bigger than `255`.
95///
96/// In core-only environments, this always uses array backed storage or static
97/// data. Static data is only used when `SmallStr::from("some static string")`
98/// is used to construct a `SmallStr`. This is useful when constructing static
99/// data structures.
100#[derive(#[automatically_derived]impl<const ARRAY_CAPACITY_MAX : usize>
::core::clone::Clone for SmallStr<ARRAY_CAPACITY_MAX> {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
SmallStr { kind: ::core::clone::Clone::clone(&self.kind) }
}
}Clone, #[automatically_derived]impl<const ARRAY_CAPACITY_MAX : usize> ::core::cmp::Eq
for SmallStr<ARRAY_CAPACITY_MAX> {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<SmallStrKind<ARRAY_CAPACITY_MAX>>;
}
}Eq, #[automatically_derived]impl<const ARRAY_CAPACITY_MAX : usize>
::core::hash::Hash for SmallStr<ARRAY_CAPACITY_MAX> {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.kind, state)
}
}Hash, #[automatically_derived]impl<const ARRAY_CAPACITY_MAX : usize>
::core::marker::StructuralPartialEq for SmallStr<ARRAY_CAPACITY_MAX> {
}
#[automatically_derived]impl<const ARRAY_CAPACITY_MAX : usize>
::core::cmp::PartialEq for SmallStr<ARRAY_CAPACITY_MAX> {
#[inline]
fn eq(&self, other: &Self) -> bool { self.kind == other.kind }
}PartialEq, #[automatically_derived]impl<const ARRAY_CAPACITY_MAX : usize>
::core::cmp::PartialOrd for SmallStr<ARRAY_CAPACITY_MAX> {
#[inline]
fn partial_cmp(&self, other: &Self)
-> ::core::option::Option<::core::cmp::Ordering> {
::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
}
}PartialOrd, #[automatically_derived]impl<const ARRAY_CAPACITY_MAX : usize>
::core::cmp::Ord for SmallStr<ARRAY_CAPACITY_MAX> {
#[inline]
fn cmp(&self, other: &Self) -> ::core::cmp::Ordering {
::core::cmp::Ord::cmp(&self.kind, &other.kind)
}
}Ord)]
101pub struct SmallStr<const ARRAY_CAPACITY_MAX: usize> {
102 kind: SmallStrKind<ARRAY_CAPACITY_MAX>,
103}
104105#[derive(#[automatically_derived]impl<const ARRAY_CAPACITY_MAX : usize>
::core::clone::Clone for SmallStrKind<ARRAY_CAPACITY_MAX> {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
match self {
Self::Array(__self_0) =>
SmallStrKind::Array(::core::clone::Clone::clone(__self_0)),
Self::Static(__self_0) =>
SmallStrKind::Static(::core::clone::Clone::clone(__self_0)),
Self::Heap(__self_0) =>
SmallStrKind::Heap(::core::clone::Clone::clone(__self_0)),
}
}
}Clone, #[automatically_derived]impl<const ARRAY_CAPACITY_MAX : usize>
::core::fmt::Debug for SmallStrKind<ARRAY_CAPACITY_MAX> {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::Array(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f, "Array",
&__self_0),
Self::Static(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Static", &__self_0),
Self::Heap(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f, "Heap",
&__self_0),
}
}
}Debug, #[automatically_derived]impl<const ARRAY_CAPACITY_MAX : usize> ::core::cmp::Eq
for SmallStrKind<ARRAY_CAPACITY_MAX> {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<ArrayStr<ARRAY_CAPACITY_MAX>>;
let _: ::core::cmp::AssertParamIsEq<&'static str>;
let _: ::core::cmp::AssertParamIsEq<alloc::boxed::Box<str>>;
}
}Eq, #[automatically_derived]impl<const ARRAY_CAPACITY_MAX : usize>
::core::hash::Hash for SmallStrKind<ARRAY_CAPACITY_MAX> {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&::core::intrinsics::discriminant_value(self),
state);
match self {
Self::Array(__self_0) =>
::core::hash::Hash::hash(__self_0, state),
Self::Static(__self_0) =>
::core::hash::Hash::hash(__self_0, state),
Self::Heap(__self_0) => ::core::hash::Hash::hash(__self_0, state),
}
}
}Hash, #[automatically_derived]impl<const ARRAY_CAPACITY_MAX : usize>
::core::marker::StructuralPartialEq for SmallStrKind<ARRAY_CAPACITY_MAX> {
}
#[automatically_derived]impl<const ARRAY_CAPACITY_MAX : usize>
::core::cmp::PartialEq for SmallStrKind<ARRAY_CAPACITY_MAX> {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other) &&
match (self, other) {
(Self::Array(__self_0), Self::Array(__arg1_0)) =>
__self_0 == __arg1_0,
(Self::Static(__self_0), Self::Static(__arg1_0)) =>
__self_0 == __arg1_0,
(Self::Heap(__self_0), Self::Heap(__arg1_0)) =>
__self_0 == __arg1_0,
_ => unsafe { ::core::intrinsics::unreachable() }
}
}
}PartialEq, #[automatically_derived]impl<const ARRAY_CAPACITY_MAX : usize>
::core::cmp::PartialOrd for SmallStrKind<ARRAY_CAPACITY_MAX> {
#[inline]
fn partial_cmp(&self, other: &Self)
-> ::core::option::Option<::core::cmp::Ordering> {
::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
}
}PartialOrd, #[automatically_derived]impl<const ARRAY_CAPACITY_MAX : usize>
::core::cmp::Ord for SmallStrKind<ARRAY_CAPACITY_MAX> {
#[inline]
fn cmp(&self, other: &Self) -> ::core::cmp::Ordering {
match (self, other) {
(Self::Array(__self_0), Self::Array(__arg1_0)) =>
::core::cmp::Ord::cmp(__self_0, __arg1_0),
(Self::Static(__self_0), Self::Static(__arg1_0)) =>
::core::cmp::Ord::cmp(__self_0, __arg1_0),
(Self::Heap(__self_0), Self::Heap(__arg1_0)) =>
::core::cmp::Ord::cmp(__self_0, __arg1_0),
_ =>
::core::cmp::Ord::cmp(&::core::intrinsics::discriminant_value(self),
&::core::intrinsics::discriminant_value(other)),
}
}
}Ord)]
106enum SmallStrKind<const ARRAY_CAPACITY_MAX: usize> {
107 Array(ArrayStr<ARRAY_CAPACITY_MAX>),
108// TODO: Reconsider this variant. I'm not sure it's really necessary, and
109 // it makes the size of all `SmallStr` values bigger.
110Static(&'static str),
111#[cfg(feature = "alloc")]
112Heap(alloc::boxed::Box<str>),
113}
114115impl<const ARRAY_CAPACITY_MAX: usize> SmallStr<ARRAY_CAPACITY_MAX> {
116/// Creates a new array-or-heap backed string depending on the length.
117 ///
118 /// In environments with dynamic memory allocation, this never returns
119 /// `None`. In core-only environments, this may return `None` when the
120 /// string length exceeds the maximum capacity.
121#[inline]
122pub fn new(s: &str) -> Option<SmallStr<ARRAY_CAPACITY_MAX>> {
123SmallStr::try_array(s).or_else(|| {
124#[cfg(not(feature = "alloc"))]
125{
126None
127}
128#[cfg(feature = "alloc")]
129{
130Some(SmallStr::from(alloc::boxed::Box::<str>::from(s)))
131 }
132 })
133 }
134135/// Like `new` but always spills to the heap when the given string does not
136 /// fit in this string's fixed capacity.
137 ///
138 /// This is only available when the `alloc` crate feature is enabled.
139#[cfg(feature = "alloc")]
140 #[inline]
141pub fn new_or_heap(s: &str) -> SmallStr<ARRAY_CAPACITY_MAX> {
142SmallStr::try_array(s).unwrap_or_else(|| {
143SmallStr::from(alloc::boxed::Box::<str>::from(s))
144 })
145 }
146147/// Like `SmallStr::new`, but this never returns a string on the heap.
148 ///
149 /// This is useful when you want a `SmallStr` that is guaranteed to never
150 /// be on the heap. For example, when constructing static data.
151 ///
152 /// If the string exceeds the maximum capacity, then `None` is returned.
153#[inline]
154pub const fn try_array(s: &str) -> Option<SmallStr<ARRAY_CAPACITY_MAX>> {
155let Some(astr) = ArrayStr::new(s) else { return None };
156let kind = SmallStrKind::Array(astr);
157Some(SmallStr { kind })
158 }
159160/// Like `SmallStr::new`, but this never returns a string on the heap.
161 ///
162 /// This is useful when you want a `SmallStr` that is guaranteed to never
163 /// be on the heap. For example, when constructing static data.
164 ///
165 /// # Panics
166 ///
167 /// If the string exceeds the maximum capacity, then this routine panics.
168#[inline]
169pub const fn array(s: &str) -> SmallStr<ARRAY_CAPACITY_MAX> {
170// MSRV(1.83): We can use `unwrap()` in a const context, so this
171 // routine isn't as necessary. But it's still nice.
172let Some(astr) = ArrayStr::new(s) else { { ::core::panicking::panic_fmt(format_args!("string too big")); }panic!("string too big") };
173let kind = SmallStrKind::Array(astr);
174SmallStr { kind }
175 }
176177/// Like `SmallStr::new`, but only accepts a static string.
178 ///
179 /// This never fails.
180#[inline]
181pub const fn statik(s: &'static str) -> SmallStr<ARRAY_CAPACITY_MAX> {
182let kind = SmallStrKind::Static(s);
183SmallStr { kind }
184 }
185186/// Returns the maximum capacity for this small string's array storage.
187#[inline]
188pub const fn array_capacity_max() -> usize {
189ARRAY_CAPACITY_MAX190 }
191192/// Returns this small string as a string slice.
193#[inline]
194pub const fn as_str(&self) -> &str {
195match self.kind {
196 SmallStrKind::Array(ref astr) => astr.as_str(),
197 SmallStrKind::Static(s) => s,
198#[cfg(feature = "alloc")]
199SmallStrKind::Heap(ref s) => s,
200 }
201 }
202}
203204/// Return a `SmallStr` that is guaranteed to live as an array.
205impl<const ARRAY_CAPACITY_MAX: usize> From<ArrayStr<ARRAY_CAPACITY_MAX>>
206for SmallStr<ARRAY_CAPACITY_MAX>
207{
208#[inline]
209fn from(s: ArrayStr<ARRAY_CAPACITY_MAX>) -> SmallStr<ARRAY_CAPACITY_MAX> {
210let kind = SmallStrKind::Array(s);
211SmallStr { kind }
212 }
213}
214215/// Return a `SmallStr` that is guaranteed to live as a static string.
216impl<const ARRAY_CAPACITY_MAX: usize> From<&'static str>
217for SmallStr<ARRAY_CAPACITY_MAX>
218{
219#[inline]
220fn from(s: &'static str) -> SmallStr<ARRAY_CAPACITY_MAX> {
221SmallStr::statik(s)
222 }
223}
224225/// Return a `SmallStr` that is guaranteed to live on the heap.
226#[cfg(feature = "alloc")]
227impl<const ARRAY_CAPACITY_MAX: usize> From<alloc::boxed::Box<str>>
228for SmallStr<ARRAY_CAPACITY_MAX>
229{
230#[inline]
231fn from(s: alloc::boxed::Box<str>) -> SmallStr<ARRAY_CAPACITY_MAX> {
232let kind = SmallStrKind::Heap(s);
233SmallStr { kind }
234 }
235}
236237impl<const ARRAY_CAPACITY_MAX: usize> core::ops::Deref238for SmallStr<ARRAY_CAPACITY_MAX>
239{
240type Target = str;
241242#[inline]
243fn deref(&self) -> &str {
244SmallStr::<ARRAY_CAPACITY_MAX>::as_str(self)
245 }
246}
247248impl<const ARRAY_CAPACITY_MAX: usize> AsRef<str>
249for SmallStr<ARRAY_CAPACITY_MAX>
250{
251#[inline]
252fn as_ref(&self) -> &str {
253self.as_str()
254 }
255}
256257impl<const ARRAY_CAPACITY_MAX: usize> PartialEq<str>
258for SmallStr<ARRAY_CAPACITY_MAX>
259{
260#[inline]
261fn eq(&self, rhs: &str) -> bool {
262self.as_str() == rhs263 }
264}
265266impl<const ARRAY_CAPACITY_MAX: usize> PartialEq<&str>
267for SmallStr<ARRAY_CAPACITY_MAX>
268{
269#[inline]
270fn eq(&self, rhs: &&str) -> bool {
271self.as_str() == *rhs272 }
273}
274275impl<const ARRAY_CAPACITY_MAX: usize> PartialEq<SmallStr<ARRAY_CAPACITY_MAX>>
276for str277{
278#[inline]
279fn eq(&self, rhs: &SmallStr<ARRAY_CAPACITY_MAX>) -> bool {
280self == rhs.as_str()
281 }
282}
283284impl<const ARRAY_CAPACITY_MAX: usize> PartialOrd<str>
285for SmallStr<ARRAY_CAPACITY_MAX>
286{
287#[inline]
288fn partial_cmp(&self, rhs: &str) -> Option<core::cmp::Ordering> {
289self.as_str().partial_cmp(rhs)
290 }
291}
292293impl<const ARRAY_CAPACITY_MAX: usize> PartialOrd<&str>
294for SmallStr<ARRAY_CAPACITY_MAX>
295{
296#[inline]
297fn partial_cmp(&self, rhs: &&str) -> Option<core::cmp::Ordering> {
298self.as_str().partial_cmp(*rhs)
299 }
300}
301302impl<const ARRAY_CAPACITY_MAX: usize> PartialOrd<SmallStr<ARRAY_CAPACITY_MAX>>
303for str304{
305#[inline]
306fn partial_cmp(
307&self,
308 rhs: &SmallStr<ARRAY_CAPACITY_MAX>,
309 ) -> Option<core::cmp::Ordering> {
310self.partial_cmp(rhs.as_str())
311 }
312}
313314impl<const ARRAY_CAPACITY_MAX: usize> core::fmt::Debug315for SmallStr<ARRAY_CAPACITY_MAX>
316{
317#[inline]
318fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
319 core::fmt::Debug::fmt(self.as_str(), f)
320 }
321}
322323impl<const ARRAY_CAPACITY_MAX: usize> core::fmt::Display324for SmallStr<ARRAY_CAPACITY_MAX>
325{
326#[inline]
327fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
328 core::fmt::Display::fmt(self.as_str(), f)
329 }
330}
331332#[cfg(feature = "defmt")]
333impl<const ARRAY_CAPACITY_MAX: usize> defmt::Format
334for SmallStr<ARRAY_CAPACITY_MAX>
335{
336#[inline]
337fn format(&self, f: defmt::Formatter) {
338defmt::write!(f, "{=str}", self.as_str())
339 }
340}
341342/// A simple array-backed string type with a fixed capacity.
343///
344/// This is used by Jiff in lieu of a `Box<str>` for supporting core-only
345/// environments without a dynamic memory allocator. For example, this is used
346/// to represent time zone abbreviations which can be relied upon to be short.
347///
348/// `N` must be less than `256` so that its length can be represented by an
349/// unsigned 8-bit integer.
350///
351/// An `ArrayStr` is guaranteed to be valid UTF-8.
352#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl<const N : usize>
::core::clone::TrivialClone for ArrayStr<N> {
}
#[automatically_derived]impl<const N : usize> ::core::clone::Clone for
ArrayStr<N> {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<u8>;
let _: ::core::clone::AssertParamIsClone<[u8; N]>;
*self
}
}Clone, #[automatically_derived]impl<const N : usize> ::core::marker::Copy for
ArrayStr<N> {
}Copy, #[automatically_derived]impl<const N : usize> ::core::cmp::Eq for ArrayStr<N>
{
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<u8>;
let _: ::core::cmp::AssertParamIsEq<[u8; N]>;
}
}Eq, #[automatically_derived]impl<const N : usize> ::core::hash::Hash for
ArrayStr<N> {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.len, state);
::core::hash::Hash::hash(&self.bytes, state)
}
}Hash, #[automatically_derived]impl<const N : usize>
::core::marker::StructuralPartialEq for ArrayStr<N> {
}
#[automatically_derived]impl<const N : usize> ::core::cmp::PartialEq for
ArrayStr<N> {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.len == other.len && self.bytes == other.bytes
}
}PartialEq, #[automatically_derived]impl<const N : usize> ::core::cmp::PartialOrd for
ArrayStr<N> {
#[inline]
fn partial_cmp(&self, other: &Self)
-> ::core::option::Option<::core::cmp::Ordering> {
::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
}
}PartialOrd, #[automatically_derived]impl<const N : usize> ::core::cmp::Ord for ArrayStr<N>
{
#[inline]
fn cmp(&self, other: &Self) -> ::core::cmp::Ordering {
match ::core::cmp::Ord::cmp(&self.len, &other.len) {
::core::cmp::Ordering::Equal =>
::core::cmp::Ord::cmp(&self.bytes, &other.bytes),
cmp => cmp,
}
}
}Ord)]
353pub struct ArrayStr<const N: usize> {
354// If it's advantageous enough, we could use an array of uninitialized
355 // bytes. But it's not clear that it's worth doing. ---AG
356/// The number of bytes used by the string in `bytes`.
357 ///
358 /// (We could technically save this byte in some cases and use a NUL
359 /// terminator. For example, since we don't permit NUL bytes in POSIX time
360 /// zone abbreviation strings, but this is simpler and only one byte and
361 /// generalizes. And we're not really trying to micro-optimize the storage
362 /// requirements when we use these array strings. Or at least, I don't know
363 /// of a reason to.)
364len: u8,
365/// The UTF-8 bytes that make up the string.
366 ///
367 /// This array---the entire array---is always valid UTF-8. And
368 /// the `0..self.len` sub-slice is also always valid UTF-8.
369bytes: [u8; N],
370}
371372impl<const N: usize> ArrayStr<N> {
373/// Creates a new fixed capacity string.
374 ///
375 /// If the given string exceeds `N` bytes, then this returns
376 /// `None`. Similarly, if `N` exceeds `u8::MAX`, then this
377 /// returns `None`.
378#[inline]
379pub const fn new(s: &str) -> Option<ArrayStr<N>> {
380let len = s.len();
381if len > N || N > u8::MAXas usize {
382return None;
383 }
384let mut bytes = [0; N];
385let mut i = 0;
386while i < s.as_bytes().len() {
387 bytes[i] = s.as_bytes()[i];
388 i += 1;
389 }
390// OK because an `ArrayStr<N>` with `N > 255` bails out above.
391Some(ArrayStr { len: lenas u8, bytes })
392 }
393394/// Returns the capacity of this array string.
395#[inline]
396pub const fn capacity() -> usize {
397N398 }
399400/// Append the bytes given to the end of this string.
401 ///
402 /// If the capacity would be exceeded, then this is a no-op and `false`
403 /// is returned. Otherwise, all of `s` is written to this array string and
404 /// `true` is returned.
405#[inline]
406pub fn push_str(&mut self, s: &str) -> bool {
407let len = self.len as usize;
408let Some(new_len) = len.checked_add(s.len()) else { return false };
409if new_len > N {
410return false;
411 }
412413let mut i = len;
414while i < new_len {
415self.bytes[i] = s.as_bytes()[i - len];
416 i += 1;
417 }
418// OK because an `ArrayStr<N>` with `N > 255` cannot be created.
419self.len = new_lenas u8;
420true
421}
422423/// Returns this array string as a string slice.
424#[inline]
425pub const fn as_str(&self) -> &str {
426// SAFETY: Firstly, the unchecked UTF-8 conversion is correct because
427 // the constructor and all mutators only accept `&str`. All mutators
428 // (just `push_str` at time of writing) only ever concatenates the
429 // given string to what is already there. Any UTF-8 string concatenated
430 // with any other UTF-8 string produces a UTF-8 string.
431 //
432 // Secondly, `self.bytes` is always valid and initialized. And
433 // `self.len` is managed as the length of bytes that make up the
434 // string.
435unsafe {
436 core::str::from_utf8_unchecked(core::slice::from_raw_parts(
437self.bytes.as_ptr(),
438self.len as usize,
439 ))
440 }
441 }
442}
443444impl<const N: usize> core::ops::Dereffor ArrayStr<N> {
445type Target = str;
446447#[inline]
448fn deref(&self) -> &str {
449ArrayStr::<N>::as_str(self)
450 }
451}
452453impl<const N: usize> AsRef<str> for ArrayStr<N> {
454#[inline]
455fn as_ref(&self) -> &str {
456self.as_str()
457 }
458}
459460impl<const N: usize> PartialEq<str> for ArrayStr<N> {
461#[inline]
462fn eq(&self, rhs: &str) -> bool {
463self.as_str() == rhs464 }
465}
466467impl<const N: usize> PartialEq<&str> for ArrayStr<N> {
468#[inline]
469fn eq(&self, rhs: &&str) -> bool {
470self.as_str() == *rhs471 }
472}
473474impl<const N: usize> PartialEq<ArrayStr<N>> for str {
475#[inline]
476fn eq(&self, rhs: &ArrayStr<N>) -> bool {
477self == rhs.as_str()
478 }
479}
480481impl<const N: usize> PartialOrd<str> for ArrayStr<N> {
482#[inline]
483fn partial_cmp(&self, rhs: &str) -> Option<core::cmp::Ordering> {
484self.as_str().partial_cmp(rhs)
485 }
486}
487488impl<const N: usize> PartialOrd<&str> for ArrayStr<N> {
489#[inline]
490fn partial_cmp(&self, rhs: &&str) -> Option<core::cmp::Ordering> {
491self.as_str().partial_cmp(*rhs)
492 }
493}
494495impl<const N: usize> PartialOrd<ArrayStr<N>> for str {
496#[inline]
497fn partial_cmp(&self, rhs: &ArrayStr<N>) -> Option<core::cmp::Ordering> {
498self.partial_cmp(rhs.as_str())
499 }
500}
501502impl<const N: usize> core::fmt::Debugfor ArrayStr<N> {
503#[inline]
504fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
505 core::fmt::Debug::fmt(self.as_str(), f)
506 }
507}
508509impl<const N: usize> core::fmt::Displayfor ArrayStr<N> {
510#[inline]
511fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
512 core::fmt::Display::fmt(self.as_str(), f)
513 }
514}
515516impl<const N: usize> core::fmt::Writefor ArrayStr<N> {
517#[inline]
518fn write_str(&mut self, s: &str) -> core::fmt::Result {
519if self.push_str(s) { Ok(()) } else { Err(core::fmt::Error) }
520 }
521}
522523#[cfg(feature = "defmt")]
524impl<const N: usize> defmt::Format for ArrayStr<N> {
525#[inline]
526fn format(&self, f: defmt::Formatter) {
527defmt::write!(f, "{=str}", self.as_str())
528 }
529}
530531/// Parses an `OsStr` into a `&str` when `&[u8]` isn't easily available.
532///
533/// The main difference between this and `OsStr::to_str` is that this will
534/// be a zero-cost conversion on Unix platforms to `&[u8]`. On Windows, this
535/// will do UTF-8 validation and return an error if it's invalid UTF-8.
536// MSRV(1.74): Use `OsStr::as_encoded_bytes` and delete this routine.
537#[cfg(feature = "std")]
538pub(crate) fn os_str_bytes<'o, O>(os_str: &'o O) -> Option<&'o [u8]>
539where
540O: ?Sized + AsRef<std::ffi::OsStr>,
541{
542let os_str = os_str.as_ref();
543#[cfg(unix)]
544{
545use std::os::unix::ffi::OsStrExt;
546Some(os_str.as_bytes())
547 }
548#[cfg(not(unix))]
549{
550// It is suspect that we're doing UTF-8 validation and then throwing
551 // away the fact that we did UTF-8 validation. So this could lead
552 // to an extra UTF-8 check if the caller ultimately needs UTF-8. If
553 // that's important, we can add a new API that returns a `&str`. But it
554 // probably won't matter because an `OsStr` in this crate is usually
555 // just an environment variable.
556os_str.to_str().map(|s| s.as_bytes())
557 }
558}
559560#[cfg(test)]
561mod tests {
562use core::fmt::Write;
563564use super::*;
565566#[test]
567fn fmt_write() {
568let mut dst = ArrayStr::<5>::new("").unwrap();
569assert!(write!(&mut dst, "abcd").is_ok());
570assert!(write!(&mut dst, "e").is_ok());
571assert!(write!(&mut dst, "f").is_err());
572 }
573574#[test]
575fn array_str_size() {
576assert_eq!(7, core::mem::size_of::<ArrayStr::<6>>());
577 }
578}