1#![allow(clippy::float_cmp, clippy::needless_return, dead_code)]
12
13use crate::Value;
14use indexmap::IndexMap as HashMap;
15use std::sync::Arc;
16
17fn as_f64(v: &Value) -> Option<f64> {
20 match v {
21 Value::Int(n) => Some(*n as f64),
22 Value::Float(f) => Some(*f),
23 Value::Str(s) => s.parse().ok(),
24 Value::Bool(b) => Some(if *b { 1.0 } else { 0.0 }),
25 _ => None,
26 }
27}
28
29fn as_i64(v: &Value) -> Option<i64> {
30 match v {
31 Value::Int(n) => Some(*n),
32 Value::Float(f) => Some(*f as i64),
33 Value::Str(s) => s.parse().ok(),
34 Value::Bool(b) => Some(if *b { 1 } else { 0 }),
35 _ => None,
36 }
37}
38
39fn both_ints(a: &Value, b: &Value) -> bool {
40 matches!(a, Value::Int(_)) && matches!(b, Value::Int(_))
41}
42
43pub fn add(a: &Value, b: &Value) -> Value {
44 if let (Value::Str(sa), Value::Str(sb)) = (a, b) {
46 return Value::Str(format!("{sa}{sb}"));
47 }
48 if let Value::Str(_) = a { if let Some(_) = as_f64(b) {} return string_concat(a, b); }
49 if let Value::Str(_) = b { return string_concat(a, b); }
50 if both_ints(a, b) {
51 return Value::Int(as_i64(a).unwrap() + as_i64(b).unwrap());
52 }
53 match (as_f64(a), as_f64(b)) {
54 (Some(x), Some(y)) => Value::Float(x + y),
55 _ => Value::Null,
56 }
57}
58
59fn string_concat(a: &Value, b: &Value) -> Value {
60 let sa = stringify_simple(a);
61 let sb = stringify_simple(b);
62 Value::Str(format!("{sa}{sb}"))
63}
64
65pub fn stringify_param(v: &Value) -> String { stringify_simple(v) }
66
67fn stringify_simple(v: &Value) -> String {
68 match v {
69 Value::Str(s) => s.clone(),
70 Value::Int(n) => n.to_string(),
71 Value::Float(f) => f.to_string(),
72 Value::Bool(b) => b.to_string(),
73 Value::Null => "null".to_string(),
74 Value::Dict(m) if m.contains_key("__precise") => precise_to_string(m),
79 _ => format!("{v}"),
80 }
81}
82
83fn precise_to_string(m: &indexmap::IndexMap<String, Value>) -> String {
84 let decimals: i64 = match m.get("decimals") { Some(Value::Int(n)) => *n, _ => 0 };
85 let integer: String = match m.get("integer") {
86 Some(Value::Str(s)) => s.clone(),
87 _ => return "0".to_string(),
88 };
89 let (sign, mut digits) = if let Some(rest) = integer.strip_prefix('-') {
90 ("-".to_string(), rest.to_string())
91 } else { ("".to_string(), integer) };
92 if decimals <= 0 {
93 for _ in 0..(-decimals) { digits.push('0'); }
95 return format!("{sign}{digits}");
96 }
97 let d = decimals as usize;
98 if digits.len() <= d {
99 let zeros = "0".repeat(d - digits.len());
101 format!("{sign}0.{zeros}{digits}")
102 } else {
103 let split = digits.len() - d;
104 let (int_part, frac_part) = digits.split_at(split);
105 format!("{sign}{int_part}.{frac_part}")
106 }
107}
108
109pub fn subtract(a: &Value, b: &Value) -> Value {
110 if both_ints(a, b) { return Value::Int(as_i64(a).unwrap() - as_i64(b).unwrap()); }
111 match (as_f64(a), as_f64(b)) {
112 (Some(x), Some(y)) => Value::Float(x - y),
113 _ => Value::Null,
114 }
115}
116
117pub fn multiply(a: &Value, b: &Value) -> Value {
118 if both_ints(a, b) { return Value::Int(as_i64(a).unwrap() * as_i64(b).unwrap()); }
119 match (as_f64(a), as_f64(b)) {
120 (Some(x), Some(y)) => Value::Float(x * y),
121 _ => Value::Null,
122 }
123}
124
125pub fn divide(a: &Value, b: &Value) -> Value {
126 match (as_f64(a), as_f64(b)) {
127 (Some(_), Some(y)) if y == 0.0 => Value::Null,
128 (Some(x), Some(y)) => Value::Float(x / y),
129 _ => Value::Null,
130 }
131}
132
133pub fn mod_val(a: &Value, b: &Value) -> Value {
134 if both_ints(a, b) {
135 let yi = as_i64(b).unwrap();
136 if yi == 0 { return Value::Null; }
137 return Value::Int(as_i64(a).unwrap() % yi);
138 }
139 match (as_f64(a), as_f64(b)) {
140 (Some(_), Some(y)) if y == 0.0 => Value::Null,
141 (Some(x), Some(y)) => Value::Float(x % y),
142 _ => Value::Null,
143 }
144}
145
146pub fn negate(v: &Value) -> Value {
147 match v {
148 Value::Int(n) => Value::Int(-n),
149 Value::Float(f) => Value::Float(-f),
150 _ => match as_f64(v) {
151 Some(x) => Value::Float(-x),
152 None => Value::Null,
153 },
154 }
155}
156
157pub fn is_equal(a: &Value, b: &Value) -> bool {
160 match (a, b) {
161 (Value::Null, Value::Null) => true,
162 (Value::Bool(x), Value::Bool(y)) => x == y,
163 (Value::Str(x), Value::Str(y)) => x == y,
164 (Value::Int(x), Value::Int(y)) => x == y,
165 (Value::Float(x), Value::Float(y)) => x == y,
166 _ => match (as_f64(a), as_f64(b)) {
167 (Some(x), Some(y)) => x == y,
168 _ => false,
169 },
170 }
171}
172
173pub fn is_greater_than(a: &Value, b: &Value) -> bool {
174 match (as_f64(a), as_f64(b)) {
175 (Some(x), Some(y)) => x > y,
176 _ => match (a, b) { (Value::Str(x), Value::Str(y)) => x > y, _ => false },
177 }
178}
179
180pub fn is_less_than(a: &Value, b: &Value) -> bool {
181 match (as_f64(a), as_f64(b)) {
182 (Some(x), Some(y)) => x < y,
183 _ => match (a, b) { (Value::Str(x), Value::Str(y)) => x < y, _ => false },
184 }
185}
186
187pub fn is_greater_than_or_equal(a: &Value, b: &Value) -> bool {
188 is_greater_than(a, b) || is_equal(a, b)
189}
190
191pub fn is_less_than_or_equal(a: &Value, b: &Value) -> bool {
192 is_less_than(a, b) || is_equal(a, b)
193}
194
195pub trait IsTruthy { fn truthy(&self) -> bool; }
202impl IsTruthy for Value { fn truthy(&self) -> bool { self.is_truthy() } }
203impl IsTruthy for bool { fn truthy(&self) -> bool { *self } }
204impl IsTruthy for &Value { fn truthy(&self) -> bool { (*self).is_truthy() } }
205impl IsTruthy for &bool { fn truthy(&self) -> bool { **self } }
206
207pub fn is_true<T: IsTruthy + ?Sized>(v: &T) -> bool { v.truthy() }
208
209pub fn is_array(v: &Value) -> bool { matches!(v, Value::Arr(_)) }
210pub fn is_object(v: &Value) -> bool { matches!(v, Value::Dict(_)) }
211pub fn is_string(v: &Value) -> bool { matches!(v, Value::Str(_)) }
212pub fn is_number(v: &Value) -> bool { matches!(v, Value::Int(_) | Value::Float(_)) }
213pub fn is_bool(v: &Value) -> bool { matches!(v, Value::Bool(_)) }
214pub fn is_integer(v: &Value) -> bool { matches!(v, Value::Int(_)) }
215pub fn is_function(_v: &Value)-> bool { false }
216
217pub fn panic_to_value(payload: Box<dyn std::any::Any + Send>) -> Value {
224 let msg = payload.downcast_ref::<String>().cloned()
225 .or_else(|| payload.downcast_ref::<&str>().map(|s| (*s).to_string()))
226 .unwrap_or_else(|| "panic".to_string());
227 Value::Str(msg)
228}
229
230pub fn panic_msg_to_error(msg: &str) -> crate::ExchangeError {
234 if let Some(start) = msg.find('[') {
235 let after = &msg[start + 1..];
236 if let Some(end) = after.find(']') {
237 let kind = &after[..end];
238 let rest = after[end + 1..].trim_start_matches(|c: char| c == ' ' || c == ':');
239 return crate::ExchangeError::new(kind, rest);
240 }
241 }
242 crate::ExchangeError::new("ExchangeError", msg)
243}
244
245pub fn catch_typed<F, T>(f: F) -> crate::Result<T>
254where
255 F: FnOnce() -> T,
256{
257 match std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) {
258 Ok(v) => Ok(v),
259 Err(payload) => {
260 let msg = payload.downcast_ref::<String>().cloned()
261 .or_else(|| payload.downcast_ref::<&str>().map(|s| (*s).to_string()))
262 .unwrap_or_else(|| "panic".to_string());
263 Err(panic_msg_to_error(&msg))
264 }
265 }
266}
267
268pub async fn call_typed<F, T>(fut: F) -> crate::Result<T>
269where
270 F: std::future::Future<Output = T>,
271{
272 use futures::FutureExt;
273 use std::panic::AssertUnwindSafe;
274 match AssertUnwindSafe(fut).catch_unwind().await {
275 Ok(v) => Ok(v),
276 Err(payload) => {
277 let msg = payload.downcast_ref::<String>().cloned()
278 .or_else(|| payload.downcast_ref::<&str>().map(|s| (*s).to_string()))
279 .unwrap_or_else(|| "panic".to_string());
280 Err(panic_msg_to_error(&msg))
281 }
282 }
283}
284
285pub fn is_instance(value: &Value, class: &Value) -> bool {
292 let (msg, cls) = match (value, class) {
293 (Value::Str(s), Value::Str(c)) => (s, c),
294 _ => return false,
295 };
296 if msg.contains(&format!("[{cls}]")) {
300 return true;
301 }
302 if let Some(actual) = extract_error_kind(msg) {
308 let mut cur = error_parent(actual);
309 while let Some(c) = cur {
310 if c == cls.as_str() {
311 return true;
312 }
313 cur = error_parent(c);
314 }
315 }
316 false
317}
318
319fn extract_error_kind(msg: &str) -> Option<&str> {
321 let start = msg.find('[')? + 1;
322 let end = msg[start..].find(']')? + start;
323 Some(&msg[start..end])
324}
325
326fn error_parent(class: &str) -> Option<&'static str> {
329 Some(match class {
330 "ExchangeError" => "BaseError",
332 "AuthenticationError" => "ExchangeError",
333 "PermissionDenied" => "AuthenticationError",
334 "AccountNotEnabled" => "PermissionDenied",
335 "AccountSuspended" => "AuthenticationError",
336 "ArgumentsRequired" => "ExchangeError",
337 "BadRequest" => "ExchangeError",
338 "BadSymbol" => "BadRequest",
339 "OperationRejected" => "ExchangeError",
340 "NoChange" => "OperationRejected",
341 "MarginModeAlreadySet" => "NoChange",
342 "MarketClosed" => "OperationRejected",
343 "ManualInteractionNeeded" => "OperationRejected",
344 "RestrictedLocation" => "OperationRejected",
345 "InsufficientFunds" => "ExchangeError",
346 "InvalidAddress" => "ExchangeError",
347 "AddressPending" => "InvalidAddress",
348 "InvalidOrder" => "ExchangeError",
349 "OrderNotFound" => "InvalidOrder",
350 "OrderNotCached" => "InvalidOrder",
351 "OrderImmediatelyFillable" => "InvalidOrder",
352 "OrderNotFillable" => "InvalidOrder",
353 "DuplicateOrderId" => "InvalidOrder",
354 "ContractUnavailable" => "InvalidOrder",
355 "NotSupported" => "ExchangeError",
356 "InvalidProxySettings" => "ExchangeError",
357 "ExchangeClosedByUser" => "ExchangeError",
358 "OperationFailed" => "BaseError",
360 "NetworkError" => "OperationFailed",
361 "DDoSProtection" => "NetworkError",
362 "RateLimitExceeded" => "NetworkError",
363 "ExchangeNotAvailable" => "NetworkError",
364 "OnMaintenance" => "ExchangeNotAvailable",
365 "InvalidNonce" => "NetworkError",
366 "ChecksumError" => "InvalidNonce",
367 "RequestTimeout" => "NetworkError",
368 "BadResponse" => "OperationFailed",
369 "NullResponse" => "BadResponse",
370 "CancelPending" => "OperationFailed",
371 "UnsubscribeError" => "BaseError",
372 _ => return None,
373 })
374}
375
376pub fn get_value(obj: &Value, key: &Value) -> Value {
379 crate::value::get_value(obj, key)
380}
381
382#[allow(clippy::mut_from_ref, invalid_reference_casting)]
396pub unsafe fn coerce_value_to_mut(v: &Value) -> &mut Value {
397 let ptr = v as *const Value as *mut Value;
398 &mut *ptr
399}
400
401pub fn get_value_mut<'a>(obj: &'a mut Value, key: &Value) -> &'a mut Value {
402 match (obj, key) {
403 (Value::Dict(m), Value::Str(k)) => Arc::make_mut(m).entry(k.clone()).or_insert(Value::Null),
404 (Value::Arr(a), Value::Int(i)) => {
405 let idx = *i as usize;
406 let a = Arc::make_mut(a);
407 while a.len() <= idx { a.push(Value::Null); }
408 &mut a[idx]
409 }
410 (other, _) => other,
411 }
412}
413
414pub fn add_element_to_object(obj: &mut Value, key: &Value, val: Value) {
415 match (obj, key) {
416 (Value::Dict(m), Value::Str(k)) => {
417 if crate::value::try_book_meta_write(m, k, &val) { return; }
418 crate::value::try_ws_subs_write(m, k, &val);
421 crate::value::try_ws_sub_field_write(m, k, &val);
422 crate::value::try_cache_hashmap_write(m, k, &val);
426 Arc::make_mut(m).insert(k.clone(), val);
427 }
428 (Value::Dict(m), other) => { Arc::make_mut(m).insert(stringify_simple(other), val); }
429 (Value::Arr(a), Value::Int(i)) => {
430 let idx = *i as usize;
431 let a = Arc::make_mut(a);
432 while a.len() <= idx { a.push(Value::Null); }
433 a[idx] = val;
434 }
435 _ => {}
436 }
437}
438
439pub fn remove(obj: &mut Value, key: &Value) {
440 match (obj, key) {
441 (Value::Dict(m), Value::Str(k)) => {
442 crate::value::try_ws_subs_remove(m, k);
443 Arc::make_mut(m).shift_remove(k);
444 }
445 (Value::Arr(a), Value::Int(i)) => {
446 let idx = *i as usize;
447 let a = Arc::make_mut(a);
448 if idx < a.len() { a.remove(idx); }
449 }
450 _ => {}
451 }
452}
453
454pub fn shift(mut arr: Value) -> Value {
459 if let Value::Arr(a) = &mut arr {
460 let inner = Arc::make_mut(a);
461 if !inner.is_empty() { return inner.remove(0); }
462 }
463 Value::Null
464}
465
466pub fn in_op(obj: &Value, key: &Value) -> bool {
467 match (obj, key) {
468 (Value::Dict(m), Value::Str(k)) => m.contains_key(k),
469 (Value::Arr(a), v) => a.iter().any(|x| is_equal(x, v)),
470 _ => false,
471 }
472}
473
474fn is_ws_internal_tag(k: &str) -> bool {
479 k == "__ws_subs_url" || k == "__ws_sub_ref"
480}
481
482pub fn object_keys(v: &Value) -> Value {
483 match v {
484 Value::Dict(m) => Value::Array(
485 m.keys().filter(|k| !is_ws_internal_tag(k))
486 .map(|k| Value::Str(k.clone())).collect()),
487 _ => Value::Array(vec![]),
488 }
489}
490
491pub fn object_values(v: &Value) -> Value {
492 match v {
493 Value::Dict(m) => Value::Array(
494 m.iter().filter(|(k, _)| !is_ws_internal_tag(k))
495 .map(|(_, val)| val.clone()).collect()),
496 _ => Value::Array(vec![]),
497 }
498}
499
500pub fn get_array_length(v: &Value) -> Value {
501 if let Value::Dict(d) = v {
506 if let Some(n) = crate::value::book_cache_len_of(d) {
507 return Value::Int(n as i64);
508 }
509 if let Some(n) = crate::value::cache_len_of_marker(d) {
510 return Value::Int(n as i64);
511 }
512 if d.contains_key("__sideKind") {
513 return Value::Int(crate::value::side_entries_len(d) as i64);
514 }
515 }
516 Value::Int(v.len() as i64)
517}
518
519pub fn get_index_of(haystack: &Value, needle: &Value) -> Value {
520 match haystack {
521 Value::Arr(a) => {
522 for (i, item) in a.iter().enumerate() {
523 if is_equal(item, needle) { return Value::Int(i as i64); }
524 }
525 Value::Int(-1)
526 }
527 Value::Str(s) => {
528 if let Value::Str(n) = needle {
529 match s.find(n.as_str()) {
530 Some(i) => Value::Int(i as i64),
531 None => Value::Int(-1),
532 }
533 } else { Value::Int(-1) }
534 }
535 _ => Value::Int(-1),
536 }
537}
538
539pub fn json_parse(v: &Value) -> Value {
542 match v {
543 Value::Str(s) => match serde_json::from_str::<serde_json::Value>(s) {
544 Ok(j) => Value::from_json(&j),
545 Err(_) => Value::Null,
546 },
547 _ => Value::Null,
548 }
549}
550
551pub fn quote_json_numbers(s: &str) -> String {
561 let b = s.as_bytes();
562 let n = b.len();
563 let mut out: Vec<u8> = Vec::with_capacity(n + 16);
564 let mut i = 0;
565 while i < n {
566 if b[i] == b'"' && i + 1 < n && b[i + 1] == b':' {
567 out.push(b'"');
568 out.push(b':');
569 let start = i + 2;
570 let mut j = start;
571 while j < n && matches!(b[j], b'+' | b'.' | b'0'..=b'9' | b'e' | b'E' | b'-') {
572 j += 1;
573 }
574 if j > start && j < n && (b[j] == b',' || b[j] == b'}') {
575 out.push(b'"');
576 out.extend_from_slice(&b[start..j]);
577 out.push(b'"');
578 out.push(b[j]);
579 i = j + 1;
580 continue;
581 }
582 i += 2;
583 continue;
584 }
585 out.push(b[i]);
586 i += 1;
587 }
588 String::from_utf8(out).unwrap_or_else(|_| s.to_string())
589}
590
591pub fn json_stringify(v: &Value) -> Value {
592 Value::Str(serde_json::to_string(&v.to_json()).unwrap_or_default())
593}
594
595pub fn math_floor(v: &Value) -> Value {
598 match as_f64(v) { Some(x) => Value::Float(x.floor()), None => Value::Null }
599}
600pub fn math_round(v: &Value) -> Value {
601 match as_f64(v) { Some(x) => Value::Float(x.round()), None => Value::Null }
602}
603pub fn math_ceil(v: &Value) -> Value {
604 match as_f64(v) { Some(x) => Value::Float(x.ceil()), None => Value::Null }
605}
606
607pub fn ternary(cond: bool, when_true: Value, when_false: Value) -> Value {
610 if cond { when_true } else { when_false }
611}
612
613pub fn println_val(v: &Value) {
614 println!("{v}");
615}
616
617pub async fn promise_all(v: &Value) -> Value {
620 v.clone()
621}
622
623pub fn get_arg(args: &[Value], idx: usize, default: Value) -> Value {
628 match args.get(idx) {
640 None => default,
641 Some(Value::Null) if !matches!(default, Value::Null) => default,
642 Some(v) => v.clone(),
643 }
644}
645
646pub fn append_to_array(arr: &mut Value, v: Value) {
647 if crate::value::try_book_cache_push(arr, &v) { return; }
648 if let Value::Arr(a) = arr {
649 Arc::make_mut(a).push(v);
650 }
651}
652
653pub fn append_to_object_array(obj: &mut Value, key: &Value, v: Value) {
659 let field = crate::get_value(obj, key);
662 if crate::value::try_book_cache_push(&field, &v) {
663 return;
664 }
665 if let (Value::Dict(m), Value::Str(k)) = (obj, key) {
667 let entry = Arc::make_mut(m).entry(k.clone())
668 .or_insert_with(|| Value::Array(Vec::new()));
669 if let Value::Arr(a) = entry {
670 Arc::make_mut(a).push(v);
671 }
672 }
673}
674
675pub fn deep_merge_dict(base: &Value, over: &Value) -> Value {
683 match (base, over) {
684 (Value::Dict(b), Value::Dict(o)) => {
685 let mut out = (**b).clone();
686 for (k, v) in o.iter() {
687 let merged = match out.get(k) {
688 Some(existing) => deep_merge_dict(existing, v),
689 None => v.clone(),
690 };
691 out.insert(k.clone(), merged);
692 }
693 Value::Map(out)
694 }
695 _ => over.clone(),
696 }
697}
698
699pub fn concat_arrays(a: &Value, b: &Value) -> Value {
700 match (a, b) {
701 (Value::Arr(x), Value::Arr(y)) => {
702 let mut out = (**x).clone();
703 out.extend(y.iter().cloned());
704 Value::Array(out)
705 }
706 _ => Value::Array(vec![]),
707 }
708}
709
710pub use crate::exchange_errors::*;
713pub use crate::precise::Precise;
714
715#[allow(non_snake_case)]
718pub mod Math {
719 use super::Value;
720 use super::{as_f64, as_i64, both_ints};
721 pub fn min(a: &Value, b: &Value) -> Value {
726 if both_ints(a, b) { return Value::Int(as_i64(a).unwrap().min(as_i64(b).unwrap())); }
727 match (as_f64(a), as_f64(b)) { (Some(x), Some(y)) => Value::Float(x.min(y)), _ => Value::Null }
728 }
729 pub fn max(a: &Value, b: &Value) -> Value {
730 if both_ints(a, b) { return Value::Int(as_i64(a).unwrap().max(as_i64(b).unwrap())); }
731 match (as_f64(a), as_f64(b)) { (Some(x), Some(y)) => Value::Float(x.max(y)), _ => Value::Null }
732 }
733 pub fn abs(a: &Value) -> Value {
734 if let Value::Int(n) = a { if let Some(v) = n.checked_abs() { return Value::Int(v); } }
737 match as_f64(a) { Some(x) => Value::Float(x.abs()), None => Value::Null }
738 }
739 pub fn pow(a: &Value, b: &Value) -> Value {
740 match (as_f64(a), as_f64(b)) { (Some(x), Some(y)) => Value::Float(x.powf(y)), _ => Value::Null }
741 }
742 pub fn floor(v: &Value) -> Value { super::math_floor(v) }
743 pub fn round(v: &Value) -> Value { super::math_round(v) }
744 pub fn ceil(v: &Value) -> Value { super::math_ceil(v) }
745 pub fn log(v: &Value) -> Value {
746 match as_f64(v) { Some(x) => Value::Float(x.ln()), None => Value::Null }
747 }
748}
749
750pub fn slice(v: &Value, start: &Value, end: &Value) -> Value {
758 let s = as_i64(start).unwrap_or(0);
759 let e_opt = as_i64(end);
760 match v {
761 Value::Str(s_val) => {
762 let chars: Vec<char> = s_val.chars().collect();
763 let len = chars.len() as i64;
764 let si = if s < 0 { (len + s).max(0) as usize } else { (s as usize).min(chars.len()) };
765 let ei = match e_opt {
766 None => chars.len(),
767 Some(n) => if n < 0 { (len + n).max(0) as usize } else { (n as usize).min(chars.len()) },
768 };
769 if si <= ei { Value::Str(chars[si..ei].iter().collect()) } else { Value::Str(String::new()) }
770 }
771 Value::Arr(a) => {
772 let len = a.len() as i64;
773 let si = if s < 0 { (len + s).max(0) as usize } else { (s as usize).min(a.len()) };
774 let ei = match e_opt {
775 None => a.len(),
776 Some(n) => if n < 0 { (len + n).max(0) as usize } else { (n as usize).min(a.len()) },
777 };
778 if si <= ei { Value::Array(a[si..ei].to_vec()) } else { Value::Array(vec![]) }
779 }
780 _ => Value::Null,
781 }
782}
783
784pub fn join(arr: &Value, sep: &Value) -> Value {
786 let s = stringify_simple(sep);
787 if let Value::Arr(a) = arr {
788 let parts: Vec<String> = a.iter().map(stringify_simple).collect();
789 Value::Str(parts.join(&s))
790 } else { Value::Str(String::new()) }
791}
792
793pub fn to_string_val(v: &Value) -> Value {
795 Value::Str(stringify_simple(v))
796}
797
798pub fn parse_int(v: &Value) -> Value {
800 match v {
801 Value::Int(_) => v.clone(),
802 Value::Float(f) => Value::Int(*f as i64),
803 Value::Str(s) => s.trim().parse::<i64>().map(Value::Int).unwrap_or(Value::Null),
804 _ => Value::Null,
805 }
806}
807
808pub fn parse_float(v: &Value) -> Value {
810 match v {
811 Value::Float(_) => v.clone(),
812 Value::Int(n) => Value::Float(*n as f64),
813 Value::Str(s) => s.trim().parse::<f64>().map(Value::Float).unwrap_or(Value::Null),
814 _ => Value::Null,
815 }
816}
817
818pub fn length(v: &Value) -> Value { get_array_length(v) }
820
821pub fn starts_with(haystack: &Value, prefix: &Value) -> bool {
823 match (haystack, prefix) {
824 (Value::Str(h), Value::Str(p)) => h.starts_with(p.as_str()),
825 _ => false,
826 }
827}
828
829pub fn ends_with(haystack: &Value, suffix: &Value) -> bool {
831 match (haystack, suffix) {
832 (Value::Str(h), Value::Str(s)) => h.ends_with(s.as_str()),
833 _ => false,
834 }
835}
836
837pub fn to_lower(v: &Value) -> Value {
839 match v { Value::Str(s) => Value::Str(s.to_lowercase()), _ => Value::Null }
840}
841pub fn to_upper(v: &Value) -> Value {
842 match v { Value::Str(s) => Value::Str(s.to_uppercase()), _ => Value::Null }
843}
844
845pub fn trim(v: &Value) -> Value {
847 match v { Value::Str(s) => Value::Str(s.trim().to_string()), _ => Value::Null }
848}
849
850pub fn index_of(haystack: &Value, needle: &Value) -> Value {
852 get_index_of(haystack, needle)
853}
854
855pub fn contains(haystack: &Value, needle: &Value) -> bool {
860 match (haystack, needle) {
861 (Value::Str(h), Value::Str(n)) => h.contains(n.as_str()),
862 (Value::Arr(a), n) => a.iter().any(|el| is_equal(el, n)),
863 _ => false,
864 }
865}
866
867pub const TRUNCATE: i64 = 0;
870pub const ROUND: i64 = 1;
871pub const ROUND_UP: i64 = 2;
872pub const ROUND_DOWN: i64 = 3;
873pub const DECIMAL_PLACES: i64 = 2;
874pub const SIGNIFICANT_DIGITS: i64 = 3;
875pub const TICK_SIZE: i64 = 4;
876pub const NO_PADDING: i64 = 5;
877pub const PAD_WITH_ZERO: i64 = 6;
878
879pub fn string_replace(s: &Value, old: &Value, new_val: &Value) -> Value {
881 match (s, old, new_val) {
882 (Value::Str(s), Value::Str(o), Value::Str(n)) => Value::Str(s.replace(o.as_str(), n)),
883 _ => s.clone(),
884 }
885}
886
887pub fn split(s: &Value, delim: &Value) -> Value {
889 match (s, delim) {
890 (Value::Str(s), Value::Str(d)) => {
891 Value::Array(s.split(d.as_str()).map(|p| Value::Str(p.to_string())).collect())
892 }
893 _ => Value::Array(vec![]),
894 }
895}
896
897pub fn concat(a: &Value, b: &Value) -> Value {
899 match (a, b) {
900 (Value::Arr(_), Value::Arr(_)) => concat_arrays(a, b),
901 (Value::Str(x), Value::Str(y)) => Value::Str(format!("{x}{y}")),
902 _ => Value::Null,
903 }
904}
905
906pub fn repeat(s: &Value, n: &Value) -> Value {
908 let count = match as_i64(n) { Some(v) => v as usize, None => 0 };
909 match s { Value::Str(s) => Value::Str(s.repeat(count)), _ => Value::Null }
910}
911
912fn base32_decode(s: &str) -> Vec<u8> {
915 const ALPHA: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
916 let mut buf: u32 = 0;
917 let mut bits: u32 = 0;
918 let mut out = Vec::new();
919 for c in s.bytes() {
920 let up = c.to_ascii_uppercase();
921 let val = match ALPHA.iter().position(|&x| x == up) {
922 Some(v) => v as u32,
923 None => continue,
924 };
925 buf = (buf << 5) | val;
926 bits += 5;
927 if bits >= 8 {
928 bits -= 8;
929 out.push((buf >> bits) as u8);
930 }
931 }
932 out
933}
934
935pub fn totp(secret: Value) -> Value {
940 use hmac::{Hmac, Mac};
941 use sha1::Sha1;
942 let sec = match &secret {
943 Value::Str(s) => s.replace(' ', ""),
944 _ => return Value::Null,
945 };
946 let key = base32_decode(&sec);
947 let epoch = std::time::SystemTime::now()
948 .duration_since(std::time::UNIX_EPOCH)
949 .map(|d| d.as_secs())
950 .unwrap_or(0);
951 let counter: u64 = epoch / 30;
952 let mut mac = match Hmac::<Sha1>::new_from_slice(&key) {
953 Ok(m) => m,
954 Err(_) => return Value::Null,
955 };
956 mac.update(&counter.to_be_bytes());
957 let digest = mac.finalize().into_bytes(); let offset = (digest[19] & 0x0f) as usize;
959 let code = ((digest[offset] as u32 & 0x7f) << 24)
960 | ((digest[offset + 1] as u32) << 16)
961 | ((digest[offset + 2] as u32) << 8)
962 | (digest[offset + 3] as u32);
963 Value::Str(format!("{:06}", code % 1_000_000))
964}
965
966pub fn encode(s: Value) -> Value {
968 match &s {
969 Value::Str(st) => Value::Array(st.bytes().map(|b| Value::Int(b as i64)).collect()),
970 Value::Arr(_) => s,
971 _ => Value::Array(vec![]),
972 }
973}
974
975pub fn hash(data: Value, algo: Value, digest: Value) -> Value {
978 let dbytes = crate::exchange::value_to_bytes(&data);
979 let a = match &algo { Value::Str(s) => s.as_str(), _ => "sha256" };
980 let dg = match &digest { Value::Str(s) => s.as_str(), _ => "hex" };
981 let raw = crate::exchange::hash_raw(&dbytes, a);
982 match dg {
983 "binary" => Value::Array(raw.iter().map(|b| Value::Int(*b as i64)).collect()),
984 "base64" => Value::Str(b64_encode(&raw)),
985 _ => Value::Str(hex::encode(&raw)),
986 }
987}
988
989pub fn hmac(data: Value, secret: Value, algo: Value, digest: Value) -> Value {
991 use hmac::{Hmac, Mac};
992 let dbytes = crate::exchange::value_to_bytes(&data);
993 let sbytes = crate::exchange::value_to_bytes(&secret);
994 let a = match &algo { Value::Str(s) => s.to_ascii_lowercase(), _ => "sha256".to_string() };
995 let dg = match &digest { Value::Str(s) => s.as_str(), _ => "hex" };
996 let raw: Vec<u8> = match a.as_str() {
997 "sha256" => { let mut m = Hmac::<sha2::Sha256>::new_from_slice(&sbytes).unwrap(); m.update(&dbytes); m.finalize().into_bytes().to_vec() }
998 "sha512" => { let mut m = Hmac::<sha2::Sha512>::new_from_slice(&sbytes).unwrap(); m.update(&dbytes); m.finalize().into_bytes().to_vec() }
999 "sha384" => { let mut m = Hmac::<sha2::Sha384>::new_from_slice(&sbytes).unwrap(); m.update(&dbytes); m.finalize().into_bytes().to_vec() }
1000 "sha1" => { let mut m = Hmac::<sha1::Sha1>::new_from_slice(&sbytes).unwrap(); m.update(&dbytes); m.finalize().into_bytes().to_vec() }
1001 "md5" => { let mut m = Hmac::<md5::Md5>::new_from_slice(&sbytes).unwrap(); m.update(&dbytes); m.finalize().into_bytes().to_vec() }
1002 _ => return Value::Null,
1003 };
1004 match dg {
1005 "binary" => Value::Array(raw.iter().map(|b| Value::Int(*b as i64)).collect()),
1006 "base64" => Value::Str(b64_encode(&raw)),
1007 _ => Value::Str(hex::encode(&raw)),
1008 }
1009}
1010
1011pub fn crc32(s: Value, signed: Value) -> Value {
1014 let bytes = crate::exchange::value_to_bytes(&s);
1015 let mut crc: u32 = 0xFFFF_FFFF;
1016 for &b in &bytes {
1017 crc ^= b as u32;
1018 for _ in 0..8 {
1019 crc = if crc & 1 != 0 { (crc >> 1) ^ 0xEDB8_8320 } else { crc >> 1 };
1020 }
1021 }
1022 crc = !crc;
1023 if matches!(signed, Value::Bool(true)) {
1024 Value::Int(crc as i32 as i64)
1025 } else {
1026 Value::Int(crc as i64)
1027 }
1028}
1029
1030struct PbReader<'a> {
1033 buf: &'a [u8],
1034 pos: usize,
1035}
1036
1037impl<'a> PbReader<'a> {
1038 fn new(buf: &'a [u8]) -> Self {
1039 Self { buf, pos: 0 }
1040 }
1041 fn eof(&self) -> bool {
1042 self.pos >= self.buf.len()
1043 }
1044 fn read_varint(&mut self) -> u64 {
1046 let mut result: u64 = 0;
1047 let mut shift = 0u32;
1048 while self.pos < self.buf.len() && shift < 64 {
1049 let b = self.buf[self.pos];
1050 self.pos += 1;
1051 result |= ((b & 0x7f) as u64) << shift;
1052 if b & 0x80 == 0 {
1053 break;
1054 }
1055 shift += 7;
1056 }
1057 result
1058 }
1059 fn read_tag(&mut self) -> (u64, u8) {
1061 let t = self.read_varint();
1062 (t >> 3, (t & 7) as u8)
1063 }
1064 fn read_bytes(&mut self) -> &'a [u8] {
1066 let len = self.read_varint() as usize;
1067 let end = self.pos.saturating_add(len).min(self.buf.len());
1068 let s = &self.buf[self.pos..end];
1069 self.pos = end;
1070 s
1071 }
1072 fn skip(&mut self, wire: u8) {
1074 match wire {
1075 0 => {
1076 self.read_varint();
1077 }
1078 1 => self.pos = self.pos.saturating_add(8).min(self.buf.len()),
1079 2 => {
1080 let len = self.read_varint() as usize;
1081 self.pos = self.pos.saturating_add(len).min(self.buf.len());
1082 }
1083 5 => self.pos = self.pos.saturating_add(4).min(self.buf.len()),
1084 _ => self.pos = self.buf.len(),
1085 }
1086 }
1087}
1088
1089fn pb_string(b: &[u8]) -> Value {
1090 Value::Str(String::from_utf8_lossy(b).into_owned())
1091}
1092
1093fn pb_decode_depth_item(b: &[u8]) -> Value {
1095 let mut r = PbReader::new(b);
1096 let mut m: HashMap<String, Value> = HashMap::new();
1097 while !r.eof() {
1098 match r.read_tag() {
1099 (1, 2) => {
1100 m.insert("price".to_string(), pb_string(r.read_bytes()));
1101 }
1102 (2, 2) => {
1103 m.insert("quantity".to_string(), pb_string(r.read_bytes()));
1104 }
1105 (_, wire) => r.skip(wire),
1106 }
1107 }
1108 Value::Map(m)
1109}
1110
1111fn pb_decode_depths(b: &[u8]) -> Value {
1114 let mut r = PbReader::new(b);
1115 let mut asks: Vec<Value> = Vec::new();
1116 let mut bids: Vec<Value> = Vec::new();
1117 let mut m: HashMap<String, Value> = HashMap::new();
1118 while !r.eof() {
1119 match r.read_tag() {
1120 (1, 2) => asks.push(pb_decode_depth_item(r.read_bytes())),
1121 (2, 2) => bids.push(pb_decode_depth_item(r.read_bytes())),
1122 (3, 2) => {
1123 m.insert("eventType".to_string(), pb_string(r.read_bytes()));
1124 }
1125 (4, 2) => {
1126 m.insert("fromVersion".to_string(), pb_string(r.read_bytes()));
1127 }
1128 (5, 2) => {
1129 m.insert("toVersion".to_string(), pb_string(r.read_bytes()));
1130 }
1131 (_, wire) => r.skip(wire),
1132 }
1133 }
1134 m.insert("asks".to_string(), Value::List(asks));
1135 m.insert("bids".to_string(), Value::List(bids));
1136 Value::Map(m)
1137}
1138
1139fn pb_decode_book_ticker(b: &[u8]) -> Value {
1142 let mut r = PbReader::new(b);
1143 let mut m: HashMap<String, Value> = HashMap::new();
1144 let fields = ["bidPrice", "bidQuantity", "askPrice", "askQuantity"];
1145 while !r.eof() {
1146 match r.read_tag() {
1147 (n @ 1..=4, 2) => {
1148 m.insert(fields[(n - 1) as usize].to_string(), pb_string(r.read_bytes()));
1149 }
1150 (_, wire) => r.skip(wire),
1151 }
1152 }
1153 Value::Map(m)
1154}
1155
1156fn pb_decode_deal_item(b: &[u8]) -> Value {
1159 let mut r = PbReader::new(b);
1160 let mut m: HashMap<String, Value> = HashMap::new();
1161 while !r.eof() {
1162 match r.read_tag() {
1163 (1, 2) => { m.insert("price".to_string(), pb_string(r.read_bytes())); }
1164 (2, 2) => { m.insert("quantity".to_string(), pb_string(r.read_bytes())); }
1165 (3, 0) => { m.insert("tradeType".to_string(), Value::Int(r.read_varint() as i64)); }
1166 (4, 0) => { m.insert("time".to_string(), Value::Int(r.read_varint() as i64)); }
1167 (_, wire) => r.skip(wire),
1168 }
1169 }
1170 Value::Map(m)
1171}
1172
1173fn pb_decode_deals(b: &[u8]) -> Value {
1176 let mut r = PbReader::new(b);
1177 let mut deals: Vec<Value> = Vec::new();
1178 let mut m: HashMap<String, Value> = HashMap::new();
1179 while !r.eof() {
1180 match r.read_tag() {
1181 (1, 2) => deals.push(pb_decode_deal_item(r.read_bytes())),
1182 (2, 2) => { m.insert("eventType".to_string(), pb_string(r.read_bytes())); }
1183 (_, wire) => r.skip(wire),
1184 }
1185 }
1186 m.insert("deals".to_string(), Value::List(deals));
1187 Value::Map(m)
1188}
1189
1190fn pb_decode_spot_kline(b: &[u8]) -> Value {
1192 let mut r = PbReader::new(b);
1193 let mut m: HashMap<String, Value> = HashMap::new();
1194 while !r.eof() {
1195 match r.read_tag() {
1196 (1, 2) => { m.insert("interval".to_string(), pb_string(r.read_bytes())); }
1197 (2, 0) => { m.insert("windowStart".to_string(), Value::Int(r.read_varint() as i64)); }
1198 (3, 2) => { m.insert("openingPrice".to_string(), pb_string(r.read_bytes())); }
1199 (4, 2) => { m.insert("closingPrice".to_string(), pb_string(r.read_bytes())); }
1200 (5, 2) => { m.insert("highestPrice".to_string(), pb_string(r.read_bytes())); }
1201 (6, 2) => { m.insert("lowestPrice".to_string(), pb_string(r.read_bytes())); }
1202 (7, 2) => { m.insert("volume".to_string(), pb_string(r.read_bytes())); }
1203 (8, 2) => { m.insert("amount".to_string(), pb_string(r.read_bytes())); }
1204 (9, 0) => { m.insert("windowEnd".to_string(), Value::Int(r.read_varint() as i64)); }
1205 (_, wire) => r.skip(wire),
1206 }
1207 }
1208 Value::Map(m)
1209}
1210
1211pub fn decode_mexc_push_data(bytes: &[u8]) -> Value {
1215 let mut r = PbReader::new(bytes);
1216 let mut m: HashMap<String, Value> = HashMap::new();
1217 while !r.eof() {
1218 match r.read_tag() {
1219 (1, 2) => {
1220 m.insert("channel".to_string(), pb_string(r.read_bytes()));
1221 }
1222 (3, 2) => {
1223 m.insert("symbol".to_string(), pb_string(r.read_bytes()));
1224 }
1225 (4, 2) => {
1226 m.insert("symbolId".to_string(), pb_string(r.read_bytes()));
1227 }
1228 (5, 0) => {
1229 m.insert("createTime".to_string(), Value::Int(r.read_varint() as i64));
1230 }
1231 (6, 0) => {
1232 m.insert("sendTime".to_string(), Value::Int(r.read_varint() as i64));
1233 }
1234 (302, 2) => {
1235 m.insert("publicIncreaseDepths".to_string(), pb_decode_depths(r.read_bytes()));
1236 }
1237 (303, 2) => {
1238 m.insert("publicLimitDepths".to_string(), pb_decode_depths(r.read_bytes()));
1239 }
1240 (313, 2) => {
1241 m.insert("publicAggreDepths".to_string(), pb_decode_depths(r.read_bytes()));
1242 }
1243 (301, 2) => {
1244 m.insert("publicDeals".to_string(), pb_decode_deals(r.read_bytes()));
1245 }
1246 (314, 2) => {
1247 m.insert("publicAggreDeals".to_string(), pb_decode_deals(r.read_bytes()));
1248 }
1249 (305, 2) => {
1250 m.insert("publicBookTicker".to_string(), pb_decode_book_ticker(r.read_bytes()));
1251 }
1252 (315, 2) => {
1253 m.insert("publicAggreBookTicker".to_string(), pb_decode_book_ticker(r.read_bytes()));
1254 }
1255 (308, 2) => {
1256 m.insert("publicSpotKline".to_string(), pb_decode_spot_kline(r.read_bytes()));
1257 }
1258 (_, wire) => r.skip(wire),
1259 }
1260 }
1261 Value::Map(m)
1262}
1263
1264pub fn rsa(message: Value, key: Value, _hash: Value) -> Value {
1267 use rsa::RsaPrivateKey;
1268 use rsa::pkcs1::DecodeRsaPrivateKey;
1269 use rsa::pkcs1v15::SigningKey;
1270 use rsa::signature::{SignatureEncoding, Signer};
1271 let msg = crate::exchange::value_to_bytes(&message);
1272 let pem = String::from_utf8_lossy(&crate::exchange::value_to_bytes(&key)).into_owned();
1273 let pk = match RsaPrivateKey::from_pkcs1_pem(pem.trim()) {
1274 Ok(k) => k,
1275 Err(_) => return Value::Str(String::new()),
1276 };
1277 let signing_key = SigningKey::<sha2::Sha256>::new(pk);
1278 let sig = signing_key.sign(&msg);
1279 Value::Str(b64_encode(&sig.to_bytes()))
1280}
1281
1282pub fn ecdsa(message: Value, secret: Value, _curve: Value, pre_hash: Value) -> Value {
1287 use k256::ecdsa::SigningKey;
1288 let empty = || Value::Map(indexmap::IndexMap::new());
1289 let msg_s = match &message { Value::Str(s) => s.trim_start_matches("0x").to_string(), _ => return empty() };
1290 let sk_s = match &secret { Value::Str(s) => s.trim_start_matches("0x").to_string(), _ => return empty() };
1291 let sk_bytes = match hex::decode(&sk_s) { Ok(b) => b, Err(_) => return empty() };
1292 let digest: Vec<u8> = match &pre_hash {
1294 Value::Str(algo) => crate::exchange::hash_raw(
1295 &crate::exchange::value_to_bytes(&message), algo),
1296 _ => match hex::decode(&msg_s) { Ok(b) => b, Err(_) => return empty() },
1297 };
1298 let sk = match SigningKey::from_slice(&sk_bytes) { Ok(k) => k, Err(_) => return empty() };
1299 let (sig, recid) = match sk.sign_prehash_recoverable(&digest) {
1300 Ok(x) => x,
1301 Err(_) => return empty(),
1302 };
1303 let bytes = sig.to_bytes(); let mut m = indexmap::IndexMap::new();
1305 m.insert("r".to_string(), Value::Str(hex::encode(&bytes[0..32])));
1306 m.insert("s".to_string(), Value::Str(hex::encode(&bytes[32..64])));
1307 m.insert("v".to_string(), Value::Int(recid.to_byte() as i64));
1308 Value::Map(m)
1309}
1310
1311fn pem_to_der(pem: &str) -> Vec<u8> {
1314 use base64::{engine::general_purpose::STANDARD, Engine as _};
1315 let body: String = pem
1316 .lines()
1317 .filter(|l| !l.starts_with("-----"))
1318 .collect::<Vec<_>>()
1319 .join("");
1320 STANDARD.decode(body.trim()).unwrap_or_default()
1321}
1322
1323pub fn eddsa(request: Value, secret: Value, _curve: Value) -> Value {
1330 use ed25519_dalek::{Signer, SigningKey};
1331 let bad = |why: &str| -> ! {
1332 panic!("{}", crate::exchange_errors::not_supported(
1333 Value::Str(format!("eddsa: {why}"))));
1334 };
1335 let msg: Vec<u8> = match &request {
1336 Value::Arr(_) => crate::exchange::value_to_bytes(&request),
1337 Value::Str(s) => {
1338 let t = s.trim_start_matches("0x");
1339 hex::decode(t).unwrap_or_else(|_| s.as_bytes().to_vec())
1340 }
1341 _ => bad("request must be bytes or a string"),
1342 };
1343 let seed: [u8; 32] = match &secret {
1347 Value::Arr(_) => {
1348 let b = crate::exchange::value_to_bytes(&secret);
1349 if b.len() >= 32 { b[..32].try_into().unwrap() } else { bad("seed shorter than 32 bytes") }
1350 }
1351 Value::Str(sec_s) if sec_s.len() == 32 => {
1352 sec_s.as_bytes().try_into().unwrap()
1353 }
1354 Value::Str(sec_s) => {
1355 let der = pem_to_der(sec_s);
1356 if der.len() >= 48 {
1357 der[16..48].try_into().unwrap()
1358 } else if der.len() >= 32 {
1359 der[der.len() - 32..].try_into().unwrap()
1360 } else {
1361 bad("secret is not a 32-byte seed or a decodable PKCS#8 key");
1362 }
1363 }
1364 _ => bad("secret must be a string or byte array"),
1365 };
1366 let sk = SigningKey::from_bytes(&seed);
1367 let sig = sk.sign(&msg);
1368 Value::Str(b64_encode(&sig.to_bytes()))
1369}
1370
1371fn b64_encode(data: &[u8]) -> String {
1373 use base64::{engine::general_purpose::STANDARD, Engine as _};
1374 STANDARD.encode(data)
1375}
1376
1377fn b64url_encode(data: &[u8]) -> String {
1379 use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
1380 URL_SAFE_NO_PAD.encode(data)
1381}
1382
1383pub fn jwt(request: Value, secret: Value, algorithm: Value, is_rsa: Value, _opts: Value) -> Value {
1386 let rsa_mode = matches!(is_rsa, Value::Bool(true));
1387 let bits = match algorithm.as_str() {
1388 Some("sha512") => "512",
1389 Some("sha384") => "384",
1390 _ => "256",
1391 };
1392 let alg = format!("{}{}", if rsa_mode { "RS" } else { "HS" }, bits);
1393 let header = format!("{{\"alg\":\"{alg}\",\"typ\":\"JWT\"}}");
1395 let payload = serde_json::to_string(&request.to_json()).unwrap_or_else(|_| "{}".to_string());
1396 let token = format!("{}.{}",
1397 b64url_encode(header.as_bytes()),
1398 b64url_encode(payload.as_bytes()));
1399 let sig_std: String = if rsa_mode {
1401 match rsa(Value::Str(token.clone()), secret, algorithm) {
1402 Value::Str(s) => s,
1403 _ => String::new(),
1404 }
1405 } else {
1406 match hmac(encode(Value::Str(token.clone())), secret, algorithm,
1407 Value::Str("base64".to_string())) {
1408 Value::Str(s) => s,
1409 _ => String::new(),
1410 }
1411 };
1412 let sig_url = sig_std.replace('+', "-").replace('/', "_")
1413 .trim_end_matches('=').to_string();
1414 Value::Str(format!("{token}.{sig_url}"))
1415}
1416
1417pub fn replace_str(s: &Value, old: &Value, new_val: &Value) -> Value {
1419 string_replace(s, old, new_val)
1420}
1421
1422pub fn replace_all_str(s: &Value, old: &Value, new_val: &Value) -> Value {
1424 let (Value::Str(sv), Value::Str(ov), Value::Str(nv)) = (s, old, new_val) else {
1425 return s.clone();
1426 };
1427 Value::Str(sv.replace(ov, nv))
1428}
1429
1430pub fn date_now() -> Value {
1432 let ms = std::time::SystemTime::now()
1433 .duration_since(std::time::UNIX_EPOCH)
1434 .map(|d| d.as_millis() as i64)
1435 .unwrap_or(0);
1436 Value::Int(ms)
1437}
1438
1439pub fn pad_start(s: &Value, len: &Value, pad: &Value) -> Value {
1441 let target = match as_i64(len) { Some(v) => v as usize, None => 0 };
1442 let p = match pad { Value::Str(p) => p.clone(), _ => " ".to_string() };
1443 match s {
1444 Value::Str(sv) => {
1445 if sv.chars().count() >= target { Value::Str(sv.clone()) }
1446 else {
1447 let need = target - sv.chars().count();
1448 Value::Str(format!("{}{}", p.repeat((need / p.chars().count().max(1)).max(1)), sv))
1449 }
1450 }
1451 _ => Value::Null,
1452 }
1453}
1454
1455pub fn pad_end(s: &Value, len: &Value, pad: &Value) -> Value {
1456 let target = match as_i64(len) { Some(v) => v as usize, None => 0 };
1457 let p = match pad { Value::Str(p) => p.clone(), _ => " ".to_string() };
1458 match s {
1459 Value::Str(sv) => {
1460 if sv.chars().count() >= target { Value::Str(sv.clone()) }
1461 else {
1462 let need = target - sv.chars().count();
1463 Value::Str(format!("{}{}", sv, p.repeat((need / p.chars().count().max(1)).max(1))))
1464 }
1465 }
1466 _ => Value::Null,
1467 }
1468}
1469
1470pub fn to_fixed(x: &Value, digits: &Value) -> Value {
1473 let d = match as_i64(digits) { Some(v) => v.max(0) as usize, None => 0 };
1474 let n = match x {
1475 Value::Int(i) => *i as f64,
1476 Value::Float(f) => *f,
1477 Value::Str(s) => s.trim().parse::<f64>().unwrap_or(0.0),
1478 _ => 0.0,
1479 };
1480 Value::Str(format!("{:.*}", d, n))
1481}
1482
1483pub fn empty_map() -> Value { Value::Map(HashMap::new()) }
1488pub fn empty_array() -> Value { Value::Array(vec![]) }