tvm_ffi/
string.rs

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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
use crate::derive::Object;
use crate::object::{unsafe_, Object, ObjectArc, ObjectCoreWithExtraItems};
use crate::type_traits::AnyCompatible;
use std::cmp::Ordering;
use std::fmt::{Debug, Display};
use std::hash::{Hash, Hasher};
use std::ops::Deref;
use tvm_ffi_sys::TVMFFITypeIndex as TypeIndex;
use tvm_ffi_sys::{TVMFFIAny, TVMFFIAnyDataUnion, TVMFFIByteArray, TVMFFIObject};

//-----------------------------------------------------
// Bytes
//-----------------------------------------------------
/// ABI stable Bytes container for ffi
#[repr(C)]
pub struct Bytes {
    data: TVMFFIAny,
}

// BytesObj for heap-allocated bytes
#[repr(C)]
#[derive(Object)]
#[type_key = "ffi.Bytes"]
#[type_index(TypeIndex::kTVMFFIBytes)]
pub(crate) struct BytesObj {
    object: Object,
    data: TVMFFIByteArray,
}

impl Bytes {
    /// Create a new empty Bytes container
    pub fn new() -> Self {
        Self {
            data: TVMFFIAny {
                type_index: TypeIndex::kTVMFFISmallBytes as i32,
                small_str_len: 0,
                data_union: TVMFFIAnyDataUnion { v_int64: 0 },
            },
        }
    }

    /// Get the length of the bytes
    pub fn len(&self) -> usize {
        self.as_slice().len()
    }

    /// Get the bytes as a slice
    pub fn as_slice(&self) -> &[u8] {
        unsafe {
            if self.data.type_index == TypeIndex::kTVMFFISmallBytes as i32 {
                std::slice::from_raw_parts(
                    self.data.data_union.v_bytes.as_ptr(),
                    self.data.small_str_len as usize,
                )
            } else {
                let str_obj: &BytesObj = &*(self.data.data_union.v_obj as *const BytesObj);
                std::slice::from_raw_parts(str_obj.data.data, str_obj.data.size)
            }
        }
    }
}

impl Default for Bytes {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

unsafe impl ObjectCoreWithExtraItems for BytesObj {
    type ExtraItem = u8;
    // extra item is the trailing \0 for ffi compatibility
    #[inline]
    /// Get the count of extra items (trailing null byte for FFI compatibility)
    fn extra_items_count(this: &Self) -> usize {
        return this.data.size + 1;
    }
}

impl<T> From<T> for Bytes
where
    T: AsRef<[u8]>,
{
    #[inline]
    /// Create Bytes from any type that can be converted to a byte slice
    fn from(src: T) -> Self {
        let value: &[u8] = src.as_ref();
        // to be compatible with normal c++
        const MAX_SMALL_BYTES_LEN: usize = 7;
        unsafe {
            if value.len() <= MAX_SMALL_BYTES_LEN {
                let mut data_union = TVMFFIAnyDataUnion { v_int64: 0 };
                data_union.v_bytes[..value.len()].copy_from_slice(value);
                // small bytes
                Self {
                    data: TVMFFIAny {
                        type_index: TypeIndex::kTVMFFISmallBytes as i32,
                        small_str_len: value.len() as u32,
                        data_union: data_union,
                    },
                }
            } else {
                // large bytes
                let mut obj_arc = ObjectArc::new_with_extra_items(BytesObj {
                    object: Object::new(),
                    data: TVMFFIByteArray {
                        data: std::ptr::null(),
                        size: value.len(),
                    },
                });
                // reset the data ptr correctly after Arc is created
                // The fresh allocation is unique and has not been exposed.
                let object = &mut *ObjectArc::as_raw_mut(&mut obj_arc);
                object.data.data = BytesObj::extra_items(object).as_ptr();
                let extra_items = BytesObj::extra_items_mut(object);
                extra_items[..value.len()].copy_from_slice(value);
                // write the trailing \0 for ffi compatibility
                extra_items[value.len()] = 0;
                Self {
                    data: TVMFFIAny {
                        type_index: TypeIndex::kTVMFFIBytes as i32,
                        small_str_len: 0,
                        data_union: TVMFFIAnyDataUnion {
                            v_obj: ObjectArc::into_raw(obj_arc) as *mut BytesObj
                                as *mut TVMFFIObject,
                        },
                    },
                }
            }
        }
    }
}

impl Deref for Bytes {
    type Target = [u8];
    #[inline]
    fn deref(&self) -> &[u8] {
        self.as_slice()
    }
}

impl Clone for Bytes {
    #[inline]
    fn clone(&self) -> Self {
        if self.data.type_index >= TypeIndex::kTVMFFIStaticObjectBegin as i32 {
            unsafe { unsafe_::inc_ref(self.data.data_union.v_obj) }
        }
        Self { data: self.data }
    }
}

impl Drop for Bytes {
    #[inline]
    fn drop(&mut self) {
        if self.data.type_index >= TypeIndex::kTVMFFIStaticObjectBegin as i32 {
            unsafe { unsafe_::dec_ref(self.data.data_union.v_obj) }
        }
    }
}

impl PartialEq for Bytes {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.as_slice() == other.as_slice()
    }
}

