use core::mem::size_of;
use std::io;
use crate::BStackRaiiAllocator;
use bstack::{BStack, BStackRange};
use bytemuck::{Pod, Zeroable};
use super::util::{alloc_image, read_fields};
use crate::io_core::{ClonePlan, TryCloneIn, dealloc_range};
use crate::primitives::EightCC;
use crate::types::compiled::{BStackOwned, BlockHeader, HEADER_SIZE};
use crate::types::traits::{BStackBlock, BStackCast};
use crate::util::{io_error, read_u64};
#[repr(C)]
#[derive(Clone, Copy, Pod, Zeroable)]
pub struct StringOnDisk {
pub header: BlockHeader,
pub data: u64,
pub len: u64,
}
const DATA_OFF: u64 = HEADER_SIZE; const LEN_OFF: u64 = HEADER_SIZE + 8; const STRING_SIZE: u64 = size_of::<StringOnDisk>() as u64;
pub struct BStackString {
range: BStackRange,
}
impl BStackString {
fn alloc_bytes<A: BStackRaiiAllocator>(allocator: &A, bytes: &[u8]) -> io::Result<u64> {
if bytes.is_empty() {
return Ok(0);
}
let mut slice = allocator.alloc(bytes.len() as u64)?;
if let Err(e) = slice.write_range(0, bytes) {
let _ = allocator.dealloc(slice);
return Err(e);
}
Ok(slice.as_range().start())
}
pub fn new<A: BStackRaiiAllocator>(allocator: &A, s: &str) -> io::Result<BStackOwned<Self>> {
let len = s.len() as u64;
let data = Self::alloc_bytes(allocator, s.as_bytes())?;
let od = StringOnDisk {
header: BlockHeader {
size: STRING_SIZE,
tag: Self::eightcc(),
},
data,
len,
};
match alloc_image(allocator, bytemuck::bytes_of(&od)) {
Ok(range) => Ok(unsafe { BStackOwned::from_raw(Self::from_range(range)) }),
Err(e) => {
if data != 0 {
let _ = unsafe { dealloc_range(allocator, BStackRange::new(data, len)) };
}
Err(e)
}
}
}
pub fn len(&self, stack: &BStack) -> io::Result<u64> {
read_u64(stack, self.range.start() + LEN_OFF)
}
pub fn is_empty(&self, stack: &BStack) -> io::Result<bool> {
Ok(self.len(stack)? == 0)
}
pub fn read_bytes(&self, stack: &BStack) -> io::Result<Vec<u8>> {
let [data, len] = read_fields::<2>(stack, self.range.start() + DATA_OFF)?;
if len == 0 {
return Ok(Vec::new());
}
if len > stack.len()? {
return Err(io_error!("corrupt string length exceeds file size"));
}
let mut buf = vec![0u8; len as usize];
stack.get_into(data, &mut buf)?;
Ok(buf)
}
pub fn to_string(&self, stack: &BStack) -> io::Result<String> {
String::from_utf8(self.read_bytes(stack)?).map_err(|e| io_error!(e))
}
pub fn set<A: BStackRaiiAllocator>(&self, allocator: &A, s: &str) -> io::Result<()> {
let handle = self.range.start();
let stack = allocator.stack();
let newlen = s.len() as u64;
let newdata = Self::alloc_bytes(allocator, s.as_bytes())?;
let mut buf = [0u8; 16];
buf[0..8].copy_from_slice(&newdata.to_le_bytes());
buf[8..16].copy_from_slice(&newlen.to_le_bytes());
let old = match stack.swap(handle + DATA_OFF, buf) {
Ok(o) => o,
Err(e) => {
if newdata != 0 {
let _ = unsafe { dealloc_range(allocator, BStackRange::new(newdata, newlen)) };
}
return Err(e);
}
};
let old_data = u64::from_le_bytes(old[0..8].try_into().unwrap());
let old_len = u64::from_le_bytes(old[8..16].try_into().unwrap());
if old_data != 0 {
let _ = unsafe { dealloc_range(allocator, BStackRange::new(old_data, old_len)) };
}
Ok(())
}
pub fn push_str<A: BStackRaiiAllocator>(&self, allocator: &A, s: &str) -> io::Result<()> {
let mut cur = self.to_string(allocator.stack())?;
cur.push_str(s);
self.set(allocator, &cur)
}
pub fn push<A: BStackRaiiAllocator>(&self, allocator: &A, ch: char) -> io::Result<()> {
let mut buf = [0u8; 4];
self.push_str(allocator, ch.encode_utf8(&mut buf))
}
pub fn truncate<A: BStackRaiiAllocator>(
&self,
allocator: &A,
new_len: usize,
) -> io::Result<()> {
let mut cur = self.to_string(allocator.stack())?;
if new_len >= cur.len() {
return Ok(());
}
if !cur.is_char_boundary(new_len) {
return Err(io_error!(
InvalidInput,
"truncate: byte index is not a UTF-8 char boundary"
));
}
cur.truncate(new_len);
self.set(allocator, &cur)
}
pub fn clear<A: BStackRaiiAllocator>(&self, allocator: &A) -> io::Result<()> {
self.set(allocator, "")
}
pub fn char_count(&self, stack: &BStack) -> io::Result<usize> {
Ok(self.to_string(stack)?.chars().count())
}
pub fn eq_str(&self, stack: &BStack, s: &str) -> io::Result<bool> {
Ok(self.read_bytes(stack)? == s.as_bytes())
}
pub fn starts_with(&self, stack: &BStack, prefix: &str) -> io::Result<bool> {
Ok(self.read_bytes(stack)?.starts_with(prefix.as_bytes()))
}
pub fn ends_with(&self, stack: &BStack, suffix: &str) -> io::Result<bool> {
Ok(self.read_bytes(stack)?.ends_with(suffix.as_bytes()))
}
pub fn contains(&self, stack: &BStack, needle: &str) -> io::Result<bool> {
Ok(self.to_string(stack)?.contains(needle))
}
}
impl BStackCast for BStackString {
fn eightcc() -> EightCC {
EightCC::new([b'S', b't', b'r', 0x80, 0x81, 0x82, 0x83, 0x84])
}
}
impl crate::types::traits::BStackEmbeddable for BStackString {}
impl BStackBlock for BStackString {
type OnDisk = StringOnDisk;
unsafe fn from_range(range: BStackRange) -> Self {
BStackString { range }
}
fn range(&self) -> BStackRange {
self.range
}
fn __bstack_drop_children<A: BStackRaiiAllocator>(
allocator: &A,
range: BStackRange,
) -> io::Result<()> {
let [data, len] = read_fields::<2>(allocator.stack(), range.start() + DATA_OFF)?;
if data != 0 {
unsafe { dealloc_range(allocator, BStackRange::new(data, len))? };
}
Ok(())
}
fn __bstack_clone_children_inplace<A: BStackRaiiAllocator>(
&self,
allocator: &A,
plan: &mut ClonePlan,
) -> io::Result<Self::OnDisk> {
let handle = self.range.start();
let [data, len] = read_fields::<2>(allocator.stack(), handle + DATA_OFF)?;
let new_data = if len != 0 {
if len > allocator.len()? {
return Err(io_error!("corrupt string length exceeds file size"));
}
let mut bytes = vec![0u8; len as usize];
allocator.stack().get_into(data, &mut bytes)?;
let dst = plan.alloc_raw(allocator, len)?;
plan.write(dst.start(), bytes);
dst.start()
} else {
0
};
let od = StringOnDisk {
header: BlockHeader {
size: STRING_SIZE,
tag: Self::eightcc(),
},
data: new_data,
len,
};
Ok(od)
}
}
impl TryCloneIn for BStackString {}