perf(client): decode gameplay facts without a JSON document tree
This commit is contained in:
@@ -0,0 +1,104 @@
|
||||
//! Full production fact loading, including file reads, interning and temporary destruction.
|
||||
//! cargo run --profile fast -p horizon-client --example block_facts_bench -- ROOT [SAMPLES]
|
||||
//! Use SAMPLES=1 with an OS peak-RSS wrapper; `digest` checks all facts
|
||||
//! and the shape sharing partition (including sharing between outlines and edges).
|
||||
use horizon_client::blocks::BlockFacts;
|
||||
use horizon_world::{DATA_VERSION, nbt::Tag, registry::BlockRegistry};
|
||||
use serde_json::Value;
|
||||
use std::{
|
||||
collections::{HashMap, hash_map::DefaultHasher},
|
||||
fs,
|
||||
hash::{Hash, Hasher},
|
||||
hint::black_box,
|
||||
path::Path,
|
||||
time::Instant,
|
||||
};
|
||||
type Result<T> = horizon_client::Result<T>;
|
||||
|
||||
fn tag(value: &Value) -> Result<Tag> {
|
||||
Ok(match value {
|
||||
Value::String(s) => Tag::String(s.as_str().into()),
|
||||
Value::Number(n) => Tag::Int(i32::try_from(n.as_i64().ok_or("registry number")?)?),
|
||||
Value::Array(a) => Tag::List(a.iter().map(tag).collect::<Result<_>>()?),
|
||||
Value::Object(o) => Tag::Compound(
|
||||
o.iter()
|
||||
.map(|(k, v)| Ok((k.as_str().into(), tag(v)?)))
|
||||
.collect::<Result<_>>()?,
|
||||
),
|
||||
_ => return Err("registry value".into()),
|
||||
})
|
||||
}
|
||||
fn registry(root: &Path) -> Result<BlockRegistry> {
|
||||
let facts: Value = serde_json::from_slice(&fs::read(root.join("facts.json"))?)?;
|
||||
Ok(BlockRegistry::from_nbt(&Tag::compound([
|
||||
("DataVersion", Tag::Int(DATA_VERSION)),
|
||||
(
|
||||
"states",
|
||||
Tag::List(
|
||||
facts["states"]
|
||||
.as_array()
|
||||
.ok_or("registry states")?
|
||||
.iter()
|
||||
.map(|s| tag(&s[4]))
|
||||
.collect::<Result<_>>()?,
|
||||
),
|
||||
),
|
||||
("defaults", tag(&facts["defaults"])?),
|
||||
]))?)
|
||||
}
|
||||
fn main() -> Result<()> {
|
||||
let args: Vec<_> = std::env::args().skip(1).collect();
|
||||
let root = Path::new(
|
||||
args.first()
|
||||
.ok_or("usage: block_facts_bench ROOT [SAMPLES|digest]")?,
|
||||
);
|
||||
let setup = Instant::now();
|
||||
let registry = registry(root)?;
|
||||
println!(
|
||||
"registry_setup_ms={:.3}",
|
||||
setup.elapsed().as_secs_f64() * 1000.0
|
||||
);
|
||||
if args.get(1).is_some_and(|s| s == "digest") {
|
||||
let facts = BlockFacts::load(root, ®istry)?;
|
||||
let mut hash = DefaultHasher::new();
|
||||
let mut shapes = HashMap::new();
|
||||
facts.air.hash(&mut hash);
|
||||
for state in &facts.states {
|
||||
format!("{state:?}").hash(&mut hash);
|
||||
for shape in [&state.outline, &state.outline_edges] {
|
||||
let next = shapes.len();
|
||||
shapes
|
||||
.entry((shape.as_ptr(), shape.len()))
|
||||
.or_insert(next)
|
||||
.hash(&mut hash);
|
||||
}
|
||||
}
|
||||
println!(
|
||||
"states={} shared_shapes={} digest={:016x}",
|
||||
facts.states.len(),
|
||||
shapes.len(),
|
||||
hash.finish()
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
let samples: usize = args.get(1).map(|s| s.parse()).transpose()?.unwrap_or(9);
|
||||
assert!(samples > 0);
|
||||
// First load is reported separately; OS file caches are not forcibly evicted.
|
||||
let load = || -> Result<f64> {
|
||||
let start = Instant::now();
|
||||
let facts = black_box(BlockFacts::load(black_box(root), black_box(®istry))?);
|
||||
let ms = start.elapsed().as_secs_f64() * 1000.0;
|
||||
drop(facts);
|
||||
Ok(ms)
|
||||
};
|
||||
println!("first_load_ms={:.3}", load()?);
|
||||
if samples > 1 {
|
||||
load()?;
|
||||
load()?;
|
||||
let mut times = (0..samples).map(|_| load()).collect::<Result<Vec<_>>>()?;
|
||||
println!("samples_ms={times:.3?}");
|
||||
times.sort_by(f64::total_cmp);
|
||||
println!("median_ms={:.3}", times[times.len() / 2]);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Per-state gameplay facts exported from vanilla's own block-state accessors
|
||||
//! (`gameplay-facts.json`), indexed by registry state ID.
|
||||
mod decode;
|
||||
use crate::Result;
|
||||
use horizon_world::registry::{BlockRegistry, BlockStateId};
|
||||
use serde_json::Value;
|
||||
@@ -112,9 +113,13 @@ pub struct BlockFacts {
|
||||
}
|
||||
impl BlockFacts {
|
||||
pub fn load(root: &Path, registry: &BlockRegistry) -> Result<Self> {
|
||||
let raw: Value = serde_json::from_slice(&fs::read(root.join("gameplay-facts.json"))?)?;
|
||||
let entries = raw["states"]
|
||||
.as_array()
|
||||
let bytes = fs::read(root.join("gameplay-facts.json"))?;
|
||||
serde_json::from_slice::<decode::Validate>(&bytes)?;
|
||||
let raw: decode::Gameplay<'_> = serde_json::from_slice(&bytes)?;
|
||||
let entries = raw
|
||||
.states
|
||||
.0
|
||||
.as_ref()
|
||||
.ok_or("missing gameplay state facts")?;
|
||||
if entries.len() != registry.len() {
|
||||
return Err("gameplay facts do not match the block registry".into());
|
||||
@@ -148,40 +153,22 @@ impl BlockFacts {
|
||||
.collect();
|
||||
let mut names: HashMap<String, Arc<str>> = HashMap::new();
|
||||
let mut intern = |s: &str| -> Arc<str> {
|
||||
names
|
||||
.entry(s.to_owned())
|
||||
.or_insert_with(|| Arc::from(s))
|
||||
.clone()
|
||||
};
|
||||
let mut shapes: HashMap<String, Arc<[[f64; 6]]>> = HashMap::new();
|
||||
let mut shape = |v: &Value, fallback: &dyn Fn() -> Vec<[f64; 6]>| -> Arc<[[f64; 6]]> {
|
||||
let Some(list) = v.as_array() else {
|
||||
return fallback().into();
|
||||
};
|
||||
shapes
|
||||
.entry(v.to_string())
|
||||
.or_insert_with(|| {
|
||||
list.iter()
|
||||
.filter_map(|b| {
|
||||
let b = b.as_array()?;
|
||||
let n = |i: usize| b.get(i).and_then(Value::as_f64).unwrap_or(0.0);
|
||||
Some([n(0), n(1), n(2), n(3), n(4), n(5)])
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.clone()
|
||||
if let Some(name) = names.get(s) {
|
||||
return name.clone();
|
||||
}
|
||||
let name: Arc<str> = Arc::from(s);
|
||||
names.insert(s.to_owned(), name.clone());
|
||||
name
|
||||
};
|
||||
let mut shapes = decode::Shapes::default();
|
||||
let mut states = Vec::with_capacity(entries.len());
|
||||
for (index, entry) in entries.iter().enumerate() {
|
||||
let id = BlockStateId(index as u32);
|
||||
if entry["id"].as_u64() != Some(index as u64) {
|
||||
if entry.id != Some(index as u64) {
|
||||
return Err("gameplay facts are not in registry order".into());
|
||||
}
|
||||
let state = registry.state(id).ok_or("missing registry state")?;
|
||||
let num = |k: &str| entry[k].as_f64().unwrap_or(0.0);
|
||||
let flag = |k: &str| entry[k].as_bool().unwrap_or(false);
|
||||
let sound = &entry["sound"];
|
||||
let sound_id = |k: &str| sound[k]["id"].as_str().unwrap_or("").to_owned();
|
||||
let sound = &entry.sound;
|
||||
let prop = |k: &str| state.properties.get(k).map(String::as_str);
|
||||
let (fluid, fluid_level, fluid_falling) = match state.name.as_str() {
|
||||
"minecraft:water" | "minecraft:lava" => {
|
||||
@@ -220,10 +207,10 @@ impl BlockFacts {
|
||||
}
|
||||
};
|
||||
let edges = move || if air { Vec::new() } else { cube_edges() };
|
||||
let outline = shape(&entry["outline"], &cube);
|
||||
let outline_edges = shape(&entry["outline_edges"], &edges);
|
||||
let outline = shapes.intern(entry.outline, cube)?;
|
||||
let outline_edges = shapes.intern(entry.outline_edges, edges)?;
|
||||
// The export holds MapColor.col; ids are positions in MAP_COLORS.
|
||||
let col = entry["map_color"].as_u64().unwrap_or(0) as u32;
|
||||
let col = entry.map_color.unwrap_or(0) as u32;
|
||||
let map_color = if col == 0 {
|
||||
0
|
||||
} else {
|
||||
@@ -234,43 +221,41 @@ impl BlockFacts {
|
||||
outline,
|
||||
outline_edges,
|
||||
name: intern(&state.name),
|
||||
emission: num("emission") as u8,
|
||||
dampening: num("dampening") as u8,
|
||||
skylight_down: flag("skylight_down"),
|
||||
shape_occlusion: flag("shape_occlusion"),
|
||||
can_occlude: flag("can_occlude"),
|
||||
solid_render: flag("solid_render"),
|
||||
hardness: num("hardness") as f32,
|
||||
requires_tool: flag("requires_tool"),
|
||||
replaceable: flag("replaceable"),
|
||||
random_ticks: flag("random_ticks"),
|
||||
block_entity: flag("block_entity"),
|
||||
render_shape: match entry["render_shape"].as_str() {
|
||||
emission: entry.emission as u8,
|
||||
dampening: entry.dampening as u8,
|
||||
skylight_down: entry.skylight_down,
|
||||
shape_occlusion: entry.shape_occlusion,
|
||||
can_occlude: entry.can_occlude,
|
||||
solid_render: entry.solid_render,
|
||||
hardness: entry.hardness as f32,
|
||||
requires_tool: entry.requires_tool,
|
||||
replaceable: entry.replaceable,
|
||||
random_ticks: entry.random_ticks,
|
||||
block_entity: entry.block_entity,
|
||||
render_shape: match entry.render_shape.as_deref() {
|
||||
Some("INVISIBLE") => RenderShape::Invisible,
|
||||
Some("ENTITYBLOCK_ANIMATED") => RenderShape::Animated,
|
||||
_ => RenderShape::Model,
|
||||
},
|
||||
full_collision: flag("full_collision"),
|
||||
friction: num("friction") as f32,
|
||||
explosion_resistance: num("explosion_resistance") as f32,
|
||||
item: intern(entry["item"].as_str().unwrap_or("minecraft:air")),
|
||||
full_collision: entry.full_collision,
|
||||
friction: entry.friction as f32,
|
||||
explosion_resistance: entry.explosion_resistance as f32,
|
||||
item: intern(entry.item.as_deref().unwrap_or("minecraft:air")),
|
||||
sounds: Sounds {
|
||||
volume: sound["volume"].as_f64().unwrap_or(1.0) as f32,
|
||||
pitch: sound["pitch"].as_f64().unwrap_or(1.0) as f32,
|
||||
break_sound: intern(&sound_id("break")),
|
||||
step: intern(&sound_id("step")),
|
||||
place: intern(&sound_id("place")),
|
||||
hit: intern(&sound_id("hit")),
|
||||
fall: intern(&sound_id("fall")),
|
||||
volume: sound.volume as f32,
|
||||
pitch: sound.pitch as f32,
|
||||
break_sound: intern(sound.r#break.id.as_deref().unwrap_or("")),
|
||||
step: intern(sound.step.id.as_deref().unwrap_or("")),
|
||||
place: intern(sound.place.id.as_deref().unwrap_or("")),
|
||||
hit: intern(sound.hit.id.as_deref().unwrap_or("")),
|
||||
fall: intern(sound.fall.id.as_deref().unwrap_or("")),
|
||||
},
|
||||
fluid,
|
||||
fluid_level,
|
||||
fluid_falling,
|
||||
waterlogged: prop("waterlogged") == Some("true"),
|
||||
random_offset: flag("offset"),
|
||||
outline_offset: entry["outline_offset"]
|
||||
.as_bool()
|
||||
.unwrap_or_else(|| flag("offset")),
|
||||
random_offset: entry.offset,
|
||||
outline_offset: entry.outline_offset.unwrap_or(entry.offset),
|
||||
legacy_solid: behaviour_states[index][1].as_u64().unwrap_or(0) & 1 != 0,
|
||||
sturdy_full: (behaviour_states[index][0].as_u64().unwrap_or(0) & 63) as u8,
|
||||
classes: classes
|
||||
|
||||
@@ -0,0 +1,290 @@
|
||||
//! Typed projection of gameplay facts. Scalar conversions deliberately retain Value's
|
||||
//! permissive defaults; maps retain its last-key-wins behavior. Repeated geometry stays
|
||||
//! borrowed until it is interned, rather than allocating a JSON tree for every state.
|
||||
use serde::{
|
||||
Deserialize, Deserializer,
|
||||
de::{MapAccess, SeqAccess, Visitor},
|
||||
};
|
||||
use serde_json::{Value, value::RawValue};
|
||||
use std::{
|
||||
collections::{HashMap, hash_map::Entry as MapEntry},
|
||||
fmt,
|
||||
hash::{Hash, Hasher},
|
||||
marker::PhantomData,
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
// RawValue skips numeric range and depth checks. A non-allocating validation pass
|
||||
// keeps the original Value loader's JSON errors, even in overwritten/unused fields.
|
||||
#[derive(Default)]
|
||||
pub(super) struct Validate;
|
||||
impl<'de> Container<'de> for Validate {}
|
||||
impl<'de> Deserialize<'de> for Validate {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
container(d)
|
||||
}
|
||||
}
|
||||
|
||||
trait Container<'de>: Default {
|
||||
fn map<A: MapAccess<'de>>(mut map: A) -> Result<Self, A::Error> {
|
||||
while map.next_key::<serde::de::IgnoredAny>()?.is_some() {
|
||||
map.next_value::<Validate>()?;
|
||||
}
|
||||
Ok(Self::default())
|
||||
}
|
||||
fn seq<A: SeqAccess<'de>>(mut seq: A) -> Result<Self, A::Error> {
|
||||
while seq.next_element::<Validate>()?.is_some() {}
|
||||
Ok(Self::default())
|
||||
}
|
||||
}
|
||||
struct ContainerVisitor<T>(PhantomData<T>);
|
||||
impl<'de, T: Container<'de>> Visitor<'de> for ContainerVisitor<T> {
|
||||
type Value = T;
|
||||
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
f.write_str("JSON facts")
|
||||
}
|
||||
fn visit_map<A: MapAccess<'de>>(self, map: A) -> Result<T, A::Error> {
|
||||
T::map(map)
|
||||
}
|
||||
fn visit_seq<A: SeqAccess<'de>>(self, seq: A) -> Result<T, A::Error> {
|
||||
T::seq(seq)
|
||||
}
|
||||
fn visit_unit<E: serde::de::Error>(self) -> Result<T, E> {
|
||||
Ok(T::default())
|
||||
}
|
||||
fn visit_bool<E: serde::de::Error>(self, _: bool) -> Result<T, E> {
|
||||
Ok(T::default())
|
||||
}
|
||||
fn visit_i64<E: serde::de::Error>(self, _: i64) -> Result<T, E> {
|
||||
Ok(T::default())
|
||||
}
|
||||
fn visit_u64<E: serde::de::Error>(self, _: u64) -> Result<T, E> {
|
||||
Ok(T::default())
|
||||
}
|
||||
fn visit_f64<E: serde::de::Error>(self, _: f64) -> Result<T, E> {
|
||||
Ok(T::default())
|
||||
}
|
||||
fn visit_str<E: serde::de::Error>(self, _: &str) -> Result<T, E> {
|
||||
Ok(T::default())
|
||||
}
|
||||
}
|
||||
fn container<'de, D: Deserializer<'de>, T: Container<'de>>(d: D) -> Result<T, D::Error> {
|
||||
d.deserialize_any(ContainerVisitor(PhantomData))
|
||||
}
|
||||
macro_rules! read_field {
|
||||
($map:ident, typed) => {
|
||||
$map.next_value()?
|
||||
};
|
||||
($map:ident, value($convert:expr)) => {
|
||||
($convert)($map.next_value::<Value>()?)
|
||||
};
|
||||
}
|
||||
macro_rules! object {
|
||||
($name:ident<$life:lifetime> { $($field:ident: $ty:ty = $default:expr => $kind:ident $(($convert:expr))?),* $(,)? }) => {
|
||||
pub(super) struct $name<$life> {
|
||||
$(pub $field: $ty,)*
|
||||
marker: PhantomData<&$life ()>,
|
||||
}
|
||||
impl Default for $name<'_> {
|
||||
fn default() -> Self { Self { $($field: $default,)* marker: PhantomData } }
|
||||
}
|
||||
impl<$life> Container<$life> for $name<$life> {
|
||||
fn map<A: MapAccess<$life>>(mut map: A) -> Result<Self, A::Error> {
|
||||
#[derive(Deserialize)]
|
||||
#[allow(non_camel_case_types)]
|
||||
#[serde(field_identifier)]
|
||||
enum Field { $($field,)* #[serde(other)] Unknown }
|
||||
let mut result = Self::default();
|
||||
while let Some(field) = map.next_key::<Field>()? {
|
||||
match field {
|
||||
$(Field::$field => result.$field = read_field!(map, $kind $(($convert))?),)*
|
||||
Field::Unknown => { map.next_value::<Validate>()?; }
|
||||
}
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
impl<$life> Deserialize<$life> for $name<$life> {
|
||||
fn deserialize<D: Deserializer<$life>>(d: D) -> Result<Self, D::Error> { container(d) }
|
||||
}
|
||||
};
|
||||
}
|
||||
fn number(v: Value) -> f64 {
|
||||
v.as_f64().unwrap_or(0.0)
|
||||
}
|
||||
fn flag(v: Value) -> bool {
|
||||
v.as_bool().unwrap_or(false)
|
||||
}
|
||||
fn unsigned(v: Value) -> Option<u64> {
|
||||
v.as_u64()
|
||||
}
|
||||
fn text(v: Value) -> Option<String> {
|
||||
if let Value::String(s) = v {
|
||||
Some(s)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct Entries<'a>(pub Option<Vec<Entry<'a>>>);
|
||||
impl<'de> Container<'de> for Entries<'de> {
|
||||
fn seq<A: SeqAccess<'de>>(mut seq: A) -> Result<Self, A::Error> {
|
||||
let mut entries = Vec::new();
|
||||
while let Some(entry) = seq.next_element()? {
|
||||
entries.push(entry);
|
||||
}
|
||||
Ok(Self(Some(entries)))
|
||||
}
|
||||
}
|
||||
impl<'de> Deserialize<'de> for Entries<'de> {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
container(d)
|
||||
}
|
||||
}
|
||||
object!(Gameplay<'a> { states: Entries<'a> = Entries::default() => typed });
|
||||
object!(SoundId<'a> { id: Option<String> = None => value(text) });
|
||||
object!(Sound<'a> {
|
||||
volume: f64 = 1.0 => value(|v: Value| v.as_f64().unwrap_or(1.0)),
|
||||
pitch: f64 = 1.0 => value(|v: Value| v.as_f64().unwrap_or(1.0)),
|
||||
r#break: SoundId<'a> = SoundId::default() => typed,
|
||||
step: SoundId<'a> = SoundId::default() => typed,
|
||||
place: SoundId<'a> = SoundId::default() => typed,
|
||||
hit: SoundId<'a> = SoundId::default() => typed,
|
||||
fall: SoundId<'a> = SoundId::default() => typed,
|
||||
});
|
||||
object!(Entry<'a> {
|
||||
id: Option<u64> = None => value(unsigned),
|
||||
emission: f64 = 0.0 => value(number),
|
||||
dampening: f64 = 0.0 => value(number),
|
||||
skylight_down: bool = false => value(flag),
|
||||
shape_occlusion: bool = false => value(flag),
|
||||
can_occlude: bool = false => value(flag),
|
||||
solid_render: bool = false => value(flag),
|
||||
hardness: f64 = 0.0 => value(number),
|
||||
requires_tool: bool = false => value(flag),
|
||||
replaceable: bool = false => value(flag),
|
||||
random_ticks: bool = false => value(flag),
|
||||
block_entity: bool = false => value(flag),
|
||||
render_shape: Option<String> = None => value(text),
|
||||
full_collision: bool = false => value(flag),
|
||||
friction: f64 = 0.0 => value(number),
|
||||
explosion_resistance: f64 = 0.0 => value(number),
|
||||
item: Option<String> = None => value(text),
|
||||
sound: Sound<'a> = Sound::default() => typed,
|
||||
offset: bool = false => value(flag),
|
||||
outline_offset: Option<bool> = None => value(|v: Value| v.as_bool()),
|
||||
map_color: Option<u64> = None => value(unsigned),
|
||||
outline: Option<&'a RawValue> = None => typed,
|
||||
outline_edges: Option<&'a RawValue> = None => typed,
|
||||
});
|
||||
|
||||
// Match Value::to_string identity without serializing: integer/float spelling is
|
||||
// distinct, as is the sign of floating zero. Object keys are already sorted by Value.
|
||||
struct ShapeKey(Value);
|
||||
fn same(a: &Value, b: &Value) -> bool {
|
||||
match (a, b) {
|
||||
(Value::Number(a), Value::Number(b)) => {
|
||||
a == b && a.as_f64().map(f64::to_bits) == b.as_f64().map(f64::to_bits)
|
||||
}
|
||||
(Value::Array(a), Value::Array(b)) => {
|
||||
a.len() == b.len() && a.iter().zip(b).all(|(a, b)| same(a, b))
|
||||
}
|
||||
(Value::Object(a), Value::Object(b)) => {
|
||||
a.len() == b.len()
|
||||
&& a.iter()
|
||||
.zip(b)
|
||||
.all(|((ak, av), (bk, bv))| ak == bk && same(av, bv))
|
||||
}
|
||||
_ => a == b,
|
||||
}
|
||||
}
|
||||
impl PartialEq for ShapeKey {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
same(&self.0, &other.0)
|
||||
}
|
||||
}
|
||||
impl Eq for ShapeKey {}
|
||||
fn shape_hash<H: Hasher>(v: &Value, h: &mut H) {
|
||||
std::mem::discriminant(v).hash(h);
|
||||
match v {
|
||||
Value::Null => {}
|
||||
Value::Bool(b) => b.hash(h),
|
||||
Value::String(s) => s.hash(h),
|
||||
Value::Number(n) => {
|
||||
n.is_f64().hash(h);
|
||||
n.hash(h);
|
||||
n.as_f64().map(f64::to_bits).hash(h);
|
||||
}
|
||||
Value::Array(a) => {
|
||||
a.len().hash(h);
|
||||
for v in a {
|
||||
shape_hash(v, h);
|
||||
}
|
||||
}
|
||||
Value::Object(o) => {
|
||||
o.len().hash(h);
|
||||
for (k, v) in o {
|
||||
k.hash(h);
|
||||
shape_hash(v, h);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Hash for ShapeKey {
|
||||
fn hash<H: Hasher>(&self, h: &mut H) {
|
||||
shape_hash(&self.0, h);
|
||||
}
|
||||
}
|
||||
#[derive(Default)]
|
||||
pub(super) struct Shapes<'a> {
|
||||
raw: HashMap<&'a str, usize>,
|
||||
canonical: HashMap<ShapeKey, usize>,
|
||||
values: Vec<Arc<[[f64; 6]]>>,
|
||||
}
|
||||
impl<'a> Shapes<'a> {
|
||||
pub fn intern(
|
||||
&mut self,
|
||||
raw: Option<&'a RawValue>,
|
||||
fallback: impl FnOnce() -> Vec<[f64; 6]>,
|
||||
) -> crate::Result<Arc<[[f64; 6]]>> {
|
||||
let Some(raw) = raw else {
|
||||
return Ok(fallback().into());
|
||||
};
|
||||
if let Some(&id) = self.raw.get(raw.get()) {
|
||||
return Ok(self.values[id].clone());
|
||||
}
|
||||
let value: Value = serde_json::from_str(raw.get())?;
|
||||
if !value.is_array() {
|
||||
return Ok(fallback().into());
|
||||
}
|
||||
let id = match self.canonical.entry(ShapeKey(value)) {
|
||||
MapEntry::Occupied(entry) => *entry.get(),
|
||||
MapEntry::Vacant(entry) => {
|
||||
let shape = entry
|
||||
.key()
|
||||
.0
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter_map(|b| {
|
||||
let b = b.as_array()?;
|
||||
Some(std::array::from_fn(|i| {
|
||||
b.get(i).and_then(Value::as_f64).unwrap_or(0.0)
|
||||
}))
|
||||
})
|
||||
.collect::<Arc<[[f64; 6]]>>();
|
||||
let id = self.values.len();
|
||||
self.values.push(shape);
|
||||
entry.insert(id);
|
||||
id
|
||||
}
|
||||
};
|
||||
self.raw.insert(raw.get(), id);
|
||||
Ok(self.values[id].clone())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "decode_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,135 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn shape_identity_and_geometry_match_the_value_loader() -> crate::Result<()> {
|
||||
let inputs = [
|
||||
"[]",
|
||||
"[ ]",
|
||||
"[[0,0,0,1,1,1]]",
|
||||
"[ [0, 0, 0, 1, 1, 1] ]",
|
||||
"[[0.0,0,0,1,1,1]]",
|
||||
"[[0e0,0,0,1,1,1]]",
|
||||
"[[-0.0,0,0,1,1,1]]",
|
||||
"[[0,0,0,1,1,1,7]]",
|
||||
"[[0,0,0,1,1,1,8]]",
|
||||
"[[1,null,\"2\"],true,{}]",
|
||||
"[[1,null,\"\\u0032\"],true,{}]",
|
||||
"[{\"z\":0,\"a\":1}]",
|
||||
"[{\"a\":1,\"z\":0}]",
|
||||
"[[18446744073709551615,-9223372036854775808,1e20]]",
|
||||
"[{\"a\":2,\"a\":1,\"z\":0}]",
|
||||
];
|
||||
let values = inputs
|
||||
.iter()
|
||||
.map(|s| serde_json::from_str::<Value>(s))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
let mut shapes = Shapes::default();
|
||||
let actual = inputs
|
||||
.iter()
|
||||
.map(|s| {
|
||||
shapes.intern(Some(serde_json::from_str::<&RawValue>(s)?), || {
|
||||
panic!("array fallback")
|
||||
})
|
||||
})
|
||||
.collect::<crate::Result<Vec<_>>>()?;
|
||||
for (i, value) in values.iter().enumerate() {
|
||||
let expected: Vec<[f64; 6]> = value
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter_map(|b| {
|
||||
let b = b.as_array()?;
|
||||
Some(std::array::from_fn(|i| {
|
||||
b.get(i).and_then(Value::as_f64).unwrap_or(0.0)
|
||||
}))
|
||||
})
|
||||
.collect();
|
||||
// Bit comparisons include negative zero.
|
||||
assert_eq!(
|
||||
actual[i]
|
||||
.iter()
|
||||
.flatten()
|
||||
.map(|v| v.to_bits())
|
||||
.collect::<Vec<_>>(),
|
||||
expected
|
||||
.iter()
|
||||
.flatten()
|
||||
.map(|v| v.to_bits())
|
||||
.collect::<Vec<_>>()
|
||||
);
|
||||
for j in 0..values.len() {
|
||||
assert_eq!(
|
||||
Arc::ptr_eq(&actual[i], &actual[j]),
|
||||
value.to_string() == values[j].to_string(),
|
||||
"{i}, {j}"
|
||||
);
|
||||
}
|
||||
}
|
||||
for input in ["null", "false", "7", "{}", "\"shape\""] {
|
||||
let raw = serde_json::from_str(input)?;
|
||||
let a = shapes.intern(Some(raw), || vec![[7.0; 6]])?;
|
||||
let b = shapes.intern(Some(raw), || vec![[7.0; 6]])?;
|
||||
assert_eq!(&*a, &[[7.0; 6]]);
|
||||
assert!(!Arc::ptr_eq(&a, &b)); // Fallbacks were never interned.
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_fields_keep_defaults_duplicates_and_wrong_type_behavior() -> crate::Result<()> {
|
||||
let input = r#"{"states":[null,[],{"id":0,"id":2,"emission":4.5,"dampening":"15",
|
||||
"hardness":-0.0,"skylight_down":true,"offset":true,"outline_offset":"true",
|
||||
"item":42,"render_shape":false,"sound":{"volume":null,"pitch":2,"break":{"id":"a\u0062"},
|
||||
"step":false,"hit":{"id":2}},"outline":[[0,1]],"unknown":{"nested":true}}]}"#;
|
||||
let parsed: Gameplay<'_> = serde_json::from_str(input)?;
|
||||
let entries = parsed.states.0.unwrap();
|
||||
assert_eq!(entries[0].id, None);
|
||||
assert_eq!(entries[1].id, None);
|
||||
let e = &entries[2];
|
||||
assert_eq!(e.id, Some(2));
|
||||
assert_eq!(e.emission, 4.5);
|
||||
assert_eq!(e.dampening, 0.0);
|
||||
assert_eq!(e.hardness.to_bits(), (-0.0f64).to_bits());
|
||||
assert!(e.skylight_down && e.outline_offset.unwrap_or(e.offset));
|
||||
assert_eq!(e.item, None);
|
||||
assert_eq!(e.render_shape, None);
|
||||
assert_eq!((e.sound.volume, e.sound.pitch), (1.0, 2.0));
|
||||
assert_eq!(e.sound.r#break.id.as_deref(), Some("ab"));
|
||||
assert_eq!(e.sound.step.id, None);
|
||||
assert_eq!(e.sound.hit.id, None);
|
||||
assert_eq!(e.outline.unwrap().get(), "[[0,1]]");
|
||||
for input in ["null", "[]", "{}", r#"{"states":null}"#, r#"{"states":{}}"#] {
|
||||
let parsed: Gameplay<'_> = serde_json::from_str(input)?;
|
||||
assert!(parsed.states.0.is_none());
|
||||
}
|
||||
for input in [
|
||||
r#"{"states":["#,
|
||||
r#"{"states":[{"id":1e400}]}"#,
|
||||
"{} trailing",
|
||||
r#"{"unknown":1e400}"#,
|
||||
] {
|
||||
let before = serde_json::from_str::<Value>(input).err().unwrap();
|
||||
let after = serde_json::from_str::<Gameplay<'_>>(input).err().unwrap();
|
||||
assert_eq!(before.classify(), after.classify());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raw_shape_capture_keeps_original_json_errors() {
|
||||
let deep = format!("{}0{}", "[".repeat(130), "]".repeat(130));
|
||||
let inputs = [
|
||||
br#"{"states":[{"outline":[[1e400]],"outline":[]}]}"#.to_vec(),
|
||||
format!("{{\"states\":[{{\"outline\":{deep}}}]}}").into_bytes(),
|
||||
br#"{"states":[{"outline":[[0]]}]} trailing"#.to_vec(),
|
||||
b"{\"states\":[{\"outline\":[[\"\xff\"]]}]}".to_vec(),
|
||||
];
|
||||
for input in inputs {
|
||||
let old = serde_json::from_slice::<Value>(&input).err().unwrap();
|
||||
let new = serde_json::from_slice::<Validate>(&input).err().unwrap();
|
||||
assert_eq!(
|
||||
(old.classify(), old.line(), old.column()),
|
||||
(new.classify(), new.line(), new.column())
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user