Skip to main content

cheetah_string/
builder.rs

1use alloc::string::String;
2use core::fmt;
3
4use crate::inline::{InlineStr, INLINE_CAPACITY};
5use crate::CheetahString;
6
7/// Append-heavy builder for constructing Cheetah string values.
8///
9/// `CheetahBuilder` keeps mutable construction separate from immutable,
10/// clone-cheap [`CheetahString`] values.
11///
12/// A builder created with [`new`](Self::new) or with a capacity of at most 23
13/// bytes keeps its contents on the stack until they outgrow inline storage,
14/// so building a short key and calling [`finish`](Self::finish) allocates
15/// nothing. A larger [`with_capacity`](Self::with_capacity) allocates that
16/// capacity up front, as `String::with_capacity` does.
17#[derive(Clone)]
18pub struct CheetahBuilder {
19    inner: Buffer,
20}
21
22#[derive(Clone)]
23enum Buffer {
24    Inline(InlineStr),
25    Heap(String),
26}
27
28impl Default for CheetahBuilder {
29    #[inline]
30    fn default() -> Self {
31        Self::new()
32    }
33}
34
35impl CheetahBuilder {
36    /// Creates an empty builder that starts in inline storage.
37    #[inline]
38    #[must_use]
39    pub fn new() -> Self {
40        Self {
41            inner: Buffer::Inline(InlineStr::empty()),
42        }
43    }
44
45    /// Creates an empty builder with room for at least `capacity` bytes.
46    ///
47    /// Up to 23 bytes fit inline without allocating; a larger capacity is
48    /// allocated immediately.
49    #[inline]
50    #[must_use]
51    pub fn with_capacity(capacity: usize) -> Self {
52        if capacity <= INLINE_CAPACITY {
53            Self::new()
54        } else {
55            Self {
56                inner: Buffer::Heap(String::with_capacity(capacity)),
57            }
58        }
59    }
60
61    /// Creates a builder from existing owned storage.
62    #[inline]
63    #[must_use]
64    pub fn from_string(value: String) -> Self {
65        Self {
66            inner: Buffer::Heap(value),
67        }
68    }
69
70    /// Moves inline contents to a heap buffer with room for `additional`
71    /// more bytes.
72    #[cold]
73    fn spill(&mut self, additional: usize) -> &mut String {
74        if let Buffer::Inline(inline) = &self.inner {
75            let needed = inline.len().saturating_add(additional);
76            let mut heap = String::with_capacity(needed.max(2 * INLINE_CAPACITY));
77            heap.push_str(inline.as_str());
78            self.inner = Buffer::Heap(heap);
79        }
80        match &mut self.inner {
81            Buffer::Heap(heap) => heap,
82            Buffer::Inline(_) => unreachable!("inline contents were just moved to the heap"),
83        }
84    }
85
86    /// Appends a string slice.
87    #[inline]
88    pub fn push_str(&mut self, value: &str) {
89        match &mut self.inner {
90            Buffer::Inline(inline) => {
91                if !inline.push_str(value) {
92                    self.spill(value.len()).push_str(value);
93                }
94            }
95            Buffer::Heap(heap) => heap.push_str(value),
96        }
97    }
98
99    /// Appends a character.
100    #[inline]
101    pub fn push(&mut self, value: char) {
102        match &mut self.inner {
103            Buffer::Inline(_) => {
104                let mut encoded = [0; 4];
105                self.push_str(value.encode_utf8(&mut encoded));
106            }
107            // `String::push` has a one-byte fast path for ASCII.
108            Buffer::Heap(heap) => heap.push(value),
109        }
110    }
111
112    /// Reserves capacity for at least `additional` more bytes.
113    #[inline]
114    pub fn reserve(&mut self, additional: usize) {
115        match &mut self.inner {
116            Buffer::Inline(inline) => {
117                if inline.len().saturating_add(additional) > INLINE_CAPACITY {
118                    self.spill(additional);
119                }
120            }
121            Buffer::Heap(heap) => heap.reserve(additional),
122        }
123    }
124
125    /// Clears the current contents while preserving capacity.
126    #[inline]
127    pub fn clear(&mut self) {
128        match &mut self.inner {
129            Buffer::Inline(inline) => *inline = InlineStr::empty(),
130            Buffer::Heap(heap) => heap.clear(),
131        }
132    }
133
134    /// Returns the current contents.
135    #[inline]
136    #[must_use]
137    pub fn as_str(&self) -> &str {
138        match &self.inner {
139            Buffer::Inline(inline) => inline.as_str(),
140            Buffer::Heap(heap) => heap.as_str(),
141        }
142    }
143
144    /// Returns the current length in bytes.
145    #[inline]
146    #[must_use]
147    pub fn len(&self) -> usize {
148        match &self.inner {
149            Buffer::Inline(inline) => inline.len(),
150            Buffer::Heap(heap) => heap.len(),
151        }
152    }
153
154    /// Returns whether the builder is empty.
155    #[inline]
156    #[must_use]
157    pub fn is_empty(&self) -> bool {
158        self.len() == 0
159    }
160
161    /// Returns the capacity in bytes: 23 while the contents are inline,
162    /// otherwise the allocated capacity.
163    #[inline]
164    #[must_use]
165    pub fn capacity(&self) -> usize {
166        match &self.inner {
167            Buffer::Inline(_) => INLINE_CAPACITY,
168            Buffer::Heap(heap) => heap.capacity(),
169        }
170    }
171
172    /// Freezes this builder into the canonical clone-cheap string value.
173    ///
174    /// Inline contents become an inline value without allocating. Use
175    /// [`CheetahBuilder::into_string`] when construction is followed by more
176    /// mutation or when spare capacity must be retained.
177    #[inline]
178    #[must_use]
179    pub fn finish(self) -> CheetahString {
180        match self.inner {
181            Buffer::Inline(inline) => CheetahString::from_inline(inline),
182            Buffer::Heap(heap) => CheetahString::from_string(heap),
183        }
184    }
185
186    /// Freezes the builder into the canonical clone-cheap string value.
187    ///
188    /// This compatibility name is retained so downstream v2 consumers can
189    /// adopt the immutable v3 core without a source migration.
190    #[deprecated(since = "3.0.0", note = "use finish()")]
191    #[inline]
192    #[must_use]
193    pub fn finish_string(self) -> CheetahString {
194        self.finish()
195    }
196
197    /// Returns the contents as an owned `String`.
198    ///
199    /// Heap contents are returned without copying, keeping their spare
200    /// capacity; inline contents are copied into a new `String`.
201    #[inline]
202    #[must_use]
203    pub fn into_string(self) -> String {
204        match self.inner {
205            Buffer::Inline(inline) => String::from(inline.as_str()),
206            Buffer::Heap(heap) => heap,
207        }
208    }
209}
210
211impl From<String> for CheetahBuilder {
212    #[inline]
213    fn from(value: String) -> Self {
214        Self::from_string(value)
215    }
216}
217
218impl From<&str> for CheetahBuilder {
219    #[inline]
220    fn from(value: &str) -> Self {
221        let mut builder = Self::with_capacity(value.len());
222        builder.push_str(value);
223        builder
224    }
225}
226
227impl Extend<char> for CheetahBuilder {
228    #[inline]
229    fn extend<T: IntoIterator<Item = char>>(&mut self, iter: T) {
230        for character in iter {
231            self.push(character);
232        }
233    }
234}
235
236impl<'a> Extend<&'a str> for CheetahBuilder {
237    #[inline]
238    fn extend<T: IntoIterator<Item = &'a str>>(&mut self, iter: T) {
239        for item in iter {
240            self.push_str(item);
241        }
242    }
243}
244
245impl fmt::Write for CheetahBuilder {
246    #[inline]
247    fn write_str(&mut self, value: &str) -> fmt::Result {
248        self.push_str(value);
249        Ok(())
250    }
251
252    #[inline]
253    fn write_char(&mut self, value: char) -> fmt::Result {
254        self.push(value);
255        Ok(())
256    }
257}
258
259impl fmt::Debug for CheetahBuilder {
260    #[inline]
261    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
262        f.debug_struct("CheetahBuilder")
263            .field("value", &self.as_str())
264            .field("capacity", &self.capacity())
265            .finish()
266    }
267}