Skip to main content

harn_vm/value/
structural.rs

1use std::rc::Rc;
2use std::sync::atomic::Ordering;
3
4use super::VmValue;
5
6/// Reference / identity equality. For heap-allocated refcounted values
7/// (List/Dict/Set/Closure) returns true only when both operands share the
8/// same underlying `Rc` allocation. For primitive scalars, falls back to
9/// structural equality (since primitives have no distinct identity).
10pub fn values_identical(a: &VmValue, b: &VmValue) -> bool {
11    match (a, b) {
12        (VmValue::List(x), VmValue::List(y)) => Rc::ptr_eq(x, y),
13        (VmValue::Dict(x), VmValue::Dict(y)) => Rc::ptr_eq(x, y),
14        (VmValue::Set(x), VmValue::Set(y)) => Rc::ptr_eq(x, y),
15        (VmValue::Closure(x), VmValue::Closure(y)) => Rc::ptr_eq(x, y),
16        (VmValue::String(x), VmValue::String(y)) => Rc::ptr_eq(x, y) || x == y,
17        (VmValue::Bytes(x), VmValue::Bytes(y)) => Rc::ptr_eq(x, y) || x == y,
18        (VmValue::BuiltinRef(x), VmValue::BuiltinRef(y)) => x == y,
19        (VmValue::BuiltinRefId { name: x, .. }, VmValue::BuiltinRefId { name: y, .. }) => x == y,
20        (VmValue::BuiltinRef(x), VmValue::BuiltinRefId { name: y, .. })
21        | (VmValue::BuiltinRefId { name: y, .. }, VmValue::BuiltinRef(x)) => x == y,
22        (VmValue::Pair(x), VmValue::Pair(y)) => Rc::ptr_eq(x, y),
23        // Primitives: identity collapses to structural equality.
24        _ => values_equal(a, b),
25    }
26}
27
28/// Stable identity key for a value. Different allocations produce different
29/// keys; two values with the same heap identity produce the same key. For
30/// primitives the key is derived from the displayed value plus type name so
31/// logically-equal primitives always compare equal.
32pub fn value_identity_key(v: &VmValue) -> String {
33    match v {
34        VmValue::List(x) => format!("list@{:p}", Rc::as_ptr(x)),
35        VmValue::Dict(x) => format!("dict@{:p}", Rc::as_ptr(x)),
36        VmValue::Set(x) => format!("set@{:p}", Rc::as_ptr(x)),
37        VmValue::Closure(x) => format!("closure@{:p}", Rc::as_ptr(x)),
38        VmValue::String(x) => format!("string@{:p}", x.as_ptr()),
39        VmValue::Bytes(x) => format!("bytes@{:p}", Rc::as_ptr(x)),
40        VmValue::BuiltinRef(name) => format!("builtin@{name}"),
41        VmValue::BuiltinRefId { name, .. } => format!("builtin@{name}"),
42        other => format!("{}@{}", other.type_name(), other.display()),
43    }
44}
45
46/// Canonical string form used as the keying material for `hash_value`.
47/// Different types never collide (the type name is prepended) and collection
48/// order is preserved so structurally-equal values always produce the same
49/// key. Not intended for cross-process stability; depends on the in-process
50/// iteration order for collections (Dict uses BTreeMap so keys are sorted).
51pub fn value_structural_hash_key(v: &VmValue) -> String {
52    let mut out = String::new();
53    write_structural_hash_key(v, &mut out);
54    out
55}
56
57/// Writes the structural hash key for a value directly into `out`,
58/// avoiding intermediate allocations. Uses length-prefixed encoding
59/// for strings and dict keys to prevent separator collisions.
60fn write_structural_hash_key(v: &VmValue, out: &mut String) {
61    match v {
62        VmValue::Nil => out.push('N'),
63        VmValue::Bool(b) => {
64            out.push(if *b { 'T' } else { 'F' });
65        }
66        VmValue::Int(n) => {
67            out.push('i');
68            out.push_str(&n.to_string());
69            out.push(';');
70        }
71        VmValue::Float(n) => {
72            out.push('f');
73            out.push_str(&n.to_bits().to_string());
74            out.push(';');
75        }
76        VmValue::String(s) => {
77            // Length-prefixed: s<len>:<content> — no ambiguity from content
78            out.push('s');
79            out.push_str(&s.len().to_string());
80            out.push(':');
81            out.push_str(s);
82        }
83        VmValue::Bytes(bytes) => {
84            out.push('b');
85            for byte in bytes.iter() {
86                out.push_str(&format!("{byte:02x}"));
87            }
88            out.push(';');
89        }
90        VmValue::Duration(ms) => {
91            out.push('d');
92            out.push_str(&ms.to_string());
93            out.push(';');
94        }
95        VmValue::List(items) => {
96            out.push('L');
97            for item in items.iter() {
98                write_structural_hash_key(item, out);
99                out.push(',');
100            }
101            out.push(']');
102        }
103        VmValue::Dict(map) => {
104            out.push('D');
105            for (k, v) in map.iter() {
106                // Length-prefixed key
107                out.push_str(&k.len().to_string());
108                out.push(':');
109                out.push_str(k);
110                out.push('=');
111                write_structural_hash_key(v, out);
112                out.push(',');
113            }
114            out.push('}');
115        }
116        VmValue::Set(items) => {
117            // Sets need sorted keys for order-independence
118            let mut keys: Vec<String> = items.iter().map(value_structural_hash_key).collect();
119            keys.sort();
120            out.push('S');
121            for k in &keys {
122                out.push_str(k);
123                out.push(',');
124            }
125            out.push('}');
126        }
127        other => {
128            let tn = other.type_name();
129            out.push('o');
130            out.push_str(&tn.len().to_string());
131            out.push(':');
132            out.push_str(tn);
133            let d = other.display();
134            out.push_str(&d.len().to_string());
135            out.push(':');
136            out.push_str(&d);
137        }
138    }
139}
140
141pub fn values_equal(a: &VmValue, b: &VmValue) -> bool {
142    match (a, b) {
143        (VmValue::Int(x), VmValue::Int(y)) => x == y,
144        (VmValue::Float(x), VmValue::Float(y)) => x == y,
145        (VmValue::String(x), VmValue::String(y)) => x == y,
146        (VmValue::Bytes(x), VmValue::Bytes(y)) => x == y,
147        (VmValue::BuiltinRef(x), VmValue::BuiltinRef(y)) => x == y,
148        (VmValue::BuiltinRefId { name: x, .. }, VmValue::BuiltinRefId { name: y, .. }) => x == y,
149        (VmValue::BuiltinRef(x), VmValue::BuiltinRefId { name: y, .. })
150        | (VmValue::BuiltinRefId { name: y, .. }, VmValue::BuiltinRef(x)) => x == y,
151        (VmValue::Bool(x), VmValue::Bool(y)) => x == y,
152        (VmValue::Nil, VmValue::Nil) => true,
153        (VmValue::Int(x), VmValue::Float(y)) => (*x as f64) == *y,
154        (VmValue::Float(x), VmValue::Int(y)) => *x == (*y as f64),
155        (VmValue::TaskHandle(a), VmValue::TaskHandle(b)) => a == b,
156        (VmValue::Channel(_), VmValue::Channel(_)) => false, // channels are never equal
157        (VmValue::Atomic(a), VmValue::Atomic(b)) => {
158            a.value.load(Ordering::SeqCst) == b.value.load(Ordering::SeqCst)
159        }
160        (VmValue::List(a), VmValue::List(b)) => {
161            a.len() == b.len() && a.iter().zip(b.iter()).all(|(x, y)| values_equal(x, y))
162        }
163        (VmValue::Dict(a), VmValue::Dict(b)) => {
164            a.len() == b.len()
165                && a.iter()
166                    .zip(b.iter())
167                    .all(|((k1, v1), (k2, v2))| k1 == k2 && values_equal(v1, v2))
168        }
169        (
170            VmValue::EnumVariant {
171                enum_name: a_e,
172                variant: a_v,
173                fields: a_f,
174            },
175            VmValue::EnumVariant {
176                enum_name: b_e,
177                variant: b_v,
178                fields: b_f,
179            },
180        ) => {
181            a_e == b_e
182                && a_v == b_v
183                && a_f.len() == b_f.len()
184                && a_f.iter().zip(b_f.iter()).all(|(x, y)| values_equal(x, y))
185        }
186        (
187            VmValue::StructInstance {
188                layout: a_layout,
189                fields: a_fields,
190            },
191            VmValue::StructInstance {
192                layout: b_layout,
193                fields: b_fields,
194            },
195        ) => {
196            if a_layout.struct_name() != b_layout.struct_name() {
197                return false;
198            }
199            let a_map = super::struct_fields_to_map(a_layout, a_fields);
200            let b_map = super::struct_fields_to_map(b_layout, b_fields);
201            a_map.len() == b_map.len()
202                && a_map
203                    .iter()
204                    .zip(b_map.iter())
205                    .all(|((k1, v1), (k2, v2))| k1 == k2 && values_equal(v1, v2))
206        }
207        (VmValue::Set(a), VmValue::Set(b)) => {
208            a.len() == b.len() && a.iter().all(|x| b.iter().any(|y| values_equal(x, y)))
209        }
210        (VmValue::Generator(_), VmValue::Generator(_)) => false, // generators are never equal
211        (VmValue::Range(a), VmValue::Range(b)) => {
212            a.start == b.start && a.end == b.end && a.inclusive == b.inclusive
213        }
214        (VmValue::Iter(a), VmValue::Iter(b)) => Rc::ptr_eq(a, b),
215        (VmValue::Pair(a), VmValue::Pair(b)) => {
216            values_equal(&a.0, &b.0) && values_equal(&a.1, &b.1)
217        }
218        _ => false,
219    }
220}
221
222pub fn compare_values(a: &VmValue, b: &VmValue) -> i32 {
223    match (a, b) {
224        (VmValue::Int(x), VmValue::Int(y)) => x.cmp(y) as i32,
225        (VmValue::Float(x), VmValue::Float(y)) => {
226            if x < y {
227                -1
228            } else if x > y {
229                1
230            } else {
231                0
232            }
233        }
234        (VmValue::Int(x), VmValue::Float(y)) => {
235            let x = *x as f64;
236            if x < *y {
237                -1
238            } else if x > *y {
239                1
240            } else {
241                0
242            }
243        }
244        (VmValue::Float(x), VmValue::Int(y)) => {
245            let y = *y as f64;
246            if *x < y {
247                -1
248            } else if *x > y {
249                1
250            } else {
251                0
252            }
253        }
254        (VmValue::String(x), VmValue::String(y)) => x.cmp(y) as i32,
255        (VmValue::Pair(x), VmValue::Pair(y)) => {
256            let c = compare_values(&x.0, &y.0);
257            if c != 0 {
258                c
259            } else {
260                compare_values(&x.1, &y.1)
261            }
262        }
263        _ => 0,
264    }
265}