~starkingdoms/starkingdoms

ref: 339f063faf61671754325b60bcad3ab02492e742 starkingdoms/kabel_test/src/string.rs -rw-r--r-- 1.5 KiB
339f063f — ghostly_zsh print, add, sub run with manually typed bytecode 1 year, 4 months ago
                                                                                
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
use std::{alloc::{self, Layout}, ops::Add};

#[derive(Debug, Clone, Copy)]
pub struct ObjString {
    pub ptr: *mut char,
    pub length: usize,
}

impl From<String> for ObjString {
    fn from(value: String) -> Self {
        unsafe {
            let layout = Layout::array::<char>(value.len()).unwrap();
            let ptr = alloc::alloc(layout) as *mut char;
            Self {
                ptr,
                length: value.len(),
            }
        }
    }
}
impl From<ObjString> for String {
    fn from(value: ObjString) -> Self {
        unsafe {
            String::from_raw_parts(value.ptr as *mut u8, value.length, value.length)
        }
    }
}
impl ToString for ObjString {
    fn to_string(&self) -> String {
        String::from(*self)
    }
}

impl Add for ObjString {
    type Output = Self;
    fn add(self, other: Self) -> Self {
        let layout = Layout::array::<char>(self.length + other.length).unwrap();
        unsafe {
            let ptr = alloc::alloc(layout) as *mut char;
            self.ptr.copy_to(ptr, self.length);
            other.ptr.copy_to(ptr.offset(self.length as isize), other.length);
            self.free();
            other.free();
            Self {
                ptr,
                length: self.length + other.length,
            }
        }
    }
}

impl ObjString {
    pub fn free(self) {
        if self.length != 0 {
            let layout = Layout::array::<char>(self.length).unwrap();
            unsafe {
                alloc::dealloc(self.ptr as *mut u8, layout)
            }
        }
    }
}