streamweave 0.10.1

Composable, async, stream-first computation in pure Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
//! # String Common Utilities
//!
//! Shared utilities for string operation nodes.

use std::any::Any;
use std::sync::Arc;

/// Concatenates two string values.
///
/// This function attempts to downcast both values to String and performs
/// concatenation. It handles:
/// - String + String: Direct concatenation
///
/// Returns the result as `Arc<dyn Any + Send + Sync>` or an error string.
pub fn concat_strings(
  v1: &Arc<dyn Any + Send + Sync>,
  v2: &Arc<dyn Any + Send + Sync>,
) -> Result<Arc<dyn Any + Send + Sync>, String> {
  // Try String + String
  if let (Ok(arc_str1), Ok(arc_str2)) = (
    v1.clone().downcast::<String>(),
    v2.clone().downcast::<String>(),
  ) {
    let result = format!("{}{}", *arc_str1, *arc_str2);
    return Ok(Arc::new(result) as Arc<dyn Any + Send + Sync>);
  }

  Err(format!(
    "Unsupported types for string concatenation: {} + {} (both inputs must be String)",
    std::any::type_name_of_val(&**v1),
    std::any::type_name_of_val(&**v2)
  ))
}

/// Gets the length of a string value.
///
/// This function attempts to downcast the value to String and returns
/// its character count as a usize.
///
/// Returns the result as `Arc<dyn Any + Send + Sync>` or an error string.
pub fn string_length(v: &Arc<dyn Any + Send + Sync>) -> Result<Arc<dyn Any + Send + Sync>, String> {
  // Try String
  if let Ok(arc_str) = v.clone().downcast::<String>() {
    let length = arc_str.len();
    return Ok(Arc::new(length) as Arc<dyn Any + Send + Sync>);
  }

  Err(format!(
    "Unsupported type for string length: {} (input must be String)",
    std::any::type_name_of_val(&**v)
  ))
}

/// Extracts a substring from a string using start and end indices.
///
/// This function attempts to downcast the string and indices to their expected types
/// and extracts the substring. It handles:
/// - String slicing with usize indices
/// - Bounds checking
/// - Invalid index ranges (start > end, out of bounds)
///
/// Returns the result as `Arc<dyn Any + Send + Sync>` or an error string.
pub fn string_slice(
  v: &Arc<dyn Any + Send + Sync>,
  start: &Arc<dyn Any + Send + Sync>,
  end: &Arc<dyn Any + Send + Sync>,
) -> Result<Arc<dyn Any + Send + Sync>, String> {
  // Try to downcast string
  let arc_str = v.clone().downcast::<String>().map_err(|_| {
    format!(
      "Unsupported type for string slice input: {} (input must be String)",
      std::any::type_name_of_val(&**v)
    )
  })?;

  // Try to downcast start index (usize, i32, i64, u32, u64)
  let start_idx = if let Ok(arc_usize) = start.clone().downcast::<usize>() {
    *arc_usize
  } else if let Ok(arc_i32) = start.clone().downcast::<i32>() {
    if *arc_i32 < 0 {
      return Err("Start index cannot be negative".to_string());
    }
    *arc_i32 as usize
  } else if let Ok(arc_i64) = start.clone().downcast::<i64>() {
    if *arc_i64 < 0 {
      return Err("Start index cannot be negative".to_string());
    }
    if *arc_i64 > usize::MAX as i64 {
      return Err("Start index too large".to_string());
    }
    *arc_i64 as usize
  } else if let Ok(arc_u32) = start.clone().downcast::<u32>() {
    *arc_u32 as usize
  } else if let Ok(arc_u64) = start.clone().downcast::<u64>() {
    if *arc_u64 > usize::MAX as u64 {
      return Err("Start index too large".to_string());
    }
    *arc_u64 as usize
  } else {
    return Err(format!(
      "Unsupported type for start index: {} (must be numeric)",
      std::any::type_name_of_val(&**start)
    ));
  };

  // Try to downcast end index (usize, i32, i64, u32, u64)
  let end_idx = if let Ok(arc_usize) = end.clone().downcast::<usize>() {
    *arc_usize
  } else if let Ok(arc_i32) = end.clone().downcast::<i32>() {
    if *arc_i32 < 0 {
      return Err("End index cannot be negative".to_string());
    }
    *arc_i32 as usize
  } else if let Ok(arc_i64) = end.clone().downcast::<i64>() {
    if *arc_i64 < 0 {
      return Err("End index cannot be negative".to_string());
    }
    if *arc_i64 > usize::MAX as i64 {
      return Err("End index too large".to_string());
    }
    *arc_i64 as usize
  } else if let Ok(arc_u32) = end.clone().downcast::<u32>() {
    *arc_u32 as usize
  } else if let Ok(arc_u64) = end.clone().downcast::<u64>() {
    if *arc_u64 > usize::MAX as u64 {
      return Err("End index too large".to_string());
    }
    *arc_u64 as usize
  } else {
    return Err(format!(
      "Unsupported type for end index: {} (must be numeric)",
      std::any::type_name_of_val(&**end)
    ));
  };

  // Validate indices
  if start_idx > end_idx {
    return Err(format!(
      "Invalid index range: start ({}) > end ({})",
      start_idx, end_idx
    ));
  }

  // Convert character indices to byte positions for Unicode-safe slicing
  let char_count = arc_str.chars().count();
  if start_idx > char_count {
    return Err(format!(
      "Start index ({}) out of bounds for string of length {} (character count)",
      start_idx, char_count
    ));
  }

  if end_idx > char_count {
    return Err(format!(
      "End index ({}) out of bounds for string of length {} (character count)",
      end_idx, char_count
    ));
  }

  // Find byte positions for character boundaries
  let mut start_byte = 0;
  let mut end_byte = arc_str.len();

  for (char_idx, (byte_idx, _)) in arc_str.char_indices().enumerate() {
    if char_idx == start_idx {
      start_byte = byte_idx;
    }
    if char_idx == end_idx {
      end_byte = byte_idx;
      break;
    }
  }

  // Handle case where end_idx equals the character count (slice to end of string)
  if end_idx == char_count {
    end_byte = arc_str.len();
  }

  // Extract substring using byte positions (now guaranteed to be at character boundaries)
  let result = arc_str[start_byte..end_byte].to_string();
  Ok(Arc::new(result) as Arc<dyn Any + Send + Sync>)
}

