Debian Codegraph @

src/shared/util/array_str.rs

raw symbols SCIP
1 // auto-generated by: jiff-cli generate shared
2
3 /// A simple and not the most-efficient fixed size string on the stack.
4 ///
5 /// This supplanted some uses of `Box<str>` for storing tiny strings in an
6 /// effort to reduce our dependence on dynamic memory allocation.
7 ///
8 /// Also, since it isn't needed and it lets us save on storage requirements,
9 /// `N` must be less than `256` (so that the length can fit in a `u8`).
10 #[derive(Clone, Copy, Eq, Hash, PartialEq, PartialOrd, Ord)]
11 #[doc(hidden)] // not part of Jiff's public API
12 pub struct ArrayStr<const N: usize> {
13 /// The UTF-8 bytes that make up the string.
14 ///
15 /// This array---the entire array---is always valid UTF-8. And
16 /// the `0..self.len` sub-slice is also always valid UTF-8.
17 bytes: [u8; N],
18 /// The number of bytes used by the string in `bytes`.
19 ///
20 /// (We could technically save this byte in some cases and use a NUL
21 /// terminator. For example, since we don't permit NUL bytes in POSIX time
22 /// zone abbreviation strings, but this is simpler and only one byte and
23 /// generalizes. And we're not really trying to micro-optimize the storage
24 /// requirements when we use these array strings. Or at least, I don't know
25 /// of a reason to.)
26 len: u8,
27 }
28
29 impl<const N: usize> ArrayStr<N> {
30 /// Creates a new fixed capacity string.
31 ///
32 /// If the given string exceeds `N` bytes, then this returns
33 /// `None`.
34 pub(crate) const fn new(s: &str) -> Option<ArrayStr<N>> {
35 let len = s.len();
36 if len > N {
37 return None;
38 }
39 let mut bytes = [0; N];
40 let mut i = 0;
41 while i < s.as_bytes().len() {
42 bytes[i] = s.as_bytes()[i];
43 i += 1;
44 }
45 // OK because we don't ever use anything bigger than u8::MAX for `N`.
46 // And we probably shouldn't, because that would be a pretty chunky
47 // array. If such a thing is needed, please file an issue to discuss.
48 debug_assert!(N <= u8::MAX as usize, "size of ArrayStr is too big");
49 Some(ArrayStr { bytes, len: len as u8 })
50 }
51
52 /// Returns the capacity of this array string.
53 pub(crate) fn capacity() -> usize {
54 N
55 }
56
57 /// Append the bytes given to the end of this string.
58 ///
59 /// If the capacity would be exceeded, then this is a no-op and `false`
60 /// is returned.
61 pub(crate) fn push_str(&mut self, s: &str) -> bool {
62 let len = usize::from(self.len);
63 let Some(new_len) = len.checked_add(s.len()) else { return false };
64 if new_len > N {
65 return false;
66 }
67 self.bytes[len..new_len].copy_from_slice(s.as_bytes());
68 // OK because we don't ever use anything bigger than u8::MAX for `N`.
69 // And we probably shouldn't, because that would be a pretty chunky
70 // array. If such a thing is needed, please file an issue to discuss.
71 debug_assert!(
72 N <= usize::from(u8::MAX),
73 "size of ArrayStr is too big"
74 );
75 self.len = u8::try_from(new_len).unwrap();
76 true
77 }
78
79 /// Returns this array string as a string slice.
80 pub(crate) fn as_str(&self) -> &str {
81 // OK because construction guarantees valid UTF-8.
82 //
83 // This is bullet proof enough to use unchecked `str` construction
84 // here, but I can't dream up of a benchmark where it matters.
85 core::str::from_utf8(&self.bytes[..usize::from(self.len)]).unwrap()
86 }
87 }
88
89 /// Easy construction of `ArrayStr` from `&'static str`.
90 ///
91 /// We specifically limit to `&'static str` to approximate string literals.
92 /// This prevents most cases of accidentally creating a non-string literal
93 /// that panics if the string is too big.
94 ///
95 /// This impl primarily exists to make writing tests more convenient.
96 impl<const N: usize> From<&'static str> for ArrayStr<N> {
97 fn from(s: &'static str) -> ArrayStr<N> {
98 ArrayStr::new(s).unwrap()
99 }
100 }
101
102 impl<const N: usize> PartialEq<str> for ArrayStr<N> {
103 fn eq(&self, rhs: &str) -> bool {
104 self.as_str() == rhs
105 }
106 }
107
108 impl<const N: usize> PartialEq<&str> for ArrayStr<N> {
109 fn eq(&self, rhs: &&str) -> bool {
110 self.as_str() == *rhs
111 }
112 }
113
114 impl<const N: usize> PartialEq<ArrayStr<N>> for str {
115 fn eq(&self, rhs: &ArrayStr<N>) -> bool {
116 self == rhs.as_str()
117 }
118 }
119
120 impl<const N: usize> core::fmt::Debug for ArrayStr<N> {
121 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
122 core::fmt::Debug::fmt(self.as_str(), f)
123 }
124 }
125
126 impl<const N: usize> core::fmt::Display for ArrayStr<N> {
127 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
128 core::fmt::Display::fmt(self.as_str(), f)
129 }
130 }
131
132 impl<const N: usize> core::fmt::Write for ArrayStr<N> {
133 fn write_str(&mut self, s: &str) -> core::fmt::Result {
134 if self.push_str(s) {
135 Ok(())
136 } else {
137 Err(core::fmt::Error)
138 }
139 }
140 }
141
142 impl<const N: usize> AsRef<str> for ArrayStr<N> {
143 fn as_ref(&self) -> &str {
144 self.as_str()
145 }
146 }
147
148 /// A self-imposed limit on the size of a time zone abbreviation, in bytes.
149 ///
150 /// POSIX says this:
151 ///
152 /// > Indicate no less than three, nor more than {TZNAME_MAX}, bytes that are
153 /// > the designation for the standard (std) or the alternative (dst -such as
154 /// > Daylight Savings Time) timezone.
155 ///
156 /// But it doesn't seem worth the trouble to query `TZNAME_MAX`. Interestingly,
157 /// IANA says:
158 ///
159 /// > are 3 or more characters specifying the standard and daylight saving time
160 /// > (DST) zone abbreviations
161 ///
162 /// Which implies that IANA thinks there is no limit. But that seems unwise.
163 /// Moreover, in practice, it seems like the `date` utility supports fairly
164 /// long abbreviations. On my mac (so, BSD `date` as I understand it):
165 ///
166 /// ```text
167 /// $ TZ=ZZZ5YYYYYYYYYYYYYYYYYYYYY date
168 /// Sun Mar 17 20:05:58 YYYYYYYYYYYYYYYYYYYYY 2024
169 /// ```
170 ///
171 /// And on my Linux machine (so, GNU `date`):
172 ///
173 /// ```text
174 /// $ TZ=ZZZ5YYYYYYYYYYYYYYYYYYYYY date
175 /// Sun Mar 17 08:05:36 PM YYYYYYYYYYYYYYYYYYYYY 2024
176 /// ```
177 ///
178 /// I don't know exactly what limit these programs use, but 30 seems good
179 /// enough?
180 ///
181 /// (Previously, I had been using 255 and stuffing the string in a `Box<str>`.
182 /// But as part of work on [#168], I was looking to remove allocation from as
183 /// many places as possible. And this was one candidate. But making room on the
184 /// stack for 255 byte abbreviations seemed gratuitous. So I picked something
185 /// smaller. If we come across an abbreviation bigger than this max, then we'll
186 /// error.)
187 ///
188 /// [#168]: https://github.com/BurntSushi/jiff/issues/168
189 const ABBREVIATION_MAX: usize = 30;
190
191 /// A type alias for centralizing the definition of a time zone abbreviation.
192 ///
193 /// Basically, this creates one single coherent place where we control the
194 /// length of a time zone abbreviation.
195 #[doc(hidden)] // not part of Jiff's public API
196 pub type Abbreviation = ArrayStr<ABBREVIATION_MAX>;
197
198 #[cfg(test)]
199 mod tests {
200 use core::fmt::Write;
201
202 use super::*;
203
204 #[test]
205 fn fmt_write() {
206 let mut dst = ArrayStr::<5>::new("").unwrap();
207 assert!(write!(&mut dst, "abcd").is_ok());
208 assert!(write!(&mut dst, "e").is_ok());
209 assert!(write!(&mut dst, "f").is_err());
210 }
211 }