1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
use core::{fmt, slice, str, convert, mem, cmp, hash};
use core::clone::Clone;
use core::ops::{self, Index};
use core::borrow::Borrow;
use alloc::{string::String, vec::Vec};
use alloc::boxed::Box;
use crate::FromUtf8Error;

const IS_INLINE: u8 = 1 << 7;
const LEN_MASK: u8 = !IS_INLINE;

#[cfg(target_pointer_width="64")]
const INLINE_CAPACITY: usize = 15;
#[cfg(target_pointer_width="32")]
const INLINE_CAPACITY: usize = 7;

#[cfg(target_pointer_width="64")]
const MAX_CAPACITY: usize = (1 << 63) - 1;
#[cfg(target_pointer_width="32")]
const MAX_CAPACITY: usize = (1 << 31) - 1;

// use the MSG of heap.len to encode the variant
// which is also MSB of inline.len
#[cfg(target_endian = "little")]
#[derive(Copy, Clone)]
#[repr(C)]
pub struct Inline {
    pub data:   [u8; INLINE_CAPACITY],
    pub len:    u8
}
#[cfg(target_endian = "little")]
#[derive(Copy, Clone)]
#[repr(C)]
pub struct Heap {
    pub ptr:    *mut u8,
    pub len:    usize
}

#[cfg(target_endian = "big")]
#[derive(Copy, Clone)]
#[repr(C)]
pub struct Inline {
    pub len:    u8,
    pub data:   [u8; INLINE_CAPACITY],
}

#[cfg(target_endian = "big")]
#[derive(Copy, Clone)]
#[repr(C)]
pub struct Heap {
    pub len:    usize,
    pub ptr:    *mut u8,
}

union SmallBytesUnion {
    inline: Inline,
    heap:   Heap
}
pub struct SmallBytes {
    union: SmallBytesUnion,
}
unsafe impl Send for SmallBytes {}
unsafe impl Sync for SmallBytes {}

#[derive(Clone)]
#[cfg_attr(feature="size", derive(datasize::DataSize))]
pub struct SmallString {
    bytes: SmallBytes,
}

#[cfg(feature="rkyv")]
mod rkyv_impl {
    use rkyv::{
        string::{ArchivedString, StringResolver},
        Archive, Deserialize, DeserializeUnsized, Fallible, Serialize, SerializeUnsized,
    };
    use super::SmallString;

    impl Archive for SmallString {
        type Archived = rkyv::string::ArchivedString;
        type Resolver = rkyv::string::StringResolver;

        #[inline]
        unsafe fn resolve(&self, pos: usize, resolver: Self::Resolver, out: *mut Self::Archived) {
            rkyv::string::ArchivedString::resolve_from_str(self.as_str(), pos, resolver, out);
        }
    }

    #[cfg(feature="rkyv")]
    impl<S: Fallible + ?Sized> Serialize<S> for SmallString
    where
        str: SerializeUnsized<S>,
    {
        #[inline]
        fn serialize(&self, serializer: &mut S) -> Result<Self::Resolver, S::Error> {
            ArchivedString::serialize_from_str(self.as_str(), serializer)
        }
    }
    impl<D: Fallible + ?Sized> Deserialize<SmallString, D> for ArchivedString
    where
        str: DeserializeUnsized<str, D>,
    {
        #[inline]
        fn deserialize(&self, _: &mut D) -> Result<SmallString, D::Error> {
            Ok(self.as_str().into())
        }
    }
    impl PartialEq<SmallString> for ArchivedString {
        #[inline]
        fn eq(&self, other: &SmallString) -> bool {
            PartialEq::eq(self.as_str(), other.as_str())
        }
    }
    
    impl PartialEq<ArchivedString> for SmallString {
        #[inline]
        fn eq(&self, other: &ArchivedString) -> bool {
            PartialEq::eq(other.as_str(), self.as_str())
        }
    }
}

#[test]
fn test_layout() {
    let s = SmallBytesUnion { inline: Inline { data: [0; INLINE_CAPACITY], len: IS_INLINE } };
    let heap = unsafe { s.heap };
    assert_eq!(heap.len, MAX_CAPACITY + 1);
}

#[inline(always)]
fn box_slice(s: &[u8]) -> Box<[u8]> {
    Box::from(s)
}
#[inline(always)]
fn box_slice_into_raw_parts(mut s: Box<[u8]>) -> (*mut u8, usize) {
    let len = s.len();
    let ptr = s.as_mut_ptr();
    mem::forget(s);
    (ptr, len)
}
#[inline(always)]
unsafe fn box_slice_from_raw_parts(ptr: *mut u8, len: usize) -> Box<[u8]> {
    let ptr = slice::from_raw_parts_mut(ptr, len) as *mut [u8];
    Box::from_raw(ptr)
}