/// Replaces all occurrences of a pattern in a string with a replacement string.
///
/// This function attempts to downcast the string, pattern, and replacement to their
/// expected types and performs replacement. It supports:
/// - String replacement with literal patterns
/// - All occurrences replacement
///
/// Returns the result as `Arc<dyn Any + Send + Sync>` or an error string.
pub fn string_replace(
  v: &Arc<dyn Any + Send + Sync>,
  pattern: &Arc<dyn Any + Send + Sync>,
  replacement: &Arc<dyn Any + Send + Sync>,
) -> Result<Arc<dyn Any + Send + Sync>, String> {
  // Try to downcast string
  let arc_str = v.clone().downcast::<String>().map_err(|_| {
    format!(
      "Unsupported type for string replace input: {} (input must be String)",
      std::any::type_name_of_val(&**v)
    )
  })?;

  // Try to downcast pattern
  let arc_pattern = pattern.clone().downcast::<String>().map_err(|_| {
    format!(
      "Unsupported type for pattern: {} (pattern must be String)",
      std::any::type_name_of_val(&**pattern)
    )
  })?;

  // Try to downcast replacement
  let arc_replacement = replacement.clone().downcast::<String>().map_err(|_| {
    format!(
      "Unsupported type for replacement: {} (replacement must be String)",
      std::any::type_name_of_val(&**replacement)
    )
  })?;

  // Perform replacement (replace all occurrences)
  let result = arc_str.replace(&*arc_pattern, &arc_replacement);
  Ok(Arc::new(result) as Arc<dyn Any + Send + Sync>)
}

/// Splits a string by a delimiter and returns a vector of strings.
///
/// This function attempts to downcast the string and delimiter to their
/// expected types and performs splitting. It supports:
/// - String splitting by literal delimiter
/// - Returns Vec<Arc<dyn Any + Send + Sync>> where each element is a String
///
/// Returns the result as `Arc<dyn Any + Send + Sync>` (wrapping Vec) or an error string.
pub fn string_split(
  v: &Arc<dyn Any + Send + Sync>,
  delimiter: &Arc<dyn Any + Send + Sync>,
) -> Result<Arc<dyn Any + Send + Sync>, String> {
  // Try to downcast string
  let arc_str = v.clone().downcast::<String>().map_err(|_| {
    format!(
      "Unsupported type for string split input: {} (input must be String)",
      std::any::type_name_of_val(&**v)
    )
  })?;

  // Try to downcast delimiter
  let arc_delimiter = delimiter.clone().downcast::<String>().map_err(|_| {
    format!(
      "Unsupported type for delimiter: {} (delimiter must be String)",
      std::any::type_name_of_val(&**delimiter)
    )
  })?;

  // Perform split
  let parts: Vec<Arc<dyn Any + Send + Sync>> = arc_str
    .split(&*arc_delimiter)
    .map(|s| Arc::new(s.to_string()) as Arc<dyn Any + Send + Sync>)
    .collect();

  Ok(Arc::new(parts) as Arc<dyn Any + Send + Sync>)
}

