use crate::primitives::WidePtr;
use crate::types::compiled::rc::CTRL_DATA_OFFSET;
mod clone;
mod error;
mod field;
mod r#move;
mod read;
mod registry;
mod schema;
mod shape;
mod teardown;
mod value;
mod walk;
pub(in crate::rtti) use error::rtti_err;
pub use error::{RttiError, RttiErrorKind, RttiResult};
pub use registry::{RTTI_TYPES, RttiRegistration, RttiRegistry, sync};
pub use schema::{
RttiBody, RttiEnum, RttiField, RttiType, RttiVariant, Shape, decode_type, encode_type,
};
pub(in crate::rtti) use schema::{class_value_slot, frame_record, layouts_match};
pub(in crate::rtti) use value::Resolved;
pub use value::{AnyRef, ForeignPtr, Moved, Value, VecRef};
#[doc(hidden)]
pub use linkme;
#[doc(hidden)]
pub use linkme::distributed_slice as distributed_slice_reexport;
pub type RttiOrdinal = u32;
pub(in crate::rtti) const RECORD_HEADER_LEN: u64 = 16;
pub(in crate::rtti) fn add_off(a: u64, b: u64) -> RttiResult<u64> {
a.checked_add(b)
.ok_or_else(|| rtti_err!(OffsetOverflow, "RTTI offset arithmetic overflow"))
}
pub(in crate::rtti) fn mul_off(a: u64, b: u64) -> RttiResult<u64> {
a.checked_mul(b)
.ok_or_else(|| rtti_err!(OffsetOverflow, "RTTI offset arithmetic overflow"))
}
#[doc(hidden)]
pub fn rtti_narrow_u32(x: usize, what: &str) -> u32 {
u32::try_from(x).unwrap_or_else(|_| {
panic!("[BSTACK0817] RTTI {what} exceeds the maximum encodable size (u32)")
})
}
pub(in crate::rtti) fn too_large(what: &str, limit: &str) -> RttiError {
rtti_err!(
TooLarge,
"RTTI {} exceeds the maximum encodable size ({})",
what,
limit
)
}
pub(in crate::rtti) fn ordinal_type_index(ordinal: RttiOrdinal) -> u32 {
ordinal.checked_add(1).unwrap_or_else(|| {
panic!("[BSTACK0817] RTTI ordinal {ordinal} exceeds the maximum encodable type index")
})
}
pub fn typed_ptr(file_id: u64, offset: u64, ordinal: RttiOrdinal) -> WidePtr {
WidePtr::from_raw(file_id, ordinal_type_index(ordinal), offset)
}
#[macro_export]
macro_rules! rtti_path {
($($seg:ident).+) => {
&[$(::core::stringify!($seg)),+]
};
}
pub use crate::primitives::OwnershipKind;
pub(in crate::rtti) const VECDESC_LEN: u64 = 16;
pub(in crate::rtti) const BYTEVEC_HEADER: u64 = 16;
pub(in crate::rtti) const FOREIGN_REPR_LEN: u64 = 16;
pub(in crate::rtti) const HEADER_TAG_OFFSET: u64 = 8;
pub(in crate::rtti) const CONTROL_SIZE: u64 = CTRL_DATA_OFFSET + 8;
pub(in crate::rtti) fn unknown_tag() -> RttiError {
rtti_err!(
UnregisteredTag,
"RTTI pointer/field references an unregistered type tag"
)
}
#[cfg(test)]
mod tests {
use linkme::distributed_slice;
use super::*;
use crate::primitives::EightCC;
fn cc(s: &str) -> EightCC {
EightCC::from_name(s)
}
fn sample_struct() -> RttiType {
RttiType {
tag: cc("Sample"),
name: "my_sample_type".to_string(),
rc: true,
weak: false,
ctrl_tag: None,
ondisk_size: 64,
body: RttiBody::Struct(
vec![
RttiField {
name: "id".to_string(),
offset: 16,
shape: Shape::Pod { width: 8 },
},
RttiField {
name: "child".to_string(),
offset: 24,
shape: Shape::Owned(cc("Child")),
},
RttiField {
name: "names".to_string(),
offset: 32,
shape: Shape::Vec(Box::new(Shape::Pod { width: 1 })),
},
RttiField {
name: "kind".to_string(),
offset: 0,
shape: Shape::Class {
mutable: false,
inner: Box::new(Shape::Pod { width: 4 }),
value: vec![7u8, 0, 0, 0].into(),
},
},
]
.into(),
),
}
}
fn sample_enum() -> RttiType {
RttiType {
tag: cc("Expr"),
name: "expr_node".to_string(),
rc: false,
weak: false,
ctrl_tag: None,
ondisk_size: 48,
body: RttiBody::Enum(RttiEnum {
disc_width: 2,
disc_off: 16,
payload_off: 24,
variants: vec![
RttiVariant {
name: "Leaf".to_string(),
disc_value: 0,
fields: vec![RttiField {
name: "value".to_string(),
offset: 0,
shape: Shape::Pod { width: 8 },
}]
.into(),
},
RttiVariant {
name: "Node".to_string(),
disc_value: 300,
fields: vec![
RttiField {
name: "left".to_string(),
offset: 0,
shape: Shape::Owned(cc("Expr")),
},
RttiField {
name: "right".to_string(),
offset: 8,
shape: Shape::Owned(cc("Expr")),
},
]
.into(),
},
]
.into(),
}),
}
}
#[test]
fn rtti_codec_struct_roundtrips() {
let ty = sample_struct();
let body = encode_type(&ty).unwrap();
let back = decode_type(ty.tag, &body).unwrap();
assert_eq!(ty, back);
}
#[test]
fn rtti_codec_enum_roundtrips() {
let ty = sample_enum();
let body = encode_type(&ty).unwrap();
let back = decode_type(ty.tag, &body).unwrap();
assert_eq!(ty, back);
}
fn reg_pair_a() -> RttiType {
RttiType {
tag: cc("SyncRegA"),
name: "sync_reg_a".to_string(),
rc: false,
weak: false,
ctrl_tag: None,
ondisk_size: 16,
body: RttiBody::Struct(
vec![RttiField {
name: "x".to_string(),
offset: 0,
shape: Shape::Pod { width: 8 },
}]
.into(),
),
}
}
fn reg_pair_b() -> RttiType {
RttiType {
tag: cc("SyncRegB"),
name: "sync_reg_b".to_string(),
rc: false,
weak: false,
ctrl_tag: None,
ondisk_size: 24,
body: RttiBody::Struct(
vec![RttiField {
name: "child".to_string(),
offset: 0,
shape: Shape::Owned(cc("SyncRegA")),
}]
.into(),
),
}
}
#[distributed_slice(RTTI_TYPES)]
static REG_A: RttiRegistration = RttiRegistration { build: reg_pair_a };
#[distributed_slice(RTTI_TYPES)]
static REG_B: RttiRegistration = RttiRegistration { build: reg_pair_b };
#[test]
fn rtti_sync_registers_compiled_types() {
let path = std::env::temp_dir().join(format!(
"bstack_raii_rtti_sync_{}.stack",
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
{
let mut reg = RttiRegistry::open(&path).unwrap();
let n = reg.sync_compiled().unwrap();
assert!(n >= 2, "expected the two registered types, appended {n}");
assert!(reg.ordinal_of(cc("SyncRegA")).is_some());
assert!(reg.ordinal_of(cc("SyncRegB")).is_some());
assert_eq!(
reg.load_type(reg.ordinal_of(cc("SyncRegA")).unwrap())
.unwrap(),
reg_pair_a()
);
assert_eq!(reg.sync_compiled().unwrap(), 0);
}
{
let mut reg = RttiRegistry::open(&path).unwrap();
assert_eq!(reg.sync_compiled().unwrap(), 0);
assert!(reg.ordinal_of(cc("SyncRegB")).is_some());
}
{
let reg = sync(&path).unwrap();
assert!(reg.ordinal_of(cc("SyncRegA")).is_some());
}
std::fs::remove_file(&path).ok();
}
#[test]
fn rtti_registry_append_load_and_reopen() {
let path = std::env::temp_dir().join(format!(
"bstack_raii_rtti_{}.stack",
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
let a = sample_struct();
let b = sample_enum();
{
let mut reg = RttiRegistry::open(&path).unwrap();
assert!(reg.is_empty());
assert_eq!(reg.append(&a).unwrap(), 0);
assert_eq!(reg.append(&b).unwrap(), 1);
assert!(reg.append(&a).is_err());
assert_eq!(reg.load_type(0).unwrap(), a);
assert_eq!(reg.load_type(1).unwrap(), b);
let ord = reg.ordinal_of(b.tag).unwrap();
assert_eq!(reg.resolve_ptr(typed_ptr(0, 4096, ord)), Some(1));
assert_eq!(reg.resolve_ptr(WidePtr::from_raw(0, 0, 4096)), None); }
{
let reg = RttiRegistry::open(&path).unwrap();
assert_eq!(reg.len(), 2);
assert_eq!(reg.tag_of(0), Some(a.tag));
assert_eq!(reg.load_type(0).unwrap(), a);
assert_eq!(reg.load_type(1).unwrap(), b);
}
std::fs::remove_file(&path).ok();
}
#[test]
fn decode_rejects_oversize_enum_discriminant_width() {
let mut body = encode_type(&sample_enum()).unwrap();
assert!(decode_type(sample_enum().tag, &body).is_ok());
body[1] = 9;
let err = decode_type(sample_enum().tag, &body).unwrap_err();
assert!(err.to_string().contains("[BSTACK0816]"), "got: {err}");
}
#[test]
fn encode_rejects_components_overflowing_their_length_fields() {
fn ty_with(name: String, shape: Shape) -> RttiType {
RttiType {
tag: cc("Big"),
name,
rc: false,
weak: false,
ctrl_tag: None,
ondisk_size: 8,
body: RttiBody::Struct(
vec![RttiField {
name: "f".to_string(),
offset: 0,
shape,
}]
.into(),
),
}
}
let over = ty_with(
"t".to_string(),
Shape::Tuple(vec![Shape::Pod { width: 1 }; 256].into()),
);
assert!(
encode_type(&over)
.unwrap_err()
.to_string()
.contains("[BSTACK0817]"),
);
let ok = ty_with(
"t".to_string(),
Shape::Tuple(vec![Shape::Pod { width: 1 }; 255].into()),
);
assert!(encode_type(&ok).is_ok());
let long = ty_with("x".repeat(70_000), Shape::Pod { width: 8 });
assert!(
encode_type(&long)
.unwrap_err()
.to_string()
.contains("[BSTACK0817]"),
);
}
}