1pub use indexmap::IndexMap as HashMap;
18use std::sync::Arc;
19#[cfg(feature = "transpiled-base")]
20use crate::exchange_generated::ExchangeBase;
21
22#[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 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 if decimals < 0 {
73 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 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 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 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 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 #[allow(non_snake_case)]
145 pub fn List(items: Vec<Value>) -> Value {
146 Value::Arr(Arc::new(items))
147 }
148
149 #[allow(non_snake_case)]
153 pub fn Map(m: HashMap<String, Value>) -> Value {
154 Value::Dict(Arc::new(m))
155 }
156
157 #[allow(non_snake_case)]
159 pub fn Array(a: Vec<Value>) -> Value {
160 Value::Arr(Arc::new(a))
161 }
162
163 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 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 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 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 pub fn describe(&self) -> Value { Value::Null }
250 pub fn reject(&self, args: &[Value]) -> Value {
254 crate::pro::ws_client::value_reject(self, args)
255 }
256 pub fn resolve(&self, args: &[Value]) -> Value {
259 crate::pro::ws_client::value_resolve(self, args)
260 }
261 pub fn future(&self, args: &[Value]) -> Value {
269 self.open_flight(args.get(0).cloned().unwrap_or(Value::Null))
270 }
271 pub fn reusable_future(&self, msg_hash: Value) -> Value {
274 self.open_flight(msg_hash)
275 }
276 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 pub fn hashmap(&self) -> Value {
298 if let Value::Dict(d) = self {
299 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 pub fn send(&self, args: &[Value]) -> Value {
316 crate::pro::ws_client::value_send(self, args)
317 }
318 pub fn decode_proto_msg(&self, _args: &[Value]) -> Value { Value::Null }
321 pub fn on_pong(&self, _args: &[Value]) -> Value {
323 crate::pro::ws_client::value_on_pong(self)
324 }
325 pub fn call(&self, _args: &[Value]) -> Value { Value::Null }
327 pub fn is_dictionary(&self, value: Value) -> Value {
331 Value::Bool(matches!(value, Value::Dict(_)))
332 }
333 #[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 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 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 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 pub fn set_markets(&mut self, markets: Value) -> Value {
397 #[cfg(feature = "transpiled-base")]
398 {
399 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 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 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 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 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 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 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
527impl 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) } }
562impl 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
582type LiveLookupFn = fn(id: &str, key: &str) -> Option<Value>;
592static 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 Some(unsafe { std::mem::transmute::<usize, LiveLookupFn>(n) })
610 }
611}
612
613type 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 Some(unsafe { std::mem::transmute::<usize, LiveSetMarketsFn>(n) })
632 }
633}
634
635#[inline]
639pub fn get_value_k(obj: &Value, key: &str) -> Value {
640 if let Value::Dict(m) = obj {
641 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
664pub fn get_value(obj: &Value, key: &Value) -> Value {
667 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 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 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 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 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 (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
767pub 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 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
788pub 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 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
837pub 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
854fn cache_str_field(item: &Value, key: &str) -> Option<String> {
860 match item {
861 Value::Dict(d) => match d.get(key) {
862 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
876fn 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
900pub(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 {
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 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
958fn 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
1000fn 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
1021fn 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
1037fn 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
1048fn 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
1061fn 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
1069fn 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
1076fn 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
1091static 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
1103pub(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
1126fn 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
1155pub(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 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 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 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 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 {
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 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 if now_empty { hm.shift_remove(&r_sym); }
1345 }
1346 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 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
1396fn cache_get_limit_inner(m: &mut HashMap<String, Value>, kind: &str, symbol: Value, limit: Value) -> Value {
1401 {
1402 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
1437fn 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
1460static 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
1473fn 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
1503static 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
1513fn 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
1532pub(crate) fn book_cache_len_of(m: &HashMap<String, Value>) -> Option<usize> {
1534 book_cache_id_of(m).map(book_cache_len)
1535}
1536
1537pub(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
1548pub(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
1559pub(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
1569pub(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
1581pub(crate) fn book_cache_set(id: i64, items: Vec<Value>) {
1583 BOOK_CACHE.lock().unwrap().insert(id, items);
1584}
1585
1586pub 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
1605pub(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 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
1622pub 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
1640struct Level {
1658 price: f64, entry: Value, }
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
1670fn 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
1677fn 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
1690fn 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 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
1716fn 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
1725pub 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
1736fn 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
1753pub 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
1776pub(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 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 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 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 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 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 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 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
2073impl Value {
2076 pub fn limit(&mut self) -> Value {
2080 book_limit(self);
2081 self.clone()
2082 }
2083
2084 pub fn reset(&mut self, snapshot: Value) -> Value {
2090 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 pub fn reset0(&mut self) -> Value {
2101 book_reset(self, Value::Null);
2102 self.clone()
2103 }
2104
2105 pub fn update(&mut self, snapshot: Value) -> Value {
2108 book_update(self, snapshot);
2109 self.clone()
2110 }
2111
2112 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 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 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}