use crate::{
AsContextMut,
module::{self, PassiveDataSegmentBytes},
store::Stored,
};
use core::convert::AsRef;
define_handle! {
struct DataSegment(u32, Stored) => DataSegmentEntity;
}
impl DataSegment {
pub fn new_active(mut ctx: impl AsContextMut) -> Self {
ctx.as_context_mut()
.store
.inner
.alloc_data_segment(DataSegmentEntity::active())
}
pub fn new_passive(mut ctx: impl AsContextMut, bytes: PassiveDataSegmentBytes) -> Self {
ctx.as_context_mut()
.store
.inner
.alloc_data_segment(DataSegmentEntity::passive(bytes))
}
}
#[derive(Debug)]
pub struct DataSegmentEntity {
bytes: Option<PassiveDataSegmentBytes>,
}
impl DataSegmentEntity {
pub fn active() -> Self {
Self { bytes: None }
}
pub fn passive(bytes: PassiveDataSegmentBytes) -> Self {
Self { bytes: Some(bytes) }
}
}
impl From<&'_ module::DataSegment> for DataSegmentEntity {
fn from(segment: &'_ module::DataSegment) -> Self {
Self {
bytes: segment.passive_data_segment_bytes(),
}
}
}
impl DataSegmentEntity {
pub fn bytes(&self) -> &[u8] {
self.bytes
.as_ref()
.map(AsRef::as_ref)
.unwrap_or_else(|| &[])
}
pub fn drop_bytes(&mut self) {
self.bytes = None;
}
}