impl Eq for Bytes {}

impl PartialOrd for Bytes {
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        self.as_slice().partial_cmp(other.as_slice())
    }
}

impl Ord for Bytes {
    #[inline]
    fn cmp(&self, other: &Self) -> Ordering {
        self.as_slice().cmp(other.as_slice())
    }
}

impl Hash for Bytes {
    #[inline]
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.as_slice().hash(state);
    }
}

impl Display for Bytes {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        Debug::fmt(&self.as_slice(), f)
    }
}

impl Debug for Bytes {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ffi.Bytes")
            .field("data", &self.as_slice())
            .finish()
    }
}

//-----------------------------------------------------
// String
//-----------------------------------------------------

/// ABI stable String container for ffi
#[repr(C)]
pub struct String {
    data: TVMFFIAny,
}

// StringObj for heap-allocated string
#[repr(C)]
#[derive(Object)]
#[type_key = "ffi.String"]
#[type_index(TypeIndex::kTVMFFIStr)]
pub(crate) struct StringObj {
    object: Object,
    data: TVMFFIByteArray,
}

unsafe impl ObjectCoreWithExtraItems for StringObj {
    type ExtraItem = u8;
    #[inline]
    /// Get the count of extra items (trailing null byte for FFI compatibility)
    fn extra_items_count(this: &Self) -> usize {
        // extra item is the trailing \0 for ffi compatibility
        return this.data.size + 1;
    }
}

impl String {
    /// Create a new empty String container
    pub fn new() -> Self {
        Self {
            data: TVMFFIAny {
                type_index: TypeIndex::kTVMFFISmallStr as i32,
                small_str_len: 0,
                data_union: TVMFFIAnyDataUnion { v_int64: 0 },
            },
        }
    }

    /// Get the length of the string in bytes
    pub fn len(&self) -> usize {
        self.as_bytes().len()
    }

    /// Get the string as a byte slice
    pub fn as_bytes(&self) -> &[u8] {
        unsafe {
            if self.data.type_index == TypeIndex::kTVMFFISmallStr as i32 {
                std::slice::from_raw_parts(
                    self.data.data_union.v_bytes.as_ptr(),
                    self.data.small_str_len as usize,
                )
            } else {
                let str_obj: &StringObj = &*(self.data.data_union.v_obj as *const StringObj);
                std::slice::from_raw_parts(str_obj.data.data, str_obj.data.size)
            }
        }
    }

    /// Get the string as a str slice
    pub fn as_str(&self) -> &str {
        unsafe { std::str::from_utf8_unchecked(self.as_bytes()) }
    }
}