impl SmallBytes {
    #[inline(always)]
    pub fn new() -> SmallBytes {
        unsafe {
            SmallBytes::from_inline(
                Inline { data: [0; INLINE_CAPACITY], len: 0 },
            )
        }
    }
}
impl<'a> From<&'a [u8]> for SmallBytes {
    #[inline]
    fn from(s: &[u8]) -> SmallBytes {
        let len = s.len();
        unsafe {
            if len > INLINE_CAPACITY {
                let s = box_slice(s);
                let (ptr, len) = box_slice_into_raw_parts(s);
                SmallBytes::from_heap(
                    Heap {
                        ptr,
                        len
                    },
                )
            } else {
                let mut data = [0; INLINE_CAPACITY];
                data[.. len].copy_from_slice(s);
                SmallBytes::from_inline(
                    Inline { data, len: len as u8 },
                )
            }
        }
    }
}

impl SmallString {
    #[inline(always)]
    pub fn new() -> SmallString {
        SmallString {
            bytes: SmallBytes::new()
        }
    }
    pub fn from_utf8(bytes: SmallBytes) -> Result<SmallString, FromUtf8Error<SmallBytes>> {
        match str::from_utf8(bytes.as_slice()) {
            Ok(_) => Ok(SmallString { bytes }),
            Err(error) => Err(FromUtf8Error {
                bytes,
                error
            })
        }
    }
}
impl Drop for SmallBytes {
    #[inline]
    fn drop(&mut self) {
        if !self.is_inline() {
            unsafe {
                box_slice_from_raw_parts(self.union.heap.ptr, self.union.heap.len);
            }
        }
    }
}
impl<'a> convert::From<&'a str> for SmallString {
    #[inline]
    fn from(s: &'a str) -> SmallString {
        SmallString {
            bytes: SmallBytes::from(s.as_bytes())
        }
    }
}
impl convert::From<Vec<u8>> for SmallBytes {
    #[inline]
    fn from(s: Vec<u8>) -> SmallBytes {
        let len = s.len();
        if len <= INLINE_CAPACITY {
            return SmallBytes::from(s.as_slice());
        }

        unsafe {
            let s = s.into_boxed_slice();
            let (ptr, len) = box_slice_into_raw_parts(s);
            let heap = Heap {
                ptr,
                len,
            };

            SmallBytes::from_heap(
                heap,
            )
        }
    }
}
impl convert::From<String> for SmallString {
    #[inline]
    fn from(s: String) -> SmallString {
        SmallString {
            bytes: SmallBytes::from(s.into_bytes())
        }
    }
}
impl Into<Vec<u8>> for SmallBytes {
    #[inline]
    fn into(self) -> Vec<u8> {
        let len = self.len();
        if self.is_inline() {
            self.as_slice().into()
        } else {
            unsafe {
                let s = box_slice_from_raw_parts(self.union.heap.ptr, len);
                // the SmallString must not drop
                mem::forget(self);

                Vec::from(s)
            }
        }
    }
}
impl Into<String> for SmallString {
    #[inline]
    fn into(self) -> String {
        unsafe {
            String::from_utf8_unchecked(self.bytes.into())
        }
    }
}
impl Clone for SmallBytes {
    #[inline]
    fn clone(&self) -> SmallBytes {
        unsafe {
            if self.is_inline() {
                // simple case
                SmallBytes {
                    union: SmallBytesUnion { inline: self.union.inline },
                }
            } else {
                let len = self.len();
                let bytes = slice::from_raw_parts(self.union.heap.ptr, len);
                let (ptr, len) = box_slice_into_raw_parts(box_slice(bytes));
                SmallBytes::from_heap(
                    Heap {
                        ptr,
                        len
                    },
                )
            }
        }
    }
}
impl FromIterator<char> for SmallString {
    fn from_iter<T: IntoIterator<Item=char>>(iter: T) -> Self {
        let mut buf = [0; INLINE_CAPACITY];
        let mut pos = 0;
        let mut iter = iter.into_iter();
        while let Some(c) = iter.next() {
            if pos + c.len_utf8() > INLINE_CAPACITY {
                let mut s = String::with_capacity(32);
                s.push_str(unsafe { str::from_utf8_unchecked(&buf[..pos]) });
                s.push(c);
                s.extend(iter);
                return s.into();
            }
            pos += c.encode_utf8(&mut buf[pos..]).len();
        }
        let bytes = unsafe { SmallBytes::from_inline(
            Inline { data: buf, len: pos as u8 },
        ) };
        SmallString { bytes }
    }
}
impl From<char> for SmallString {
    fn from(c: char) -> SmallString {
        let mut buf = [0; INLINE_CAPACITY];
        let len = c.encode_utf8(&mut buf).len();
        let bytes = unsafe { SmallBytes::from_inline(
            Inline { data: buf, len: len as u8 },
        ) };
        SmallString { bytes }
    }
}


#[cfg(feature="size")]
impl datasize::DataSize for SmallBytes {
    const IS_DYNAMIC: bool = true;
    const STATIC_HEAP_SIZE: usize = core::mem::size_of::<Self>();

    fn estimate_heap_size(&self) -> usize {
        if self.is_inline() {
            Self::STATIC_HEAP_SIZE
        } else {
            Self::STATIC_HEAP_SIZE + self.len()
        }
    }
}

define_common_string!(SmallString, SmallStringUnion);
define_common_bytes!(SmallBytes, SmallBytesUnion);