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}").into());
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}").into())
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.to_string(),
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.to_string(),
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_number(v: &Value) -> bool { matches!(v, Value::Int(_) | Value::Float(_)) }
212pub fn is_bool(v: &Value) -> bool { matches!(v, Value::Bool(_)) }
213pub fn is_function(_v: &Value)-> bool { false }
214
215pub fn panic_to_value(payload: Box<dyn std::any::Any + Send>) -> Value {
222 let msg = payload.downcast_ref::<String>().cloned()
223 .or_else(|| payload.downcast_ref::<&str>().map(|s| (*s).to_string()))
224 .unwrap_or_else(|| "panic".to_string());
225 Value::Str(msg.into())
226}
227
228pub fn panic_msg_to_error(msg: &str) -> crate::ExchangeError {
232 if let Some(start) = msg.find('[') {
233 let after = &msg[start + 1..];
234 if let Some(end) = after.find(']') {
235 let kind = &after[..end];
236 let rest = after[end + 1..].trim_start_matches(|c: char| c == ' ' || c == ':');
237 return crate::ExchangeError::new(kind, rest);
238 }
239 }
240 crate::ExchangeError::new("ExchangeError", msg)
241}
242
243pub fn catch_typed<F, T>(f: F) -> crate::Result<T>
252where
253 F: FnOnce() -> T,
254{
255 match std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) {
256 Ok(v) => Ok(v),
257 Err(payload) => {
258 let msg = payload.downcast_ref::<String>().cloned()
259 .or_else(|| payload.downcast_ref::<&str>().map(|s| (*s).to_string()))
260 .unwrap_or_else(|| "panic".to_string());
261 Err(panic_msg_to_error(&msg))
262 }
263 }
264}
265
266pub async fn call_typed<F, T>(fut: F) -> crate::Result<T>
267where
268 F: std::future::Future<Output = T>,
269{
270 use futures::FutureExt;
271 use std::panic::AssertUnwindSafe;
272 match AssertUnwindSafe(fut).catch_unwind().await {
273 Ok(v) => Ok(v),
274 Err(payload) => {
275 let msg = payload.downcast_ref::<String>().cloned()
276 .or_else(|| payload.downcast_ref::<&str>().map(|s| (*s).to_string()))
277 .unwrap_or_else(|| "panic".to_string());
278 Err(panic_msg_to_error(&msg))
279 }
280 }
281}
282
283pub fn is_instance(value: &Value, class: &Value) -> bool {
290 let (msg, cls) = match (value, class) {
291 (Value::Str(s), Value::Str(c)) => (s, c),
292 _ => return false,
293 };
294 if msg.contains(&format!("[{cls}]")) {
298 return true;
299 }
300 if let Some(actual) = extract_error_kind(msg) {
306 let mut cur = error_parent(actual);
307 while let Some(c) = cur {
308 if c == cls.as_ref() {
309 return true;
310 }
311 cur = error_parent(c);
312 }
313 }
314 false
315}
316
317fn extract_error_kind(msg: &str) -> Option<&str> {
319 let start = msg.find('[')? + 1;
320 let end = msg[start..].find(']')? + start;
321 Some(&msg[start..end])
322}
323
324fn error_parent(class: &str) -> Option<&'static str> {
327 Some(match class {
328 "ExchangeError" => "BaseError",
330 "AuthenticationError" => "ExchangeError",
331 "PermissionDenied" => "AuthenticationError",
332 "AccountNotEnabled" => "PermissionDenied",
333 "AccountSuspended" => "AuthenticationError",
334 "ArgumentsRequired" => "ExchangeError",
335 "BadRequest" => "ExchangeError",
336 "BadSymbol" => "BadRequest",
337 "OperationRejected" => "ExchangeError",
338 "NoChange" => "OperationRejected",
339 "MarginModeAlreadySet" => "NoChange",
340 "MarketClosed" => "OperationRejected",
341 "ManualInteractionNeeded" => "OperationRejected",
342 "RestrictedLocation" => "OperationRejected",
343 "InsufficientFunds" => "ExchangeError",
344 "InvalidAddress" => "ExchangeError",
345 "AddressPending" => "InvalidAddress",
346 "InvalidOrder" => "ExchangeError",
347 "OrderNotFound" => "InvalidOrder",
348 "OrderNotCached" => "InvalidOrder",
349 "OrderImmediatelyFillable" => "InvalidOrder",
350 "OrderNotFillable" => "InvalidOrder",
351 "DuplicateOrderId" => "InvalidOrder",
352 "ContractUnavailable" => "InvalidOrder",
353 "NotSupported" => "ExchangeError",
354 "InvalidProxySettings" => "ExchangeError",
355 "ExchangeClosedByUser" => "ExchangeError",
356 "OperationFailed" => "BaseError",
358 "NetworkError" => "OperationFailed",
359 "DDoSProtection" => "NetworkError",
360 "RateLimitExceeded" => "NetworkError",
361 "ExchangeNotAvailable" => "NetworkError",
362 "OnMaintenance" => "ExchangeNotAvailable",
363 "InvalidNonce" => "NetworkError",
364 "ChecksumError" => "InvalidNonce",
365 "RequestTimeout" => "NetworkError",
366 "BadResponse" => "OperationFailed",
367 "NullResponse" => "BadResponse",
368 "CancelPending" => "OperationFailed",
369 "UnsubscribeError" => "BaseError",
370 _ => return None,
371 })
372}
373
374pub fn get_value(obj: &Value, key: &Value) -> Value {
377 crate::value::get_value(obj, key)
378}
379
380#[allow(clippy::mut_from_ref, invalid_reference_casting)]
394pub unsafe fn coerce_value_to_mut(v: &Value) -> &mut Value {
395 let ptr = v as *const Value as *mut Value;
396 &mut *ptr
397}
398
399pub fn get_value_mut<'a>(obj: &'a mut Value, key: &Value) -> &'a mut Value {
400 match (obj, key) {
401 (Value::Dict(m), Value::Str(k)) => Arc::make_mut(m).entry(k.to_string()).or_insert(Value::Null),
402 (Value::Arr(a), Value::Int(i)) => {
403 let idx = *i as usize;
404 let a = Arc::make_mut(a);
405 while a.len() <= idx { a.push(Value::Null); }
406 &mut a[idx]
407 }
408 (other, _) => other,
409 }
410}
411
412pub fn add_element_to_object(obj: &mut Value, key: &Value, val: Value) {
413 match (obj, key) {
414 (Value::Dict(m), Value::Str(k)) => {
415 if crate::value::try_book_meta_write(m, k, &val) { return; }
416 crate::value::try_ws_subs_write(m, k, &val);
419 crate::value::try_ws_sub_field_write(m, k, &val);
420 crate::value::try_cache_hashmap_write(m, k, &val);
424 Arc::make_mut(m).insert(k.to_string(), val);
425 }
426 (Value::Dict(m), other) => { Arc::make_mut(m).insert(stringify_simple(other), val); }
427 (Value::Arr(a), Value::Int(i)) => {
428 let idx = *i as usize;
429 let a = Arc::make_mut(a);
430 while a.len() <= idx { a.push(Value::Null); }
431 a[idx] = val;
432 }
433 _ => {}
434 }
435}
436
437pub fn remove(obj: &mut Value, key: &Value) {
438 match (obj, key) {
439 (Value::Dict(m), Value::Str(k)) => {
440 crate::value::try_ws_subs_remove(m, k);
441 Arc::make_mut(m).shift_remove(k.as_ref());
442 }
443 (Value::Arr(a), Value::Int(i)) => {
444 let idx = *i as usize;
445 let a = Arc::make_mut(a);
446 if idx < a.len() { a.remove(idx); }
447 }
448 _ => {}
449 }
450}
451
452pub fn shift(mut arr: Value) -> Value {
457 if let Value::Arr(a) = &mut arr {
458 let inner = Arc::make_mut(a);
459 if !inner.is_empty() { return inner.remove(0); }
460 }
461 Value::Null
462}
463
464pub fn in_op(obj: &Value, key: &Value) -> bool {
465 match (obj, key) {
466 (Value::Dict(m), Value::Str(k)) => m.contains_key(k.as_ref()),
467 (Value::Arr(a), v) => a.iter().any(|x| is_equal(x, v)),
468 _ => false,
469 }
470}
471
472fn is_ws_internal_tag(k: &str) -> bool {
477 k == "__ws_subs_url" || k == "__ws_sub_ref"
478}
479
480pub fn object_keys(v: &Value) -> Value {
481 match v {
482 Value::Dict(m) => Value::Array(
483 m.keys().filter(|k| !is_ws_internal_tag(k))
484 .map(|k| Value::Str(k.clone().into())).collect()),
485 _ => Value::Array(vec![]),
486 }
487}
488
489pub fn object_values(v: &Value) -> Value {
490 match v {
491 Value::Dict(m) => Value::Array(
492 m.iter().filter(|(k, _)| !is_ws_internal_tag(k))
493 .map(|(_, val)| val.clone()).collect()),
494 _ => Value::Array(vec![]),
495 }
496}
497
498pub fn get_array_length(v: &Value) -> Value {
499 if let Value::Dict(d) = v {
504 if let Some(n) = crate::value::book_cache_len_of(d) {
505 return Value::Int(n as i64);
506 }
507 if let Some(n) = crate::value::cache_len_of_marker(d) {
508 return Value::Int(n as i64);
509 }
510 if d.contains_key("__sideKind") {
511 return Value::Int(crate::value::side_entries_len(d) as i64);
512 }
513 }
514 Value::Int(v.len() as i64)
515}
516
517pub fn get_index_of(haystack: &Value, needle: &Value) -> Value {
518 match haystack {
519 Value::Arr(a) => {
520 for (i, item) in a.iter().enumerate() {
521 if is_equal(item, needle) { return Value::Int(i as i64); }
522 }
523 Value::Int(-1)
524 }
525 Value::Str(s) => {
526 if let Value::Str(n) = needle {
527 match s.find(n.as_ref()) {
528 Some(i) => Value::Int(i as i64),
529 None => Value::Int(-1),
530 }
531 } else { Value::Int(-1) }
532 }
533 _ => Value::Int(-1),
534 }
535}
536
537pub fn json_parse(v: &Value) -> Value {
540 match v {
541 Value::Str(s) => match serde_json::from_str::<serde_json::Value>(s) {
542 Ok(j) => Value::from_json(&j),
543 Err(_) => Value::Null,
544 },
545 _ => Value::Null,
546 }
547}
548
549pub fn quote_json_numbers(s: &str) -> String {
559 let b = s.as_bytes();
560 let n = b.len();
561 let mut out: Vec<u8> = Vec::with_capacity(n + 16);
562 let mut i = 0;
563 while i < n {
564 if b[i] == b'"' && i + 1 < n && b[i + 1] == b':' {
565 out.push(b'"');
566 out.push(b':');
567 let start = i + 2;
568 let mut j = start;
569 while j < n && matches!(b[j], b'+' | b'.' | b'0'..=b'9' | b'e' | b'E' | b'-') {
570 j += 1;
571 }
572 if j > start && j < n && (b[j] == b',' || b[j] == b'}') {
573 out.push(b'"');
574 out.extend_from_slice(&b[start..j]);
575 out.push(b'"');
576 out.push(b[j]);
577 i = j + 1;
578 continue;
579 }
580 i += 2;
581 continue;
582 }
583 out.push(b[i]);
584 i += 1;
585 }
586 String::from_utf8(out).unwrap_or_else(|_| s.to_string())
587}
588
589pub fn json_stringify(v: &Value) -> Value {
590 Value::Str(serde_json::to_string(&v.to_json()).unwrap_or_default().into())
591}
592
593pub fn math_floor(v: &Value) -> Value {
596 match as_f64(v) { Some(x) => Value::Float(x.floor()), None => Value::Null }
597}
598pub fn math_round(v: &Value) -> Value {
599 match as_f64(v) { Some(x) => Value::Float(x.round()), None => Value::Null }
600}
601pub fn math_ceil(v: &Value) -> Value {
602 match as_f64(v) { Some(x) => Value::Float(x.ceil()), None => Value::Null }
603}
604
605pub fn println_val(v: &Value) {
608 println!("{v}");
609}
610
611pub async fn promise_all(v: &Value) -> Value {
614 v.clone()
615}
616
617pub fn get_arg(args: &[Value], idx: usize, default: Value) -> Value {
622 match args.get(idx) {
634 None => default,
635 Some(Value::Null) if !matches!(default, Value::Null) => default,
636 Some(v) => v.clone(),
637 }
638}
639
640pub fn append_to_array(arr: &mut Value, v: Value) {
641 if crate::value::try_book_cache_push(arr, &v) { return; }
642 if let Value::Arr(a) = arr {
643 Arc::make_mut(a).push(v);
644 }
645}
646
647pub fn append_to_object_array(obj: &mut Value, key: &Value, v: Value) {
653 let field = crate::get_value(obj, key);
656 if crate::value::try_book_cache_push(&field, &v) {
657 return;
658 }
659 if let (Value::Dict(m), Value::Str(k)) = (obj, key) {
661 let entry = Arc::make_mut(m).entry(k.to_string())
662 .or_insert_with(|| Value::Array(Vec::new()));
663 if let Value::Arr(a) = entry {
664 Arc::make_mut(a).push(v);
665 }
666 }
667}
668
669pub fn deep_merge_dict(base: &Value, over: &Value) -> Value {
677 match (base, over) {
678 (Value::Dict(b), Value::Dict(o)) => {
679 let mut out = (**b).clone();
680 for (k, v) in o.iter() {
681 let merged = match out.get(k) {
682 Some(existing) => deep_merge_dict(existing, v),
683 None => v.clone(),
684 };
685 out.insert(k.clone(), merged);
686 }
687 Value::Map(out)
688 }
689 _ => over.clone(),
690 }
691}
692
693pub fn concat_arrays(a: &Value, b: &Value) -> Value {
694 match (a, b) {
695 (Value::Arr(x), Value::Arr(y)) => {
696 let mut out = (**x).clone();
697 out.extend(y.iter().cloned());
698 Value::Array(out)
699 }
700 _ => Value::Array(vec![]),
701 }
702}
703
704pub use crate::exchange_errors::*;
707pub use crate::precise::Precise;
708
709#[allow(non_snake_case)]
712pub mod Math {
713 use super::Value;
714 use super::{as_f64, as_i64, both_ints};
715 pub fn min(a: &Value, b: &Value) -> Value {
720 if both_ints(a, b) { return Value::Int(as_i64(a).unwrap().min(as_i64(b).unwrap())); }
721 match (as_f64(a), as_f64(b)) { (Some(x), Some(y)) => Value::Float(x.min(y)), _ => Value::Null }
722 }
723 pub fn max(a: &Value, b: &Value) -> Value {
724 if both_ints(a, b) { return Value::Int(as_i64(a).unwrap().max(as_i64(b).unwrap())); }
725 match (as_f64(a), as_f64(b)) { (Some(x), Some(y)) => Value::Float(x.max(y)), _ => Value::Null }
726 }
727 pub fn abs(a: &Value) -> Value {
728 if let Value::Int(n) = a { if let Some(v) = n.checked_abs() { return Value::Int(v); } }
731 match as_f64(a) { Some(x) => Value::Float(x.abs()), None => Value::Null }
732 }
733 pub fn pow(a: &Value, b: &Value) -> Value {
734 match (as_f64(a), as_f64(b)) { (Some(x), Some(y)) => Value::Float(x.powf(y)), _ => Value::Null }
735 }
736 pub fn floor(v: &Value) -> Value { super::math_floor(v) }
737 pub fn round(v: &Value) -> Value { super::math_round(v) }
738 pub fn ceil(v: &Value) -> Value { super::math_ceil(v) }
739 pub fn log(v: &Value) -> Value {
740 match as_f64(v) { Some(x) => Value::Float(x.ln()), None => Value::Null }
741 }
742}
743
744pub fn slice(v: &Value, start: &Value, end: &Value) -> Value {
752 let s = as_i64(start).unwrap_or(0);
753 let e_opt = as_i64(end);
754 match v {
755 Value::Str(s_val) => {
756 let chars: Vec<char> = s_val.chars().collect();
757 let len = chars.len() as i64;
758 let si = if s < 0 { (len + s).max(0) as usize } else { (s as usize).min(chars.len()) };
759 let ei = match e_opt {
760 None => chars.len(),
761 Some(n) => if n < 0 { (len + n).max(0) as usize } else { (n as usize).min(chars.len()) },
762 };
763 if si <= ei { Value::Str(chars[si..ei].iter().collect::<String>().into()) } else { Value::Str(String::new().into()) }
764 }
765 Value::Arr(a) => {
766 let len = a.len() as i64;
767 let si = if s < 0 { (len + s).max(0) as usize } else { (s as usize).min(a.len()) };
768 let ei = match e_opt {
769 None => a.len(),
770 Some(n) => if n < 0 { (len + n).max(0) as usize } else { (n as usize).min(a.len()) },
771 };
772 if si <= ei { Value::Array(a[si..ei].to_vec()) } else { Value::Array(vec![]) }
773 }
774 _ => Value::Null,
775 }
776}
777
778pub fn join(arr: &Value, sep: &Value) -> Value {
780 let s = stringify_simple(sep);
781 if let Value::Arr(a) = arr {
782 let parts: Vec<String> = a.iter().map(stringify_simple).collect();
783 Value::Str(parts.join(&s).into())
784 } else { Value::Str(String::new().into()) }
785}
786
787pub fn to_string_val(v: &Value) -> Value {
789 Value::Str(stringify_simple(v).into())
790}
791
792pub fn parse_int(v: &Value) -> Value {
794 match v {
795 Value::Int(_) => v.clone(),
796 Value::Float(f) => Value::Int(*f as i64),
797 Value::Str(s) => s.trim().parse::<i64>().map(Value::Int).unwrap_or(Value::Null),
798 _ => Value::Null,
799 }
800}
801
802pub fn parse_float(v: &Value) -> Value {
804 match v {
805 Value::Float(_) => v.clone(),
806 Value::Int(n) => Value::Float(*n as f64),
807 Value::Str(s) => s.trim().parse::<f64>().map(Value::Float).unwrap_or(Value::Null),
808 _ => Value::Null,
809 }
810}
811
812pub fn starts_with(haystack: &Value, prefix: &Value) -> bool {
814 match (haystack, prefix) {
815 (Value::Str(h), Value::Str(p)) => h.starts_with(p.as_ref()),
816 _ => false,
817 }
818}
819
820pub fn ends_with(haystack: &Value, suffix: &Value) -> bool {
822 match (haystack, suffix) {
823 (Value::Str(h), Value::Str(s)) => h.ends_with(s.as_ref()),
824 _ => false,
825 }
826}
827
828pub fn to_lower(v: &Value) -> Value {
830 match v { Value::Str(s) => Value::Str(s.to_lowercase().into()), _ => Value::Null }
831}
832pub fn to_upper(v: &Value) -> Value {
833 match v { Value::Str(s) => Value::Str(s.to_uppercase().into()), _ => Value::Null }
834}
835
836pub fn trim(v: &Value) -> Value {
838 match v { Value::Str(s) => Value::Str(s.trim().to_string().into()), _ => Value::Null }
839}
840
841pub fn contains(haystack: &Value, needle: &Value) -> bool {
846 match (haystack, needle) {
847 (Value::Str(h), Value::Str(n)) => h.contains(n.as_ref()),
848 (Value::Arr(a), n) => a.iter().any(|el| is_equal(el, n)),
849 _ => false,
850 }
851}
852
853pub const TRUNCATE: i64 = 0;
856pub const ROUND: i64 = 1;
857pub const ROUND_UP: i64 = 2;
858pub const ROUND_DOWN: i64 = 3;
859pub const DECIMAL_PLACES: i64 = 2;
860pub const SIGNIFICANT_DIGITS: i64 = 3;
861pub const TICK_SIZE: i64 = 4;
862pub const NO_PADDING: i64 = 5;
863pub const PAD_WITH_ZERO: i64 = 6;
864
865pub fn string_replace(s: &Value, old: &Value, new_val: &Value) -> Value {
867 match (s, old, new_val) {
868 (Value::Str(s), Value::Str(o), Value::Str(n)) => Value::Str(s.replace(o.as_ref(), n.as_ref()).into()),
869 _ => s.clone(),
870 }
871}
872
873pub fn split(s: &Value, delim: &Value) -> Value {
875 match (s, delim) {
876 (Value::Str(s), Value::Str(d)) => {
877 Value::Array(s.split(d.as_ref()).map(|p| Value::Str(p.to_string().into())).collect())
878 }
879 _ => Value::Array(vec![]),
880 }
881}
882
883pub fn repeat(s: &Value, n: &Value) -> Value {
885 let count = match as_i64(n) { Some(v) => v as usize, None => 0 };
886 match s { Value::Str(s) => Value::Str(s.repeat(count).into()), _ => Value::Null }
887}
888
889fn base32_decode(s: &str) -> Vec<u8> {
892 const ALPHA: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
893 let mut buf: u32 = 0;
894 let mut bits: u32 = 0;
895 let mut out = Vec::new();
896 for c in s.bytes() {
897 let up = c.to_ascii_uppercase();
898 let val = match ALPHA.iter().position(|&x| x == up) {
899 Some(v) => v as u32,
900 None => continue,
901 };
902 buf = (buf << 5) | val;
903 bits += 5;
904 if bits >= 8 {
905 bits -= 8;
906 out.push((buf >> bits) as u8);
907 }
908 }
909 out
910}
911
912pub fn totp(secret: Value) -> Value {
917 use hmac::{Hmac, Mac};
918 use sha1::Sha1;
919 let sec = match &secret {
920 Value::Str(s) => s.replace(' ', ""),
921 _ => return Value::Null,
922 };
923 let key = base32_decode(&sec);
924 let epoch = std::time::SystemTime::now()
925 .duration_since(std::time::UNIX_EPOCH)
926 .map(|d| d.as_secs())
927 .unwrap_or(0);
928 let counter: u64 = epoch / 30;
929 let mut mac = match Hmac::<Sha1>::new_from_slice(&key) {
930 Ok(m) => m,
931 Err(_) => return Value::Null,
932 };
933 mac.update(&counter.to_be_bytes());
934 let digest = mac.finalize().into_bytes(); let offset = (digest[19] & 0x0f) as usize;
936 let code = ((digest[offset] as u32 & 0x7f) << 24)
937 | ((digest[offset + 1] as u32) << 16)
938 | ((digest[offset + 2] as u32) << 8)
939 | (digest[offset + 3] as u32);
940 Value::Str(format!("{:06}", code % 1_000_000).into())
941}
942
943pub fn encode(s: Value) -> Value {
945 match &s {
946 Value::Str(st) => Value::Array(st.bytes().map(|b| Value::Int(b as i64)).collect()),
947 Value::Arr(_) => s,
948 _ => Value::Array(vec![]),
949 }
950}
951
952pub fn hash(data: Value, algo: Value, digest: Value) -> Value {
955 let dbytes = crate::exchange::value_to_bytes(&data);
956 let a = match &algo { Value::Str(s) => s.as_ref(), _ => "sha256" };
957 let dg = match &digest { Value::Str(s) => s.as_ref(), _ => "hex" };
958 let raw = crate::exchange::hash_raw(&dbytes, a);
959 match dg {
960 "binary" => Value::Array(raw.iter().map(|b| Value::Int(*b as i64)).collect()),
961 "base64" => Value::Str(b64_encode(&raw).into()),
962 _ => Value::Str(hex::encode(&raw).into()),
963 }
964}
965
966pub fn hmac(data: Value, secret: Value, algo: Value, digest: Value) -> Value {
968 use hmac::{Hmac, Mac};
969 let dbytes = crate::exchange::value_to_bytes(&data);
970 let sbytes = crate::exchange::value_to_bytes(&secret);
971 let a = match &algo { Value::Str(s) => s.to_ascii_lowercase(), _ => "sha256".to_string() };
972 let dg = match &digest { Value::Str(s) => s.as_ref(), _ => "hex" };
973 let raw: Vec<u8> = match a.as_str() {
974 "sha256" => { let mut m = Hmac::<sha2::Sha256>::new_from_slice(&sbytes).unwrap(); m.update(&dbytes); m.finalize().into_bytes().to_vec() }
975 "sha512" => { let mut m = Hmac::<sha2::Sha512>::new_from_slice(&sbytes).unwrap(); m.update(&dbytes); m.finalize().into_bytes().to_vec() }
976 "sha384" => { let mut m = Hmac::<sha2::Sha384>::new_from_slice(&sbytes).unwrap(); m.update(&dbytes); m.finalize().into_bytes().to_vec() }
977 "sha1" => { let mut m = Hmac::<sha1::Sha1>::new_from_slice(&sbytes).unwrap(); m.update(&dbytes); m.finalize().into_bytes().to_vec() }
978 "md5" => { let mut m = Hmac::<md5::Md5>::new_from_slice(&sbytes).unwrap(); m.update(&dbytes); m.finalize().into_bytes().to_vec() }
979 _ => return Value::Null,
980 };
981 match dg {
982 "binary" => Value::Array(raw.iter().map(|b| Value::Int(*b as i64)).collect()),
983 "base64" => Value::Str(b64_encode(&raw).into()),
984 _ => Value::Str(hex::encode(&raw).into()),
985 }
986}
987
988pub fn crc32(s: Value, signed: Value) -> Value {
991 let bytes = crate::exchange::value_to_bytes(&s);
992 let mut crc: u32 = 0xFFFF_FFFF;
993 for &b in &bytes {
994 crc ^= b as u32;
995 for _ in 0..8 {
996 crc = if crc & 1 != 0 { (crc >> 1) ^ 0xEDB8_8320 } else { crc >> 1 };
997 }
998 }
999 crc = !crc;
1000 if matches!(signed, Value::Bool(true)) {
1001 Value::Int(crc as i32 as i64)
1002 } else {
1003 Value::Int(crc as i64)
1004 }
1005}
1006
1007struct PbReader<'a> {
1010 buf: &'a [u8],
1011 pos: usize,
1012}
1013
1014impl<'a> PbReader<'a> {
1015 fn new(buf: &'a [u8]) -> Self {
1016 Self { buf, pos: 0 }
1017 }
1018 fn eof(&self) -> bool {
1019 self.pos >= self.buf.len()
1020 }
1021 fn read_varint(&mut self) -> u64 {
1023 let mut result: u64 = 0;
1024 let mut shift = 0u32;
1025 while self.pos < self.buf.len() && shift < 64 {
1026 let b = self.buf[self.pos];
1027 self.pos += 1;
1028 result |= ((b & 0x7f) as u64) << shift;
1029 if b & 0x80 == 0 {
1030 break;
1031 }
1032 shift += 7;
1033 }
1034 result
1035 }
1036 fn read_tag(&mut self) -> (u64, u8) {
1038 let t = self.read_varint();
1039 (t >> 3, (t & 7) as u8)
1040 }
1041 fn read_bytes(&mut self) -> &'a [u8] {
1043 let len = self.read_varint() as usize;
1044 let end = self.pos.saturating_add(len).min(self.buf.len());
1045 let s = &self.buf[self.pos..end];
1046 self.pos = end;
1047 s
1048 }
1049 fn skip(&mut self, wire: u8) {
1051 match wire {
1052 0 => {
1053 self.read_varint();
1054 }
1055 1 => self.pos = self.pos.saturating_add(8).min(self.buf.len()),
1056 2 => {
1057 let len = self.read_varint() as usize;
1058 self.pos = self.pos.saturating_add(len).min(self.buf.len());
1059 }
1060 5 => self.pos = self.pos.saturating_add(4).min(self.buf.len()),
1061 _ => self.pos = self.buf.len(),
1062 }
1063 }
1064}
1065
1066fn pb_string(b: &[u8]) -> Value {
1067 Value::Str(String::from_utf8_lossy(b).into_owned().into())
1068}
1069
1070fn pb_decode_depth_item(b: &[u8]) -> Value {
1072 let mut r = PbReader::new(b);
1073 let mut m: HashMap<String, Value> = HashMap::new();
1074 while !r.eof() {
1075 match r.read_tag() {
1076 (1, 2) => {
1077 m.insert("price".to_string(), pb_string(r.read_bytes()));
1078 }
1079 (2, 2) => {
1080 m.insert("quantity".to_string(), pb_string(r.read_bytes()));
1081 }
1082 (_, wire) => r.skip(wire),
1083 }
1084 }
1085 Value::Map(m)
1086}
1087
1088fn pb_decode_depths(b: &[u8]) -> Value {
1091 let mut r = PbReader::new(b);
1092 let mut asks: Vec<Value> = Vec::new();
1093 let mut bids: Vec<Value> = Vec::new();
1094 let mut m: HashMap<String, Value> = HashMap::new();
1095 while !r.eof() {
1096 match r.read_tag() {
1097 (1, 2) => asks.push(pb_decode_depth_item(r.read_bytes())),
1098 (2, 2) => bids.push(pb_decode_depth_item(r.read_bytes())),
1099 (3, 2) => {
1100 m.insert("eventType".to_string(), pb_string(r.read_bytes()));
1101 }
1102 (4, 2) => {
1103 m.insert("fromVersion".to_string(), pb_string(r.read_bytes()));
1104 }
1105 (5, 2) => {
1106 m.insert("toVersion".to_string(), pb_string(r.read_bytes()));
1107 }
1108 (_, wire) => r.skip(wire),
1109 }
1110 }
1111 m.insert("asks".to_string(), Value::List(asks));
1112 m.insert("bids".to_string(), Value::List(bids));
1113 Value::Map(m)
1114}
1115
1116fn pb_decode_book_ticker(b: &[u8]) -> Value {
1119 let mut r = PbReader::new(b);
1120 let mut m: HashMap<String, Value> = HashMap::new();
1121 let fields = ["bidPrice", "bidQuantity", "askPrice", "askQuantity"];
1122 while !r.eof() {
1123 match r.read_tag() {
1124 (n @ 1..=4, 2) => {
1125 m.insert(fields[(n - 1) as usize].to_string(), pb_string(r.read_bytes()));
1126 }
1127 (_, wire) => r.skip(wire),
1128 }
1129 }
1130 Value::Map(m)
1131}
1132
1133fn pb_decode_deal_item(b: &[u8]) -> Value {
1136 let mut r = PbReader::new(b);
1137 let mut m: HashMap<String, Value> = HashMap::new();
1138 while !r.eof() {
1139 match r.read_tag() {
1140 (1, 2) => { m.insert("price".to_string(), pb_string(r.read_bytes())); }
1141 (2, 2) => { m.insert("quantity".to_string(), pb_string(r.read_bytes())); }
1142 (3, 0) => { m.insert("tradeType".to_string(), Value::Int(r.read_varint() as i64)); }
1143 (4, 0) => { m.insert("time".to_string(), Value::Int(r.read_varint() as i64)); }
1144 (_, wire) => r.skip(wire),
1145 }
1146 }
1147 Value::Map(m)
1148}
1149
1150fn pb_decode_deals(b: &[u8]) -> Value {
1153 let mut r = PbReader::new(b);
1154 let mut deals: Vec<Value> = Vec::new();
1155 let mut m: HashMap<String, Value> = HashMap::new();
1156 while !r.eof() {
1157 match r.read_tag() {
1158 (1, 2) => deals.push(pb_decode_deal_item(r.read_bytes())),
1159 (2, 2) => { m.insert("eventType".to_string(), pb_string(r.read_bytes())); }
1160 (_, wire) => r.skip(wire),
1161 }
1162 }
1163 m.insert("deals".to_string(), Value::List(deals));
1164 Value::Map(m)
1165}
1166
1167fn pb_decode_spot_kline(b: &[u8]) -> Value {
1169 let mut r = PbReader::new(b);
1170 let mut m: HashMap<String, Value> = HashMap::new();
1171 while !r.eof() {
1172 match r.read_tag() {
1173 (1, 2) => { m.insert("interval".to_string(), pb_string(r.read_bytes())); }
1174 (2, 0) => { m.insert("windowStart".to_string(), Value::Int(r.read_varint() as i64)); }
1175 (3, 2) => { m.insert("openingPrice".to_string(), pb_string(r.read_bytes())); }
1176 (4, 2) => { m.insert("closingPrice".to_string(), pb_string(r.read_bytes())); }
1177 (5, 2) => { m.insert("highestPrice".to_string(), pb_string(r.read_bytes())); }
1178 (6, 2) => { m.insert("lowestPrice".to_string(), pb_string(r.read_bytes())); }
1179 (7, 2) => { m.insert("volume".to_string(), pb_string(r.read_bytes())); }
1180 (8, 2) => { m.insert("amount".to_string(), pb_string(r.read_bytes())); }
1181 (9, 0) => { m.insert("windowEnd".to_string(), Value::Int(r.read_varint() as i64)); }
1182 (_, wire) => r.skip(wire),
1183 }
1184 }
1185 Value::Map(m)
1186}
1187
1188pub fn decode_mexc_push_data(bytes: &[u8]) -> Value {
1192 let mut r = PbReader::new(bytes);
1193 let mut m: HashMap<String, Value> = HashMap::new();
1194 while !r.eof() {
1195 match r.read_tag() {
1196 (1, 2) => {
1197 m.insert("channel".to_string(), pb_string(r.read_bytes()));
1198 }
1199 (3, 2) => {
1200 m.insert("symbol".to_string(), pb_string(r.read_bytes()));
1201 }
1202 (4, 2) => {
1203 m.insert("symbolId".to_string(), pb_string(r.read_bytes()));
1204 }
1205 (5, 0) => {
1206 m.insert("createTime".to_string(), Value::Int(r.read_varint() as i64));
1207 }
1208 (6, 0) => {
1209 m.insert("sendTime".to_string(), Value::Int(r.read_varint() as i64));
1210 }
1211 (302, 2) => {
1212 m.insert("publicIncreaseDepths".to_string(), pb_decode_depths(r.read_bytes()));
1213 }
1214 (303, 2) => {
1215 m.insert("publicLimitDepths".to_string(), pb_decode_depths(r.read_bytes()));
1216 }
1217 (313, 2) => {
1218 m.insert("publicAggreDepths".to_string(), pb_decode_depths(r.read_bytes()));
1219 }
1220 (301, 2) => {
1221 m.insert("publicDeals".to_string(), pb_decode_deals(r.read_bytes()));
1222 }
1223 (314, 2) => {
1224 m.insert("publicAggreDeals".to_string(), pb_decode_deals(r.read_bytes()));
1225 }
1226 (305, 2) => {
1227 m.insert("publicBookTicker".to_string(), pb_decode_book_ticker(r.read_bytes()));
1228 }
1229 (315, 2) => {
1230 m.insert("publicAggreBookTicker".to_string(), pb_decode_book_ticker(r.read_bytes()));
1231 }
1232 (308, 2) => {
1233 m.insert("publicSpotKline".to_string(), pb_decode_spot_kline(r.read_bytes()));
1234 }
1235 (_, wire) => r.skip(wire),
1236 }
1237 }
1238 Value::Map(m)
1239}
1240
1241pub fn rsa(message: Value, key: Value, _hash: Value) -> Value {
1244 use rsa::RsaPrivateKey;
1245 use rsa::pkcs1::DecodeRsaPrivateKey;
1246 use rsa::pkcs1v15::SigningKey;
1247 use rsa::signature::{SignatureEncoding, Signer};
1248 let msg = crate::exchange::value_to_bytes(&message);
1249 let pem = String::from_utf8_lossy(&crate::exchange::value_to_bytes(&key)).into_owned();
1250 let pk = match RsaPrivateKey::from_pkcs1_pem(pem.trim()) {
1251 Ok(k) => k,
1252 Err(_) => return Value::Str(String::new().into()),
1253 };
1254 let signing_key = SigningKey::<sha2::Sha256>::new(pk);
1255 let sig = signing_key.sign(&msg);
1256 Value::Str(b64_encode(&sig.to_bytes()).into())
1257}
1258
1259pub fn ecdsa(message: Value, secret: Value, _curve: Value, pre_hash: Value) -> Value {
1264 use k256::ecdsa::SigningKey;
1265 let empty = || Value::Map(indexmap::IndexMap::new());
1266 let msg_s = match &message { Value::Str(s) => s.trim_start_matches("0x").to_string(), _ => return empty() };
1267 let sk_s = match &secret { Value::Str(s) => s.trim_start_matches("0x").to_string(), _ => return empty() };
1268 let sk_bytes = match hex::decode(&sk_s) { Ok(b) => b, Err(_) => return empty() };
1269 let digest: Vec<u8> = match &pre_hash {
1271 Value::Str(algo) => crate::exchange::hash_raw(
1272 &crate::exchange::value_to_bytes(&message), algo),
1273 _ => match hex::decode(&msg_s) { Ok(b) => b, Err(_) => return empty() },
1274 };
1275 let sk = match SigningKey::from_slice(&sk_bytes) { Ok(k) => k, Err(_) => return empty() };
1276 let (sig, recid) = match sk.sign_prehash_recoverable(&digest) {
1277 Ok(x) => x,
1278 Err(_) => return empty(),
1279 };
1280 let bytes = sig.to_bytes(); let mut m = indexmap::IndexMap::new();
1282 m.insert("r".to_string(), Value::Str(hex::encode(&bytes[0..32]).into()));
1283 m.insert("s".to_string(), Value::Str(hex::encode(&bytes[32..64]).into()));
1284 m.insert("v".to_string(), Value::Int(recid.to_byte() as i64));
1285 Value::Map(m)
1286}
1287
1288fn pem_to_der(pem: &str) -> Vec<u8> {
1291 use base64::{engine::general_purpose::STANDARD, Engine as _};
1292 let body: String = pem
1293 .lines()
1294 .filter(|l| !l.starts_with("-----"))
1295 .collect::<Vec<_>>()
1296 .join("");
1297 STANDARD.decode(body.trim()).unwrap_or_default()
1298}
1299
1300pub fn eddsa(request: Value, secret: Value, _curve: Value) -> Value {
1307 use ed25519_dalek::{Signer, SigningKey};
1308 let bad = |why: &str| -> ! {
1309 panic!("{}", crate::exchange_errors::not_supported(
1310 Value::Str(format!("eddsa: {why}").into())));
1311 };
1312 let msg: Vec<u8> = match &request {
1313 Value::Arr(_) => crate::exchange::value_to_bytes(&request),
1314 Value::Str(s) => {
1315 let t = s.trim_start_matches("0x");
1316 hex::decode(t).unwrap_or_else(|_| s.as_bytes().to_vec())
1317 }
1318 _ => bad("request must be bytes or a string"),
1319 };
1320 let seed: [u8; 32] = match &secret {
1324 Value::Arr(_) => {
1325 let b = crate::exchange::value_to_bytes(&secret);
1326 if b.len() >= 32 { b[..32].try_into().unwrap() } else { bad("seed shorter than 32 bytes") }
1327 }
1328 Value::Str(sec_s) if sec_s.len() == 32 => {
1329 sec_s.as_bytes().try_into().unwrap()
1330 }
1331 Value::Str(sec_s) => {
1332 let der = pem_to_der(sec_s);
1333 if der.len() >= 48 {
1334 der[16..48].try_into().unwrap()
1335 } else if der.len() >= 32 {
1336 der[der.len() - 32..].try_into().unwrap()
1337 } else {
1338 bad("secret is not a 32-byte seed or a decodable PKCS#8 key");
1339 }
1340 }
1341 _ => bad("secret must be a string or byte array"),
1342 };
1343 let sk = SigningKey::from_bytes(&seed);
1344 let sig = sk.sign(&msg);
1345 Value::Str(b64_encode(&sig.to_bytes()).into())
1346}
1347
1348fn b64_encode(data: &[u8]) -> String {
1350 use base64::{engine::general_purpose::STANDARD, Engine as _};
1351 STANDARD.encode(data)
1352}
1353
1354fn b64url_encode(data: &[u8]) -> String {
1356 use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
1357 URL_SAFE_NO_PAD.encode(data)
1358}
1359
1360pub fn jwt(request: Value, secret: Value, algorithm: Value, is_rsa: Value, _opts: Value) -> Value {
1363 let rsa_mode = matches!(is_rsa, Value::Bool(true));
1364 let bits = match algorithm.as_str() {
1365 Some("sha512") => "512",
1366 Some("sha384") => "384",
1367 _ => "256",
1368 };
1369 let alg = format!("{}{}", if rsa_mode { "RS" } else { "HS" }, bits);
1370 let header = format!("{{\"alg\":\"{alg}\",\"typ\":\"JWT\"}}");
1372 let payload = serde_json::to_string(&request.to_json()).unwrap_or_else(|_| "{}".to_string());
1373 let token = format!("{}.{}",
1374 b64url_encode(header.as_bytes()),
1375 b64url_encode(payload.as_bytes()));
1376 let sig_std: String = if rsa_mode {
1378 match rsa(Value::Str(token.clone().into()), secret, algorithm) {
1379 Value::Str(s) => s.to_string(),
1380 _ => String::new(),
1381 }
1382 } else {
1383 match hmac(encode(Value::Str(token.clone().into())), secret, algorithm,
1384 Value::Str("base64".into())) {
1385 Value::Str(s) => s.to_string(),
1386 _ => String::new(),
1387 }
1388 };
1389 let sig_url = sig_std.replace('+', "-").replace('/', "_")
1390 .trim_end_matches('=').to_string();
1391 Value::Str(format!("{token}.{sig_url}").into())
1392}
1393
1394pub fn replace_str(s: &Value, old: &Value, new_val: &Value) -> Value {
1396 string_replace(s, old, new_val)
1397}
1398
1399pub fn replace_all_str(s: &Value, old: &Value, new_val: &Value) -> Value {
1401 let (Value::Str(sv), Value::Str(ov), Value::Str(nv)) = (s, old, new_val) else {
1402 return s.clone();
1403 };
1404 Value::Str(sv.replace(ov.as_ref(), nv.as_ref()).into())
1405}
1406
1407pub fn date_now() -> Value {
1409 let ms = std::time::SystemTime::now()
1410 .duration_since(std::time::UNIX_EPOCH)
1411 .map(|d| d.as_millis() as i64)
1412 .unwrap_or(0);
1413 Value::Int(ms)
1414}
1415
1416pub fn pad_start(s: &Value, len: &Value, pad: &Value) -> Value {
1418 let target = match as_i64(len) { Some(v) => v as usize, None => 0 };
1419 let p = match pad { Value::Str(p) => p.clone(), _ => " ".to_string().into() };
1420 match s {
1421 Value::Str(sv) => {
1422 if sv.chars().count() >= target { Value::Str(sv.clone()) }
1423 else {
1424 let need = target - sv.chars().count();
1425 Value::Str(format!("{}{}", p.repeat((need / p.chars().count().max(1)).max(1)), sv).into())
1426 }
1427 }
1428 _ => Value::Null,
1429 }
1430}
1431
1432pub fn pad_end(s: &Value, len: &Value, pad: &Value) -> Value {
1433 let target = match as_i64(len) { Some(v) => v as usize, None => 0 };
1434 let p = match pad { Value::Str(p) => p.clone(), _ => " ".to_string().into() };
1435 match s {
1436 Value::Str(sv) => {
1437 if sv.chars().count() >= target { Value::Str(sv.clone()) }
1438 else {
1439 let need = target - sv.chars().count();
1440 Value::Str(format!("{}{}", sv, p.repeat((need / p.chars().count().max(1)).max(1))).into())
1441 }
1442 }
1443 _ => Value::Null,
1444 }
1445}
1446
1447pub fn to_fixed(x: &Value, digits: &Value) -> Value {
1450 let d = match as_i64(digits) { Some(v) => v.max(0) as usize, None => 0 };
1451 let n = match x {
1452 Value::Int(i) => *i as f64,
1453 Value::Float(f) => *f,
1454 Value::Str(s) => s.trim().parse::<f64>().unwrap_or(0.0),
1455 _ => 0.0,
1456 };
1457 Value::Str(format!("{:.*}", d, n).into())
1458}
1459
1460