/// Joins an array of strings with a delimiter.
///
/// This function attempts to downcast the array and delimiter to their
/// expected types and performs joining. It supports:
/// - Joining Vec<Arc<dyn Any + Send + Sync>> where each element is a String
/// - Returns a single joined string
///
/// Returns the result as `Arc<dyn Any + Send + Sync>` or an error string.
pub fn string_join(
  v: &Arc<dyn Any + Send + Sync>,
  delimiter: &Arc<dyn Any + Send + Sync>,
) -> Result<Arc<dyn Any + Send + Sync>, String> {
  // Try to downcast array
  let arc_vec = v
    .clone()
    .downcast::<Vec<Arc<dyn Any + Send + Sync>>>()
    .map_err(|_| {
      format!(
        "Unsupported type for string join input: {} (input must be Vec<Arc<dyn Any + Send + Sync>>)",
        std::any::type_name_of_val(&**v)
      )
    })?;

  // Try to downcast delimiter
  let arc_delimiter = delimiter.clone().downcast::<String>().map_err(|_| {
    format!(
      "Unsupported type for delimiter: {} (delimiter must be String)",
      std::any::type_name_of_val(&**delimiter)
    )
  })?;

  // Convert each element to String and join
  let mut parts = Vec::new();
  for (idx, item) in arc_vec.iter().enumerate() {
    let arc_str = item.clone().downcast::<String>().map_err(|_| {
      format!(
        "Unsupported type for array element at index {}: {} (all elements must be String)",
        idx,
        std::any::type_name_of_val(&**item)
      )
    })?;
    parts.push((*arc_str).clone());
  }

  // Join with delimiter
  let result = parts.join(&*arc_delimiter);
  Ok(Arc::new(result) as Arc<dyn Any + Send + Sync>)
}

/// Checks if a string contains a substring.
///
/// This function attempts to downcast the string and substring to their
/// expected types and performs the contains check. It supports:
/// - Case-sensitive substring matching
///
/// Returns the result as `Arc<dyn Any + Send + Sync>` (bool) or an error string.
pub fn string_contains(
  v: &Arc<dyn Any + Send + Sync>,
  substring: &Arc<dyn Any + Send + Sync>,
) -> Result<Arc<dyn Any + Send + Sync>, String> {
  // Try to downcast string
  let arc_str = v.clone().downcast::<String>().map_err(|_| {
    format!(
      "Unsupported type for string contains input: {} (input must be String)",
      std::any::type_name_of_val(&**v)
    )
  })?;

  // Try to downcast substring
  let arc_substring = substring.clone().downcast::<String>().map_err(|_| {
    format!(
      "Unsupported type for substring: {} (substring must be String)",
      std::any::type_name_of_val(&**substring)
    )
  })?;

  // Perform contains check (case-sensitive)
  let result = arc_str.contains(&*arc_substring);
  Ok(Arc::new(result) as Arc<dyn Any + Send + Sync>)
}

/// Checks if a string starts with a prefix.
///
/// This function attempts to downcast the string and prefix to their
/// expected types and performs the starts_with check. It supports:
/// - Case-sensitive prefix matching
///
/// Returns the result as `Arc<dyn Any + Send + Sync>` (bool) or an error string.
pub fn string_starts_with(
  v: &Arc<dyn Any + Send + Sync>,
  prefix: &Arc<dyn Any + Send + Sync>,
) -> Result<Arc<dyn Any + Send + Sync>, String> {
  // Try to downcast string
  let arc_str = v.clone().downcast::<String>().map_err(|_| {
    format!(
      "Unsupported type for string starts_with input: {} (input must be String)",
      std::any::type_name_of_val(&**v)
    )
  })?;

  // Try to downcast prefix
  let arc_prefix = prefix.clone().downcast::<String>().map_err(|_| {
    format!(
      "Unsupported type for prefix: {} (prefix must be String)",
      std::any::type_name_of_val(&**prefix)
    )
  })?;

  // Perform starts_with check (case-sensitive)
  let result = arc_str.starts_with(&*arc_prefix);
  Ok(Arc::new(result) as Arc<dyn Any + Send + Sync>)
}

