cao_lang/vm/runtime/
cao_lang_string.rs1use std::{alloc::Layout, fmt::Debug, ptr::NonNull};
2
3use crate::alloc::AllocProxy;
4
5pub struct CaoLangString {
7 pub(crate) len: usize,
8 pub(crate) ptr: NonNull<u8>,
9 pub(crate) alloc: AllocProxy,
10}
11
12impl Debug for CaoLangString {
13 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
14 let str = self.as_str();
15 write!(f, "String: {str:?}")
16 }
17}
18
19impl Drop for CaoLangString {
20 fn drop(&mut self) {
21 unsafe { self.alloc.dealloc(self.ptr, Self::layout(self.len)) }
22 }
23}
24
25impl CaoLangString {
26 pub fn as_str(&self) -> &str {
27 unsafe {
28 let ptr = self.ptr;
29 let len = self.len;
30 std::str::from_utf8_unchecked(std::slice::from_raw_parts(ptr.as_ptr(), len))
31 }
32 }
33
34 pub fn len(&self) -> usize {
35 self.len
36 }
37
38 pub fn is_empty(&self) -> bool {
39 self.len() == 0
40 }
41
42 pub(crate) fn layout(len: usize) -> Layout {
44 std::alloc::Layout::array::<char>(len).unwrap()
45 }
46}