impl<T> From<T> for String
where
    T: AsRef<str>,
{
    #[inline]
    /// Create String from any type that can be converted to a string slice
    fn from(src: T) -> Self {
        unsafe {
            let value: &str = src.as_ref();
            let bytes = value.as_bytes();
            const MAX_SMALL_BYTES_LEN: usize = 7;
            if bytes.len() <= MAX_SMALL_BYTES_LEN {
                let mut data_union = TVMFFIAnyDataUnion { v_int64: 0 };
                data_union.v_bytes[..bytes.len()].copy_from_slice(bytes);
                Self {
                    data: TVMFFIAny {
                        type_index: TypeIndex::kTVMFFISmallStr as i32,
                        small_str_len: bytes.len() as u32,
                        data_union: data_union,
                    },
                }
            } else {
                let mut obj_arc = ObjectArc::new_with_extra_items(StringObj {
                    object: Object::new(),
                    data: TVMFFIByteArray {
                        data: std::ptr::null(),
                        size: bytes.len(),
                    },
                });
                // The fresh allocation is unique and has not been exposed.
                let object = &mut *ObjectArc::as_raw_mut(&mut obj_arc);
                object.data.data = StringObj::extra_items(object).as_ptr();
                let extra_items = StringObj::extra_items_mut(object);
                extra_items[..bytes.len()].copy_from_slice(bytes);
                // write the trailing \0 for ffi compatibility
                extra_items[bytes.len()] = 0;
                Self {
                    data: TVMFFIAny {
                        type_index: TypeIndex::kTVMFFIStr as i32,
                        small_str_len: 0,
                        data_union: TVMFFIAnyDataUnion {
                            v_obj: ObjectArc::into_raw(obj_arc) as *mut StringObj
                                as *mut TVMFFIObject,
                        },
                    },
                }
            }
        }
    }
}

impl Default for String {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

impl Deref for String {
    type Target = str;
    #[inline]
    fn deref(&self) -> &str {
        self.as_str()
    }
}

impl Clone for String {
    #[inline]
    fn clone(&self) -> Self {
        if self.data.type_index >= TypeIndex::kTVMFFIStaticObjectBegin as i32 {
            unsafe { unsafe_::inc_ref(self.data.data_union.v_obj) }
        }
        Self { data: self.data }
    }
}

impl Drop for String {
    #[inline]
    fn drop(&mut self) {
        if self.data.type_index >= TypeIndex::kTVMFFIStaticObjectBegin as i32 {
            unsafe { unsafe_::dec_ref(self.data.data_union.v_obj) }
        }
    }
}

impl PartialEq for String {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.as_bytes() == other.as_bytes()
    }
}

// Allows `my_string == "hello"`
impl<T> PartialEq<T> for String
where
    T: AsRef<str>,
{
    #[inline]
    fn eq(&self, other: &T) -> bool {
        self.as_str() == other.as_ref()
    }
}

impl Eq for String {}

impl<T> PartialEq<T> for Bytes
where
    T: AsRef<[u8]>,
{
    #[inline]
    fn eq(&self, other: &T) -> bool {
        self.as_slice() == other.as_ref()
    }
}

impl PartialOrd for String {
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        self.as_str().partial_cmp(other.as_str())
    }
}

impl Ord for String {
    #[inline]
    fn cmp(&self, other: &Self) -> Ordering {
        self.as_str().cmp(other.as_str())
    }
}

impl Hash for String {
    #[inline]
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.as_str().hash(state);
    }
}

impl Display for String {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        Debug::fmt(&self.as_str(), f)
    }
}

impl Debug for String {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ffi.String")
            .field("data", &self.as_str())
            .finish()
    }
}

//-----------------------------------------------------
// AnyCompatible implementation for Bytes and String
//-----------------------------------------------------
unsafe impl AnyCompatible for Bytes {
    fn type_str() -> std::string::String {
        "ffi.Bytes".to_string()
    }

    // Bytes are small bytes or a bytes object, never None.
    #[inline]
    unsafe fn is_undefined(field: *const Self) -> bool {
        (*std::ptr::addr_of!((*field).data.type_index)) == TypeIndex::kTVMFFINone as i32
    }