/// Checks if a string ends with a suffix.
///
/// This function attempts to downcast the string and suffix to their
/// expected types and performs the ends_with check. It supports:
/// - Case-sensitive suffix matching
///
/// Returns the result as `Arc<dyn Any + Send + Sync>` (bool) or an error string.
pub fn string_ends_with(
  v: &Arc<dyn Any + Send + Sync>,
  suffix: &Arc<dyn Any + Send + Sync>,
) -> Result<Arc<dyn Any + Send + Sync>, String> {
  // Try to downcast string
  let arc_str = v.clone().downcast::<String>().map_err(|_| {
    format!(
      "Unsupported type for string ends_with input: {} (input must be String)",
      std::any::type_name_of_val(&**v)
    )
  })?;

  // Try to downcast suffix
  let arc_suffix = suffix.clone().downcast::<String>().map_err(|_| {
    format!(
      "Unsupported type for suffix: {} (suffix must be String)",
      std::any::type_name_of_val(&**suffix)
    )
  })?;

  // Perform ends_with check (case-sensitive)
  let result = arc_str.ends_with(&*arc_suffix);
  Ok(Arc::new(result) as Arc<dyn Any + Send + Sync>)
}

/// Checks if a string matches a regex pattern.
///
/// This function attempts to downcast the string and pattern to their
/// expected types and performs regex matching. It supports:
/// - Regex pattern matching (compiled at runtime)
/// - Returns boolean (true if matches, false otherwise)
///
/// Returns the result as `Arc<dyn Any + Send + Sync>` (bool) or an error string.
pub fn string_match(
  v: &Arc<dyn Any + Send + Sync>,
  pattern: &Arc<dyn Any + Send + Sync>,
) -> Result<Arc<dyn Any + Send + Sync>, String> {
  // Try to downcast string
  let arc_str = v.clone().downcast::<String>().map_err(|_| {
    format!(
      "Unsupported type for string match input: {} (input must be String)",
      std::any::type_name_of_val(&**v)
    )
  })?;

  // Try to downcast pattern
  let arc_pattern_str = pattern.clone().downcast::<String>().map_err(|_| {
    format!(
      "Unsupported type for pattern: {} (pattern must be String)",
      std::any::type_name_of_val(&**pattern)
    )
  })?;

  // Compile regex pattern
  let regex_pattern =
    regex::Regex::new(&arc_pattern_str).map_err(|e| format!("Invalid regex pattern: {}", e))?;

  // Perform regex match
  let result = regex_pattern.is_match(&arc_str);
  Ok(Arc::new(result) as Arc<dyn Any + Send + Sync>)
}

/// Checks if two strings are equal.
///
/// This function attempts to downcast both strings to their
/// expected types and performs equality comparison. It supports:
/// - Case-sensitive string equality
///
/// Returns the result as `Arc<dyn Any + Send + Sync>` (bool) or an error string.
pub fn string_equal(
  v1: &Arc<dyn Any + Send + Sync>,
  v2: &Arc<dyn Any + Send + Sync>,
) -> Result<Arc<dyn Any + Send + Sync>, String> {
  // Try to downcast first string
  let arc_str1 = v1.clone().downcast::<String>().map_err(|_| {
    format!(
      "Unsupported type for string equal input 1: {} (input must be String)",
      std::any::type_name_of_val(&**v1)
    )
  })?;

  // Try to downcast second string
  let arc_str2 = v2.clone().downcast::<String>().map_err(|_| {
    format!(
      "Unsupported type for string equal input 2: {} (input must be String)",
      std::any::type_name_of_val(&**v2)
    )
  })?;

  // Perform equality check (case-sensitive)
  let result = *arc_str1 == *arc_str2;
  Ok(Arc::new(result) as Arc<dyn Any + Send + Sync>)
}

