1#[allow(
23 unused_imports,
24 clippy::wildcard_imports,
25 reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use std::fmt;
30use std::ops::{
31 Bound, Index, Range, RangeBounds, RangeFrom, RangeFull, RangeInclusive,
32 RangeTo, RangeToInclusive,
33};
34
35use ctb_formats_dctf::{
36 decode_dctf_buf, decode_utf_8e_128_buf, determine_dctf_error_len,
37 determine_utf_8e_128_error_len,
38};
39
40use crate::{DcChar, DcString, DcUtfError};
41
42#[repr(transparent)]
44#[derive(Eq, PartialEq, Ord, PartialOrd, Hash)]
45pub struct DcStr {
46 pub(crate) inner: [u8],
47}
48
49impl DcStr {
50 pub fn from_bytes(bytes: &[u8]) -> Result<&Self, DcUtfError> {
56 validate_dctf(bytes)?;
57 #[expect(
58 unsafe_code,
59 reason = "DcStr is #[repr(transparent)] around [u8], and bytes have been validated as valid DcTF"
60 )]
61 Ok(unsafe { Self::from_bytes_unchecked(bytes) })
63 }
64
65 #[must_use]
70 #[expect(
71 unsafe_code,
72 clippy::transmute_ptr_to_ptr,
73 reason = "DcStr is #[repr(transparent)] around [u8], so &[u8] and &DcStr have identical layout; pointer casts require as which is denied by clippy"
74 )]
75 pub const unsafe fn from_bytes_unchecked(bytes: &[u8]) -> &Self {
76 unsafe { std::mem::transmute::<&[u8], &Self>(bytes) }
78 }
79
80 pub fn from_bytes_mut(bytes: &mut [u8]) -> Result<&mut Self, DcUtfError> {
86 validate_dctf(bytes)?;
87 #[expect(
88 unsafe_code,
89 reason = "DcStr is #[repr(transparent)] around [u8], and bytes have been validated as valid DcTF"
90 )]
91 Ok(unsafe { Self::from_bytes_unchecked_mut(bytes) })
93 }
94
95 #[expect(
100 unsafe_code,
101 clippy::transmute_ptr_to_ptr,
102 reason = "DcStr is #[repr(transparent)] around [u8], so &mut [u8] and &mut DcStr have identical layout; pointer casts require as which is denied by clippy"
103 )]
104 pub unsafe fn from_bytes_unchecked_mut(bytes: &mut [u8]) -> &mut Self {
105 unsafe { std::mem::transmute::<&mut [u8], &mut Self>(bytes) }
107 }
108
109 #[must_use]
111 pub const fn as_bytes(&self) -> &[u8] {
112 &self.inner
113 }
114
115 #[must_use]
117 pub const fn len(&self) -> usize {
118 self.inner.len()
119 }
120
121 #[must_use]
123 pub const fn is_empty(&self) -> bool {
124 self.inner.is_empty()
125 }
126
127 #[inline]
133 #[must_use]
134 pub fn is_char_boundary(&self, index: usize) -> bool {
135 if index == 0 || index == self.inner.len() {
136 return true;
137 }
138 match self.inner.get(index) {
139 Some(&b) => (b & 0xC0) != 0x80,
140 None => false,
141 }
142 }
143
144 pub fn get<R: RangeBounds<usize>>(&self, range: R) -> Option<&Self> {
147 let len = self.len();
148 let start = match range.start_bound() {
149 Bound::Included(&n) => n,
150 Bound::Excluded(&n) => n.checked_add(1)?,
151 Bound::Unbounded => 0,
152 };
153 let end = match range.end_bound() {
154 Bound::Included(&n) => n.checked_add(1)?,
155 Bound::Excluded(&n) => n,
156 Bound::Unbounded => len,
157 };
158 if start <= end
159 && end <= len
160 && self.is_char_boundary(start)
161 && self.is_char_boundary(end)
162 {
163 let slice = self.inner.get(start..end)?;
164 #[expect(
165 unsafe_code,
166 reason = "Subslice is bounded by checked char boundaries of a valid DcStr"
167 )]
168 Some(unsafe { Self::from_bytes_unchecked(slice) })
170 } else {
171 None
172 }
173 }
174
175 #[must_use]
177 pub fn chars(&self) -> DcChars<'_> {
178 DcChars { slice: &self.inner }
179 }
180
181 #[must_use]
184 pub fn char_indices(&self) -> DcCharIndices<'_> {
185 DcCharIndices {
186 offset: 0,
187 chars: self.chars(),
188 }
189 }
190
191 #[must_use]
193 pub fn to_dclist(&self) -> Vec<u128> {
194 self.chars().map(|c| c.0).collect()
195 }
196}
197
198impl<'a> From<&'a str> for &'a DcStr {
199 #[inline]
200 fn from(s: &'a str) -> Self {
201 #[expect(
202 unsafe_code,
203 reason = "Valid standard UTF-8 is unconditionally valid DcTF"
204 )]
205 unsafe {
207 DcStr::from_bytes_unchecked(s.as_bytes())
208 }
209 }
210}
211
212impl PartialEq<str> for DcStr {
213 #[inline]
214 fn eq(&self, other: &str) -> bool {
215 self == <&Self>::from(other)
216 }
217}
218
219impl PartialEq<&str> for DcStr {
220 #[inline]
221 fn eq(&self, other: &&str) -> bool {
222 self == <&Self>::from(*other)
223 }
224}
225
226impl PartialEq<String> for DcStr {
227 #[inline]
228 fn eq(&self, other: &String) -> bool {
229 self == <&Self>::from(other.as_str())
230 }
231}
232
233impl AsRef<[u8]> for DcStr {
234 #[inline]
235 fn as_ref(&self) -> &[u8] {
236 &self.inner
237 }
238}
239
240impl AsRef<DcStr> for DcStr {
241 #[inline]
242 fn as_ref(&self) -> &Self {
243 self
244 }
245}
246
247impl ToOwned for DcStr {
248 type Owned = DcString;
249
250 fn to_owned(&self) -> Self::Owned {
251 DcString {
252 inner: self.inner.to_vec(),
253 }
254 }
255}
256
257impl Index<Range<usize>> for DcStr {
258 type Output = Self;
259
260 #[inline]
261 #[expect(
262 clippy::expect_used,
263 reason = "Range bounds are ensured by preceding assertions and len check"
264 )]
265 fn index(&self, range: Range<usize>) -> &Self::Output {
266 let (start, end) = (range.start, range.end);
267 assert!(start <= end && end <= self.len(), "index out of bounds");
268 assert!(
269 self.is_char_boundary(start),
270 "range start {start} is not a character boundary"
271 );
272 assert!(
273 self.is_char_boundary(end),
274 "range end {end} is not a character boundary"
275 );
276 let slice = self
277 .inner
278 .get(range)
279 .expect("range bounds verified preceding index");
280 #[expect(
281 unsafe_code,
282 reason = "Subslice is bounded by checked char boundaries"
283 )]
284 unsafe {
286 Self::from_bytes_unchecked(slice)
287 }
288 }
289}
290
291impl Index<RangeFrom<usize>> for DcStr {
292 type Output = Self;
293
294 #[inline]
295 fn index(&self, range: RangeFrom<usize>) -> &Self::Output {
296 &self[range.start..self.len()]
297 }
298}
299
300impl Index<RangeTo<usize>> for DcStr {
301 type Output = Self;
302
303 #[inline]
304 fn index(&self, range: RangeTo<usize>) -> &Self::Output {
305 &self[0..range.end]
306 }
307}
308
309impl Index<RangeFull> for DcStr {
310 type Output = Self;
311
312 #[inline]
313 fn index(&self, _: RangeFull) -> &Self::Output {
314 self
315 }
316}
317
318impl Index<RangeInclusive<usize>> for DcStr {
319 type Output = Self;
320
321 #[inline]
322 #[expect(
323 clippy::expect_used,
324 reason = "Valid slice range end + 1 will not overflow usize"
325 )]
326 fn index(&self, range: RangeInclusive<usize>) -> &Self::Output {
327 let start = *range.start();
328 let end = range
329 .end()
330 .checked_add(1)
331 .expect("range end + 1 overflow in index");
332 &self[start..end]
333 }
334}
335
336impl Index<RangeToInclusive<usize>> for DcStr {
337 type Output = Self;
338
339 #[inline]
340 #[expect(
341 clippy::expect_used,
342 reason = "Valid slice range end + 1 will not overflow usize"
343 )]
344 fn index(&self, range: RangeToInclusive<usize>) -> &Self::Output {
345 let end = range
346 .end
347 .checked_add(1)
348 .expect("range end + 1 overflow in index");
349 &self[0..end]
350 }
351}
352
353impl fmt::Display for DcStr {
354 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
355 for ch in self.chars() {
356 write!(f, "{ch}")?;
357 }
358 Ok(())
359 }
360}
361
362impl fmt::Debug for DcStr {
363 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
364 write!(f, "\"{self}\"")
365 }
366}
367
368#[derive(Clone, Debug)]
370pub struct DcChars<'a> {
371 pub(crate) slice: &'a [u8],
372}
373
374impl Iterator for DcChars<'_> {
375 type Item = DcChar;
376
377 fn next(&mut self) -> Option<Self::Item> {
378 if self.slice.is_empty() {
379 return None;
380 }
381 let (val, len) = decode_dctf_buf(self.slice)?;
382 self.slice = self.slice.get(len..)?;
383 Some(DcChar(val))
384 }
385}
386
387impl DoubleEndedIterator for DcChars<'_> {
388 fn next_back(&mut self) -> Option<Self::Item> {
389 if self.slice.is_empty() {
390 return None;
391 }
392 let mut lead_idx = self.slice.len().saturating_sub(1);
394 while lead_idx > 0 {
395 let b = self.slice.get(lead_idx).copied()?;
396 if (b & 0xC0) != 0x80 {
397 break;
398 }
399 lead_idx = lead_idx.saturating_sub(1);
400 }
401 let tail = self.slice.get(lead_idx..)?;
402 let (val, _len) = decode_dctf_buf(tail)?;
403 self.slice = self.slice.get(..lead_idx)?;
404 Some(DcChar(val))
405 }
406}
407
408impl std::iter::FusedIterator for DcChars<'_> {}
409
410#[derive(Clone, Debug)]
412pub struct DcCharIndices<'a> {
413 pub(crate) offset: usize,
414 pub(crate) chars: DcChars<'a>,
415}
416
417impl Iterator for DcCharIndices<'_> {
418 type Item = (usize, DcChar);
419
420 fn next(&mut self) -> Option<Self::Item> {
421 let pre_len = self.chars.slice.len();
422 let ch = self.chars.next()?;
423 let post_len = self.chars.slice.len();
424 let idx = self.offset;
425 let consumed = pre_len.saturating_sub(post_len);
426 self.offset = self.offset.saturating_add(consumed);
427 Some((idx, ch))
428 }
429}
430
431impl std::iter::FusedIterator for DcCharIndices<'_> {}
432
433pub fn validate_dctf(bytes: &[u8]) -> Result<(), DcUtfError> {
438 let mut i = 0usize;
439 while i < bytes.len() {
440 let Some(slice) = bytes.get(i..) else { break };
441 if let Some((_val, size)) = decode_dctf_buf(slice) {
442 i = i.saturating_add(size);
443 } else {
444 let error_len = determine_dctf_error_len(slice);
445 return Err(DcUtfError {
446 valid_up_to: i,
447 error_len,
448 });
449 }
450 }
451 Ok(())
452}
453
454pub fn validate_dcutf(bytes: &[u8]) -> Result<(), DcUtfError> {
459 let mut i = 0usize;
460 while i < bytes.len() {
461 let Some(slice) = bytes.get(i..) else { break };
462 if let Some((_val, size)) = decode_utf_8e_128_buf(slice) {
463 i = i.saturating_add(size);
464 } else {
465 let error_len = determine_utf_8e_128_error_len(slice);
466 return Err(DcUtfError {
467 valid_up_to: i,
468 error_len,
469 });
470 }
471 }
472 Ok(())
473}
474
475#[cfg(test)]
476#[allow(
477 clippy::panic,
478 clippy::expect_used,
479 clippy::unwrap_used,
480 clippy::unwrap_in_result,
481 clippy::panic_in_result_fn,
482 clippy::indexing_slicing,
483 clippy::arithmetic_side_effects,
484 reason = "Standard repository test boilerplate"
485)]
486mod tests {
487 use super::*;
488 use crate::DcString;
489 use crate::converters::dctext::dclist_to_dcutf;
490
491 #[crate::ctb_test]
492 fn test_dctf_tier_iteration_chunk_splits_and_dcutf_conversion() {
493 let mut values = vec![
494 0x00u128,
495 0x7F,
496 0x80,
497 0x7FF,
498 0x800,
499 0xD7FF,
500 0xD800,
501 0xDFFF,
502 0xE000,
503 0xFFFF,
504 0x1_0000,
505 0x10_FFFF,
506 0x11_0000,
507 0x1F_FFFF,
508 0x20_0000,
509 0x22_0000,
510 0x3FF_FFFF,
511 0x400_0000,
512 0x7FFF_FFFF,
513 0x8000_0000,
514 0xF_FFFF_FFFF,
515 ];
516 for k in 0..=15usize {
517 let min_val = if k == 0 {
518 1u128 << 36
519 } else {
520 1u128 << (32 + 6 * k)
521 };
522 let max_bits = 38 + 6 * k;
523 let max_val = if max_bits == 128 {
524 u128::MAX
525 } else {
526 (1u128 << max_bits) - 1
527 };
528 values.push(min_val);
529 values.push(max_val);
530 }
531
532 let mut s = DcString::new();
533 for &v in &values {
534 s.push(DcChar(v));
535 }
536
537 let forward: Vec<u128> = s.chars().map(|c| c.0).collect();
539 assert_eq!(forward, values);
540 let mut reverse: Vec<u128> = s.chars().rev().map(|c| c.0).collect();
541 reverse.reverse();
542 assert_eq!(reverse, values);
543
544 let bytes = s.as_bytes();
546 for split in 0..=bytes.len() {
547 let prefix = &bytes[..split];
548 if s.is_char_boundary(split) {
549 validate_dctf(prefix).unwrap();
550 } else {
551 let err = validate_dctf(prefix).unwrap_err();
552 assert_eq!(
554 err.error_len(),
555 None,
556 "Expected incomplete prefix (None) at byte split {split}"
557 );
558 }
559 }
560
561 let dcutf_bytes = dclist_to_dcutf(&s.to_dclist());
563 let roundtripped = DcString::from_dcutf(dcutf_bytes).unwrap();
564 assert_eq!(roundtripped, s);
565
566 let overlap = [0xFFu8, 0x87, 0x81, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80];
569 let from_dcutf = DcString::from_dcutf(overlap.to_vec()).unwrap();
570 assert_eq!(
571 from_dcutf.chars().collect::<Vec<_>>(),
572 vec![DcChar(1u128 << 36)]
573 );
574 let from_dctf = DcStr::from_bytes(&overlap).unwrap();
575 assert_eq!(
576 from_dctf.chars().collect::<Vec<_>>(),
577 vec![DcChar(13_262_859_010_048u128)]
578 );
579 }
580}