ctb_formats_dcstring/
dcstring_impl.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Owned string buffer for DcTF format.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use std::borrow::Borrow;
30use std::fmt;
31use std::ops::{Deref, DerefMut};
32
33use ctb_formats_dctf::{
34    decode_utf_8e_128_buf, determine_utf_8e_128_error_len, encode_dctf_buf,
35};
36
37use crate::{DcChar, DcCharExt, DcStr, DcUtfError, validate_dctf};
38
39/// An owned, growable string buffer containing valid DcTF data. Analogous to `DcMstring` and Rust's `String`.
40#[derive(Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
41pub struct DcString {
42    pub(crate) inner: Vec<u8>,
43}
44
45impl DcString {
46    /// Creates a new, empty `DcString`.
47    #[must_use]
48    pub const fn new() -> Self {
49        Self { inner: Vec::new() }
50    }
51
52    /// Creates a new, empty `DcString` with pre-allocated capacity in bytes.
53    #[must_use]
54    pub fn with_capacity(capacity: usize) -> Self {
55        Self {
56            inner: Vec::with_capacity(capacity),
57        }
58    }
59
60    /// Validates an existing `Vec<u8>` as DcTF and wraps it in a `DcString`.
61    ///
62    /// # Errors
63    /// Returns `DcUtfError` if the bytes are not valid DcTF.
64    pub fn from_dctf(bytes: Vec<u8>) -> Result<Self, DcUtfError> {
65        validate_dctf(&bytes)?;
66        Ok(Self { inner: bytes })
67    }
68
69    /// Creates a `DcString` from a `Vec<u8>` of DcTF bytes without validation.
70    ///
71    /// # Safety
72    /// The caller must ensure that `bytes` contains valid DcTF data.
73    #[must_use]
74    #[expect(unsafe_code, reason = "Caller guarantees bytes are valid DcTF")]
75    pub const unsafe fn from_dctf_unchecked(bytes: Vec<u8>) -> Self {
76        Self { inner: bytes }
77    }
78
79    /// Validates an existing `Vec<u8>` as legacy UTF-8e-128 (`DcUtf`), transcoding
80    /// it to canonical `DcTF`, and returns a `DcString`.
81    ///
82    /// # Errors
83    /// Returns `DcUtfError` if the bytes are not valid `DcUtf`.
84    pub fn from_dcutf(bytes: Vec<u8>) -> Result<Self, DcUtfError> {
85        let mut out = Self::with_capacity(bytes.len());
86        let mut i = 0usize;
87        while i < bytes.len() {
88            let Some(slice) = bytes.get(i..) else { break };
89            if let Some((val, size)) = decode_utf_8e_128_buf(slice) {
90                out.push(DcChar(val));
91                i = i.saturating_add(size);
92            } else {
93                let error_len = determine_utf_8e_128_error_len(slice);
94                return Err(DcUtfError {
95                    valid_up_to: i,
96                    error_len,
97                });
98            }
99        }
100        Ok(out)
101    }
102
103    /// Consumes this `DcString` and returns the underlying byte buffer.
104    #[must_use]
105    pub fn into_bytes(self) -> Vec<u8> {
106        self.inner
107    }
108
109    /// Appends a character (`DcChar` or `char`) to the end of this string.
110    pub fn push(&mut self, ch: impl Into<DcChar>) {
111        let dc = ch.into();
112        let mut buf = [0u8; 24];
113        let n = encode_dctf_buf(&mut buf, dc.0);
114        if let Some(slice) = buf.get(..n) {
115            self.inner.extend_from_slice(slice);
116        }
117    }
118
119    /// Appends a standard UTF-8 string slice to the end of this string.
120    pub fn push_str(&mut self, s: &str) {
121        self.inner.extend_from_slice(s.as_bytes());
122    }
123
124    /// Appends another `DcStr` slice to the end of this string.
125    pub fn push_dc_str(&mut self, s: &DcStr) {
126        self.inner.extend_from_slice(s.as_bytes());
127    }
128
129    /// Shortens this `DcString` to the specified byte length.
130    ///
131    /// If `new_len` is greater than or equal to current length, this has no effect.
132    /// Panics if `new_len` does not lie on a character boundary.
133    pub fn truncate(&mut self, new_len: usize) {
134        if new_len <= self.inner.len() {
135            assert!(
136                self.is_char_boundary(new_len),
137                "new_len {new_len} is not on a character boundary"
138            );
139            self.inner.truncate(new_len);
140        }
141    }
142
143    /// Removes the last character from this string buffer and returns it,
144    /// or `None` if the string is empty.
145    pub fn pop(&mut self) -> Option<DcChar> {
146        let ch = self.chars().next_back()?;
147        let ch_len = ch.len_dctf();
148        let new_len = self.inner.len().saturating_sub(ch_len);
149        self.inner.truncate(new_len);
150        Some(ch)
151    }
152
153    /// Clears the string, removing all contents.
154    pub fn clear(&mut self) {
155        self.inner.clear();
156    }
157
158    /// Reserves capacity for at least `additional` more bytes.
159    pub fn reserve(&mut self, additional: usize) {
160        self.inner.reserve(additional);
161    }
162
163    /// Returns the total number of bytes this string buffer can hold without
164    /// reallocating.
165    #[must_use]
166    pub fn capacity(&self) -> usize {
167        self.inner.capacity()
168    }
169
170    /// Retains only the characters specified by the predicate.
171    pub fn retain<F: FnMut(DcChar) -> bool>(&mut self, mut f: F) {
172        let mut target = Vec::with_capacity(self.inner.len());
173        for ch in self.chars() {
174            if f(ch) {
175                let mut buf = [0u8; 24];
176                let n = encode_dctf_buf(&mut buf, ch.0);
177                if let Some(slice) = buf.get(..n) {
178                    target.extend_from_slice(slice);
179                }
180            }
181        }
182        self.inner = target;
183    }
184}
185
186impl Deref for DcString {
187    type Target = DcStr;
188
189    #[inline]
190    fn deref(&self) -> &Self::Target {
191        #[expect(
192            unsafe_code,
193            reason = "DcString inner bytes are validated valid DcTF"
194        )]
195        // Safety: DcString inner bytes are guaranteed to be valid DcTF.
196        unsafe {
197            DcStr::from_bytes_unchecked(&self.inner)
198        }
199    }
200}
201
202impl DerefMut for DcString {
203    #[inline]
204    fn deref_mut(&mut self) -> &mut Self::Target {
205        #[expect(
206            unsafe_code,
207            reason = "DcString inner bytes are validated valid DcTF"
208        )]
209        // Safety: DcString inner bytes are guaranteed to be valid DcTF.
210        unsafe {
211            DcStr::from_bytes_unchecked_mut(&mut self.inner)
212        }
213    }
214}
215
216impl Borrow<DcStr> for DcString {
217    #[inline]
218    fn borrow(&self) -> &DcStr {
219        self
220    }
221}
222
223impl AsRef<DcStr> for DcString {
224    #[inline]
225    fn as_ref(&self) -> &DcStr {
226        self
227    }
228}
229
230impl AsRef<[u8]> for DcString {
231    #[inline]
232    fn as_ref(&self) -> &[u8] {
233        &self.inner
234    }
235}
236
237impl From<String> for DcString {
238    #[inline]
239    fn from(s: String) -> Self {
240        Self {
241            inner: s.into_bytes(),
242        }
243    }
244}
245
246impl From<&str> for DcString {
247    #[inline]
248    fn from(s: &str) -> Self {
249        Self {
250            inner: s.as_bytes().to_vec(),
251        }
252    }
253}
254
255impl From<&[u128]> for DcString {
256    fn from(list: &[u128]) -> Self {
257        let mut s = Self::with_capacity(list.len());
258        for &dc in list {
259            s.push(DcChar(dc));
260        }
261        s
262    }
263}
264
265impl From<Vec<u128>> for DcString {
266    fn from(list: Vec<u128>) -> Self {
267        Self::from(list.as_slice())
268    }
269}
270
271impl FromIterator<DcChar> for DcString {
272    fn from_iter<I: IntoIterator<Item = DcChar>>(iter: I) -> Self {
273        let mut s = Self::new();
274        for ch in iter {
275            s.push(ch);
276        }
277        s
278    }
279}
280
281impl FromIterator<char> for DcString {
282    fn from_iter<I: IntoIterator<Item = char>>(iter: I) -> Self {
283        let mut s = Self::new();
284        for ch in iter {
285            s.push(ch);
286        }
287        s
288    }
289}
290
291impl Extend<DcChar> for DcString {
292    fn extend<I: IntoIterator<Item = DcChar>>(&mut self, iter: I) {
293        for ch in iter {
294            self.push(ch);
295        }
296    }
297}
298
299impl Extend<char> for DcString {
300    fn extend<I: IntoIterator<Item = char>>(&mut self, iter: I) {
301        for ch in iter {
302            self.push(ch);
303        }
304    }
305}
306
307impl PartialEq<str> for DcString {
308    #[inline]
309    fn eq(&self, other: &str) -> bool {
310        &**self == <&DcStr>::from(other)
311    }
312}
313
314impl PartialEq<&str> for DcString {
315    #[inline]
316    fn eq(&self, other: &&str) -> bool {
317        &**self == <&DcStr>::from(*other)
318    }
319}
320
321impl PartialEq<String> for DcString {
322    #[inline]
323    fn eq(&self, other: &String) -> bool {
324        &**self == <&DcStr>::from(other.as_str())
325    }
326}
327
328impl fmt::Display for DcString {
329    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
330        fmt::Display::fmt(&**self, f)
331    }
332}
333
334impl fmt::Debug for DcString {
335    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
336        write!(f, "DcString({self})")
337    }
338}
339
340#[cfg(test)]
341#[allow(
342    clippy::panic,
343    clippy::expect_used,
344    clippy::unwrap_used,
345    clippy::unwrap_in_result,
346    clippy::panic_in_result_fn,
347    clippy::indexing_slicing,
348    clippy::arithmetic_side_effects,
349    reason = "Standard repository test boilerplate"
350)]
351mod tests {
352    use super::*;
353    use crate::validate_dcutf;
354    use ctb_formats_dcdata::dc::SHORT_DC_REGION_START;
355    use ctb_formats_dctf::encode_utf_8e_128_buf;
356
357    #[crate::ctb_test]
358    fn test_dc_char() {
359        let c_ascii = DcChar::from_char('A');
360        assert_eq!(c_ascii.as_char(), Some('A'));
361        assert!(c_ascii.is_ascii());
362        assert!(c_ascii.is_unicode());
363        assert!(c_ascii.is_unicode_scalar());
364        assert!(!c_ascii.is_short_dc());
365        assert_eq!(c_ascii.to_short_dc(), None);
366        assert_eq!(format!("{c_ascii}"), "A");
367
368        let c_at = DcChar::from_char('@');
369        assert_eq!(format!("{c_at}"), "@@");
370
371        let c_short = DcChar(SHORT_DC_REGION_START + 42);
372        assert_eq!(c_short.as_char(), None);
373        assert!(!c_short.is_ascii());
374        assert!(!c_short.is_unicode());
375        assert!(c_short.is_short_dc());
376        assert_eq!(c_short.to_short_dc(), Some(42));
377        assert_eq!(
378            format!("{c_short}"),
379            format!("@{}@", SHORT_DC_REGION_START + 42)
380        );
381
382        // Surrogate codepoint (allowed in DcUtf as a Unicode codepoint, but not a scalar char)
383        let c_surrogate = DcChar(0xDBFF);
384        assert_eq!(c_surrogate.as_char(), None);
385        assert!(c_surrogate.is_unicode());
386        assert!(!c_surrogate.is_unicode_scalar());
387    }
388
389    #[crate::ctb_test]
390    fn test_dc_string_and_dc_str() {
391        let mut s = DcString::new();
392        s.push('h');
393        s.push('i');
394        s.push_str(" ");
395        s.push(DcChar(SHORT_DC_REGION_START));
396
397        assert_eq!(s.len(), 3 + DcChar(SHORT_DC_REGION_START).len_dctf());
398        assert!(!s.is_empty());
399        assert!(s.is_char_boundary(0));
400        assert!(s.is_char_boundary(1));
401        assert!(s.is_char_boundary(2));
402        assert!(s.is_char_boundary(3));
403        assert!(!s.is_char_boundary(4)); // interior byte of 0xFF sequence
404        assert!(s.is_char_boundary(s.len()));
405
406        // Slicing
407        let sub = &s[0..2];
408        assert_eq!(sub.as_bytes(), b"hi");
409        assert_eq!(sub, "hi");
410        assert_ne!(s, "hi "); // contains SHORT_DC_REGION_START (0xFF)
411
412        // Iteration
413        let chars: Vec<DcChar> = s.chars().collect();
414        assert_eq!(
415            chars,
416            vec![
417                DcChar::from_char('h'),
418                DcChar::from_char('i'),
419                DcChar::from_char(' '),
420                DcChar(SHORT_DC_REGION_START)
421            ]
422        );
423
424        // Reverse iteration
425        let rev_chars: Vec<DcChar> = s.chars().rev().collect();
426        assert_eq!(
427            rev_chars,
428            vec![
429                DcChar(SHORT_DC_REGION_START),
430                DcChar::from_char(' '),
431                DcChar::from_char('i'),
432                DcChar::from_char('h')
433            ]
434        );
435
436        // Character indices
437        let indices: Vec<(usize, DcChar)> = s.char_indices().collect();
438        assert_eq!(
439            indices,
440            vec![
441                (0, DcChar::from_char('h')),
442                (1, DcChar::from_char('i')),
443                (2, DcChar::from_char(' ')),
444                (3, DcChar(SHORT_DC_REGION_START))
445            ]
446        );
447
448        // Mutation: pop
449        let popped = s.pop();
450        assert_eq!(popped, Some(DcChar(SHORT_DC_REGION_START)));
451        assert_eq!(s, "hi ");
452
453        // Mutation: truncate
454        s.truncate(2);
455        assert_eq!(s, "hi");
456
457        // Mutation: retain
458        s.retain(|c| c != DcChar::from_char('i'));
459        assert_eq!(s, "h");
460    }
461
462    #[crate::ctb_test]
463    fn test_validation_and_errors() {
464        validate_dctf(b"hello world").unwrap();
465        validate_dcutf(b"hello world").unwrap();
466
467        let mut buf = Vec::new();
468        buf.extend_from_slice(b"abc");
469        let mut dc_buf = [0u8; 24];
470        let n = encode_utf_8e_128_buf(&mut dc_buf, SHORT_DC_REGION_START + 100);
471        buf.extend_from_slice(&dc_buf[..n]);
472        validate_dcutf(&buf).unwrap();
473
474        let mut dctf_buf = Vec::new();
475        dctf_buf.extend_from_slice(b"abc");
476        let n_dctf = encode_dctf_buf(&mut dc_buf, SHORT_DC_REGION_START + 100);
477        dctf_buf.extend_from_slice(&dc_buf[..n_dctf]);
478        validate_dctf(&dctf_buf).unwrap();
479
480        // Invalid continuation byte as start
481        let err = validate_dctf(b"abc\x80def").unwrap_err();
482        assert_eq!(err.valid_up_to(), 3);
483        assert_eq!(err.error_len(), Some(1));
484
485        // Truncated extended sequence in DcTF and DcUtf
486        let err_dctf = validate_dctf(b"\xFF\x81\x80").unwrap_err();
487        assert_eq!(err_dctf.valid_up_to(), 0);
488        assert_eq!(err_dctf.error_len(), None);
489
490        let err = validate_dcutf(b"\xFF\x84\x84").unwrap_err();
491        assert_eq!(err.valid_up_to(), 0);
492        assert_eq!(err.error_len(), None);
493
494        // Safe conversion via from_bytes / from_dctf / from_dcutf
495        let dc_str = DcStr::from_bytes(b"hello").unwrap();
496        assert_eq!(dc_str, "hello");
497
498        let dc_string_dctf = DcString::from_dctf(dctf_buf).unwrap();
499        assert_eq!(dc_string_dctf.chars().count(), 4);
500
501        let dc_string = DcString::from_dcutf(buf).unwrap();
502        assert_eq!(dc_string.chars().count(), 4);
503        assert_eq!(dc_string, dc_string_dctf);
504    }
505}