/// Converts a string to a different case (upper, lower, or title).
///
/// This function attempts to downcast the string and case type to their
/// expected types and performs case conversion. It supports:
/// - "upper" or "uppercase": Converts to uppercase
/// - "lower" or "lowercase": Converts to lowercase
/// - "title" or "titlecase": Converts to title case (first letter of each word uppercase)
///
/// Returns the result as `Arc<dyn Any + Send + Sync>` or an error string.
pub fn string_case(
  v: &Arc<dyn Any + Send + Sync>,
  case_type: &Arc<dyn Any + Send + Sync>,
) -> Result<Arc<dyn Any + Send + Sync>, String> {
  // Try to downcast string
  let arc_str = v.clone().downcast::<String>().map_err(|_| {
    format!(
      "Unsupported type for string case input: {} (input must be String)",
      std::any::type_name_of_val(&**v)
    )
  })?;

  // Try to downcast case type
  let arc_case_type = case_type.clone().downcast::<String>().map_err(|_| {
    format!(
      "Unsupported type for case type: {} (case type must be String)",
      std::any::type_name_of_val(&**case_type)
    )
  })?;

  // Perform case conversion
  let result = match arc_case_type.to_lowercase().as_str() {
    "upper" | "uppercase" => arc_str.to_uppercase(),
    "lower" | "lowercase" => arc_str.to_lowercase(),
    "title" | "titlecase" => {
      // Title case: first letter of each word uppercase, rest lowercase
      arc_str
        .split_whitespace()
        .map(|word| {
          let mut chars = word.chars();
          match chars.next() {
            None => String::new(),
            Some(first) => {
              first.to_uppercase().collect::<String>() + &chars.as_str().to_lowercase()
            }
          }
        })
        .collect::<Vec<_>>()
        .join(" ")
    }
    _ => {
      return Err(format!(
        "Unsupported case type: {} (must be 'upper', 'lower', or 'title')",
        *arc_case_type
      ));
    }
  };

  Ok(Arc::new(result) as Arc<dyn Any + Send + Sync>)
}

/// Trims leading and trailing whitespace from a string.
///
/// This function attempts to downcast the string to its expected type
/// and performs trimming. It supports:
/// - Trimming leading and trailing whitespace
///
/// Returns the result as `Arc<dyn Any + Send + Sync>` or an error string.
pub fn string_trim(v: &Arc<dyn Any + Send + Sync>) -> Result<Arc<dyn Any + Send + Sync>, String> {
  // Try to downcast string
  let arc_str = v.clone().downcast::<String>().map_err(|_| {
    format!(
      "Unsupported type for string trim input: {} (input must be String)",
      std::any::type_name_of_val(&**v)
    )
  })?;

  // Perform trim
  let result = arc_str.trim().to_string();
  Ok(Arc::new(result) as Arc<dyn Any + Send + Sync>)
}

/// Pads a string to a specified length with a padding character.
///
/// This function attempts to downcast the string, length, padding character, and side
/// to their expected types and performs padding. It supports:
/// - Left padding: Pads on the left side
/// - Right padding: Pads on the right side
/// - Center padding: Pads on both sides (preferring left if odd)
///
/// Returns the result as `Arc<dyn Any + Send + Sync>` or an error string.
pub fn string_pad(
  v: &Arc<dyn Any + Send + Sync>,
  length: &Arc<dyn Any + Send + Sync>,
  padding: &Arc<dyn Any + Send + Sync>,
  side: &Arc<dyn Any + Send + Sync>,
) -> Result<Arc<dyn Any + Send + Sync>, String> {
  // Try to downcast string
  let arc_str = v.clone().downcast::<String>().map_err(|_| {
    format!(
      "Unsupported type for string pad input: {} (input must be String)",
      std::any::type_name_of_val(&**v)
    )
  })?;

  // Helper to convert Arc<dyn Any> to usize, handling various numeric types
  let get_usize = |val: &Arc<dyn Any + Send + Sync>, name: &str| -> Result<usize, String> {
    if let Ok(arc_usize) = val.clone().downcast::<usize>() {
      Ok(*arc_usize)
    } else if let Ok(arc_i32) = val.clone().downcast::<i32>() {
      if *arc_i32 < 0 {
        return Err(format!("{} cannot be negative", name));
      }
      (*arc_i32)
        .try_into()
        .map_err(|_| format!("{} too large", name))
    } else if let Ok(arc_i64) = val.clone().downcast::<i64>() {
      if *arc_i64 < 0 {
        return Err(format!("{} cannot be negative", name));
      }
      (*arc_i64)
        .try_into()
        .map_err(|_| format!("{} too large", name))
    } else if let Ok(arc_u32) = val.clone().downcast::<u32>() {
      (*arc_u32)
        .try_into()
        .map_err(|_| format!("{} too large", name))
    } else if let Ok(arc_u64) = val.clone().downcast::<u64>() {
      (*arc_u64)
        .try_into()
        .map_err(|_| format!("{} too large", name))
    } else {
      Err(format!(
        "Unsupported type for {}: {} (must be numeric)",
        name,
        std::any::type_name_of_val(&**val)
      ))
    }
  };

  let target_length = get_usize(length, "length")?;

  // Try to downcast padding character (default to space if not provided or empty)
  let padding_char = if let Ok(arc_pad_str) = padding.clone().downcast::<String>() {
    let pad_str = &*arc_pad_str;
    if pad_str.is_empty() {
      ' '
    } else {
      pad_str.chars().next().unwrap_or(' ')
    }
  } else if let Ok(arc_char) = padding.clone().downcast::<char>() {
    *arc_char
  } else {
    ' ' // Default to space
  };

  // Try to downcast side (default to "right" if not provided)
  let side_str = if let Ok(arc_side) = side.clone().downcast::<String>() {
    arc_side.to_lowercase()
  } else {
    "right".to_string() // Default to right padding
  };

  let current_len = arc_str.chars().count();
  if current_len >= target_length {
    // String is already long enough, return as-is
    return Ok(arc_str.clone());
  }

  let pad_count = target_length - current_len;
  let pad_str: String = std::iter::repeat_n(padding_char, pad_count).collect();

  let result = match side_str.as_str() {
    "left" => format!("{}{}", pad_str, arc_str),
    "right" => format!("{}{}", arc_str, pad_str),
    "center" => {
      let left_pad = pad_count / 2;
      let right_pad = pad_count - left_pad;
      let left_str: String = std::iter::repeat_n(padding_char, left_pad).collect();
      let right_str: String = std::iter::repeat_n(padding_char, right_pad).collect();
      format!("{}{}{}", left_str, arc_str, right_str)
    }
    _ => {
      return Err(format!(
        "Unsupported padding side: {} (must be 'left', 'right', or 'center')",
        side_str
      ));
    }
  };

  Ok(Arc::new(result) as Arc<dyn Any + Send + Sync>)
}

