use std::sync::Arc;
use flow_types::{Constructor, EnumShape, RecordShape};
use crate::value::{Meta, Value};
#[derive(Clone, Debug)]
pub struct Record {
shape: Arc<RecordShape>,
fields: Arc<[Value]>,
meta: Meta,
}
impl Record {
pub fn new(shape: Arc<RecordShape>, fields: Vec<Value>) -> Option<Self> {
let arity = shape.fields().len();
(fields.len() == arity).then(|| Record {
meta: Meta::around(&fields),
shape,
fields: fields.into(),
})
}
pub fn shape(&self) -> &Arc<RecordShape> {
&self.shape
}
pub fn fields(&self) -> &[Value] {
&self.fields
}
pub(crate) fn meta(&self) -> Meta {
self.meta
}
pub(crate) fn id(&self) -> [usize; 2] {
[
Arc::as_ptr(&self.shape).addr(),
Arc::as_ptr(&self.fields).cast::<Value>().addr(),
]
}
pub(crate) fn fields_mut(&mut self) -> Option<&mut [Value]> {
Arc::get_mut(&mut self.fields)
}
pub fn field(&self, index: usize) -> Option<&Value> {
self.fields.get(index)
}
}
impl Drop for Record {
fn drop(&mut self) {
if let Some(fields) = self.fields_mut() {
crate::value::dismantle(fields.iter_mut());
}
}
}
#[derive(Clone, Debug)]
pub struct Variant {
shape: Arc<EnumShape>,
index: u32,
meta: Meta,
payload: Arc<[Value]>,
}
impl Variant {
pub fn new(shape: Arc<EnumShape>, index: usize, payload: Vec<Value>) -> Option<Self> {
let arity = shape.constructor(index)?.payload().arity();
let index = u32::try_from(index).ok()?;
(payload.len() == arity).then(|| Variant {
meta: Meta::around(&payload),
shape,
index,
payload: payload.into(),
})
}
pub fn shape(&self) -> &Arc<EnumShape> {
&self.shape
}
pub fn index(&self) -> usize {
#[expect(
clippy::as_conversions,
reason = "a u32 that came from a usize widens back to it losslessly"
)]
let index = self.index as usize;
index
}
pub fn constructor(&self) -> &Constructor {
&self.shape.constructors()[self.index()]
}
pub fn payload(&self) -> &[Value] {
&self.payload
}
pub(crate) fn meta(&self) -> Meta {
self.meta
}
pub(crate) fn id(&self) -> [usize; 3] {
[
Arc::as_ptr(&self.shape).addr(),
self.index(),
Arc::as_ptr(&self.payload).cast::<Value>().addr(),
]
}
pub(crate) fn payload_mut(&mut self) -> Option<&mut [Value]> {
Arc::get_mut(&mut self.payload)
}
}
impl Drop for Variant {
fn drop(&mut self) {
if let Some(payload) = self.payload_mut() {
crate::value::dismantle(payload.iter_mut());
}
}
}