use crate::bson::{self, Element, ARRAY, DOCUMENT, STRING};
use crate::error::{Error, Result};
use crate::value::{Float3, FloatQ, Value};
pub const TYPE_VALUE_VAR: &str = "DynamicValueVariable";
pub const TYPE_REF_VAR: &str = "DynamicReferenceVariable";
pub const TYPE_VAR_SPACE: &str = "DynamicVariableSpace";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SlotLoc {
pub key: u64,
pub offset: usize,
pub end: usize,
pub id: String,
pub parent_ref: Option<String>,
pub name: String,
pub children_array: Option<usize>,
pub container_lengths: Vec<usize>,
}
#[derive(Debug, Clone)]
pub struct ComponentView {
pub offset: usize,
pub type_index: i64,
pub type_name: String,
pub references: Vec<String>,
}
pub fn field<'a>(buf: &'a [u8], doc_off: usize, name: &str) -> Result<Option<Element<'a>>> {
Ok(bson::elements(buf, doc_off)?
.into_iter()
.find(|e| e.key == name))
}
pub fn root_slot_offset(buf: &[u8]) -> Result<usize> {
let object =
field(buf, 0, "Object")?.ok_or_else(|| Error::Invalid("root has no Object".into()))?;
if object.ty != DOCUMENT {
return Err(Error::Invalid("Object is not a document".into()));
}
Ok(object.value_at)
}
pub fn read_types(buf: &[u8]) -> Result<Vec<String>> {
let Some(types) = field(buf, 0, "Types")? else {
return Ok(Vec::new());
};
if types.ty != ARRAY {
return Err(Error::Invalid("Types is not an array".into()));
}
let mut out = Vec::new();
for el in bson::elements(buf, types.value_at)? {
if el.ty != STRING {
return Err(Error::Invalid("Types entry is not a string".into()));
}
out.push(bson::decode_string(el.value)?.to_string());
}
Ok(out)
}
pub fn read_string_field(buf: &[u8], doc_off: usize, name: &str) -> Result<Option<String>> {
let Some(el) = field(buf, doc_off, name)? else {
return Ok(None);
};
read_string_value(buf, &el, name)
}
fn read_string_value(buf: &[u8], el: &Element<'_>, name: &str) -> Result<Option<String>> {
if let Some(data) = sync_data(buf, el)? {
return read_string_value(buf, &data, name);
}
match el.ty {
STRING => Ok(Some(bson::decode_string(el.value)?.to_string())),
bson::NULL => Ok(None),
_ => Err(Error::Invalid(format!("{name} is not a string"))),
}
}
fn sync_data<'a>(buf: &'a [u8], el: &Element<'a>) -> Result<Option<Element<'a>>> {
if el.ty != DOCUMENT {
return Ok(None);
}
let els = bson::elements(buf, el.value_at)?;
if !els.iter().any(|e| e.key == "ID") {
return Ok(None);
}
Ok(els.into_iter().find(|e| e.key == "Data"))
}
pub fn read_slot(buf: &[u8], offset: usize, container_lengths: Vec<usize>) -> Result<SlotLoc> {
let end = bson::doc_end(buf, offset)?;
let id = read_string_field(buf, offset, "ID")?.unwrap_or_default();
let parent_ref = read_string_field(buf, offset, "ParentReference")?;
let name = read_string_field(buf, offset, "Name")?.unwrap_or_default();
let children_array = match field(buf, offset, "Children")? {
Some(el) if el.ty == ARRAY => Some(el.value_at),
Some(_) => return Err(Error::Invalid("Children is not an array".into())),
None => None,
};
Ok(SlotLoc {
key: 0,
offset,
end,
id,
parent_ref,
name,
children_array,
container_lengths,
})
}
pub fn child_slot_offsets(buf: &[u8], slot_off: usize) -> Result<Vec<usize>> {
let Some(children) = field(buf, slot_off, "Children")? else {
return Ok(Vec::new());
};
if children.ty != ARRAY {
return Err(Error::Invalid("Children is not an array".into()));
}
let mut out = Vec::new();
for el in bson::elements(buf, children.value_at)? {
if el.ty != DOCUMENT {
return Err(Error::Invalid(
"Children entry is not a slot document".into(),
));
}
out.push(el.value_at);
}
Ok(out)
}
pub fn walk_slots(
buf: &[u8],
slot_off: usize,
outer: &[usize],
out: &mut Vec<SlotLoc>,
) -> Result<()> {
let mut chain = outer.to_vec();
chain.push(slot_off);
let slot = read_slot(buf, slot_off, chain.clone())?;
let children_array = slot.children_array;
out.push(slot);
if let Some(arr) = children_array {
let mut child_outer = chain;
child_outer.push(arr);
for child in child_slot_offsets(buf, slot_off)? {
walk_slots(buf, child, &child_outer, out)?;
}
}
Ok(())
}
pub fn all_slots(buf: &[u8]) -> Result<Vec<SlotLoc>> {
let root = root_slot_offset(buf)?;
let mut out = Vec::new();
walk_slots(buf, root, &[0], &mut out)?;
Ok(out)
}
pub fn find_slot_by_id(buf: &[u8], id: &str) -> Result<Option<SlotLoc>> {
Ok(all_slots(buf)?.into_iter().find(|s| s.id == id))
}
pub fn components_of_slot(
buf: &[u8],
slot_off: usize,
types: &[String],
) -> Result<Vec<ComponentView>> {
let Some(comps) = field(buf, slot_off, "Components")? else {
return Ok(Vec::new());
};
if comps.ty != DOCUMENT {
return Err(Error::Invalid(
"Components is not a UniquePtr document".into(),
));
}
let Some(data) = field(buf, comps.value_at, "Data")? else {
return Ok(Vec::new());
};
if data.ty != ARRAY {
return Err(Error::Invalid("Components.Data is not an array".into()));
}
let mut out = Vec::new();
for el in bson::elements(buf, data.value_at)? {
if el.ty != DOCUMENT {
return Err(Error::Invalid("component is not a document".into()));
}
let type_index = match field(buf, el.value_at, "Type")? {
Some(t) => bson::decode_int(t.value, t.ty)?,
None => return Err(Error::Invalid("component has no Type".into())),
};
let type_name = types
.get(usize::try_from(type_index).unwrap_or(usize::MAX))
.cloned()
.unwrap_or_default();
let mut references = Vec::new();
if let Some(body) = field(buf, el.value_at, "Data")? {
if body.ty == DOCUMENT || body.ty == ARRAY {
collect_ref_targets(buf, body.value_at, &mut references)?;
}
}
out.push(ComponentView {
offset: el.value_at,
type_index,
type_name,
references,
});
}
Ok(out)
}
fn collect_ref_targets(buf: &[u8], doc_off: usize, out: &mut Vec<String>) -> Result<()> {
let elems = bson::elements(buf, doc_off)?;
let has_id = elems.iter().any(|e| e.key == "ID");
if has_id {
if let Some(data) = elems.iter().find(|e| e.key == "Data") {
if data.ty == STRING {
out.push(bson::decode_string(data.value)?.to_string());
}
}
}
for el in &elems {
if el.ty == DOCUMENT || el.ty == ARRAY {
collect_ref_targets(buf, el.value_at, out)?;
}
}
Ok(())
}
pub fn collect_ids(buf: &[u8], doc_off: usize, out: &mut Vec<String>) -> Result<()> {
for el in bson::elements(buf, doc_off)? {
if el.key == "ID" && el.ty == STRING {
out.push(bson::decode_string(el.value)?.to_string());
}
if el.ty == DOCUMENT || el.ty == ARRAY {
collect_ids(buf, el.value_at, out)?;
}
}
Ok(())
}
pub fn document_ids(buf: &[u8]) -> Result<Vec<String>> {
let mut out = Vec::new();
collect_ids(buf, 0, &mut out)?;
Ok(out)
}
pub fn read_slot_value(buf: &[u8], slot_off: usize, name: &str) -> Result<Value> {
let el = field(buf, slot_off, name)?.ok_or_else(|| Error::FieldNotFound(name.to_string()))?;
decode_slot_value(buf, &el)
}
pub fn decode_optional_value(buf: &[u8], el: &Element<'_>) -> Result<Option<Value>> {
if let Some(data) = sync_data(buf, el)? {
return decode_optional_value(buf, &data);
}
if el.ty == bson::NULL {
return Ok(None);
}
decode_slot_value(buf, el).map(Some)
}
pub fn decode_slot_value(buf: &[u8], el: &Element<'_>) -> Result<Value> {
if let Some(data) = sync_data(buf, el)? {
return decode_slot_value(buf, &data);
}
match el.ty {
bson::DOUBLE => Ok(Value::F64(bson::decode_f64(el.value)?)),
bson::INT64 => Ok(Value::I64(bson::decode_i64(el.value)?)),
bson::INT32 => Ok(Value::I64(i64::from(bson::decode_i32(el.value)?))),
bson::BOOL => Ok(Value::Bool(bson::decode_bool(el.value)?)),
STRING => Ok(Value::String(bson::decode_string(el.value)?.to_string())),
DOCUMENT => {
if let Ok(q) = bson::decode_floatq(el.value) {
return Ok(Value::FloatQ(q));
}
if let Ok(v) = bson::decode_float3(el.value) {
return Ok(Value::Float3(v));
}
Err(Error::Invalid(format!(
"cannot read field {} as a value",
el.key
)))
}
ARRAY => decode_float_array(buf, el.value_at)
.ok_or_else(|| Error::Invalid(format!("cannot read field {} as a value", el.key))),
_ => Err(Error::Invalid(format!(
"cannot read field {} as a value",
el.key
))),
}
}
fn decode_float_array(buf: &[u8], array_off: usize) -> Option<Value> {
let els = bson::elements(buf, array_off).ok()?;
let mut nums = Vec::with_capacity(els.len());
for el in els {
if el.ty != bson::DOUBLE {
return None;
}
nums.push(bson::decode_f64(el.value).ok()?);
}
match nums.as_slice() {
[x, y, z] => Some(Value::Float3(Float3 {
x: *x,
y: *y,
z: *z,
})),
[x, y, z, w] => Some(Value::FloatQ(FloatQ {
x: *x,
y: *y,
z: *z,
w: *w,
})),
_ => None,
}
}
pub fn read_number_field(buf: &[u8], doc_off: usize, name: &str) -> Result<Option<i64>> {
let Some(el) = field(buf, doc_off, name)? else {
return Ok(None);
};
Ok(Some(bson::decode_int(el.value, el.ty)?))
}
pub fn read_bool_field(buf: &[u8], doc_off: usize, name: &str) -> Result<Option<bool>> {
let Some(el) = field(buf, doc_off, name)? else {
return Ok(None);
};
match el.ty {
bson::BOOL => Ok(Some(bson::decode_bool(el.value)?)),
bson::INT32 | bson::INT64 => Ok(Some(bson::decode_int(el.value, el.ty)? != 0)),
_ => Err(Error::Invalid(format!("{name} is not a bool"))),
}
}
pub fn asset_views(buf: &[u8]) -> Result<Vec<(String, Option<i64>)>> {
let Some(asset) = asset_array(buf)? else {
return Ok(Vec::new());
};
if asset.ty != ARRAY {
return Err(Error::Invalid("Assets is not an array".into()));
}
let mut out = Vec::new();
for el in bson::elements(buf, asset.value_at)? {
if el.ty != DOCUMENT {
return Err(Error::Invalid("Assets entry is not a document".into()));
}
let id = asset_id(buf, el.value_at)?;
let type_index = match field(buf, el.value_at, "Type")? {
Some(t) => Some(bson::decode_int(t.value, t.ty)?),
None => None,
};
out.push((id, type_index));
}
Ok(out)
}
pub fn asset_array(buf: &[u8]) -> Result<Option<Element<'_>>> {
if let Some(assets) = field(buf, 0, "Assets")? {
return Ok(Some(assets));
}
field(buf, 0, "Asset")
}
pub fn asset_id(buf: &[u8], doc_off: usize) -> Result<String> {
if let Some(id) = read_string_field(buf, doc_off, "ID")? {
if !id.is_empty() {
return Ok(id);
}
}
let Some(data) = field(buf, doc_off, "Data")? else {
return Ok(String::new());
};
if data.ty != DOCUMENT {
return Ok(String::new());
}
Ok(read_string_field(buf, data.value_at, "ID")?.unwrap_or_default())
}
pub fn is_dyn_type(type_name: &str) -> Option<DynKind> {
if type_name.contains(TYPE_VALUE_VAR) {
Some(DynKind::Value)
} else if type_name.contains(TYPE_REF_VAR) {
Some(DynKind::Reference)
} else if type_name.contains(TYPE_VAR_SPACE) {
Some(DynKind::Space)
} else {
None
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DynKind {
Value,
Reference,
Space,
}
pub fn interpret_dyn_fields(fields: &[(String, crate::value::DynValue)]) -> crate::value::DynValue {
use crate::value::DynValue;
let has_id = fields.iter().any(|(k, _)| k == "ID");
if has_id {
if let Some((_, data)) = fields.iter().find(|(k, _)| k == "Data") {
return data.clone();
}
}
let num = |name: &str| -> Option<f64> {
fields
.iter()
.find(|(k, _)| k == name)
.and_then(|(_, v)| v.as_f64())
};
if let (Some(x), Some(y), Some(z), Some(w)) = (num("x"), num("y"), num("z"), num("w")) {
return DynValue::FloatQ(FloatQ { x, y, z, w });
}
if let (Some(x), Some(y), Some(z)) = (num("x"), num("y"), num("z")) {
return DynValue::Float3(Float3 { x, y, z });
}
DynValue::Null
}