/// Appends a suffix to a string.
///
/// This function attempts to downcast the string and suffix to their expected types
/// and performs concatenation (base + suffix). It supports:
/// - String + String: Direct concatenation
///
/// Returns the result as `Arc<dyn Any + Send + Sync>` or an error string.
pub fn append_suffix(
  base: &Arc<dyn Any + Send + Sync>,
  suffix: &Arc<dyn Any + Send + Sync>,
) -> Result<Arc<dyn Any + Send + Sync>, String> {
  // Try String + String
  if let (Ok(arc_str1), Ok(arc_str2)) = (
    base.clone().downcast::<String>(),
    suffix.clone().downcast::<String>(),
  ) {
    let result = format!("{}{}", *arc_str1, *arc_str2);
    return Ok(Arc::new(result) as Arc<dyn Any + Send + Sync>);
  }

  Err(format!(
    "Unsupported types for string append: {} + {} (both inputs must be String)",
    std::any::type_name_of_val(&**base),
    std::any::type_name_of_val(&**suffix)
  ))
}

/// Capitalizes the first character of a string.
///
/// This function attempts to downcast the string to its expected type
/// and capitalizes the first character while leaving the rest unchanged. It supports:
/// - Capitalization of ASCII and Unicode characters
/// - Empty strings remain unchanged
///
/// Returns the result as `Arc<dyn Any + Send + Sync>` or an error string.
pub fn capitalize_string(
  v: &Arc<dyn Any + Send + Sync>,
) -> Result<Arc<dyn Any + Send + Sync>, String> {
  // Try to downcast string
  let arc_str = v.clone().downcast::<String>().map_err(|_| {
    format!(
      "Unsupported type for string capitalize input: {} (input must be String)",
      std::any::type_name_of_val(&**v)
    )
  })?;

  // Capitalize the first character
  let mut chars = arc_str.chars();
  let result = if let Some(first_char) = chars.next() {
    first_char.to_uppercase().collect::<String>() + chars.as_str()
  } else {
    // Empty string, return as-is
    (*arc_str).clone()
  };

  Ok(Arc::new(result) as Arc<dyn Any + Send + Sync>)
}

/// Converts a string to lowercase.
///
/// This function attempts to downcast the string to its expected type
/// and converts all characters to lowercase. It supports:
/// - ASCII and Unicode character lowercase conversion
/// - Empty strings remain unchanged
///
/// Returns the result as `Arc<dyn Any + Send + Sync>` or an error string.
pub fn lowercase_string(
  v: &Arc<dyn Any + Send + Sync>,
) -> Result<Arc<dyn Any + Send + Sync>, String> {
  // Try to downcast string
  let arc_str = v.clone().downcast::<String>().map_err(|_| {
    format!(
      "Unsupported type for string lowercase input: {} (input must be String)",
      std::any::type_name_of_val(&**v)
    )
  })?;

  // Convert to lowercase
  let result = arc_str.to_lowercase();
  Ok(Arc::new(result) as Arc<dyn Any + Send + Sync>)
}

