Skip to main content

ccxt_base/
value.rs

1// Native Rust – hand-written Value type.
2//
3// The ast-transpiler emits `Value::Map(...)`, `Value::Str(...)`, etc.
4// This module defines those variants so generated code compiles without
5// requiring serde_json macros in every file.
6//
7// At the HTTP boundary (exchange.rs) we convert between Value and
8// serde_json::Value for serialisation / deserialisation.
9
10// Value::Map uses `IndexMap` (re-exported here as `HashMap` so the rest
11// of the codebase — including transpiler-emitted `std::collections::
12// HashMap::new()` calls swapped to `indexmap::IndexMap::new()` by a
13// post-pass — keeps building literals via the same API). Insertion
14// order matters for JSON / URL-encoded payloads: exchanges like bingx /
15// digifinex / mexc reject (and the static request fixtures assert)
16// specific key orders such as `{symbol,type,side,quantity,price}`.
17pub use indexmap::IndexMap as HashMap;
18use std::sync::Arc;
19#[cfg(feature = "transpiled-base")]
20use crate::exchange_generated::ExchangeBase;
21
22/// A dynamic value type that mirrors the CCXT JavaScript Value semantics.
23///
24/// `Dict`/`Arr` hold their containers behind an `Arc` so that `clone()` is
25/// an O(1) refcount bump instead of a deep copy — the transpiled parsers
26/// and the static-test assertions clone Values pervasively (every
27/// `safeString`/`safeNumber`, every recursion level), which dominated
28/// runtime. Mutation goes through `Arc::make_mut` (copy-on-write): it
29/// only deep-copies when the container is actually shared.
30///
31/// NOTE: the variants are named `Dict`/`Arr`, but construction uses the
32/// associated functions `Value::Map(..)` / `Value::Array(..)` /
33/// `Value::List(..)` (which wrap the `Arc`) so the ~18k transpiler-emitted
34/// `Value::Map({..})` / `Value::List(vec![..])` call sites need no change.
35/// Pattern matches use `Value::Dict(..)` / `Value::Arr(..)`.
36#[derive(Debug, Clone, PartialEq)]
37pub enum Value {
38    Null,
39    Bool(bool),
40    Int(i64),
41    Float(f64),
42    Str(String),
43    Dict(Arc<HashMap<String, Value>>),
44    Arr(Arc<Vec<Value>>),
45}
46
47impl Default for Value {
48    fn default() -> Self {
49        Value::Null
50    }
51}
52
53impl Value {
54    /// Mirrors TS `Precise.reduce()`: when this Value is a
55    /// `Precise::new(...)` Map (carries the `__precise` marker), strip
56    /// trailing zeros from `integer` and bump `decimals` down to match.
57    /// Used by phemex's `to_en` after it shifts `decimals` by the
58    /// market's `valueScale`: subtracts decimals, then reduce balances
59    /// the integer side so the final `stringify_param` renders the
60    /// scaled integer correctly (`0.1` × 10^8 → `10000000`).
61    pub fn reduce(&mut self) {
62        let m = match self { Value::Dict(m) if m.contains_key("__precise") => Arc::make_mut(m), _ => return };
63        let mut decimals: i64 = match m.get("decimals") {
64            Some(Value::Int(n)) => *n,
65            _ => return,
66        };
67        let mut integer: String = match m.get("integer") {
68            Some(Value::Str(s)) => s.clone(),
69            _ => return,
70        };
71        // Negative decimals → pad zeros onto the integer.
72        if decimals < 0 {
73            // careful: a leading '-' (negative number) stays at the front.
74            let (sign, digits) = if let Some(rest) = integer.strip_prefix('-') {
75                ("-", rest.to_string())
76            } else { ("", integer.clone()) };
77            let padded = format!("{digits}{:0<width$}", "", width = (-decimals) as usize);
78            integer = format!("{sign}{padded}");
79            decimals = 0;
80        }
81        // Trim trailing zeros while there are decimal places to consume.
82        while decimals > 0 && integer.ends_with('0') && integer.len() > 1 {
83            integer.pop();
84            decimals -= 1;
85        }
86        m.insert("integer".to_string(),  Value::Str(integer));
87        m.insert("decimals".to_string(), Value::Int(decimals));
88    }
89
90    /// `append(item)` on an Array — pushes the item. Mirrors TS
91    /// `array.push` shape (single arg, no return).
92    ///
93    /// On a WS-cache Map (carrying a `__cacheKind` marker; see
94    /// `crate::pro::cache`) it dispatches to the per-kind logic below.
95    pub fn append(&mut self, item: Value) {
96        match self {
97            Value::Arr(a) => Arc::make_mut(a).push(item),
98            Value::Dict(m) if m.contains_key("__cacheKind") => {
99                cache_append(self, item);
100            }
101            _ => {}
102        }
103    }
104
105    /// `clear()` — resets the rolling buffer for a cache marker (or
106    /// truncates the inner array of an `Arr` value).
107    pub fn clear(&mut self) {
108        match self {
109            Value::Arr(a) => Arc::make_mut(a).clear(),
110            Value::Dict(m) if m.contains_key("__cacheKind") => {
111                if let Some(id) = cache_id_of_m(m) {
112                    with_cache_cell(id, |c| {
113                        if let Some(Value::Arr(data)) = c.get_mut("_data") { Arc::make_mut(data).clear(); }
114                        cache_reset_bookkeeping(c);
115                    });
116                } else {
117                    let m = Arc::make_mut(m);
118                    if let Some(Value::Arr(data)) = m.get_mut("_data") {
119                        Arc::make_mut(data).clear();
120                    }
121                    cache_reset_bookkeeping(m);
122                }
123            }
124            _ => {}
125        }
126    }
127
128    /// `getLimit(symbol, limit)` for the cache markers. Returns the
129    /// count of new updates since the last call (clamped by `limit`
130    /// when supplied) and arms the per-symbol / global reset flag so
131    /// the next `append` zeroes the counter.
132    pub fn get_limit(&mut self, symbol: Value, limit: Value) -> Value {
133        if matches!(self, Value::Dict(d) if d.contains_key("__cacheKind")) {
134            cache_get_limit(self, symbol, limit)
135        } else {
136            limit
137        }
138    }
139
140    /// Constructor named to match the ast-transpiler's emission shape:
141    /// `Value::List(vec![...])`. Aliases `Value::Array`. Note that this
142    /// is a function, not a variant — so pattern matches still use
143    /// `Value::Array(_)`, not `Value::List(_)`.
144    #[allow(non_snake_case)]
145    pub fn List(items: Vec<Value>) -> Value {
146        Value::Arr(Arc::new(items))
147    }
148
149    /// Construction shim — the transpiler emits `Value::Map({..IndexMap..})`
150    /// in ~18k places; this wraps the map in the `Arc` the `Dict` variant
151    /// now holds. (An associated fn, not a variant — patterns use `Dict`.)
152    #[allow(non_snake_case)]
153    pub fn Map(m: HashMap<String, Value>) -> Value {
154        Value::Dict(Arc::new(m))
155    }
156
157    /// Construction shim for `Value::Array(vec)` call sites.
158    #[allow(non_snake_case)]
159    pub fn Array(a: Vec<Value>) -> Value {
160        Value::Arr(Arc::new(a))
161    }
162
163    // ── constructors ──────────────────────────────────────────────────────────
164
165    pub fn str(s: impl Into<String>) -> Self {
166        Value::Str(s.into())
167    }
168
169    pub fn int(n: i64) -> Self {
170        Value::Int(n)
171    }
172
173    pub fn float(f: f64) -> Self {
174        Value::Float(f)
175    }
176
177    pub fn bool(b: bool) -> Self {
178        Value::Bool(b)
179    }
180
181    pub fn map(m: HashMap<String, Value>) -> Self {
182        Value::Map(m)
183    }
184
185    pub fn array(a: Vec<Value>) -> Self {
186        Value::Array(a)
187    }
188
189    // ── type checks ───────────────────────────────────────────────────────────
190
191    pub fn is_null(&self)   -> bool { matches!(self, Value::Null) }
192    pub fn is_str(&self)    -> bool { matches!(self, Value::Str(_)) }
193    pub fn is_int(&self)    -> bool { matches!(self, Value::Int(_)) }
194    pub fn is_float(&self)  -> bool { matches!(self, Value::Float(_)) }
195    pub fn is_number(&self) -> bool { matches!(self, Value::Int(_) | Value::Float(_)) }
196    pub fn is_bool(&self)   -> bool { matches!(self, Value::Bool(_)) }
197    pub fn is_map(&self)    -> bool { matches!(self, Value::Dict(_)) }
198    pub fn is_array(&self)  -> bool { matches!(self, Value::Arr(_)) }
199    pub fn is_truthy(&self) -> bool {
200        match self {
201            Value::Null       => false,
202            Value::Bool(b)    => *b,
203            Value::Int(n)     => *n != 0,
204            Value::Float(f)   => *f != 0.0,
205            Value::Str(s)     => !s.is_empty(),
206            Value::Dict(m)    => !m.is_empty(),
207            Value::Arr(a)     => !a.is_empty(),
208        }
209    }
210
211    // ── accessors ─────────────────────────────────────────────────────────────
212
213    pub fn as_str(&self)   -> Option<&str>  { if let Value::Str(s) = self { Some(s) } else { None } }
214    pub fn as_i64(&self)   -> Option<i64>   { if let Value::Int(n) = self { Some(*n) } else { None } }
215    pub fn as_f64(&self)   -> Option<f64> {
216        match self {
217            Value::Float(f) => Some(*f),
218            Value::Int(n)   => Some(*n as f64),
219            _               => None,
220        }
221    }
222    pub fn as_bool(&self)  -> Option<bool>  { if let Value::Bool(b) = self { Some(*b) } else { None } }
223    pub fn as_map(&self)   -> Option<&HashMap<String, Value>> {
224        if let Value::Dict(m) = self { Some(&**m) } else { None }
225    }
226    pub fn as_array(&self) -> Option<&Vec<Value>> {
227        if let Value::Arr(a) = self { Some(&**a) } else { None }
228    }
229
230    /// Length of array, map, or string; 0 for everything else.
231    /// String length counts Unicode chars (matches TS `String#length`
232    /// closely enough for ASCII-only API addresses/identifiers).
233    pub fn len(&self) -> usize {
234        match self {
235            Value::Arr(a)   => a.len(),
236            Value::Dict(m)  => m.len(),
237            Value::Str(s)   => s.chars().count(),
238            _               => 0,
239        }
240    }
241
242    pub fn is_empty(&self) -> bool { self.len() == 0 }
243
244    // ── duck-typed method stubs that transpiled code calls on a Value ────
245    // These exist so transpiled code that calls methods on Value-typed
246    // locals (e.g. `parentRestInstance.describe()`) compiles. They return
247    // `Value::Null` and are placeholders for richer dispatch.
248
249    pub fn describe(&self) -> Value { Value::Null }
250    /// `client.reject(error, messageHash)` — stores a rejection the `watch`
251    /// drive loop delivers to the awaiting caller. Routes by the client
252    /// handle's `url` to the WS registry (no-op on a non-client Value).
253    pub fn reject(&self, args: &[Value]) -> Value {
254        crate::pro::ws_client::value_reject(self, args)
255    }
256    /// `client.resolve(value, messageHash)` — stores the resolved value the
257    /// `watch` drive loop returns. Routes by the client handle's `url`.
258    pub fn resolve(&self, args: &[Value]) -> Value {
259        crate::pro::ws_client::value_resolve(self, args)
260    }
261    /// `client.future(messageHash)` — TS's atomic check-and-insert: opens a
262    /// single-flight for the hash (or joins the open one) and hands back a
263    /// handle. Registering is the whole point — it is what makes a concurrent
264    /// caller's `messageHash in client.futures` test true, so only one of them
265    /// does the work (venue `authenticate` leader election). Await the handle
266    /// with `exchange_stubs::ws_await_flight`; the transpiler emits that
267    /// wherever the TS source awaits.
268    pub fn future(&self, args: &[Value]) -> Value {
269        self.open_flight(args.get(0).cloned().unwrap_or(Value::Null))
270    }
271    /// `client.reusable_future(messageHash)` — shared flight per hash, i.e. the
272    /// same registry and handle as `future`.
273    pub fn reusable_future(&self, msg_hash: Value) -> Value {
274        self.open_flight(msg_hash)
275    }
276    /// Shared body of `future` / `reusable_future`: open-or-join the flight on
277    /// the client this handle names, and return a handle to it. A non-client
278    /// receiver (or a non-string hash) degrades to the old pass-the-hash-back
279    /// behaviour so unrelated transpiled code keeps compiling.
280    fn open_flight(&self, msg_hash: Value) -> Value {
281        let hash = match &msg_hash {
282            Value::Str(h) => h.clone(),
283            _ => return msg_hash,
284        };
285        match crate::pro::ws_client::url_of(self) {
286            Some(url) => {
287                let led = crate::pro::ws_client::begin_flight(&url, &hash);
288                crate::pro::ws_client::flight_handle(&url, &hash, led)
289            }
290            None => msg_hash,
291        }
292    }
293    /// Field accessor: `cache.hashmap` — same as the WS Cache marker's
294    /// hashmap sub-dict. Some transpiled WS code reads this directly
295    /// via the JS field-access syntax rather than going through
296    /// `get_value`.
297    pub fn hashmap(&self) -> Value {
298        if let Value::Dict(d) = self {
299            // Cache marker: the live hashmap lives in the shared CACHE_STORE
300            // (keyed by __cache_id), not on the marker Dict. Return a copy with
301            // each symbol bucket tagged with a `__cache_backref` so that a
302            // transpiled write-back like `cache.hashmap[symbol][id] = order`
303            // (the JS reference write) persists through to the store — see
304            // try_cache_hashmap_write.
305            if let Some(id) = cache_id_of(self) {
306                let hm = with_cache_cell(id, |m| m.get("hashmap").cloned().unwrap_or(Value::Null));
307                return tag_cache_hashmap_buckets(hm, id);
308            }
309            if let Some(v) = d.get("hashmap") { return v.clone(); }
310        }
311        Value::Null
312    }
313    /// `client.send(payload)` — queues a frame on the WS connection (routed by
314    /// the client handle's `url`). No-op on a non-client Value.
315    pub fn send(&self, args: &[Value]) -> Value {
316        crate::pro::ws_client::value_send(self, args)
317    }
318    /// `client.decode_proto_msg(...)` — exchange-specific protobuf
319    /// decode helper; stubbed to `Value::Null`.
320    pub fn decode_proto_msg(&self, _args: &[Value]) -> Value { Value::Null }
321    /// `client.on_pong(...)` — WS heartbeat hook; records the pong time.
322    pub fn on_pong(&self, _args: &[Value]) -> Value {
323        crate::pro::ws_client::value_on_pong(self)
324    }
325    /// WS stub — transpiled `fn(...args)` over a Value-typed callable.
326    pub fn call(&self, _args: &[Value]) -> Value { Value::Null }
327    /// `exchange.isDictionary(value)` — transpiled tests treat `exchange`
328    /// as `Value` instead of the typed `Exchange`, so we mirror the
329    /// dict-typecheck method here.
330    pub fn is_dictionary(&self, value: Value) -> Value {
331        Value::Bool(matches!(value, Value::Dict(_)))
332    }
333    /// Lifts this snapshot's `options` + `currencies` onto a throwaway base
334    /// `Exchange` so the *transpiled* conversion methods can run against it.
335    /// The afterConstruct test transpiles its call sites with `exchange:
336    /// Value`, so these methods have to exist on `Value` — but the logic
337    /// must stay in the transpiled base, not be duplicated here.
338    #[cfg(feature = "transpiled-base")]
339    fn snapshot_as_exchange(&self) -> crate::exchange::Exchange {
340        let mut ex = crate::exchange::Exchange::new(None);
341        ex.options = crate::runtime::get_value(self, &Value::Str("options".to_string()));
342        ex.currencies = crate::runtime::get_value(self, &Value::Str("currencies".to_string()));
343        ex
344    }
345
346    /// `exchange.networkCodeToId(code, currency)` on a snapshot `Value` —
347    /// delegates to the transpiled `Exchange::network_code_to_id`.
348    pub fn network_code_to_id(&self, code: Value, args: &[Value]) -> Value {
349        #[cfg(feature = "transpiled-base")]
350        {
351            let currency = args.first().cloned().unwrap_or(Value::Null);
352            return crate::exchange::BaseCore::new(self.snapshot_as_exchange()).network_code_to_id(code, &[currency]);
353        }
354        #[cfg(not(feature = "transpiled-base"))]
355        {
356            let _ = args;
357            code
358        }
359    }
360
361    /// `exchange.networkIdToCode(networkId, currency)` on a snapshot `Value`
362    /// — delegates to the transpiled `Exchange::network_id_to_code`.
363    pub fn network_id_to_code(&self, args: &[Value]) -> Value {
364        #[cfg(feature = "transpiled-base")]
365        {
366            return crate::exchange::BaseCore::new(self.snapshot_as_exchange()).network_id_to_code(args);
367        }
368        #[cfg(not(feature = "transpiled-base"))]
369        {
370            let _ = args;
371            Value::Null
372        }
373    }
374
375    /// `exchange.extend(a, b, ...)` on a snapshot `Value` — CCXT's shallow
376    /// object merge. Pure (ignores exchange state), so it delegates to the
377    /// transpiled `Exchange::extend`. Used by the (prediction-aware) transpiled
378    /// test harness, where `exchange` is a dynamic `Value` handle.
379    pub fn extend(&self, a: Value, args: &[Value]) -> Value {
380        #[cfg(feature = "transpiled-base")]
381        {
382            return self.snapshot_as_exchange().extend(a, args);
383        }
384        #[cfg(not(feature = "transpiled-base"))]
385        {
386            let _ = args;
387            a
388        }
389    }
390
391    /// `exchange.setMarkets(markets)` on a snapshot `Value` — used by the
392    /// prediction test harness to seed event-derived markets. Delegates the
393    /// indexing to the transpiled `Exchange::set_markets`, then writes the
394    /// computed `markets`/`markets_by_id`/`symbols` back onto the `Value`
395    /// handle so later `get_value(exchange, "markets")` reads see them.
396    pub fn set_markets(&mut self, markets: Value) -> Value {
397        #[cfg(feature = "transpiled-base")]
398        {
399            // If this snapshot is backed by a live Core (`__live_id`), route to
400            // it so the Core's own `set_markets` runs — for a prediction venue
401            // that's `PredictionExchange::set_markets` (outcome→symbol aliasing +
402            // populateOutcomes), populating the outcome caches on the very
403            // instance the method dispatch uses. Without this, the prediction
404            // static request tests seed markets onto a throwaway snapshot and the
405            // live Core resolves every outcome by (re)fetching events.
406            if let Value::Dict(m) = &*self {
407                if let Some(Value::Str(id)) = m.get("__live_id") {
408                    if let Some(cb) = live_set_markets_get() {
409                        return cb(&id.clone(), markets);
410                    }
411                }
412            }
413            let mut ex = crate::exchange::BaseCore::new(self.snapshot_as_exchange());
414            let result = ex.set_markets(markets, &[]);
415            crate::runtime::add_element_to_object(self, &Value::Str("markets".to_string()), ex.markets.clone());
416            crate::runtime::add_element_to_object(self, &Value::Str("markets_by_id".to_string()), ex.markets_by_id.clone());
417            crate::runtime::add_element_to_object(self, &Value::Str("symbols".to_string()), ex.symbols.clone());
418            return result;
419        }
420        #[cfg(not(feature = "transpiled-base"))]
421        {
422            let _ = markets;
423            Value::Null
424        }
425    }
426    /// `side.storeArray(delta)` — insert/update/delete by price (or
427    /// by id for the indexed variant). Defined here (rather than next
428    /// to `store`) so that derived exchange code which calls
429    /// `Value::store_array` on a non-side Value still compiles as a
430    /// no-op.
431    pub fn store_array(&mut self, delta: Value) {
432        if side_kind(self).is_some() { side_store_array(self, delta); }
433    }
434    pub fn append_to_array(&self, _v: Value) {}
435
436    // ── conversion to / from serde_json ───────────────────────────────────────
437
438    pub fn to_json(&self) -> serde_json::Value {
439        match self {
440            Value::Null        => serde_json::Value::Null,
441            Value::Bool(b)     => serde_json::Value::Bool(*b),
442            Value::Int(n)      => serde_json::json!(*n),
443            Value::Float(f)    => serde_json::json!(*f),
444            Value::Str(s)      => serde_json::Value::String(s.clone()),
445            Value::Arr(a)      => serde_json::Value::Array(a.iter().map(Value::to_json).collect()),
446            Value::Dict(m)     => {
447                // A side marker keeps its entries in the shared side store —
448                // serialize as the plain `[[price, amount], …]` array (CCXT's
449                // orderbook.bids/asks shape), matching jsonStringify(orderbook)
450                // in the other languages rather than exposing the internal side
451                // struct. The WS deep-compare unwraps markers itself, so it's
452                // unaffected.
453                if m.contains_key("__side_id") {
454                    let entries = side_entries_view(m);
455                    return serde_json::Value::Array(entries.iter().map(Value::to_json).collect());
456                }
457                // A shared book keeps its scalar meta (nonce/timestamp/…) in the
458                // book store and tags itself with internal markers — drop the
459                // markers and surface the meta so the serialized book is the
460                // clean { bids, asks, timestamp, datetime, nonce, symbol } form.
461                let is_book = m.contains_key("__book_id") || m.contains_key("__bookKind");
462                let mut obj = serde_json::Map::new();
463                for (k, v) in m.iter() {
464                    if is_book && matches!(k.as_str(), "__bookKind" | "__book_id" | "_depth") {
465                        continue;
466                    }
467                    obj.insert(k.clone(), v.to_json());
468                }
469                if let Some(Value::Int(id)) = m.get("__book_id") {
470                    for (k, v) in book_meta_snapshot(*id) { obj.insert(k, v.to_json()); }
471                }
472                // A cache marker keeps its rolling buffer in the shared cache
473                // store — surface it under `_data` for serialization.
474                if m.contains_key("__cacheKind") {
475                    let data = cache_data_snapshot(m);
476                    obj.insert("_data".to_string(),
477                        serde_json::Value::Array(data.iter().map(Value::to_json).collect()));
478                }
479                serde_json::Value::Object(obj)
480            }
481        }
482    }
483
484    pub fn from_json(v: &serde_json::Value) -> Self {
485        match v {
486            serde_json::Value::Null        => Value::Null,
487            serde_json::Value::Bool(b)     => Value::Bool(*b),
488            serde_json::Value::Number(n)   => {
489                if let Some(i) = n.as_i64()  {
490                    Value::Int(i)
491                } else if n.is_u64() {
492                    // Integer in (i64::MAX, u64::MAX] — a large order/trade/
493                    // account id. `Value::Int` is i64 and `f64` would round it,
494                    // so preserve the exact digits as a string (Go does the
495                    // same). CCXT's safe_integer/safe_number read it back as a
496                    // number when needed.
497                    Value::Str(n.to_string())
498                } else if let Some(f) = n.as_f64() {
499                    Value::Float(f)
500                } else {
501                    Value::Null
502                }
503            }
504            serde_json::Value::String(s)   => Value::Str(s.clone()),
505            serde_json::Value::Array(a)    => Value::Array(a.iter().map(Value::from_json).collect()),
506            serde_json::Value::Object(m)   => Value::Map(
507                m.iter().map(|(k, v)| (k.clone(), Value::from_json(v))).collect()
508            ),
509        }
510    }
511}
512
513impl std::fmt::Display for Value {
514    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
515        match self {
516            Value::Null        => write!(f, "null"),
517            Value::Bool(b)     => write!(f, "{b}"),
518            Value::Int(n)      => write!(f, "{n}"),
519            Value::Float(fl)   => write!(f, "{fl}"),
520            Value::Str(s)      => write!(f, "{s}"),
521            Value::Arr(a)      => write!(f, "[{} items]", a.len()),
522            Value::Dict(m)     => write!(f, "{{{}  keys}}", m.len()),
523        }
524    }
525}
526
527// ── From / Into conversions ───────────────────────────────────────────────────
528
529// Operator overloads so transpiled code's `!x`, `x && y`, `x || y` over
530// Value compile. They follow JS-style truthiness on the Value, not value
531// equality. Result type is `Value::Bool`.
532
533impl std::ops::Not for Value {
534    type Output = Value;
535    fn not(self) -> Value { Value::Bool(!self.is_truthy()) }
536}
537
538impl std::ops::Not for &Value {
539    type Output = Value;
540    fn not(self) -> Value { Value::Bool(!self.is_truthy()) }
541}
542
543impl std::ops::BitAnd for Value {
544    type Output = Value;
545    fn bitand(self, rhs: Value) -> Value {
546        Value::Bool(self.is_truthy() && rhs.is_truthy())
547    }
548}
549
550impl std::ops::BitOr for Value {
551    type Output = Value;
552    fn bitor(self, rhs: Value) -> Value {
553        Value::Bool(self.is_truthy() || rhs.is_truthy())
554    }
555}
556
557impl From<&str>    for Value { fn from(s: &str)   -> Self { Value::Str(s.to_owned()) } }
558impl From<String>  for Value { fn from(s: String) -> Self { Value::Str(s) } }
559impl From<i64>     for Value { fn from(n: i64)    -> Self { Value::Int(n) } }
560impl From<f64>     for Value { fn from(f: f64)    -> Self { Value::Float(f) } }
561impl From<bool>    for Value { fn from(b: bool)   -> Self { Value::Bool(b) } }
562/// `From<ExchangeError>` makes `error.clone()` flow into `&[Value]`
563/// slices without an explicit conversion — surfaces the typed error
564/// as a `[Kind] message`-shaped string Value, matching how
565/// `runtime::panic_msg_to_error` round-trips it back into a typed
566/// `ExchangeError` for the caller.
567impl From<crate::ExchangeError> for Value {
568    fn from(e: crate::ExchangeError) -> Self {
569        Value::Str(format!("[{}] {}", e.kind, e.message))
570    }
571}
572impl From<HashMap<String, Value>> for Value {
573    fn from(m: HashMap<String, Value>) -> Self { Value::Map(m) }
574}
575impl From<Vec<Value>> for Value {
576    fn from(a: Vec<Value>) -> Self { Value::Array(a) }
577}
578impl From<serde_json::Value> for Value {
579    fn from(v: serde_json::Value) -> Self { Value::from_json(&v) }
580}
581
582// ── Helper free-functions (generated code calls these) ────────────────────────
583
584/// Optional live-snapshot accessor. Installed by `ccxt_tests::live_dispatch`
585/// so reads of the heavy fields (`markets`, `markets_by_id`, `symbols`, …)
586/// on the test-runner's snapshot don't deep-clone the entire ~4k-entry
587/// markets Map on every helper invocation. When `get_value` sees a Map
588/// carrying `__live_id`, it consults this callback to resolve the key
589/// directly from the cached real `<Id>Core`. Production / non-test code
590/// leaves the callback unset and falls through to the normal map lookup.
591type LiveLookupFn = fn(id: &str, key: &str) -> Option<Value>;
592// Plain atomic-load-style global — `tokio::main` spawns worker threads
593// that wouldn't see a `thread_local!` value set in main, so the lookup
594// has to be shared across all threads. Stored as a usize because
595// `AtomicPtr<fn>` is awkward to express. `fn` pointers are always
596// non-null when set; 0 means "not installed".
597static LIVE_LOOKUP_PTR: std::sync::atomic::AtomicUsize =
598    std::sync::atomic::AtomicUsize::new(0);
599
600pub fn set_live_lookup(f: LiveLookupFn) {
601    LIVE_LOOKUP_PTR.store(f as usize, std::sync::atomic::Ordering::Release);
602}
603
604fn live_lookup_get() -> Option<LiveLookupFn> {
605    let n = LIVE_LOOKUP_PTR.load(std::sync::atomic::Ordering::Acquire);
606    if n == 0 { None } else {
607        // SAFETY: only ever stored as `fn(&str, &str) -> Option<Value>`
608        // via `set_live_lookup`; the pointer-to-fn round-trip is sound.
609        Some(unsafe { std::mem::transmute::<usize, LiveLookupFn>(n) })
610    }
611}
612
613// Companion to `LiveLookupFn` but for writing: routes `exchange.setMarkets(...)`
614// on a `__live_id` snapshot to the registered *live* Core, so the Core's
615// `PredictionExchange::set_markets` override (outcome aliasing + populateOutcomes)
616// runs against the real instance the method dispatch will use. Returns the
617// resulting markets. See `Value::set_markets`.
618type LiveSetMarketsFn = fn(id: &str, markets: Value) -> Value;
619static LIVE_SET_MARKETS_PTR: std::sync::atomic::AtomicUsize =
620    std::sync::atomic::AtomicUsize::new(0);
621
622pub fn set_live_set_markets(f: LiveSetMarketsFn) {
623    LIVE_SET_MARKETS_PTR.store(f as usize, std::sync::atomic::Ordering::Release);
624}
625
626fn live_set_markets_get() -> Option<LiveSetMarketsFn> {
627    let n = LIVE_SET_MARKETS_PTR.load(std::sync::atomic::Ordering::Acquire);
628    if n == 0 { None } else {
629        // SAFETY: only ever stored as `fn(&str, Value) -> Value` via
630        // `set_live_set_markets`; the pointer-to-fn round-trip is sound.
631        Some(unsafe { std::mem::transmute::<usize, LiveSetMarketsFn>(n) })
632    }
633}
634
635/// Hot-path `get_value` variant that takes the key as a `&str` directly,
636/// skipping a `Value::Str` heap allocation. Used by the `safe_*_k`
637/// fast-path readers the transpiler routes literal-key calls through.
638#[inline]
639pub fn get_value_k(obj: &Value, key: &str) -> Value {
640    if let Value::Dict(m) = obj {
641        // A shared order book keeps its scalar meta (nonce/timestamp/…) in the
642        // book store; route those through it so the safe_* helpers (which go via
643        // get_value_k) see the shared value, not the empty Dict slot.
644        if is_book_meta_key(key) {
645            if let Some(id) = book_id_of(m) { return book_meta_get(id, key); }
646        }
647        if key == "cache" {
648            if let Some(id) = book_id_of(m) { return book_cache_handle(id); }
649        }
650        if let Some(v) = m.get(key) {
651            if !matches!(v, Value::Null) {
652                return v.clone();
653            }
654        }
655        if let Some(id_val) = m.get("__live_id") {
656            if let (Value::Str(id), Some(cb)) = (id_val, live_lookup_get()) {
657                if let Some(v) = cb(id, key) { return v; }
658            }
659        }
660    }
661    Value::Null
662}
663
664/// Access a value in a map by string key, or array by integer key encoded as
665/// a `Value::Str` / `Value::Int`. Returns `Value::Null` on miss.
666pub fn get_value(obj: &Value, key: &Value) -> Value {
667    // Cache / order-book / side markers expose numeric indexing as if
668    // they were arrays — `cache[i]` reads `_data[i]`, `side[i]` reads
669    // `_entries[i]`. Handle this before the regular dict lookup so the
670    // transpiled `get_value(&cache, &Value::Int(0))` calls reach the
671    // right backing buffer.
672    // The index may arrive as an Int (`get_value(&side, &Value::Int(0))`) or as
673    // a numeric string — the `safe_*` helpers stringify their key, so
674    // `safe_value(cache, 0)` reaches here as `Str("0")`. Accept both.
675    if let Value::Dict(m) = obj {
676        let idx = match key {
677            Value::Int(i) if *i >= 0 => Some(*i as usize),
678            Value::Str(s) => s.parse::<usize>().ok(),
679            _ => None,
680        };
681        if let Some(i) = idx {
682            if let Some(id) = book_cache_id_of(m) {
683                return book_cache_at(id, i);
684            }
685            if m.contains_key("__cacheKind") {
686                return cache_at(m, i);
687            }
688            if m.contains_key("__sideKind") {
689                return side_entry_at(m, i);
690            }
691        }
692    }
693    match (obj, key) {
694        (Value::Dict(m), Value::Str(k)) => {
695            // A shared order book keeps its scalar meta (nonce/timestamp/…) in
696            // the book store so mutations propagate across clones.
697            if is_book_meta_key(k) {
698                if let Some(id) = book_id_of(m) { return book_meta_get(id, k); }
699            }
700            if k == "cache" {
701                if let Some(id) = book_id_of(m) { return book_cache_handle(id); }
702            }
703            // A cache marker's `hashmap` (bucket index) lives in the shared
704            // CACHE_STORE cell, not the marker Dict — route the read there so a
705            // transpiled `cache.hashmap` sees live bucket state (the base-ws
706            // eviction test counts `Object.keys(cache.hashmap)`).
707            if k == "hashmap" && m.contains_key("__cacheKind") {
708                if let Some(id) = cache_id_of_m(m) {
709                    return with_cache_cell(id, |c| c.get("hashmap").cloned().unwrap_or(Value::Null));
710                }
711                return m.get("hashmap").cloned().unwrap_or(Value::Null);
712            }
713            // A client handle (`Map{url, subscriptions, futures}`) serves its
714            // subscriptions/futures live from the WS registry, so a read after a
715            // write (upbit sets subs then reads them back to build its subscribe
716            // frame) is coherent rather than a stale embedded snapshot.
717            if (k == "subscriptions" || k == "futures")
718                && m.contains_key("subscriptions") && m.contains_key("futures")
719            {
720                if let Some(Value::Str(url)) = m.get("url") {
721                    return crate::pro::ws_client::client_field_live(url, k);
722                }
723            }
724            // Snapshot value wins WHEN PRESENT AND NON-NULL. Tests that
725            // mutate `exchange.options` (e.g. kucoin broker-id test) need
726            // the snapshot view to take precedence; but `to_value`
727            // pre-populates heavy fields like `markets` with `Null`
728            // before `load_markets` runs, so we still need to fall back
729            // to the live-lookup if the snapshot value is null.
730            let snapshot_val = m.get(k);
731            if let Some(v) = snapshot_val {
732                if !matches!(v, Value::Null) {
733                    return v.clone();
734                }
735            }
736            if let Some(id_val) = m.get("__live_id") {
737                if let (Value::Str(id), Some(cb)) = (id_val, live_lookup_get()) {
738                    if let Some(v) = cb(id, k) { return v; }
739                }
740            }
741            Value::Null
742        }
743        (Value::Arr(a), Value::Int(i)) => a.get(*i as usize).cloned().unwrap_or(Value::Null),
744        (Value::Arr(a), Value::Str(k)) => {
745            if let Ok(i) = k.parse::<usize>() {
746                a.get(i).cloned().unwrap_or(Value::Null)
747            } else {
748                Value::Null
749            }
750        }
751        // JS string indexing: `s[i]` returns the i-th character as a
752        // 1-char string (e.g. bitfinex `amountString[0] === '-'` to detect
753        // a negative). Char-based so multi-byte UTF-8 is handled.
754        (Value::Str(s), Value::Int(i)) => {
755            if *i < 0 {
756                return Value::Null;
757            }
758            match s.chars().nth(*i as usize) {
759                Some(c) => Value::Str(c.to_string()),
760                None    => Value::Null,
761            }
762        }
763        _ => Value::Null,
764    }
765}
766
767/// Set a key/index in a map or array value.
768pub fn set_value(obj: &mut Value, key: &Value, val: Value) {
769    match (obj, key) {
770        (Value::Dict(m), Value::Str(k)) => {
771            if try_book_meta_write(m, k, &val) { return; }
772            // Persist to the live client AND keep the local snapshot coherent so
773            // code that reads back what it just wrote (upbit builds its subscribe
774            // frame from `object_keys(client.subscriptions)`) sees the new entry.
775            try_ws_subs_write(m, k, &val);
776            try_ws_sub_field_write(m, k, &val);
777            Arc::make_mut(m).insert(k.clone(), val);
778        }
779        (Value::Arr(a), Value::Int(i)) => {
780            let idx = *i as usize;
781            let a = Arc::make_mut(a);
782            if idx < a.len() { a[idx] = val; }
783        }
784        _ => {}
785    }
786}
787
788// ── safeXxx helpers (mirrors Exchange.ts safe helpers) ─────────────────────
789
790pub fn safe_string(obj: &Value, key: &str, default: Option<&str>) -> Option<String> {
791    let v = get_value(obj, &Value::Str(key.to_owned()));
792    match v {
793        Value::Str(s)  => Some(s),
794        Value::Int(n)  => Some(n.to_string()),
795        Value::Float(f)=> Some(f.to_string()),
796        // Booleans are not strings/finite numbers → TS `safeString` returns the
797        // default for them (not "true"/"false"), same as lists/dicts.
798        Value::Null    => default.map(str::to_owned),
799        _              => default.map(str::to_owned),
800    }
801}
802
803pub fn safe_number(obj: &Value, key: &str, default: Option<f64>) -> Option<f64> {
804    let v = get_value(obj, &Value::Str(key.to_owned()));
805    match v {
806        Value::Float(f) => Some(f),
807        Value::Int(n)   => Some(n as f64),
808        Value::Str(s)   => s.parse::<f64>().ok().or(default),
809        _               => default,
810    }
811}
812
813pub fn safe_integer(obj: &Value, key: &str, default: Option<i64>) -> Option<i64> {
814    let v = get_value(obj, &Value::Str(key.to_owned()));
815    match v {
816        Value::Int(n)   => Some(n),
817        Value::Float(f) => Some(f as i64),
818        Value::Str(s)   => s.parse::<i64>().ok().or(default),
819        _               => default,
820    }
821}
822
823pub fn safe_bool(obj: &Value, key: &str, default: Option<bool>) -> Option<bool> {
824    let v = get_value(obj, &Value::Str(key.to_owned()));
825    match v {
826        Value::Bool(b)  => Some(b),
827        Value::Int(n)   => Some(n != 0),
828        Value::Str(s)   => match s.to_lowercase().as_str() {
829            "true" | "1" | "yes" => Some(true),
830            "false"| "0" | "no"  => Some(false),
831            _                    => default,
832        },
833        _               => default,
834    }
835}
836
837/// Recursively merges `src` into `dst`.
838/// For map/map overlaps the source fields win (deep extend).
839pub fn deep_extend(dst: Value, src: Value) -> Value {
840    match (dst, src) {
841        (Value::Dict(mut d), Value::Dict(s)) => {
842            let dm = Arc::make_mut(&mut d);
843            let sm = Arc::try_unwrap(s).unwrap_or_else(|arc| (*arc).clone());
844            for (k, v) in sm {
845                let entry = dm.shift_remove(&k).unwrap_or(Value::Null);
846                dm.insert(k, deep_extend(entry, v));
847            }
848            Value::Dict(d)
849        }
850        (_, src) => src,
851    }
852}
853
854// ────────────────────────────────────────────────────────────────────────────
855// WS cache helpers — operate on the `Value::Dict` marker maps produced by
856// `crate::pro::cache`. Logic mirrors `ts/src/base/ws/Cache.ts`.
857// ────────────────────────────────────────────────────────────────────────────
858
859fn cache_str_field(item: &Value, key: &str) -> Option<String> {
860    match item {
861        Value::Dict(d) => match d.get(key) {
862            // Coerce to the string the TS uses as an object key: exchanges send
863            // integer order ids, and JS `byId[1]` / `byId["1"]` are the same slot,
864            // so a numeric id must dedupe like its string form (else the bucket
865            // lookup and the _data removal disagree and a duplicate row leaks).
866            Some(Value::Str(s)) => Some(s.clone()),
867            Some(Value::Int(n)) => Some(n.to_string()),
868            Some(Value::Float(f)) => Some(f.to_string()),
869            Some(Value::Bool(b)) => Some(b.to_string()),
870            _ => None,
871        },
872        _ => None,
873    }
874}
875
876/// Tag every symbol bucket of a cache hashmap copy with a `__cache_backref`
877/// = [cache_id, symbol] so a later `bucket[id] = order` write can be routed
878/// back into the shared CACHE_STORE (see `try_cache_hashmap_write`). Mirrors
879/// the JS reference semantics where `cache.hashmap[symbol]` is the live row.
880fn tag_cache_hashmap_buckets(hm: Value, id: i64) -> Value {
881    if let Value::Dict(d) = &hm {
882        let mut out: HashMap<String, Value> = HashMap::new();
883        for (sym, bucket) in d.iter() {
884            if let Value::Dict(bd) = bucket {
885                let mut nb: HashMap<String, Value> = (**bd).clone();
886                nb.insert(
887                    "__cache_backref".to_string(),
888                    Value::Arr(std::sync::Arc::new(vec![Value::Int(id), Value::Str(sym.clone())])),
889                );
890                out.insert(sym.clone(), Value::Dict(std::sync::Arc::new(nb)));
891            } else {
892                out.insert(sym.clone(), bucket.clone());
893            }
894        }
895        return Value::Dict(std::sync::Arc::new(out));
896    }
897    hm
898}
899
900/// When a transpiled `bucket[key] = item` write lands on a cache-hashmap bucket
901/// tagged by `tag_cache_hashmap_buckets`, persist `item` into the shared
902/// CACHE_STORE: update `hashmap[symbol][key]` and the matching `_data` row.
903/// This is how cross-handler mutations of a cached order (fee/trades
904/// accumulation in handleMyTrade, later read by handleOrder) survive Rust's
905/// copy-on-write `Value` semantics. Returns true if a write-through happened.
906pub(crate) fn try_cache_hashmap_write(bucket: &HashMap<String, Value>, key: &str, item: &Value) -> bool {
907    let (id, sym) = match bucket.get("__cache_backref") {
908        Some(Value::Arr(a)) => match (a.first(), a.get(1)) {
909            (Some(Value::Int(id)), Some(Value::Str(s))) => (*id, s.clone()),
910            _ => return false,
911        },
912        _ => return false,
913    };
914    with_cache_cell(id, |m| {
915        // hashmap[sym][key] = item
916        {
917            let hm = cache_dict_field_mut(m, "hashmap");
918            let b = hm.entry(sym.clone()).or_insert_with(|| Value::Map(HashMap::new()));
919            if let Value::Dict(bd) = b {
920                Arc::make_mut(bd).insert(key.to_string(), item.clone());
921            }
922        }
923        // update the matching _data row (matched by symbol + id/side == key)
924        let data = cache_data_mut(m);
925        for x in data.iter_mut() {
926            if cache_str_field(x, "symbol").as_deref() == Some(&sym)
927                && (cache_str_field(x, "id").as_deref() == Some(key)
928                    || cache_str_field(x, "side").as_deref() == Some(key))
929            {
930                *x = item.clone();
931                break;
932            }
933        }
934    });
935    true
936}
937
938fn cache_kind(v: &Value) -> Option<String> {
939    match v {
940        Value::Dict(d) => match d.get("__cacheKind") {
941            Some(Value::Str(s)) => Some(s.clone()),
942            _ => None,
943        },
944        _ => None,
945    }
946}
947
948fn cache_max_size(v: &Value) -> Option<usize> {
949    match v {
950        Value::Dict(d) => match d.get("maxSize") {
951            Some(Value::Int(n)) if *n > 0 => Some(*n as usize),
952            _ => None,
953        },
954        _ => None,
955    }
956}
957
958/// `_data` is the rolling buffer Vec for every cache kind. Returns a
959/// mutable handle to the inner Vec by going through `Arc::make_mut`.
960fn cache_data_mut(m: &mut HashMap<String, Value>) -> &mut Vec<Value> {
961    let entry = m.entry("_data".to_string()).or_insert_with(|| Value::Array(Vec::new()));
962    if let Value::Arr(a) = entry {
963        return Arc::make_mut(a);
964    }
965    *entry = Value::Array(Vec::new());
966    if let Value::Arr(a) = entry {
967        return Arc::make_mut(a);
968    }
969    unreachable!()
970}
971
972fn cache_dict_field_mut<'a>(m: &'a mut HashMap<String, Value>, key: &str) -> &'a mut HashMap<String, Value> {
973    let entry = m.entry(key.to_string()).or_insert_with(|| Value::Map(HashMap::new()));
974    if let Value::Dict(d) = entry {
975        return Arc::make_mut(d);
976    }
977    *entry = Value::Map(HashMap::new());
978    if let Value::Dict(d) = entry {
979        return Arc::make_mut(d);
980    }
981    unreachable!()
982}
983
984fn cache_int_field(m: &HashMap<String, Value>, key: &str) -> i64 {
985    match m.get(key) { Some(Value::Int(n)) => *n, _ => 0 }
986}
987
988fn cache_set_int(m: &mut HashMap<String, Value>, key: &str, value: i64) {
989    m.insert(key.to_string(), Value::Int(value));
990}
991
992fn cache_bool_field(m: &HashMap<String, Value>, key: &str) -> bool {
993    matches!(m.get(key), Some(Value::Bool(true)))
994}
995
996fn cache_set_bool(m: &mut HashMap<String, Value>, key: &str, value: bool) {
997    m.insert(key.to_string(), Value::Bool(value));
998}
999
1000// Reset the per-kind bookkeeping that a `clear()` must drop, mirroring the TS
1001// `ArrayCache` / `ArrayCacheByTimestamp` `clear()` overrides (base/ws/Cache.ts):
1002// the keyed caches find rows through the hashmap and report new-update counts,
1003// so a `clear()` that only truncates `_data` leaves the hashmap + counters
1004// claiming rows that are gone — `getLimit()` then keeps reporting phantom
1005// updates and the next `append` merges into an orphaned reference. Only fields
1006// already present are reset (guards the bare-marker fallback path). The caller
1007// truncates `_data` separately.
1008fn cache_reset_bookkeeping(state: &mut HashMap<String, Value>) {
1009    for k in ["hashmap", "_newUpdatesBySymbol", "_seenUpdatesBySymbol", "_seenUpdatesAll",
1010              "_clearUpdatesBySymbol", "_sizeTracker"] {
1011        if state.contains_key(k) {
1012            state.insert(k.to_string(), Value::Map(HashMap::new()));
1013        }
1014    }
1015    if state.contains_key("_allNewUpdates") { cache_set_int(state, "_allNewUpdates", 0); }
1016    if state.contains_key("_newUpdates") { cache_set_int(state, "_newUpdates", 0); }
1017    if state.contains_key("_clearAllUpdates") { cache_set_bool(state, "_clearAllUpdates", false); }
1018    if state.contains_key("_clearUpdates") { cache_set_bool(state, "_clearUpdates", false); }
1019}
1020
1021// ── ArrayCache update-counter scopes ────────────────────────────────────────
1022// The keyed caches (BySymbolById / ByOutcomeById / BySymbolBySide) count the
1023// distinct second-level keys (id / side) seen since the last poll, kept in TWO
1024// independent scopes so a symbol-scoped poll and a global poll clear each other
1025// without interfering (mirrors `seenUpdatesBySymbol` / `seenUpdatesAll` in
1026// base/ws/Cache.ts). A "set" is a `Map<key2, Bool>` nested under `field[key1]`.
1027
1028// Apply a pending global-scope clear at the top of `append` (TS `clearAllUpdates`).
1029fn cache_apply_clear_all(m: &mut HashMap<String, Value>) {
1030    if cache_bool_field(m, "_clearAllUpdates") {
1031        cache_set_bool(m, "_clearAllUpdates", false);
1032        cache_set_int(m, "_allNewUpdates", 0);
1033        cache_dict_field_mut(m, "_seenUpdatesAll").clear();
1034    }
1035}
1036
1037// Take (and reset) the pending symbol-scoped clear flag for `key1`.
1038fn cache_take_symbol_clear(m: &mut HashMap<String, Value>, key1: &str) -> bool {
1039    let cs = cache_dict_field_mut(m, "_clearUpdatesBySymbol");
1040    if matches!(cs.get(key1), Some(Value::Bool(true))) {
1041        cs.insert(key1.to_string(), Value::Bool(false));
1042        true
1043    } else {
1044        false
1045    }
1046}
1047
1048// Add `key2` to the seen-set `field[key1]`; returns the resulting set size.
1049fn cache_seen_add(m: &mut HashMap<String, Value>, field: &str, key1: &str, key2: &str) -> i64 {
1050    let outer = cache_dict_field_mut(m, field);
1051    let set = outer.entry(key1.to_string()).or_insert_with(|| Value::Map(HashMap::new()));
1052    if let Value::Dict(sd) = set {
1053        let sd = Arc::make_mut(sd);
1054        sd.insert(key2.to_string(), Value::Bool(true));
1055        sd.len() as i64
1056    } else {
1057        0
1058    }
1059}
1060
1061// Size of the seen-set `field[key1]` (0 if absent).
1062fn cache_seen_size(m: &mut HashMap<String, Value>, field: &str, key1: &str) -> i64 {
1063    match cache_dict_field_mut(m, field).get(key1) {
1064        Some(Value::Dict(sd)) => sd.len() as i64,
1065        _ => 0,
1066    }
1067}
1068
1069// Empty the seen-set `field[key1]` (leaves the bucket in place).
1070fn cache_seen_clear(m: &mut HashMap<String, Value>, field: &str, key1: &str) {
1071    if let Some(Value::Dict(sd)) = cache_dict_field_mut(m, field).get_mut(key1) {
1072        Arc::make_mut(sd).clear();
1073    }
1074}
1075
1076// Remove `key2` from the seen-set `field[key1]`; returns whether it was present.
1077// Drops the outer bucket once its set is empty (TS eviction cleanup).
1078fn cache_seen_remove(m: &mut HashMap<String, Value>, field: &str, key1: &str, key2: &str) -> bool {
1079    let outer = cache_dict_field_mut(m, field);
1080    let (removed, empty) = if let Some(Value::Dict(sd)) = outer.get_mut(key1) {
1081        let sd = Arc::make_mut(sd);
1082        let removed = sd.shift_remove(key2).is_some();
1083        (removed, sd.is_empty())
1084    } else {
1085        (false, false)
1086    };
1087    if empty { outer.shift_remove(key1); }
1088    removed
1089}
1090
1091// ── Shared cache backing store ──────────────────────────────────────────────
1092// ArrayCache & friends must survive COW clones the way order-book sides do: a
1093// handler creates a cache, stores a *clone* in `self.ohlcvs[sym][tf]`, appends
1094// to the local, then re-reads the stored clone to resolve (gate watchOHLCV).
1095// With the rolling buffer + hashmap + counters kept in the Dict, the clone and
1096// the local diverge on the first append (Arc::make_mut) and the re-read is
1097// empty. So hold the whole mutable cache state (`_data`, `hashmap`, counters)
1098// in a registry keyed by a stable `__cache_id`; every COW clone shares it.
1099static CACHE_STORE: once_cell::sync::Lazy<std::sync::Mutex<std::collections::HashMap<i64, HashMap<String, Value>>>> =
1100    once_cell::sync::Lazy::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
1101static NEXT_CACHE_ID: std::sync::atomic::AtomicI64 = std::sync::atomic::AtomicI64::new(1);
1102
1103/// Register a cache's initial mutable state, returning its shared id.
1104pub(crate) fn alloc_cache_id(initial: HashMap<String, Value>) -> i64 {
1105    let id = NEXT_CACHE_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1106    CACHE_STORE.lock().unwrap().insert(id, initial);
1107    id
1108}
1109
1110fn cache_id_of(v: &Value) -> Option<i64> {
1111    match v {
1112        Value::Dict(d) => match d.get("__cache_id") { Some(Value::Int(n)) => Some(*n), _ => None },
1113        _ => None,
1114    }
1115}
1116fn cache_id_of_m(m: &HashMap<String, Value>) -> Option<i64> {
1117    match m.get("__cache_id") { Some(Value::Int(n)) => Some(*n), _ => None }
1118}
1119
1120fn with_cache_cell<R>(id: i64, f: impl FnOnce(&mut HashMap<String, Value>) -> R) -> R {
1121    let mut g = CACHE_STORE.lock().unwrap();
1122    let cell = g.entry(id).or_insert_with(HashMap::new);
1123    f(cell)
1124}
1125
1126/// Snapshot a cache marker's rolling buffer (from the shared cell if it carries
1127/// a `__cache_id`, else the inline `_data` field for legacy markers).
1128fn cache_data_snapshot(m: &HashMap<String, Value>) -> Vec<Value> {
1129    if let Some(id) = cache_id_of_m(m) {
1130        return with_cache_cell(id, |c| match c.get("_data") {
1131            Some(Value::Arr(a)) => (**a).clone(),
1132            _ => Vec::new(),
1133        });
1134    }
1135    match m.get("_data") { Some(Value::Arr(a)) => (**a).clone(), _ => Vec::new() }
1136}
1137
1138fn cache_len_of(m: &HashMap<String, Value>) -> usize {
1139    if let Some(id) = cache_id_of_m(m) {
1140        return with_cache_cell(id, |c| match c.get("_data") { Some(Value::Arr(a)) => a.len(), _ => 0 });
1141    }
1142    match m.get("_data") { Some(Value::Arr(a)) => a.len(), _ => 0 }
1143}
1144
1145fn cache_at(m: &HashMap<String, Value>, i: usize) -> Value {
1146    if let Some(id) = cache_id_of_m(m) {
1147        return with_cache_cell(id, |c| match c.get("_data") {
1148            Some(Value::Arr(a)) => a.get(i).cloned().unwrap_or(Value::Null),
1149            _ => Value::Null,
1150        });
1151    }
1152    match m.get("_data") { Some(Value::Arr(a)) => a.get(i).cloned().unwrap_or(Value::Null), _ => Value::Null }
1153}
1154
1155/// Public: cache buffer length, or None when `m` isn't a cache marker.
1156pub(crate) fn cache_len_of_marker(m: &HashMap<String, Value>) -> Option<usize> {
1157    if m.contains_key("__cacheKind") { Some(cache_len_of(m)) } else { None }
1158}
1159
1160pub(crate) fn cache_append(target: &mut Value, item: Value) {
1161    let kind = cache_kind(target).unwrap_or_default();
1162    let cap = cache_max_size(target);
1163    if let Some(id) = cache_id_of(target) {
1164        with_cache_cell(id, |m| cache_append_inner(m, &kind, cap, item));
1165    } else if let Value::Dict(m_arc) = target {
1166        let m = Arc::make_mut(m_arc);
1167        cache_append_inner(m, &kind, cap, item);
1168    }
1169}
1170
1171fn cache_append_inner(m: &mut HashMap<String, Value>, kind: &str, cap: Option<usize>, item: Value) {
1172    {
1173        match kind {
1174            "ArrayCache" => {
1175                let data = cache_data_mut(m);
1176                if let Some(cap) = cap { if data.len() == cap { data.remove(0); } }
1177                data.push(item.clone());
1178                // Base ArrayCache counts every append (not distinct ids), per scope.
1179                cache_apply_clear_all(m);
1180                let sym = cache_str_field(&item, "symbol").unwrap_or_default();
1181                if cache_take_symbol_clear(m, &sym) {
1182                    cache_dict_field_mut(m, "_newUpdatesBySymbol").insert(sym.clone(), Value::Int(0));
1183                }
1184                {
1185                    let nubs = cache_dict_field_mut(m, "_newUpdatesBySymbol");
1186                    let cur = match nubs.get(&sym) { Some(Value::Int(n)) => *n, _ => 0 };
1187                    nubs.insert(sym, Value::Int(cur + 1));
1188                }
1189                let all = cache_int_field(m, "_allNewUpdates");
1190                cache_set_int(m, "_allNewUpdates", all + 1);
1191            }
1192            "ArrayCacheByTimestamp" => {
1193                let ts_key = match item {
1194                    Value::Arr(ref a) => match a.first() {
1195                        Some(Value::Int(n))   => n.to_string(),
1196                        Some(Value::Float(f)) => f.to_string(),
1197                        Some(Value::Str(s))   => s.clone(),
1198                        _ => String::new(),
1199                    },
1200                    _ => String::new(),
1201                };
1202                let existing_idx = {
1203                    let hm = cache_dict_field_mut(m, "hashmap");
1204                    match hm.get(&ts_key) { Some(Value::Int(n)) => Some(*n as usize), _ => None }
1205                };
1206                if let Some(idx) = existing_idx {
1207                    let data = cache_data_mut(m);
1208                    if idx < data.len() && data[idx] != item { data[idx] = item.clone(); }
1209                } else {
1210                    // Evict if at cap; shift hashmap indices down.
1211                    let evicting = match cap { Some(c) => {
1212                        let data_len = cache_data_mut(m).len();
1213                        data_len == c
1214                    }, None => false };
1215                    if evicting {
1216                        let removed = {
1217                            let data = cache_data_mut(m);
1218                            if data.is_empty() { Value::Null } else { data.remove(0) }
1219                        };
1220                        let removed_key = match &removed {
1221                            Value::Arr(a) => match a.first() {
1222                                Some(Value::Int(n))   => n.to_string(),
1223                                Some(Value::Float(f)) => f.to_string(),
1224                                Some(Value::Str(s))   => s.clone(),
1225                                _ => String::new(),
1226                            },
1227                            _ => String::new(),
1228                        };
1229                        let hm = cache_dict_field_mut(m, "hashmap");
1230                        hm.shift_remove(&removed_key);
1231                        for v in hm.values_mut() {
1232                            if let Value::Int(n) = v { *n = n.saturating_sub(1); }
1233                        }
1234                    }
1235                    let new_idx = {
1236                        let data = cache_data_mut(m);
1237                        let i = data.len();
1238                        data.push(item);
1239                        i
1240                    };
1241                    let hm = cache_dict_field_mut(m, "hashmap");
1242                    hm.insert(ts_key.clone(), Value::Int(new_idx as i64));
1243                }
1244                // size tracker / new updates
1245                if cache_bool_field(m, "_clearUpdates") {
1246                    cache_set_bool(m, "_clearUpdates", false);
1247                    let st = cache_dict_field_mut(m, "_sizeTracker");
1248                    st.clear();
1249                }
1250                {
1251                    let st = cache_dict_field_mut(m, "_sizeTracker");
1252                    st.insert(ts_key, Value::Bool(true));
1253                }
1254                let st_len = match m.get("_sizeTracker") {
1255                    Some(Value::Dict(d)) => d.len() as i64,
1256                    _ => 0,
1257                };
1258                cache_set_int(m, "_newUpdates", st_len);
1259            }
1260            "ArrayCacheBySymbolById" | "ArrayCacheBySymbolBySide" | "ArrayCacheByOutcomeById" => {
1261                // ArrayCacheByOutcomeById keys the outer bucket on `outcome` — prediction
1262                // markets stream several outcomes of one market that can share an order id,
1263                // so a symbol-keyed lookup would merge two distinct outcomes into one row.
1264                // The others key on `symbol`. Second level is `id` except BySymbolBySide.
1265                let key1_name = if kind == "ArrayCacheByOutcomeById" { "outcome" } else { "symbol" };
1266                let symbol = cache_str_field(&item, key1_name).unwrap_or_default();
1267                let key2_name = if kind == "ArrayCacheBySymbolBySide" { "side" } else { "id" };
1268                let key2 = cache_str_field(&item, key2_name).unwrap_or_default();
1269                let was_duplicate = {
1270                    let hm = cache_dict_field_mut(m, "hashmap");
1271                    let bucket = hm.entry(symbol.clone())
1272                        .or_insert_with(|| Value::Map(HashMap::new()));
1273                    if let Value::Dict(bd) = bucket {
1274                        Arc::make_mut(bd);
1275                    }
1276                    if let Some(Value::Dict(bd)) = hm.get(&symbol) {
1277                        bd.contains_key(&key2)
1278                    } else { false }
1279                };
1280                let item_to_store = if was_duplicate {
1281                    let merged = {
1282                        let hm = cache_dict_field_mut(m, "hashmap");
1283                        let bucket = hm.get(&symbol).cloned();
1284                        let existing = match bucket {
1285                            Some(Value::Dict(bd)) => bd.get(&key2).cloned(),
1286                            _ => None,
1287                        };
1288                        match (existing, item.clone()) {
1289                            (Some(Value::Dict(old)), Value::Dict(new_)) => {
1290                                let mut merged = (*old).clone();
1291                                for (k, v) in new_.iter() { merged.insert(k.clone(), v.clone()); }
1292                                Value::Dict(Arc::new(merged))
1293                            }
1294                            (_, new_) => new_,
1295                        }
1296                    };
1297                    {
1298                        let hm = cache_dict_field_mut(m, "hashmap");
1299                        let bucket = hm.entry(symbol.clone())
1300                            .or_insert_with(|| Value::Map(HashMap::new()));
1301                        if let Value::Dict(bd) = bucket {
1302                            Arc::make_mut(bd).insert(key2.clone(), merged.clone());
1303                        }
1304                    }
1305                    // Remove the existing slot from _data.
1306                    {
1307                        let data = cache_data_mut(m);
1308                        if let Some(pos) = data.iter().position(|x| {
1309                            cache_str_field(x, key2_name).as_deref() == Some(&key2)
1310                                && cache_str_field(x, key1_name).as_deref() == Some(&symbol)
1311                        }) { data.remove(pos); }
1312                    }
1313                    merged
1314                } else {
1315                    let hm = cache_dict_field_mut(m, "hashmap");
1316                    let bucket = hm.entry(symbol.clone())
1317                        .or_insert_with(|| Value::Map(HashMap::new()));
1318                    if let Value::Dict(bd) = bucket {
1319                        Arc::make_mut(bd).insert(key2.clone(), item.clone());
1320                    }
1321                    item.clone()
1322                };
1323                // Evict from front if at cap.
1324                let evicting = match cap { Some(c) => {
1325                    cache_data_mut(m).len() == c
1326                }, None => false };
1327                if evicting {
1328                    let removed = {
1329                        let data = cache_data_mut(m);
1330                        if data.is_empty() { Value::Null } else { data.remove(0) }
1331                    };
1332                    let r_sym = cache_str_field(&removed, key1_name).unwrap_or_default();
1333                    let r_key2 = cache_str_field(&removed, key2_name).unwrap_or_default();
1334                    {
1335                        let hm = cache_dict_field_mut(m, "hashmap");
1336                        let now_empty = if let Some(Value::Dict(bd)) = hm.get_mut(&r_sym) {
1337                            let bd = Arc::make_mut(bd);
1338                            bd.shift_remove(&r_key2);
1339                            bd.is_empty()
1340                        } else { false };
1341                        // Drop the emptied outer bucket, else a stream of short-lived
1342                        // keys leaks one empty object per key forever (mirrors TS
1343                        // `delete this.hashmap[deleteKey]` when its last id is gone).
1344                        if now_empty { hm.shift_remove(&r_sym); }
1345                    }
1346                    // The evicted key2 leaves both update scopes; a single-scope
1347                    // poller never fires the other scope's clear, so decrement the
1348                    // counts here or they would report the evicted id forever.
1349                    if cache_seen_remove(m, "_seenUpdatesBySymbol", &r_sym, &r_key2) {
1350                        let nubs = cache_dict_field_mut(m, "_newUpdatesBySymbol");
1351                        if let Some(Value::Int(n)) = nubs.get(&r_sym).cloned() {
1352                            nubs.insert(r_sym.clone(), Value::Int(n - 1));
1353                        }
1354                    }
1355                    if cache_seen_remove(m, "_seenUpdatesAll", &r_sym, &r_key2) {
1356                        let all = cache_int_field(m, "_allNewUpdates");
1357                        cache_set_int(m, "_allNewUpdates", all - 1);
1358                    }
1359                }
1360                cache_data_mut(m).push(item_to_store);
1361
1362                // Keyed caches count the distinct second-level keys (id / side)
1363                // seen per scope. Mirror ArrayCacheBySymbolById/BySymbolBySide
1364                // .append (base/ws/Cache.ts): symbol scope and global scope keep
1365                // independent seen-sets, each cleared only by its own poll.
1366                cache_apply_clear_all(m);
1367                if cache_take_symbol_clear(m, &symbol) {
1368                    cache_seen_clear(m, "_seenUpdatesBySymbol", &symbol);
1369                }
1370                let sz = cache_seen_add(m, "_seenUpdatesBySymbol", &symbol, &key2);
1371                cache_dict_field_mut(m, "_newUpdatesBySymbol").insert(symbol.clone(), Value::Int(sz));
1372                let before = cache_seen_size(m, "_seenUpdatesAll", &symbol);
1373                let after = cache_seen_add(m, "_seenUpdatesAll", &symbol, &key2);
1374                let all = cache_int_field(m, "_allNewUpdates");
1375                cache_set_int(m, "_allNewUpdates", all + (after - before));
1376            }
1377            _ => {}
1378        }
1379    }
1380}
1381
1382
1383pub(crate) fn cache_get_limit(target: &mut Value, symbol: Value, limit: Value) -> Value {
1384    let kind = cache_kind(target).unwrap_or_default();
1385    if let Some(id) = cache_id_of(target) {
1386        return with_cache_cell(id, |m| cache_get_limit_inner(m, &kind, symbol, limit));
1387    }
1388    if let Value::Dict(m_arc) = target {
1389        let m = Arc::make_mut(m_arc);
1390        cache_get_limit_inner(m, &kind, symbol, limit)
1391    } else {
1392        limit
1393    }
1394}
1395
1396// Mirrors `ArrayCache.getLimit` (base/ws/Cache.ts). A `symbol` arg polls the
1397// symbol scope and arms its clear; `undefined` (Null) polls the global scope.
1398// The count is `undefined` only when the key was never seen — then the caller's
1399// `limit` passes through unclamped.
1400fn cache_get_limit_inner(m: &mut HashMap<String, Value>, kind: &str, symbol: Value, limit: Value) -> Value {
1401    {
1402        // `ArrayCacheByTimestamp` doesn't track per-symbol updates —
1403        // both `getLimit(undefined, …)` and `getLimit(sym, …)` return
1404        // `this.newUpdates` and arm a single global `clearUpdates` flag.
1405        if kind == "ArrayCacheByTimestamp" {
1406            let v = cache_int_field(m, "_newUpdates");
1407            cache_set_bool(m, "_clearUpdates", true);
1408            return match limit {
1409                Value::Int(l) => Value::Int(v.min(l)),
1410                _             => Value::Int(v),
1411            };
1412        }
1413        let new_updates_value: Option<i64> = match &symbol {
1414            Value::Null => {
1415                cache_set_bool(m, "_clearAllUpdates", true);
1416                Some(cache_int_field(m, "_allNewUpdates"))
1417            }
1418            Value::Str(sym) => {
1419                let v = match cache_dict_field_mut(m, "_newUpdatesBySymbol").get(sym) {
1420                    Some(Value::Int(n)) => Some(*n),
1421                    _ => None,
1422                };
1423                cache_dict_field_mut(m, "_clearUpdatesBySymbol")
1424                    .insert(sym.clone(), Value::Bool(true));
1425                v
1426            }
1427            _ => None,
1428        };
1429        match (new_updates_value, &limit) {
1430            (None,    _)              => limit.clone(),
1431            (Some(v), Value::Int(l))  => Value::Int(v.min(*l)),
1432            (Some(v), _)              => Value::Int(v),
1433        }
1434    }
1435}
1436
1437// ────────────────────────────────────────────────────────────────────────────
1438// WS order-book helpers — operate on the `Value::Dict` markers from
1439// `crate::pro::order_book`. Tag layout:
1440//   * `__bookKind`  ∈ {OrderBook, IndexedOrderBook, CountedOrderBook}
1441//   * `__sideKind`  ∈ {OrderBookSide, IndexedOrderBookSide,
1442//                      CountedOrderBookSide}  (carried under `bids`/`asks`)
1443// ────────────────────────────────────────────────────────────────────────────
1444
1445fn as_f64(v: &Value) -> f64 {
1446    match v {
1447        Value::Float(f) => *f,
1448        Value::Int(n)   => *n as f64,
1449        Value::Str(s)   => s.parse().unwrap_or(0.0),
1450        _ => 0.0,
1451    }
1452}
1453
1454fn book_kind(v: &Value) -> Option<String> {
1455    match v { Value::Dict(d) => match d.get("__bookKind") {
1456        Some(Value::Str(s)) => Some(s.clone()), _ => None,
1457    }, _ => None }
1458}
1459
1460// ────────────────────────────────────────────────────────────────────────────
1461// Shared book scalar-metadata store.
1462//
1463// Like side entries, an OrderBook's scalar fields must be shared across clones:
1464// WS handlers mutate a book pulled out of `self.orderbooks` (a COW clone) and
1465// expect the write visible on the next message — okx's per-message seqId nonce
1466// check reads the book's `nonce`, written inside `handle_order_book_message` on
1467// a clone. These fields live in a store keyed by a stable `__book_id`; bids/asks
1468// stay in the Dict (their entries are already shared via `__side_id`).
1469static BOOK_META: once_cell::sync::Lazy<std::sync::Mutex<std::collections::HashMap<i64, HashMap<String, Value>>>> =
1470    once_cell::sync::Lazy::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
1471static NEXT_BOOK_ID: std::sync::atomic::AtomicI64 = std::sync::atomic::AtomicI64::new(1);
1472
1473/// Scalar book fields that live in the shared meta store (not the Dict).
1474fn is_book_meta_key(k: &str) -> bool {
1475    matches!(k, "timestamp" | "datetime" | "nonce" | "symbol" | "checksum")
1476}
1477
1478pub(crate) fn alloc_book_id() -> i64 {
1479    let id = NEXT_BOOK_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1480    BOOK_META.lock().unwrap().insert(id, HashMap::new());
1481    id
1482}
1483
1484fn book_id_of(m: &HashMap<String, Value>) -> Option<i64> {
1485    match m.get("__book_id") { Some(Value::Int(n)) => Some(*n), _ => None }
1486}
1487
1488fn book_meta_get(id: i64, k: &str) -> Value {
1489    BOOK_META.lock().unwrap().get(&id).and_then(|m| m.get(k).cloned()).unwrap_or(Value::Null)
1490}
1491
1492pub(crate) fn book_meta_set(id: i64, k: &str, v: Value) {
1493    let mut g = BOOK_META.lock().unwrap();
1494    g.entry(id).or_default().insert(k.to_string(), v);
1495}
1496
1497fn book_meta_snapshot(id: i64) -> Vec<(String, Value)> {
1498    BOOK_META.lock().unwrap().get(&id)
1499        .map(|m| m.iter().map(|(k, v)| (k.clone(), v.clone())).collect())
1500        .unwrap_or_default()
1501}
1502
1503// A JS `OrderBook` also carries a mutable `cache` array — venues that fetch a
1504// REST/`req` snapshot buffer live deltas into `orderbook.cache` while the
1505// snapshot is in flight (binance, htx, …). Like the sides/meta, the cache must
1506// be shared across clones: `orderbook.cache.push(msg)` transpiles to
1507// `append_to_array(get_value(&book, "cache"), msg)`, and get_value returns a COW
1508// clone. So `get_value(book, "cache")` returns a lightweight handle carrying
1509// `__book_cache_id`, and length/index/append/clear route through this store.
1510static BOOK_CACHE: once_cell::sync::Lazy<std::sync::Mutex<std::collections::HashMap<i64, Vec<Value>>>> =
1511    once_cell::sync::Lazy::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
1512
1513/// Build a cache handle for a book id (returned by `get_value(book, "cache")`).
1514fn book_cache_handle(id: i64) -> Value {
1515    let mut h = HashMap::new();
1516    h.insert("__book_cache_id".to_string(), Value::Int(id));
1517    Value::Dict(Arc::new(h))
1518}
1519
1520fn book_cache_id_of(m: &HashMap<String, Value>) -> Option<i64> {
1521    match m.get("__book_cache_id") { Some(Value::Int(n)) => Some(*n), _ => None }
1522}
1523
1524pub(crate) fn book_cache_push(id: i64, v: Value) {
1525    BOOK_CACHE.lock().unwrap().entry(id).or_default().push(v);
1526}
1527
1528fn book_cache_len(id: i64) -> usize {
1529    BOOK_CACHE.lock().unwrap().get(&id).map(|c| c.len()).unwrap_or(0)
1530}
1531
1532/// Length of a cache handle Dict's backing store, or None if `m` isn't a handle.
1533pub(crate) fn book_cache_len_of(m: &HashMap<String, Value>) -> Option<usize> {
1534    book_cache_id_of(m).map(book_cache_len)
1535}
1536
1537/// If `m` is a tagged live-subscriptions snapshot, apply `client.subscriptions
1538/// [key] = val` to the live WS client and return true.
1539pub(crate) fn try_ws_subs_write(m: &HashMap<String, Value>, key: &str, val: &Value) -> bool {
1540    if key == "__ws_subs_url" { return false; }
1541    if let Some(Value::Str(url)) = m.get("__ws_subs_url") {
1542        crate::pro::ws_client::value_subs_insert(url, key, val.clone());
1543        return true;
1544    }
1545    false
1546}
1547
1548/// If `m` is a tagged subscription dict (`__ws_sub_ref`), persist a field write
1549/// `subscription[key] = val` to the live WS client and return true.
1550pub(crate) fn try_ws_sub_field_write(m: &HashMap<String, Value>, key: &str, val: &Value) -> bool {
1551    if key == "__ws_sub_ref" { return false; }
1552    if let Some(Value::Str(subref)) = m.get("__ws_sub_ref") {
1553        crate::pro::ws_client::value_sub_field_write(subref, key, val.clone());
1554        return true;
1555    }
1556    false
1557}
1558
1559/// If `m` is a tagged live-subscriptions snapshot, apply `delete
1560/// client.subscriptions[key]` to the live WS client and return true.
1561pub(crate) fn try_ws_subs_remove(m: &HashMap<String, Value>, key: &str) -> bool {
1562    if let Some(Value::Str(url)) = m.get("__ws_subs_url") {
1563        crate::pro::ws_client::value_subs_remove(url, key);
1564        return true;
1565    }
1566    false
1567}
1568
1569/// If `obj` is a cache handle, push `v` into its store and return true.
1570pub(crate) fn try_book_cache_push(obj: &Value, v: &Value) -> bool {
1571    if let Value::Dict(m) = obj {
1572        if let Some(id) = book_cache_id_of(m) { book_cache_push(id, v.clone()); return true; }
1573    }
1574    false
1575}
1576
1577fn book_cache_at(id: i64, i: usize) -> Value {
1578    BOOK_CACHE.lock().unwrap().get(&id).and_then(|c| c.get(i).cloned()).unwrap_or(Value::Null)
1579}
1580
1581/// Replace a book's cache contents (from `book.cache = [...]`, usually to clear).
1582pub(crate) fn book_cache_set(id: i64, items: Vec<Value>) {
1583    BOOK_CACHE.lock().unwrap().insert(id, items);
1584}
1585
1586/// Snapshot a WS cache's rolling buffer as a plain array. Handles both the
1587/// `_data`-backed ArrayCache / ArrayCacheByTimestamp (trades, ohlcv, tickers)
1588/// and the registry-backed order-book cache handle. Returns `None` when `v`
1589/// isn't a cache — `to_array` then falls back to its generic Dict handling.
1590/// Without this, `to_array(cache)` would surface the cache's meta fields
1591/// (`__cacheKind`, counters, boolean flags) as if they were entries.
1592pub fn cache_entries_as_value(v: &Value) -> Option<Value> {
1593    if let Value::Dict(m) = v {
1594        if let Some(id) = book_cache_id_of(m) {
1595            let items = BOOK_CACHE.lock().unwrap().get(&id).cloned().unwrap_or_default();
1596            return Some(Value::Array(items));
1597        }
1598        if m.contains_key("__cacheKind") {
1599            return Some(Value::Array(cache_data_snapshot(m)));
1600        }
1601    }
1602    None
1603}
1604
1605/// If `m` is a shared book and `k` a meta key, write `v` to the book store and
1606/// return true (the caller should skip its own Dict insert); else false.
1607pub(crate) fn try_book_meta_write(m: &HashMap<String, Value>, k: &str, v: &Value) -> bool {
1608    if is_book_meta_key(k) {
1609        if let Some(id) = book_id_of(m) { book_meta_set(id, k, v.clone()); return true; }
1610    }
1611    // `book.cache = [...]` — replace the shared cache store (usually a clear).
1612    if k == "cache" {
1613        if let Some(id) = book_id_of(m) {
1614            let items = match v { Value::Arr(a) => a.as_ref().clone(), _ => Vec::new() };
1615            book_cache_set(id, items);
1616            return true;
1617        }
1618    }
1619    false
1620}
1621
1622/// Expand a shared book Dict into a plain Dict carrying its meta fields (for
1623/// serialization / equality). Strips `__book_id` so the result is inert.
1624pub fn book_fields_as_value(v: &Value) -> Option<Value> {
1625    match v {
1626        Value::Dict(d) if d.contains_key("__book_id") => {
1627            let mut out: HashMap<String, Value> = (**d).clone();
1628            out.shift_remove("__book_id");
1629            if let Some(Value::Int(id)) = d.get("__book_id") {
1630                if let Some(meta) = BOOK_META.lock().unwrap().get(id) {
1631                    for (k, val) in meta.iter() { out.insert(k.clone(), val.clone()); }
1632                }
1633            }
1634            Some(Value::Dict(Arc::new(out)))
1635        }
1636        _ => None,
1637    }
1638}
1639
1640// ────────────────────────────────────────────────────────────────────────────
1641// Shared side backing store.
1642//
1643// In JS an `OrderBookSide` is a mutable object; the WS handlers routinely do
1644// `const bookside = book['asks']; storeDeltas(bookside, deltas)` where the
1645// helper mutates `bookside` in place and the change is visible through `book`.
1646// Our `Value` is copy-on-write (Arc), so cloning the side Dict and mutating the
1647// clone (the transpiled `handle_deltas(side.clone(), …)` shape) would lose the
1648// writes. To restore shared mutability we keep the side's `_entries` (and the
1649// indexed-side `hashmap`) OUTSIDE the Dict, in a global store keyed by a stable
1650// `__side_id` that survives cloning. All reads and writes go through the store,
1651// so every clone of a side Dict points at the same buffer — matching JS.
1652/// One order-book level. The price sort-key is stored inline so the bisect
1653/// reads it straight from the contiguous `entries` Vec instead of chasing a
1654/// per-level `Arc<Vec<Value>>` (the scattered-allocation cache cost L1nkus
1655/// flagged). `entry` keeps the full original level Value (extra columns, string
1656/// forms) so reads, checksums and serialization stay byte-identical.
1657struct Level {
1658    price: f64,   // raw price; the sort key (bids sort on -price)
1659    entry: Value, // the full [price, amount, …] level as delivered
1660}
1661struct SideCell {
1662    entries: Vec<Level>,
1663    hashmap: HashMap<String, Value>,
1664}
1665
1666static SIDE_STORE: once_cell::sync::Lazy<std::sync::Mutex<std::collections::HashMap<i64, SideCell>>> =
1667    once_cell::sync::Lazy::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
1668static NEXT_SIDE_ID: std::sync::atomic::AtomicI64 = std::sync::atomic::AtomicI64::new(1);
1669
1670/// Allocate a fresh, empty side cell and return its id.
1671fn alloc_side_id() -> i64 {
1672    let id = NEXT_SIDE_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1673    SIDE_STORE.lock().unwrap().insert(id, SideCell { entries: Vec::new(), hashmap: HashMap::new() });
1674    id
1675}
1676
1677/// Clear (but keep) an existing side cell — used on reset so the id stays
1678/// stable across reseeds instead of leaking a new cell each time.
1679fn clear_side_cell(id: i64) {
1680    let mut g = SIDE_STORE.lock().unwrap();
1681    let cell = g.entry(id).or_insert_with(|| SideCell { entries: Vec::new(), hashmap: HashMap::new() });
1682    cell.entries.clear();
1683    cell.hashmap.clear();
1684}
1685
1686fn side_id_of(m: &HashMap<String, Value>) -> Option<i64> {
1687    match m.get("__side_id") { Some(Value::Int(n)) => Some(*n), _ => None }
1688}
1689
1690/// Snapshot a side's entries (clone) — for read paths (indexing, length, JSON).
1691fn side_entries_view(m: &HashMap<String, Value>) -> Vec<Value> {
1692    match side_id_of(m) {
1693        Some(id) => SIDE_STORE.lock().unwrap().get(&id)
1694            .map(|c| c.entries.iter().map(|l| l.entry.clone()).collect()).unwrap_or_default(),
1695        // Legacy fallback: a side Dict that still carries an inline `_entries`.
1696        None => match m.get("_entries") { Some(Value::Arr(a)) => a.as_ref().clone(), _ => Vec::new() },
1697    }
1698}
1699
1700fn side_entry_at(m: &HashMap<String, Value>, i: usize) -> Value {
1701    match side_id_of(m) {
1702        Some(id) => SIDE_STORE.lock().unwrap().get(&id)
1703            .and_then(|c| c.entries.get(i).map(|l| l.entry.clone())).unwrap_or(Value::Null),
1704        None => match m.get("_entries") {
1705            Some(Value::Arr(a)) => a.get(i).cloned().unwrap_or(Value::Null), _ => Value::Null },
1706    }
1707}
1708
1709pub(crate) fn side_entries_len(m: &HashMap<String, Value>) -> usize {
1710    match side_id_of(m) {
1711        Some(id) => SIDE_STORE.lock().unwrap().get(&id).map(|c| c.entries.len()).unwrap_or(0),
1712        None => match m.get("_entries") { Some(Value::Arr(a)) => a.len(), _ => 0 },
1713    }
1714}
1715
1716/// Mutate a side's cell (entries + hashmap) under the store lock. No-op if the
1717/// side carries no `__side_id`.
1718fn with_side_cell<R>(m: &HashMap<String, Value>, f: impl FnOnce(&mut SideCell) -> R) -> Option<R> {
1719    let id = side_id_of(m)?;
1720    let mut g = SIDE_STORE.lock().unwrap();
1721    let cell = g.entry(id).or_insert_with(|| SideCell { entries: Vec::new(), hashmap: HashMap::new() });
1722    Some(f(cell))
1723}
1724
1725/// Public: snapshot a side marker's entries as a `Value` array, or `None` when
1726/// `v` is not a side marker. Entries live in the shared side store (not the
1727/// Dict), so callers that need the raw `[[price, size, …], …]` list — test
1728/// helpers, serializers — go through this.
1729pub fn side_entries_as_value(v: &Value) -> Option<Value> {
1730    match v {
1731        Value::Dict(d) if d.contains_key("__sideKind") => Some(Value::List(side_entries_view(d))),
1732        _ => None,
1733    }
1734}
1735
1736/// `[price, amount]` for one level row (`Value::Arr`), coercing Str/Int/Float.
1737/// Returns `None` for a short/non-numeric row so it can be dropped.
1738fn row_price_amount(row: &Value) -> Option<[f64; 2]> {
1739    let r = match row { Value::Arr(a) => a, _ => return None };
1740    let num = |cell: Option<&Value>| -> f64 {
1741        match cell {
1742            Some(Value::Float(f)) => *f,
1743            Some(Value::Int(n)) => *n as f64,
1744            Some(Value::Str(s)) => s.parse().unwrap_or(f64::NAN),
1745            _ => f64::NAN,
1746        }
1747    };
1748    let p = num(r.first());
1749    let a = num(r.get(1));
1750    if p.is_nan() || a.is_nan() { None } else { Some([p, a]) }
1751}
1752
1753/// Read a side marker's levels as `[price, amount]` pairs straight from the
1754/// shared side store — no intermediate `Value` list is materialised, so the
1755/// typed `OrderBook::from_value` decode reads the book without cloning every
1756/// level. Returns `None` when `v` is not a side marker (the caller then reads a
1757/// plain `Value::Arr`). NaN/short rows are dropped (not valid book levels).
1758pub fn side_price_amounts(v: &Value) -> Option<Vec<[f64; 2]>> {
1759    let d = match v {
1760        Value::Dict(d) if d.contains_key("__sideKind") => d,
1761        _ => return None,
1762    };
1763    let out = match side_id_of(d) {
1764        Some(id) => match SIDE_STORE.lock().unwrap().get(&id) {
1765            Some(cell) => cell.entries.iter().filter_map(|l| row_price_amount(&l.entry)).collect(),
1766            None => Vec::new(),
1767        },
1768        None => match d.get("_entries") {
1769            Some(Value::Arr(a)) => a.iter().filter_map(row_price_amount).collect(),
1770            _ => Vec::new(),
1771        },
1772    };
1773    Some(out)
1774}
1775
1776/// Build a fresh side marker Dict backed by a new (empty) shared cell.
1777pub(crate) fn make_side_marker(side_kind: &str, is_bid: bool, depth: i64) -> Value {
1778    let sid = alloc_side_id();
1779    let mut m = HashMap::new();
1780    m.insert("__sideKind".to_string(), Value::Str(side_kind.to_string()));
1781    m.insert("_isBid".to_string(),     Value::Bool(is_bid));
1782    m.insert("_depth".to_string(),     Value::Int(depth));
1783    m.insert("__side_id".to_string(),  Value::Int(sid));
1784    Value::Dict(Arc::new(m))
1785}
1786
1787fn side_kind(v: &Value) -> Option<String> {
1788    match v { Value::Dict(d) => match d.get("__sideKind") {
1789        Some(Value::Str(s)) => Some(s.clone()), _ => None,
1790    }, _ => None }
1791}
1792
1793fn side_is_bid(m: &HashMap<String, Value>) -> bool {
1794    matches!(m.get("_isBid"), Some(Value::Bool(true)))
1795}
1796
1797fn side_depth(m: &HashMap<String, Value>) -> usize {
1798    match m.get("_depth") {
1799        Some(Value::Int(n)) if *n > 0 => *n as usize,
1800        _ => usize::MAX / 2,
1801    }
1802}
1803
1804fn level_price(entries: &[Level]) -> impl Fn(usize) -> f64 + '_ {
1805    move |i: usize| entries[i].price
1806}
1807
1808fn bisect_left_by(len: usize, target: f64, is_bid: bool, get_price: impl Fn(usize) -> f64) -> usize {
1809    let mut lo = 0usize;
1810    let mut hi = len;
1811    while lo < hi {
1812        let mid = (lo + hi) / 2;
1813        let p = get_price(mid);
1814        let ip = if is_bid { -p } else { p };
1815        if ip < target { lo = mid + 1; } else { hi = mid; }
1816    }
1817    lo
1818}
1819
1820fn delta_field<T>(d: &Value, idx: usize, parse: impl Fn(&Value) -> T, default: T) -> T {
1821    match d {
1822        Value::Arr(a) => match a.get(idx) { Some(v) => parse(v), None => default },
1823        _ => default,
1824    }
1825}
1826
1827fn entry_id(entries: &[Level], i: usize) -> String {
1828    if let Value::Arr(a) = &entries[i].entry {
1829        if let Some(v) = a.get(2) {
1830            return match v {
1831                Value::Str(s) => s.clone(),
1832                Value::Int(n) => n.to_string(),
1833                _ => String::new(),
1834            };
1835        }
1836    }
1837    String::new()
1838}
1839
1840fn side_store_array(side: &Value, delta: Value) {
1841    let kind = side_kind(side).unwrap_or_default();
1842    let m = match side { Value::Dict(d) => d.as_ref(), _ => return };
1843    let is_bid = side_is_bid(m);
1844    with_side_cell(m, |cell| {
1845    match kind.as_str() {
1846        "OrderBookSide" => {
1847            let price = delta_field(&delta, 0, as_f64, 0.0);
1848            let size  = delta_field(&delta, 1, as_f64, 0.0);
1849            let target = if is_bid { -price } else { price };
1850            let entries = &mut cell.entries;
1851            let idx = bisect_left_by(entries.len(), target, is_bid, level_price(entries));
1852            let matches_here = idx < entries.len()
1853                && (if is_bid { -entries[idx].price } else { entries[idx].price }) == target;
1854            if size != 0.0 {
1855                if matches_here {
1856                    entries[idx] = Level { price, entry: delta };
1857                } else {
1858                    entries.insert(idx, Level { price, entry: delta });
1859                }
1860            } else if matches_here {
1861                entries.remove(idx);
1862            }
1863        }
1864        "CountedOrderBookSide" => {
1865            let price = delta_field(&delta, 0, as_f64, 0.0);
1866            let size  = delta_field(&delta, 1, as_f64, 0.0);
1867            let count = delta_field(&delta, 2, as_f64, 0.0);
1868            // JS gates a counted store on `size && count`, but some venues drive
1869            // a counted book with no numeric count in slot 2 — bitget stores
1870            // `[price, size, [rawPrice, rawSize]]` (the raw pair, for checksums).
1871            // Only treat slot 2 as a count when it's actually a number; otherwise
1872            // gate on size alone so the entry stores.
1873            let has_count = matches!(&delta,
1874                Value::Arr(a) if matches!(a.get(2), Some(Value::Int(_)) | Some(Value::Float(_))));
1875            let store_it = if has_count { size != 0.0 && count != 0.0 } else { size != 0.0 };
1876            let target = if is_bid { -price } else { price };
1877            let entries = &mut cell.entries;
1878            let idx = bisect_left_by(entries.len(), target, is_bid, level_price(entries));
1879            let matches_here = idx < entries.len()
1880                && (if is_bid { -entries[idx].price } else { entries[idx].price }) == target;
1881            if store_it {
1882                if matches_here {
1883                    entries[idx] = Level { price, entry: delta };
1884                } else {
1885                    entries.insert(idx, Level { price, entry: delta });
1886                }
1887            } else if matches_here {
1888                entries.remove(idx);
1889            }
1890        }
1891        "IndexedOrderBookSide" => {
1892            let price_opt = match &delta {
1893                Value::Arr(a) => a.first().and_then(|v| match v {
1894                    Value::Float(f) => Some(*f),
1895                    Value::Int(n)   => Some(*n as f64),
1896                    _ => None,
1897                }),
1898                _ => None,
1899            };
1900            let size = delta_field(&delta, 1, as_f64, 0.0);
1901            let id = match &delta {
1902                Value::Arr(a) => match a.get(2) {
1903                    Some(Value::Str(s)) => s.clone(),
1904                    Some(Value::Int(n)) => n.to_string(),
1905                    _ => String::new(),
1906                },
1907                _ => String::new(),
1908            };
1909            let mut index_price = price_opt.map(|p| if is_bid { -p } else { p });
1910            let old_price_opt = {
1911                match cell.hashmap.get(&id) {
1912                    Some(Value::Float(f)) => Some(*f),
1913                    Some(Value::Int(n))   => Some(*n as f64),
1914                    _ => None,
1915                }
1916            };
1917            if size != 0.0 {
1918                if let Some(old_price) = old_price_opt {
1919                    index_price = index_price.or(Some(old_price));
1920                    if Some(old_price) == index_price {
1921                        // Find slot by walking from bisect_left
1922                        let target = old_price;
1923                        let raw = if is_bid { -old_price } else { old_price };
1924                        let entries = &mut cell.entries;
1925                        let mut idx = bisect_left_by(entries.len(), target, is_bid, level_price(entries));
1926                        while idx < entries.len() && entry_id(entries, idx) != id { idx += 1; }
1927                        if idx < entries.len() { entries[idx] = Level { price: raw, entry: delta }; }
1928                        return;
1929                    }
1930                    // Different price — remove old slot
1931                    let target = old_price;
1932                    let entries = &mut cell.entries;
1933                    let mut old_idx = bisect_left_by(entries.len(), target, is_bid, level_price(entries));
1934                    while old_idx < entries.len() && entry_id(entries, old_idx) != id { old_idx += 1; }
1935                    if old_idx < entries.len() { entries.remove(old_idx); }
1936                }
1937                let target = match index_price { Some(p) => p, None => return };
1938                let raw = if is_bid { -target } else { target };
1939                // Insert sorted with secondary id tiebreaker
1940                let entries = &mut cell.entries;
1941                let mut idx = bisect_left_by(entries.len(), target, is_bid, level_price(entries));
1942                while idx < entries.len() {
1943                    let ip = if is_bid { -entries[idx].price } else { entries[idx].price };
1944                    if ip != target { break; }
1945                    if entry_id(entries, idx) >= id { break; }
1946                    idx += 1;
1947                }
1948                entries.insert(idx, Level { price: raw, entry: delta });
1949                cell.hashmap.insert(id, Value::Float(target));
1950            } else if let Some(old_price) = old_price_opt {
1951                // Delete by id
1952                let target = old_price;
1953                let entries = &mut cell.entries;
1954                let mut idx = bisect_left_by(entries.len(), target, is_bid, level_price(entries));
1955                while idx < entries.len() && entry_id(entries, idx) != id { idx += 1; }
1956                if idx < entries.len() { entries.remove(idx); }
1957                cell.hashmap.shift_remove(&id);
1958            }
1959        }
1960        _ => {}
1961    }
1962    });
1963}
1964
1965fn side_limit(side: &Value) {
1966    let m = match side { Value::Dict(d) => d.as_ref(), _ => return };
1967    let depth = side_depth(m);
1968    with_side_cell(m, |cell| {
1969        if cell.entries.len() > depth { cell.entries.truncate(depth); }
1970    });
1971}
1972
1973fn book_reseed_sides(book: &mut Value, snapshot: &Value) {
1974    let kind = book_kind(book).unwrap_or_default();
1975    let side_kind_str = match kind.as_str() {
1976        "IndexedOrderBook" => "IndexedOrderBookSide",
1977        "CountedOrderBook" => "CountedOrderBookSide",
1978        _                  => "OrderBookSide",
1979    };
1980    let bids_deltas = crate::get_value(snapshot, &Value::Str("bids".to_string()));
1981    let asks_deltas = crate::get_value(snapshot, &Value::Str("asks".to_string()));
1982    if let Value::Dict(book_arc) = book {
1983        let book_m = Arc::make_mut(book_arc);
1984        let depth = match book_m.get("_depth") {
1985            Some(Value::Int(n)) => *n,
1986            _ => i64::MAX / 2,
1987        };
1988        // Rebuild bids/asks. Reuse the existing side's `__side_id` (clearing its
1989        // backing cell) so repeated resets don't leak a fresh cell each time.
1990        for (side_key, deltas, is_bid) in [
1991            ("bids", &bids_deltas, true),
1992            ("asks", &asks_deltas, false),
1993        ] {
1994            let sid = match book_m.get(side_key) {
1995                Some(Value::Dict(d)) => match d.get("__side_id") {
1996                    Some(Value::Int(n)) => { clear_side_cell(*n); *n }
1997                    _ => alloc_side_id(),
1998                },
1999                _ => alloc_side_id(),
2000            };
2001            let mut m = HashMap::new();
2002            m.insert("__sideKind".to_string(),  Value::Str(side_kind_str.to_string()));
2003            m.insert("_isBid".to_string(),      Value::Bool(is_bid));
2004            m.insert("_depth".to_string(),      Value::Int(depth));
2005            m.insert("__side_id".to_string(),   Value::Int(sid));
2006            let side = Value::Map(m);
2007            if let Value::Arr(rows) = deltas {
2008                for row in rows.iter() {
2009                    if let Value::Arr(_) = row { side_store_array(&side, row.clone()); }
2010                }
2011            }
2012            book_m.insert(side_key.to_string(), side);
2013        }
2014    }
2015}
2016
2017pub(crate) fn book_limit(book: &mut Value) {
2018    if book_kind(book).is_none() { return; }
2019    if let Value::Dict(arc) = book {
2020        let m = Arc::make_mut(arc);
2021        if let Some(side) = m.get_mut("bids") { side_limit(side); }
2022        if let Some(side) = m.get_mut("asks") { side_limit(side); }
2023    }
2024}
2025
2026pub(crate) fn book_reset(book: &mut Value, snapshot: Value) {
2027    if book_kind(book).is_none() { return; }
2028    book_reseed_sides(book, &snapshot);
2029    let id = match book { Value::Dict(d) => book_id_of(d), _ => None };
2030    if let Some(id) = id {
2031        let ts = match crate::get_value(&snapshot, &Value::Str("timestamp".to_string())) {
2032            Value::Int(n)   => Some(n),
2033            Value::Float(f) => Some(f as i64),
2034            _ => None,
2035        };
2036        let dt = ts.and_then(|n| chrono::DateTime::<chrono::Utc>::from_timestamp_millis(n)
2037            .map(|t| t.to_rfc3339_opts(chrono::SecondsFormat::Millis, true)));
2038        book_meta_set(id, "timestamp", ts.map(Value::Int).unwrap_or(Value::Null));
2039        book_meta_set(id, "datetime",  dt.map(Value::Str).unwrap_or(Value::Null));
2040        book_meta_set(id, "nonce",     crate::get_value(&snapshot, &Value::Str("nonce".to_string())));
2041        book_meta_set(id, "symbol",    crate::get_value(&snapshot, &Value::Str("symbol".to_string())));
2042    }
2043}
2044
2045pub(crate) fn book_update(book: &mut Value, snapshot: Value) {
2046    if book_kind(book).is_none() { return; }
2047    // Skip stale updates.
2048    let new_nonce = match crate::get_value(&snapshot, &Value::Str("nonce".to_string())) {
2049        Value::Int(n) => Some(n), _ => None,
2050    };
2051    let cur_nonce = match book {
2052        Value::Dict(d) => match book_id_of(d).map(|id| book_meta_get(id, "nonce")) {
2053            Some(Value::Int(n)) => Some(n), _ => None,
2054        },
2055        _ => None,
2056    };
2057    if let (Some(n), Some(cur)) = (new_nonce, cur_nonce) {
2058        if n <= cur { return; }
2059    }
2060    book_reset(book, snapshot);
2061}
2062
2063pub(crate) fn book_store_array_side(book: &mut Value, side_key: &str, delta: Value) {
2064    if let Value::Dict(arc) = book {
2065        let m = Arc::make_mut(arc);
2066        if let Some(side) = m.get_mut(side_key) {
2067            side_store_array(side, delta);
2068        }
2069    }
2070}
2071
2072
2073// ─── Value method API exposed to the transpiled tests ─────────────────────
2074
2075impl Value {
2076    /// `book.limit()` — trim both sides to `_depth`. Returns a clone
2077    /// of `self` so transpiled `return book.limit();` lines still
2078    /// match the `-> Value` signature.
2079    pub fn limit(&mut self) -> Value {
2080        book_limit(self);
2081        self.clone()
2082    }
2083
2084    /// `book.reset(snapshot)` — wipe + reseed bids/asks + metadata.
2085    /// Returns self for the same reason as `limit()`. A bare
2086    /// `book.reset()` is also valid (matches the TS `OrderBook` shape);
2087    /// when called without a snapshot, we just rebind the existing one
2088    /// (effectively a no-op metadata refresh).
2089    pub fn reset(&mut self, snapshot: Value) -> Value {
2090        // `client.reset(error)` — a WS client handle (carries "url") resets its
2091        // registry entry; everything else is an OrderBook snapshot reset.
2092        if matches!(&self, Value::Dict(d) if d.contains_key("url") && d.contains_key("subscriptions")) {
2093            return crate::pro::ws_client::value_reset(self);
2094        }
2095        book_reset(self, snapshot);
2096        self.clone()
2097    }
2098    /// Zero-arg `reset()` form used by per-exchange WS code that just
2099    /// wants to clear the rolling buffers.
2100    pub fn reset0(&mut self) -> Value {
2101        book_reset(self, Value::Null);
2102        self.clone()
2103    }
2104
2105    /// `book.update(snapshot)` — same as reset but only when the
2106    /// supplied nonce moves forward.
2107    pub fn update(&mut self, snapshot: Value) -> Value {
2108        book_update(self, snapshot);
2109        self.clone()
2110    }
2111
2112    /// `side.store(price, size)` — convenience that builds a 2-element
2113    /// delta. Routed through the side's `store_array`. Only useful on a
2114    /// side marker (returned by `book['bids']`), not the book itself.
2115    pub fn store(&mut self, price: Value, size: Value) {
2116        if side_kind(self).is_some() {
2117            let delta = Value::List(vec![price, size]);
2118            side_store_array(self, delta);
2119        }
2120    }
2121
2122    /// Book-level side mutators — the transpiler rewrites side-extraction
2123    /// patterns (`let bids = book['bids']; bids.X(...)`) into calls on
2124    /// these methods so the mutation reaches the book's actual side
2125    /// dict rather than a COW-cloned copy of it.
2126    pub fn store_to_bids(&mut self, price: Value, size: Value) {
2127        let delta = Value::List(vec![price, size]);
2128        book_store_array_side(self, "bids", delta);
2129    }
2130    pub fn store_to_asks(&mut self, price: Value, size: Value) {
2131        let delta = Value::List(vec![price, size]);
2132        book_store_array_side(self, "asks", delta);
2133    }
2134    pub fn store_array_to_bids(&mut self, delta: Value) {
2135        book_store_array_side(self, "bids", delta);
2136    }
2137    pub fn store_array_to_asks(&mut self, delta: Value) {
2138        book_store_array_side(self, "asks", delta);
2139    }
2140}
2141
2142#[cfg(test)]
2143mod json_int_precision_tests {
2144    use super::Value;
2145
2146    #[test]
2147    fn preserves_large_u64_ids_losslessly() {
2148        // 12345678901234567890 > i64::MAX but ≤ u64::MAX — must not round.
2149        let v: serde_json::Value = serde_json::from_str(r#"{"id": 12345678901234567890}"#).unwrap();
2150        let parsed = Value::from_json(&v);
2151        let id = crate::runtime::get_value(&parsed, &Value::Str("id".to_string()));
2152        assert_eq!(id, Value::Str("12345678901234567890".to_string()));
2153    }
2154
2155    #[test]
2156    fn small_ints_stay_ints_floats_stay_floats() {
2157        let v: serde_json::Value = serde_json::from_str(r#"{"a": 42, "b": -7, "c": 1.5}"#).unwrap();
2158        let p = Value::from_json(&v);
2159        assert_eq!(crate::runtime::get_value(&p, &Value::Str("a".to_string())), Value::Int(42));
2160        assert_eq!(crate::runtime::get_value(&p, &Value::Str("b".to_string())), Value::Int(-7));
2161        assert_eq!(crate::runtime::get_value(&p, &Value::Str("c".to_string())), Value::Float(1.5));
2162    }
2163}