1#![deny(warnings)]
8#![deny(missing_docs)]
9#![allow(clippy::enum_clike_unportable_variant)]
12
13use std::{
14 borrow::{Borrow, Cow},
15 fmt, hash,
16 mem::ManuallyDrop,
17 ops::Deref,
18 ptr::NonNull,
19 slice::from_raw_parts,
20 str::from_utf8_unchecked,
21 sync::Arc,
22};
23
24use serde::{Deserialize, Serialize};
25
26mod clone;
27
28pub use self::clone::CheapMetaString;
29
30pub mod interning;
31use self::interning::{InternedString, InternedStringState, Interner};
32
33const ZERO_VALUE: usize = 0;
34const TOP_MOST_BIT: usize = usize::MAX & !(isize::MAX as usize);
35const INLINED_STR_DATA_BUF_LEN: usize = std::mem::size_of::<usize>() * 3;
36const TOP_BYTE_INDEX: usize = if cfg!(target_endian = "little") {
39 std::mem::size_of::<usize>() - 1
40} else {
41 0
42};
43const INLINED_STR_TAG_INDEX: usize = std::mem::size_of::<usize>() * 2 + TOP_BYTE_INDEX;
44const INLINED_STR_MAX_LEN: usize = INLINED_STR_TAG_INDEX;
45const INLINED_STR_MAX_LEN_U8: u8 = INLINED_STR_MAX_LEN as u8;
46
47const UNION_TYPE_TAG_VALUE_STATIC: u8 = get_offset_tag_value(0);
48const UNION_TYPE_TAG_VALUE_INTERNED_FIXED_SIZE: u8 = get_offset_tag_value(1);
49const UNION_TYPE_TAG_VALUE_INTERNED_GENERIC_MAP: u8 = get_offset_tag_value(2);
50const UNION_TYPE_TAG_VALUE_SHARED: u8 = get_offset_tag_value(3);
51
52const fn get_offset_tag_value(tag: u8) -> u8 {
53 const UNION_TYPE_TAG_VALUE_BASE: u8 = INLINED_STR_MAX_LEN as u8 + 1;
54
55 if tag > (u8::MAX - INLINED_STR_MAX_LEN as u8) {
56 panic!("Union type tag value must fit in the discriminant byte.");
57 }
58
59 tag + UNION_TYPE_TAG_VALUE_BASE
60}
61
62const fn get_scaled_union_tag(tag: u8) -> usize {
63 const UNION_TYPE_TAG_VALUE_SHIFT: u32 = (std::mem::size_of::<usize>() as u32 - 1) * 8;
65
66 (tag as usize) << UNION_TYPE_TAG_VALUE_SHIFT
67}
68
69#[cfg(not(target_pointer_width = "64"))]
71const _INVARIANTS_CHECK: () = {
72 compile_error!("`stringtheory` is only supported on 64-bit platforms.");
73};
74
75const fn is_tagged(cap: u8) -> bool {
76 cap & 0b10000000 != 0
77}
78
79const fn tag_cap(cap: usize) -> usize {
80 cap | TOP_MOST_BIT
81}
82
83const fn untag_cap(cap: usize) -> usize {
84 cap & !(TOP_MOST_BIT)
85}
86
87#[derive(Clone, Copy, Eq, PartialEq)]
88#[repr(usize)]
89enum Zero {
90 Zero = ZERO_VALUE,
91}
92
93#[derive(Clone, Copy, Debug, Eq, PartialEq)]
94#[repr(usize)]
95enum Tag {
96 Static = get_scaled_union_tag(UNION_TYPE_TAG_VALUE_STATIC),
97 InternedFixedSize = get_scaled_union_tag(UNION_TYPE_TAG_VALUE_INTERNED_FIXED_SIZE),
98 InternedGenericMap = get_scaled_union_tag(UNION_TYPE_TAG_VALUE_INTERNED_GENERIC_MAP),
99 Shared = get_scaled_union_tag(UNION_TYPE_TAG_VALUE_SHARED),
100}
101
102#[repr(C)]
103#[derive(Clone, Copy)]
104struct EmptyUnion {
105 ptr: Zero, len: Zero, cap: Zero, }
109
110impl EmptyUnion {
111 const fn new() -> Self {
112 Self {
113 ptr: Zero::Zero,
114 len: Zero::Zero,
115 cap: Zero::Zero,
116 }
117 }
118}
119
120#[repr(C)]
121#[derive(Clone, Copy)]
122struct OwnedUnion {
123 ptr: *mut u8, len: usize, cap: usize, }
127
128impl OwnedUnion {
129 #[inline]
130 fn as_str(&self) -> &str {
131 unsafe { from_utf8_unchecked(from_raw_parts(self.ptr, self.len)) }
134 }
135
136 fn into_owned(self) -> String {
137 unsafe { String::from_raw_parts(self.ptr, self.len, untag_cap(self.cap)) }
140 }
141}
142
143#[repr(C)]
144#[derive(Clone, Copy)]
145struct StaticUnion {
146 value: &'static str, _cap: Tag, }
149
150impl StaticUnion {
151 #[inline]
152 const fn as_str(&self) -> &str {
153 self.value
154 }
155}
156
157#[repr(C)]
158struct InternedUnion {
159 state: InternedStateUnion, _cap: Tag, }
162
163impl Drop for InternedUnion {
164 fn drop(&mut self) {
165 match self._cap {
166 Tag::InternedFixedSize => {
167 let state = unsafe { ManuallyDrop::take(&mut self.state.fixed_size) };
168 drop(state);
169 }
170 Tag::InternedGenericMap => {
171 let state = unsafe { ManuallyDrop::take(&mut self.state.generic_map) };
172 drop(state);
173 }
174 _ => unreachable!(),
175 }
176 }
177}
178
179impl Clone for InternedUnion {
180 fn clone(&self) -> Self {
181 let state = unsafe {
184 match self._cap {
185 Tag::InternedFixedSize => InternedStateUnion {
186 fixed_size: self.state.fixed_size.clone(),
187 },
188 Tag::InternedGenericMap => InternedStateUnion {
189 generic_map: self.state.generic_map.clone(),
190 },
191 _ => unreachable!(),
192 }
193 };
194
195 Self { state, _cap: self._cap }
196 }
197}
198
199#[repr(C)]
200union InternedStateUnion {
201 fixed_size: ManuallyDrop<self::interning::fixed_size::StringState>,
202 generic_map: ManuallyDrop<self::interning::map::StringState>,
203}
204
205#[repr(C)]
206struct SharedUnion {
207 ptr: NonNull<str>, _cap: Tag, }
210
211impl SharedUnion {
212 #[inline]
213 const fn as_str(&self) -> &str {
214 unsafe { self.ptr.as_ref() }
216 }
217}
218
219#[repr(C)]
220#[derive(Clone, Copy)]
221struct InlinedUnion {
222 data: [u8; INLINED_STR_DATA_BUF_LEN], }
225
226impl InlinedUnion {
227 #[inline]
228 fn as_str(&self) -> &str {
229 let len = self.data[INLINED_STR_MAX_LEN] as usize;
230
231 unsafe { from_utf8_unchecked(&self.data[0..len]) }
234 }
235}
236
237#[repr(C)]
238#[derive(Clone, Copy)]
239struct DiscriminantUnion {
240 data: [u8; INLINED_STR_DATA_BUF_LEN],
242}
243
244#[derive(Debug, Eq, PartialEq)]
245enum UnionType {
246 Empty,
247 Owned,
248 Static,
249 InternedFixedSize,
250 InternedGenericMap,
251 Inlined,
252 Shared,
253}
254
255impl UnionType {
256 #[inline]
257 const fn is_owned(&self) -> bool {
258 matches!(self, UnionType::Owned)
259 }
260}
261
262impl DiscriminantUnion {
263 #[inline]
264 const fn get_union_type(&self) -> UnionType {
265 let tag_byte = self.data[INLINED_STR_TAG_INDEX];
330
331 if is_tagged(tag_byte) {
332 return UnionType::Owned;
333 }
334
335 match tag_byte {
338 0 => UnionType::Empty,
340
341 1..=INLINED_STR_MAX_LEN_U8 => UnionType::Inlined,
343
344 UNION_TYPE_TAG_VALUE_STATIC => UnionType::Static,
347 UNION_TYPE_TAG_VALUE_INTERNED_FIXED_SIZE => UnionType::InternedFixedSize,
348 UNION_TYPE_TAG_VALUE_INTERNED_GENERIC_MAP => UnionType::InternedGenericMap,
349 UNION_TYPE_TAG_VALUE_SHARED => UnionType::Shared,
350
351 _ => UnionType::Empty,
354 }
355 }
356}
357
358union Inner {
380 empty: EmptyUnion,
381 owned: OwnedUnion,
382 static_: StaticUnion,
383 interned: ManuallyDrop<InternedUnion>,
384 shared: ManuallyDrop<SharedUnion>,
385 inlined: InlinedUnion,
386 discriminant: DiscriminantUnion,
387}
388
389impl Inner {
390 const fn empty() -> Self {
391 Self {
392 empty: EmptyUnion::new(),
393 }
394 }
395
396 fn owned(value: String) -> Self {
397 match value.capacity() {
398 0 => Self::empty(),
400 cap => {
401 let mut value = value.into_bytes();
402
403 let ptr = value.as_mut_ptr();
404 let len = value.len();
405
406 std::mem::forget(value);
408
409 Self {
410 owned: OwnedUnion {
411 ptr,
412 len,
413 cap: tag_cap(cap),
414 },
415 }
416 }
417 }
418 }
419
420 const fn static_str(value: &'static str) -> Self {
421 match value.len() {
422 0 => Self::empty(),
423 _ => Self {
424 static_: StaticUnion {
425 value,
426 _cap: Tag::Static,
427 },
428 },
429 }
430 }
431
432 fn interned(value: InternedString) -> Self {
433 match value.len() {
434 0 => Self::empty(),
435 _len => {
436 let (state, tag) = match value.into_state() {
437 InternedStringState::FixedSize(fixed_size) => (
438 InternedStateUnion {
439 fixed_size: ManuallyDrop::new(fixed_size),
440 },
441 Tag::InternedFixedSize,
442 ),
443 InternedStringState::GenericMap(generic_map) => (
444 InternedStateUnion {
445 generic_map: ManuallyDrop::new(generic_map),
446 },
447 Tag::InternedGenericMap,
448 ),
449 };
450
451 Self {
452 interned: ManuallyDrop::new(InternedUnion { state, _cap: tag }),
453 }
454 }
455 }
456 }
457
458 fn shared(value: Arc<str>) -> Self {
459 match value.len() {
460 0 => Self::empty(),
461 _len => Self {
462 shared: ManuallyDrop::new(SharedUnion {
463 ptr: unsafe { NonNull::new_unchecked(Arc::into_raw(value).cast_mut()) },
465 _cap: Tag::Shared,
466 }),
467 },
468 }
469 }
470
471 fn try_inlined(value: &str) -> Option<Self> {
472 match value.len() {
473 0 => Some(Self::empty()),
474 len => {
475 if len > INLINED_STR_MAX_LEN {
476 return None;
477 }
478
479 let mut data = [0; INLINED_STR_DATA_BUF_LEN];
480
481 data[INLINED_STR_MAX_LEN] = len as u8;
483
484 let buf = value.as_bytes();
485 data[0..len].copy_from_slice(buf);
486
487 Some(Self {
488 inlined: InlinedUnion { data },
489 })
490 }
491 }
492 }
493
494 #[inline]
495 fn as_str(&self) -> &str {
496 let union_type = unsafe { self.discriminant.get_union_type() };
497 match union_type {
498 UnionType::Empty => "",
499 UnionType::Owned => {
500 let owned = unsafe { &self.owned };
501 owned.as_str()
502 }
503 UnionType::Static => {
504 let static_ = unsafe { &self.static_ };
505 static_.as_str()
506 }
507 UnionType::InternedFixedSize => {
508 let interned = unsafe { &self.interned.state.fixed_size };
509 interned.as_str()
510 }
511 UnionType::InternedGenericMap => {
512 let interned = unsafe { &self.interned.state.generic_map };
513 interned.as_str()
514 }
515 UnionType::Shared => {
516 let shared = unsafe { &self.shared };
517 shared.as_str()
518 }
519 UnionType::Inlined => {
520 let inlined = unsafe { &self.inlined };
521 inlined.as_str()
522 }
523 }
524 }
525
526 #[inline]
527 const fn get_union_type(&self) -> UnionType {
528 unsafe { self.discriminant.get_union_type() }
529 }
530
531 fn into_owned(mut self) -> String {
532 let union_type = unsafe { self.discriminant.get_union_type() };
533 match union_type {
534 UnionType::Empty => String::new(),
535 UnionType::Owned => {
536 let owned = unsafe { self.owned };
539 self.empty = EmptyUnion::new();
540
541 owned.into_owned()
542 }
543 UnionType::Static => {
544 let static_ = unsafe { self.static_ };
545 static_.as_str().to_owned()
546 }
547 UnionType::InternedFixedSize => {
548 let interned = unsafe { &self.interned.state.fixed_size };
549 interned.as_str().to_owned()
550 }
551 UnionType::InternedGenericMap => {
552 let interned = unsafe { &self.interned.state.generic_map };
553 interned.as_str().to_owned()
554 }
555 UnionType::Shared => {
556 let shared = unsafe { &self.shared };
557 shared.as_str().to_owned()
558 }
559 UnionType::Inlined => {
560 let inlined = unsafe { self.inlined };
561 inlined.as_str().to_owned()
562 }
563 }
564 }
565}
566
567impl Drop for Inner {
568 fn drop(&mut self) {
569 let union_type = unsafe { self.discriminant.get_union_type() };
570 match union_type {
571 UnionType::Owned => {
572 let owned = unsafe { &mut self.owned };
573
574 let ptr = owned.ptr;
575 let len = owned.len;
576 let cap = untag_cap(owned.cap);
577
578 let data = unsafe { Vec::<u8>::from_raw_parts(ptr, len, cap) };
582 drop(data);
583 }
584 UnionType::InternedFixedSize | UnionType::InternedGenericMap => {
585 let interned = unsafe { &mut self.interned };
586
587 let data = unsafe { ManuallyDrop::take(interned) };
590 drop(data);
591 }
592 UnionType::Shared => {
593 let shared = unsafe { &mut self.shared };
594
595 unsafe {
601 Arc::decrement_strong_count(shared.ptr.as_ptr().cast_const());
602 }
603 }
604 _ => {}
605 }
606 }
607}
608
609impl Clone for Inner {
610 fn clone(&self) -> Self {
611 let union_type = unsafe { self.discriminant.get_union_type() };
612 match union_type {
613 UnionType::Empty => Self::empty(),
614 UnionType::Owned => {
615 let owned = unsafe { self.owned };
616 let s = owned.as_str();
617
618 Self::try_inlined(s).unwrap_or_else(|| Self::owned(s.to_owned()))
624 }
625 UnionType::Static => Self {
626 static_: unsafe { self.static_ },
627 },
628 UnionType::InternedFixedSize | UnionType::InternedGenericMap => Self {
629 interned: unsafe { self.interned.clone() },
630 },
631 UnionType::Shared => {
632 let shared = unsafe { &self.shared };
633
634 unsafe {
639 Arc::increment_strong_count(shared.ptr.as_ptr().cast_const());
640 }
641
642 Self {
643 shared: ManuallyDrop::new(SharedUnion {
644 ptr: shared.ptr,
645 _cap: Tag::Shared,
646 }),
647 }
648 }
649 UnionType::Inlined => Self {
650 inlined: unsafe { self.inlined },
651 },
652 }
653 }
654}
655
656unsafe impl Send for Inner {}
658
659unsafe impl Sync for Inner {}
662
663#[derive(Clone)]
727pub struct MetaString {
728 inner: Inner,
729}
730
731impl MetaString {
732 pub const fn empty() -> Self {
736 Self { inner: Inner::empty() }
737 }
738
739 pub const fn from_static(s: &'static str) -> Self {
743 Self {
744 inner: Inner::static_str(s),
745 }
746 }
747
748 pub fn try_inline(s: &str) -> Option<Self> {
750 Inner::try_inlined(s).map(|inner| Self { inner })
751 }
752
753 pub fn from_interner<I>(s: &str, interner: &I) -> Self
758 where
759 I: Interner,
760 {
761 if let Some(inlined) = Self::try_inline(s) {
762 return inlined;
763 }
764 if let Some(interned) = interner.try_intern(s) {
765 return Self::from(interned);
766 }
767 Self::from(s.to_owned())
768 }
769
770 pub fn is_empty(&self) -> bool {
772 self.deref().is_empty()
773 }
774
775 pub const fn is_cheaply_cloneable(&self) -> bool {
777 !self.inner.get_union_type().is_owned()
779 }
780
781 pub fn into_owned(self) -> String {
786 self.inner.into_owned()
787 }
788}
789
790#[cfg(feature = "trace-model")]
791impl libdd_trace_model::TraceText for MetaString {
792 fn from_static(s: &'static str) -> Self {
793 MetaString::from_static(s)
794 }
795}
796
797impl Default for MetaString {
798 fn default() -> Self {
799 Self::empty()
800 }
801}
802
803impl hash::Hash for MetaString {
804 fn hash<H: hash::Hasher>(&self, state: &mut H) {
805 self.deref().hash(state)
806 }
807}
808
809impl PartialEq<str> for MetaString {
810 fn eq(&self, other: &str) -> bool {
811 self.deref() == other
812 }
813}
814
815impl PartialEq<&str> for MetaString {
816 fn eq(&self, other: &&str) -> bool {
817 self.deref() == *other
818 }
819}
820
821impl PartialEq<MetaString> for MetaString {
822 fn eq(&self, other: &MetaString) -> bool {
823 self.deref() == other.deref()
824 }
825}
826
827impl Eq for MetaString {}
828
829impl PartialOrd for MetaString {
830 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
831 Some(self.cmp(other))
832 }
833}
834
835impl Ord for MetaString {
836 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
837 self.deref().cmp(other.deref())
838 }
839}
840
841impl Borrow<str> for MetaString {
842 fn borrow(&self) -> &str {
843 self.deref()
844 }
845}
846
847impl Serialize for MetaString {
848 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
849 where
850 S: serde::Serializer,
851 {
852 serializer.serialize_str(self.deref())
853 }
854}
855
856impl<'de> Deserialize<'de> for MetaString {
857 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
858 where
859 D: serde::Deserializer<'de>,
860 {
861 struct MetaStringVisitor;
862
863 impl<'de> serde::de::Visitor<'de> for MetaStringVisitor {
864 type Value = MetaString;
865
866 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
867 formatter.write_str("a string")
868 }
869
870 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
871 where
872 E: serde::de::Error,
873 {
874 Ok(MetaString::from(v))
875 }
876 }
877
878 deserializer.deserialize_str(MetaStringVisitor)
879 }
880}
881
882impl From<String> for MetaString {
883 fn from(s: String) -> Self {
884 Self { inner: Inner::owned(s) }
885 }
886}
887
888impl From<&str> for MetaString {
889 fn from(s: &str) -> Self {
890 Self::try_inline(s).unwrap_or_else(|| Self::from(s.to_owned()))
891 }
892}
893
894impl From<Cow<'_, str>> for MetaString {
895 fn from(s: Cow<'_, str>) -> Self {
898 match s {
899 Cow::Borrowed(s) => Self::from(s),
900 Cow::Owned(s) => Self::from(s),
901 }
902 }
903}
904
905impl From<InternedString> for MetaString {
906 fn from(s: InternedString) -> Self {
907 Self {
908 inner: Inner::interned(s),
909 }
910 }
911}
912
913impl From<Arc<str>> for MetaString {
914 fn from(s: Arc<str>) -> Self {
915 Self {
916 inner: Inner::shared(s),
917 }
918 }
919}
920
921impl From<MetaString> for protobuf::Chars {
922 fn from(value: MetaString) -> Self {
923 value.into_owned().into()
924 }
925}
926
927impl<'a> From<&'a MetaString> for protobuf::Chars {
928 fn from(value: &'a MetaString) -> Self {
929 value.deref().into()
935 }
936}
937
938impl Deref for MetaString {
939 type Target = str;
940
941 fn deref(&self) -> &str {
942 self.inner.as_str()
943 }
944}
945
946impl AsRef<str> for MetaString {
947 fn as_ref(&self) -> &str {
948 self.deref()
949 }
950}
951
952impl fmt::Debug for MetaString {
953 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
954 self.deref().fmt(f)
955 }
956}
957
958impl fmt::Display for MetaString {
959 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
960 self.deref().fmt(f)
961 }
962}
963
964#[cfg(test)]
965mod tests {
966 use std::{borrow::Cow, num::NonZeroUsize, sync::Arc};
967
968 use proptest::{prelude::*, proptest};
969
970 use super::{
971 interning::GenericMapInterner, CheapMetaString, InlinedUnion, Inner, MetaString, UnionType,
972 INLINED_STR_MAX_LEN, INLINED_STR_TAG_INDEX, UNION_TYPE_TAG_VALUE_INTERNED_FIXED_SIZE,
973 UNION_TYPE_TAG_VALUE_INTERNED_GENERIC_MAP, UNION_TYPE_TAG_VALUE_SHARED, UNION_TYPE_TAG_VALUE_STATIC,
974 };
975 use crate::interning::{FixedSizeInterner, Interner as _};
976
977 fn discriminant_byte(inner: &Inner) -> u8 {
978 unsafe { inner.discriminant.data[INLINED_STR_TAG_INDEX] }
979 }
980
981 #[test]
982 fn struct_sizes() {
983 assert_eq!(std::mem::size_of::<MetaString>(), std::mem::size_of::<usize>() * 3);
985 assert_eq!(std::mem::size_of::<Inner>(), std::mem::size_of::<usize>() * 3);
986
987 assert_eq!(std::mem::size_of::<InlinedUnion>(), std::mem::size_of::<Inner>());
990 }
991
992 #[test]
993 fn inline_capacity_matches_target_endianness() {
994 let expected_inline_capacity = if cfg!(target_endian = "little") { 23 } else { 16 };
995
996 assert_eq!(INLINED_STR_MAX_LEN, expected_inline_capacity);
997 }
998
999 #[test]
1000 fn discriminant_byte_tracks_endian_specific_variant_tags() {
1001 let owned = MetaString::from(String::from("owned-value"));
1002 assert_eq!(owned.inner.get_union_type(), UnionType::Owned);
1003 assert!(discriminant_byte(&owned.inner) & 0b1000_0000 != 0);
1004
1005 let static_value = MetaString::from_static("static-value");
1006 assert_eq!(static_value.inner.get_union_type(), UnionType::Static);
1007 assert_eq!(discriminant_byte(&static_value.inner), UNION_TYPE_TAG_VALUE_STATIC);
1008
1009 let shared = MetaString::from(Arc::<str>::from("shared-value"));
1010 assert_eq!(shared.inner.get_union_type(), UnionType::Shared);
1011 assert_eq!(discriminant_byte(&shared.inner), UNION_TYPE_TAG_VALUE_SHARED);
1012
1013 let fixed_size_interner = FixedSizeInterner::<1>::new(NonZeroUsize::new(1024).unwrap());
1014 let fixed_size = MetaString::from(fixed_size_interner.try_intern("fixed-size-value").unwrap());
1015 assert_eq!(fixed_size.inner.get_union_type(), UnionType::InternedFixedSize);
1016 assert_eq!(
1017 discriminant_byte(&fixed_size.inner),
1018 UNION_TYPE_TAG_VALUE_INTERNED_FIXED_SIZE
1019 );
1020
1021 let generic_map_interner = GenericMapInterner::new(NonZeroUsize::new(1024).unwrap());
1022 let generic_map = MetaString::from(generic_map_interner.try_intern("generic-map-value").unwrap());
1023 assert_eq!(generic_map.inner.get_union_type(), UnionType::InternedGenericMap);
1024 assert_eq!(
1025 discriminant_byte(&generic_map.inner),
1026 UNION_TYPE_TAG_VALUE_INTERNED_GENERIC_MAP
1027 );
1028 }
1029
1030 #[test]
1031 fn inlined_string_uses_every_byte_before_tag_byte() {
1032 let input = "a".repeat(INLINED_STR_MAX_LEN);
1033 let meta = MetaString::try_inline(&input).expect("input should fit exactly in inline storage");
1034
1035 assert_eq!(meta.inner.get_union_type(), UnionType::Inlined);
1036 assert_eq!(discriminant_byte(&meta.inner), INLINED_STR_MAX_LEN as u8);
1037 let inlined = unsafe { meta.inner.inlined };
1038 assert_eq!(&inlined.data[..INLINED_STR_MAX_LEN], input.as_bytes());
1039 }
1040
1041 #[test]
1042 fn inlined_string_rejects_one_byte_past_tag_byte() {
1043 let input = "a".repeat(INLINED_STR_MAX_LEN + 1);
1044
1045 assert!(MetaString::try_inline(&input).is_none());
1046 }
1047
1048 #[test]
1049 fn static_str_inlineable() {
1050 let s = "hello";
1053 let meta = MetaString::from_static(s);
1054
1055 assert_eq!(meta.inner.get_union_type(), UnionType::Static);
1056 assert_eq!(s, &*meta);
1057 assert_eq!(s, meta.into_owned());
1058 }
1059
1060 #[test]
1061 fn static_str_not_inlineable() {
1062 let s = "hello there, world! it's me, margaret!";
1063 let meta = MetaString::from_static(s);
1064
1065 assert_eq!(s, &*meta);
1066 assert_eq!(meta.inner.get_union_type(), UnionType::Static);
1067 assert_eq!(s, meta.into_owned());
1068 }
1069
1070 #[test]
1071 fn owned_string() {
1072 let s_orig = "hello";
1073 let s = String::from(s_orig);
1074 let meta = MetaString::from(s);
1075
1076 assert_eq!(s_orig, &*meta);
1077 assert_eq!(meta.inner.get_union_type(), UnionType::Owned);
1078 assert_eq!(s_orig, meta.into_owned());
1079 }
1080
1081 #[test]
1082 fn inlined_string() {
1083 let s = "hello";
1084 let meta = MetaString::from(s);
1085
1086 assert_eq!(s, &*meta);
1087 assert_eq!(meta.inner.get_union_type(), UnionType::Inlined);
1088 assert_eq!(s, meta.into_owned());
1089 }
1090
1091 #[test]
1092 fn cow_string() {
1093 let meta = MetaString::from(Cow::Borrowed("hello"));
1094 assert_eq!(&*meta, "hello");
1095 assert_eq!(meta.inner.get_union_type(), UnionType::Inlined);
1096
1097 let long = "a borrowed string too long to inline";
1098 assert!(long.len() > INLINED_STR_MAX_LEN);
1099 let meta = MetaString::from(Cow::Borrowed(long));
1100 assert_eq!(&*meta, long);
1101 assert_eq!(meta.inner.get_union_type(), UnionType::Owned);
1102
1103 let owned = String::from("hello");
1105 let ptr = owned.as_ptr();
1106 let meta = MetaString::from(Cow::<str>::Owned(owned));
1107 assert_eq!(&*meta, "hello");
1108 assert_eq!(meta.inner.get_union_type(), UnionType::Owned);
1109 assert_eq!(meta.as_ptr(), ptr);
1110 }
1111
1112 #[test]
1113 fn interned_string() {
1114 let intern_str = "hello interned str!";
1115
1116 let fs_interner = FixedSizeInterner::<1>::new(NonZeroUsize::new(1024).unwrap());
1117 let s = fs_interner.try_intern(intern_str).unwrap();
1118 assert_eq!(intern_str, &*s);
1119
1120 let meta = MetaString::from(s);
1121 assert_eq!(intern_str, &*meta);
1122 assert_eq!(meta.inner.get_union_type(), UnionType::InternedFixedSize);
1123 assert_eq!(intern_str, meta.into_owned());
1124
1125 let gm_interner = GenericMapInterner::new(NonZeroUsize::new(1024).unwrap());
1126 let s = gm_interner.try_intern(intern_str).unwrap();
1127 assert_eq!(intern_str, &*s);
1128
1129 let meta = MetaString::from(s);
1130 assert_eq!(intern_str, &*meta);
1131 assert_eq!(meta.inner.get_union_type(), UnionType::InternedGenericMap);
1132 assert_eq!(intern_str, meta.into_owned());
1133 }
1134
1135 #[test]
1136 fn shared_string() {
1137 let shared_str = "hello shared str!";
1138
1139 let s = Arc::<str>::from(shared_str);
1140 assert_eq!(shared_str, &*s);
1141
1142 let meta = MetaString::from(s);
1143 assert_eq!(shared_str, &*meta);
1144 assert_eq!(meta.inner.get_union_type(), UnionType::Shared);
1145 assert_eq!(shared_str, meta.into_owned());
1146 }
1147
1148 #[test]
1149 fn meta_string_sorts_by_string_value() {
1150 let mut values = [
1151 MetaString::from("gamma"),
1152 MetaString::from("alpha"),
1153 MetaString::from("beta"),
1154 ];
1155 values.sort();
1156
1157 assert_eq!(
1158 values.iter().map(|value| &**value).collect::<Vec<_>>(),
1159 ["alpha", "beta", "gamma"]
1160 );
1161 }
1162
1163 #[test]
1164 fn protobuf_chars_conversions_preserve_value() {
1165 let chars: protobuf::Chars = MetaString::from("protobuf-value").into();
1166 let chars_ref: &str = chars.as_ref();
1167 assert_eq!(chars_ref, "protobuf-value");
1168
1169 let meta = MetaString::from("protobuf-ref-value");
1170 let chars: protobuf::Chars = (&meta).into();
1171 let chars_ref: &str = chars.as_ref();
1172 assert_eq!(chars_ref, "protobuf-ref-value");
1173 }
1174
1175 #[test]
1176 fn cheap_meta_string_trait_reports_cheap_clone_availability() {
1177 let shared = MetaString::from(Arc::<str>::from("shared-value"));
1178 assert_eq!(shared.try_cheap_clone().as_deref(), Some("shared-value"));
1179
1180 let owned = MetaString::from(String::from("owned-value"));
1181 assert!(owned.try_cheap_clone().is_none());
1182 }
1183
1184 #[test]
1185 fn shared_string_clone() {
1186 let shared_str = "hello shared str!";
1187 let s = Arc::<str>::from(shared_str);
1188 let meta = MetaString::from(s);
1189
1190 let meta2 = meta.clone();
1192 assert_eq!(shared_str, &*meta2);
1193
1194 drop(meta);
1197 assert_eq!(shared_str, &*meta2);
1198 }
1199
1200 #[test]
1201 fn empty_string_shared() {
1202 let shared_str = "";
1203
1204 let s = Arc::<str>::from(shared_str);
1205 assert_eq!(shared_str, &*s);
1206
1207 let meta = MetaString::from(s);
1208 assert_eq!(shared_str, &*meta);
1209 assert_eq!(meta.inner.get_union_type(), UnionType::Empty);
1210 assert_eq!(shared_str, meta.into_owned());
1211 }
1212
1213 #[test]
1214 fn empty_string_interned() {
1215 let intern_str = "";
1216
1217 let interner = GenericMapInterner::new(NonZeroUsize::new(1024).unwrap());
1218 let s = interner.try_intern(intern_str).unwrap();
1219 assert_eq!(intern_str, &*s);
1220
1221 let meta = MetaString::from(s);
1222 assert_eq!(intern_str, &*meta);
1223 assert_eq!(meta.inner.get_union_type(), UnionType::Empty);
1224 assert_eq!(intern_str, meta.into_owned());
1225 }
1226
1227 #[test]
1228 fn empty_string_static() {
1229 let s = "";
1230
1231 let meta = MetaString::from_static(s);
1232 assert_eq!(s, &*meta);
1233 assert_eq!(meta.inner.get_union_type(), UnionType::Empty);
1234 assert_eq!(s, meta.into_owned());
1235 }
1236
1237 #[test]
1238 fn empty_string_inlined() {
1239 let s = "";
1240
1241 let meta = MetaString::try_inline(s).expect("empty string definitely 'fits'");
1242 assert_eq!(s, &*meta);
1243 assert_eq!(meta.inner.get_union_type(), UnionType::Empty);
1244 assert_eq!(s, meta.into_owned());
1245 }
1246
1247 #[test]
1248 fn empty_string_owned() {
1249 let s = String::with_capacity(32);
1252 let actual_cap = s.capacity();
1253
1254 let meta = MetaString::from(s);
1255 assert_eq!("", &*meta);
1256 assert_eq!(meta.inner.get_union_type(), UnionType::Owned);
1257
1258 let owned = meta.into_owned();
1259 assert_eq!(owned.capacity(), actual_cap);
1260 assert_eq!("", owned);
1261 }
1262
1263 #[test]
1264 fn empty_string_owned_zero_capacity() {
1265 let s = String::new();
1267
1268 let meta = MetaString::from(s);
1269 assert_eq!("", &*meta);
1270 assert_eq!(meta.inner.get_union_type(), UnionType::Empty);
1271 assert_eq!("", meta.into_owned());
1272 }
1273
1274 #[test]
1275 fn is_cheaply_cloneable() {
1276 let s =
1278 String::from("big ol' stringy string that can't be inlined and lives out its bleak existence in the heap");
1279 let ms = MetaString::from(s);
1280 assert!(!ms.is_cheaply_cloneable());
1281
1282 let ms = MetaString::empty();
1284 assert!(ms.is_cheaply_cloneable());
1285
1286 let s = "hello";
1288 let ms = MetaString::try_inline(s).expect("inlined string should fit");
1289 assert!(ms.is_cheaply_cloneable());
1290
1291 let s = "hello there, world! it's me, margaret!";
1293 let ms = MetaString::from_static(s);
1294 assert!(ms.is_cheaply_cloneable());
1295
1296 let interner = GenericMapInterner::new(NonZeroUsize::new(1024).unwrap());
1298 let s = interner.try_intern("hello interned str!").unwrap();
1299 let ms = MetaString::from(s);
1300 assert!(ms.is_cheaply_cloneable());
1301
1302 let s = Arc::from("hello shared str!");
1304 let ms = MetaString::from(s);
1305 assert!(ms.is_cheaply_cloneable());
1306 }
1307
1308 const LONG: &str = "this string is definitely longer than twenty-three bytes";
1311
1312 fn hash_of(ms: &MetaString) -> u64 {
1313 use std::hash::{Hash as _, Hasher as _};
1314
1315 let mut hasher = std::collections::hash_map::DefaultHasher::new();
1316 ms.hash(&mut hasher);
1317 hasher.finish()
1318 }
1319
1320 #[test]
1321 fn serde_round_trips_every_variant() {
1322 let interner = GenericMapInterner::new(NonZeroUsize::new(1024).unwrap());
1326 let cases: Vec<(MetaString, &str)> = vec![
1327 (MetaString::empty(), ""),
1328 (MetaString::try_inline("hi").expect("fits inline"), "hi"),
1329 (MetaString::from_static(LONG), LONG),
1330 (MetaString::from(String::from(LONG)), LONG),
1331 (MetaString::from(interner.try_intern(LONG).expect("interns")), LONG),
1332 (MetaString::from(Arc::<str>::from(LONG)), LONG),
1333 ];
1334
1335 for (ms, expected) in cases {
1336 let json = serde_json::to_string(&ms).expect("serialization should succeed");
1337
1338 let as_plain: String = serde_json::from_str(&json).expect("serialized form should be a JSON string");
1340 assert_eq!(as_plain, expected, "serialized form should carry the string content");
1341
1342 let back: MetaString = serde_json::from_str(&json).expect("deserialization should succeed");
1343 assert_eq!(back, expected, "deserialized value should match the original content");
1344 assert_eq!(ms, back, "round-trip should preserve equality");
1345 }
1346 }
1347
1348 #[test]
1349 fn equal_content_hashes_equally_across_variants() {
1350 let interner = GenericMapInterner::new(NonZeroUsize::new(1024).unwrap());
1353 let variants = [
1354 MetaString::from_static(LONG),
1355 MetaString::from(String::from(LONG)),
1356 MetaString::from(interner.try_intern(LONG).expect("interns")),
1357 MetaString::from(Arc::<str>::from(LONG)),
1358 ];
1359
1360 assert_eq!(variants[0].inner.get_union_type(), UnionType::Static);
1362 assert_eq!(variants[1].inner.get_union_type(), UnionType::Owned);
1363 assert_eq!(variants[2].inner.get_union_type(), UnionType::InternedGenericMap);
1364 assert_eq!(variants[3].inner.get_union_type(), UnionType::Shared);
1365
1366 let expected_hash = hash_of(&variants[0]);
1367 for variant in &variants {
1368 assert_eq!(
1369 hash_of(variant),
1370 expected_hash,
1371 "hash must depend only on content, not the backing variant"
1372 );
1373 assert_eq!(
1374 *variant, variants[0],
1375 "equal content must compare equal across variants"
1376 );
1377 }
1378
1379 let inlined = MetaString::from("short");
1381 let static_ = MetaString::from_static("short");
1382 assert_eq!(inlined.inner.get_union_type(), UnionType::Inlined);
1383 assert_eq!(static_.inner.get_union_type(), UnionType::Static);
1384 assert_eq!(hash_of(&inlined), hash_of(&static_));
1385 }
1386
1387 #[test]
1388 fn from_interner_inlines_short_strings() {
1389 let interner = GenericMapInterner::new(NonZeroUsize::new(1024).unwrap());
1391 let ms = MetaString::from_interner("short", &interner);
1392
1393 assert_eq!(ms.inner.get_union_type(), UnionType::Inlined);
1394 assert_eq!(ms, "short");
1395 assert_eq!(interner.len(), 0, "inlining must not add an interner entry");
1396 }
1397
1398 #[test]
1399 fn from_interner_interns_non_inlineable_strings() {
1400 let interner = GenericMapInterner::new(NonZeroUsize::new(1024).unwrap());
1402 assert!(LONG.len() > INLINED_STR_MAX_LEN);
1403
1404 let ms = MetaString::from_interner(LONG, &interner);
1405
1406 assert_eq!(ms.inner.get_union_type(), UnionType::InternedGenericMap);
1407 assert_eq!(ms, LONG);
1408 assert_eq!(interner.len(), 1, "the string should have been interned");
1409 }
1410
1411 #[test]
1412 fn from_interner_falls_back_to_owned_when_interner_is_full() {
1413 let interner = GenericMapInterner::new(NonZeroUsize::new(16).unwrap());
1416 assert!(LONG.len() > INLINED_STR_MAX_LEN);
1417
1418 let ms = MetaString::from_interner(LONG, &interner);
1419
1420 assert_eq!(ms.inner.get_union_type(), UnionType::Owned);
1421 assert_eq!(ms, LONG);
1422 assert_eq!(
1423 interner.len(),
1424 0,
1425 "the interner had no room, so nothing should be interned"
1426 );
1427 }
1428
1429 fn arb_unicode_str_max_len(max_len: usize) -> impl Strategy<Value = String> {
1430 ".{0,23}".prop_filter("resulting string is too long", move |s| s.len() <= max_len)
1431 }
1432
1433 proptest! {
1434 #![proptest_config(ProptestConfig::with_cases(10000))]
1435
1436 #[test]
1437 #[cfg_attr(miri, ignore)]
1438 fn property_test_inlined_string(
1439 input in arb_unicode_str_max_len(INLINED_STR_MAX_LEN),
1440 ) {
1441 assert!(input.len() <= INLINED_STR_MAX_LEN, "input should fit in the inline buffer");
1442 let meta = MetaString::try_inline(&input).expect("input should fit");
1443
1444 if input.is_empty() {
1445 assert_eq!(meta.inner.get_union_type(), UnionType::Empty);
1446 } else {
1447 assert_eq!(input, &*meta);
1448 assert_eq!(meta.inner.get_union_type(), UnionType::Inlined);
1449 }
1450 }
1451
1452 #[test]
1453 #[cfg_attr(miri, ignore)]
1454 fn property_test_owned_string(
1455 input in ".*",
1456 ) {
1457 let is_empty = input.is_empty();
1458 let meta = MetaString::from(input);
1459
1460 if is_empty {
1461 assert_eq!(meta.inner.get_union_type(), UnionType::Empty);
1462 } else {
1463 assert_eq!(meta.inner.get_union_type(), UnionType::Owned);
1464 }
1465 }
1466 }
1467}