/// Converts a string to uppercase.
///
/// This function attempts to downcast the string to its expected type
/// and converts all characters to uppercase. It supports:
/// - ASCII and Unicode character uppercase conversion
/// - Empty strings remain unchanged
///
/// Returns the result as `Arc<dyn Any + Send + Sync>` or an error string.
pub fn uppercase_string(
  v: &Arc<dyn Any + Send + Sync>,
) -> Result<Arc<dyn Any + Send + Sync>, String> {
  // Try to downcast string
  let arc_str = v.clone().downcast::<String>().map_err(|_| {
    format!(
      "Unsupported type for string uppercase input: {} (input must be String)",
      std::any::type_name_of_val(&**v)
    )
  })?;

  // Convert to uppercase
  let result = arc_str.to_uppercase();
  Ok(Arc::new(result) as Arc<dyn Any + Send + Sync>)
}

/// Gets the character at a specific index in a string.
///
/// This function attempts to downcast the string and index to their expected types
/// and returns the character at the specified index. It supports:
/// - UTF-8 aware character indexing (not byte indexing)
/// - Bounds checking
///
/// Returns the result as `Arc<dyn Any + Send + Sync>` or an error string.
pub fn char_at(
  string_value: &Arc<dyn Any + Send + Sync>,
  index_value: &Arc<dyn Any + Send + Sync>,
) -> Result<Arc<dyn Any + Send + Sync>, String> {
  // Try to downcast string
  let arc_str = string_value.clone().downcast::<String>().map_err(|_| {
    format!(
      "Unsupported type for string char_at input: {} (input must be String)",
      std::any::type_name_of_val(&**string_value)
    )
  })?;

  // Try to downcast index to various numeric types
  let index = if let Ok(idx) = index_value.clone().downcast::<usize>() {
    *idx
  } else if let Ok(idx) = index_value.clone().downcast::<u32>() {
    *idx as usize
  } else if let Ok(idx) = index_value.clone().downcast::<u64>() {
    *idx as usize
  } else if let Ok(idx) = index_value.clone().downcast::<i32>() {
    if *idx < 0 {
      return Err("Index cannot be negative".to_string());
    }
    *idx as usize
  } else if let Ok(idx) = index_value.clone().downcast::<i64>() {
    if *idx < 0 {
      return Err("Index cannot be negative".to_string());
    }
    *idx as usize
  } else {
    return Err(format!(
      "Unsupported type for char_at index: {} (index must be a non-negative integer)",
      std::any::type_name_of_val(&**index_value)
    ));
  };

  // Get the character at the index (UTF-8 aware)
  let chars: Vec<char> = arc_str.chars().collect();
  if index >= chars.len() {
    return Err(format!(
      "Index {} is out of bounds for string of length {} (character count)",
      index,
      chars.len()
    ));
  }

  let result = chars[index].to_string();
  Ok(Arc::new(result) as Arc<dyn Any + Send + Sync>)
}

/// Prepends a prefix to a string.
///
/// This function attempts to downcast the prefix and base string to their expected types
/// and performs concatenation (prefix + base). It supports:
/// - String + String: Direct concatenation (prefix + base)
///
/// Returns the result as `Arc<dyn Any + Send + Sync>` or an error string.
pub fn prepend_prefix(
  prefix: &Arc<dyn Any + Send + Sync>,
  base: &Arc<dyn Any + Send + Sync>,
) -> Result<Arc<dyn Any + Send + Sync>, String> {
  // Try String + String
  if let (Ok(arc_prefix), Ok(arc_base)) = (
    prefix.clone().downcast::<String>(),
    base.clone().downcast::<String>(),
  ) {
    let result = format!("{}{}", *arc_prefix, *arc_base);
    return Ok(Arc::new(result) as Arc<dyn Any + Send + Sync>);
  }

  Err(format!(
    "Unsupported types for string prepend: {} + {} (both inputs must be String)",
    std::any::type_name_of_val(&**prefix),
    std::any::type_name_of_val(&**base)
  ))
}