    unsafe fn copy_to_any_view(this: &Self, data: &mut TVMFFIAny) {
        *data = this.data;
    }

    unsafe fn move_to_any(src: Self, data: &mut TVMFFIAny) {
        *data = src.data;
        std::mem::forget(src);
    }

    unsafe fn check_any_strict(data: &TVMFFIAny) -> bool {
        return data.type_index == TypeIndex::kTVMFFISmallBytes as i32
            || data.type_index == TypeIndex::kTVMFFIBytes as i32;
    }

    unsafe fn copy_from_any_view_after_check(data: &TVMFFIAny) -> Self {
        if data.type_index >= TypeIndex::kTVMFFIStaticObjectBegin as i32 {
            unsafe { unsafe_::inc_ref(data.data_union.v_obj) }
        }
        Self { data: *data }
    }

    unsafe fn move_from_any_after_check(data: &mut TVMFFIAny) -> Self {
        Self { data: *data }
    }

    unsafe fn try_cast_from_any_view(data: &TVMFFIAny) -> Result<Self, ()> {
        if data.type_index == TypeIndex::kTVMFFIByteArrayPtr as i32 {
            // deep copy from bytearray ptr
            let bytes = &*(data.data_union.v_ptr as *const TVMFFIByteArray);
            Ok(Self::from(std::slice::from_raw_parts(
                bytes.data, bytes.size,
            )))
        } else if data.type_index == TypeIndex::kTVMFFISmallBytes as i32 {
            Ok(Self { data: *data })
        } else if data.type_index == TypeIndex::kTVMFFIBytes as i32 {
            unsafe { unsafe_::inc_ref(data.data_union.v_obj) }
            Ok(Self { data: *data })
        } else {
            Err(())
        }
    }
}

unsafe impl AnyCompatible for String {
    fn type_str() -> std::string::String {
        "ffi.String".to_string()
    }

    // A string is a small string or a string object, never None.
    #[inline]
    unsafe fn is_undefined(field: *const Self) -> bool {
        (*std::ptr::addr_of!((*field).data.type_index)) == TypeIndex::kTVMFFINone as i32
    }

    unsafe fn copy_to_any_view(this: &Self, data: &mut TVMFFIAny) {
        *data = this.data;
    }

    unsafe fn move_to_any(src: Self, data: &mut TVMFFIAny) {
        *data = src.data;
        std::mem::forget(src);
    }

    unsafe fn check_any_strict(data: &TVMFFIAny) -> bool {
        return data.type_index == TypeIndex::kTVMFFISmallStr as i32
            || data.type_index == TypeIndex::kTVMFFIStr as i32;
    }

    unsafe fn copy_from_any_view_after_check(data: &TVMFFIAny) -> Self {
        if data.type_index >= TypeIndex::kTVMFFIStaticObjectBegin as i32 {
            unsafe { unsafe_::inc_ref(data.data_union.v_obj) }
        }
        Self { data: *data }
    }

    unsafe fn move_from_any_after_check(data: &mut TVMFFIAny) -> Self {
        Self { data: *data }
    }

    unsafe fn try_cast_from_any_view(data: &TVMFFIAny) -> Result<Self, ()> {
        if data.type_index == TypeIndex::kTVMFFIRawStr as i32 {
            // 1. Create a CStr wrapper from the raw pointer.
            let c_str =
                std::ffi::CStr::from_ptr(data.data_union.v_c_str as *const std::os::raw::c_char);
            Ok(Self::from(c_str.to_str().expect("Invalid UTF-8")))
        } else if data.type_index == TypeIndex::kTVMFFISmallStr as i32 {
            Ok(Self { data: *data })
        } else if data.type_index == TypeIndex::kTVMFFIStr as i32 {
            unsafe { unsafe_::inc_ref(data.data_union.v_obj) }
            Ok(Self { data: *data })
        } else {
            Err(())
        }
    }
}