/// Formats a string template with a value using Rust's format! macro.
///
/// This function attempts to downcast the template and value to their expected types
/// and performs string formatting. It supports:
/// - Single placeholder substitution: "{}" in template replaced with value
/// - Automatic string conversion for values
/// - Standard Rust formatting syntax
///
/// Returns the result as `Arc<dyn Any + Send + Sync>` or an error string.
pub fn format_string(
  template: &Arc<dyn Any + Send + Sync>,
  value: &Arc<dyn Any + Send + Sync>,
) -> Result<Arc<dyn Any + Send + Sync>, String> {
  // Try to downcast template
  let arc_template = template.clone().downcast::<String>().map_err(|_| {
    format!(
      "Unsupported type for template: {} (template must be String)",
      std::any::type_name_of_val(&**template)
    )
  })?;

  // Convert value to string for formatting
  let value_str = if let Ok(arc_str) = value.clone().downcast::<String>() {
    (*arc_str).clone()
  } else if let Ok(arc_i32) = value.clone().downcast::<i32>() {
    arc_i32.to_string()
  } else if let Ok(arc_i64) = value.clone().downcast::<i64>() {
    arc_i64.to_string()
  } else if let Ok(arc_u32) = value.clone().downcast::<u32>() {
    arc_u32.to_string()
  } else if let Ok(arc_u64) = value.clone().downcast::<u64>() {
    arc_u64.to_string()
  } else if let Ok(arc_f64) = value.clone().downcast::<f64>() {
    arc_f64.to_string()
  } else if let Ok(arc_bool) = value.clone().downcast::<bool>() {
    arc_bool.to_string()
  } else {
    // Fallback: use Debug representation
    format!("{:?}", value)
  };

  // Perform formatting
  let result = arc_template.replace("{}", &value_str);
  Ok(Arc::new(result) as Arc<dyn Any + Send + Sync>)
}

/// Finds the index of a substring within a string.
///
/// This function attempts to downcast the string and substring to their
/// expected types and performs index finding. It supports:
/// - Case-sensitive substring search
/// - Returns index as i64, -1 if not found
///
/// Returns the result as `Arc<dyn Any + Send + Sync>` (i64) or an error string.
pub fn string_index_of(
  v: &Arc<dyn Any + Send + Sync>,
  substring: &Arc<dyn Any + Send + Sync>,
) -> Result<Arc<dyn Any + Send + Sync>, String> {
  // Try to downcast string
  let arc_str = v.clone().downcast::<String>().map_err(|_| {
    format!(
      "Unsupported type for string index_of input: {} (input must be String)",
      std::any::type_name_of_val(&**v)
    )
  })?;

  // Try to downcast substring
  let arc_substring = substring.clone().downcast::<String>().map_err(|_| {
    format!(
      "Unsupported type for substring: {} (substring must be String)",
      std::any::type_name_of_val(&**substring)
    )
  })?;

  // Find the index (case-sensitive)
  let index = arc_str
    .find(&*arc_substring)
    .map(|i| i as i64)
    .unwrap_or(-1);
  Ok(Arc::new(index) as Arc<dyn Any + Send + Sync>)
}

/// Finds the last index of a substring within a string.
///
/// This function attempts to downcast the string and substring to their
/// expected types and performs last index finding. It supports:
/// - Case-sensitive substring search
/// - Returns last index as i64, -1 if not found
///
/// Returns the result as `Arc<dyn Any + Send + Sync>` (i64) or an error string.
pub fn string_last_index_of(
  v: &Arc<dyn Any + Send + Sync>,
  substring: &Arc<dyn Any + Send + Sync>,
) -> Result<Arc<dyn Any + Send + Sync>, String> {
  // Try to downcast string
  let arc_str = v.clone().downcast::<String>().map_err(|_| {
    format!(
      "Unsupported type for string last_index_of input: {} (input must be String)",
      std::any::type_name_of_val(&**v)
    )
  })?;

  // Try to downcast substring
  let arc_substring = substring.clone().downcast::<String>().map_err(|_| {
    format!(
      "Unsupported type for substring: {} (substring must be String)",
      std::any::type_name_of_val(&**substring)
    )
  })?;

  // Find the last index (case-sensitive)
  let index = arc_str
    .rfind(&*arc_substring)
    .map(|i| i as i64)
    .unwrap_or(-1);
  Ok(Arc::new(index) as Arc<dyn Any + Send + Sync>)
}

/// Reverses the character order of a string.
///
/// This function attempts to downcast the string to its expected type
/// and performs character reversal. It supports:
/// - Reversing the character order of a string
///
/// Returns the result as `Arc<dyn Any + Send + Sync>` or an error string.
pub fn string_reverse(
  v: &Arc<dyn Any + Send + Sync>,
) -> Result<Arc<dyn Any + Send + Sync>, String> {
  // Try to downcast string
  let arc_str = v.clone().downcast::<String>().map_err(|_| {
    format!(
      "Unsupported type for string reverse input: {} (input must be String)",
      std::any::type_name_of_val(&**v)
    )
  })?;

  // Reverse the string by collecting chars in reverse order
  let result: String = arc_str.chars().rev().collect();
  Ok(Arc::new(result) as Arc<dyn Any + Send + Sync>)
}