lling-llang 0.1.0

WFST framework for text normalization and grammar correction
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
//! String semiring for label accumulation in WFSTs.
//!
//! The string semiring operates on strings with:
//! - **⊕ = lcp/lcs**: Longest common prefix (left) or suffix (right)
//! - **⊗ = ·**: String concatenation
//! - **0̄ = ∞**: Infinite string (identity for lcp/lcs)
//! - **1̄ = ε**: Empty string (identity for concatenation)
//!
//! # Variants
//!
//! - [`LeftStringWeight`]: Uses longest common prefix (left-distributive)
//! - [`RightStringWeight`]: Uses longest common suffix (right-distributive)
//!
//! # Not a True Semiring
//!
//! String semirings are only **weakly left/right distributive**, not fully
//! distributive. For example, with LeftStringWeight:
//!
//! - Left-distributive: `a ⊗ (b ⊕ c) = (a ⊗ b) ⊕ (a ⊗ c)` ✓
//! - Right-distributive: `(a ⊕ b) ⊗ c ≠ (a ⊗ c) ⊕ (b ⊗ c)` ✗
//!
//! This is acceptable for many WFST algorithms that only require one-sided
//! distributivity (e.g., determinization uses left-distributivity).
//!
//! # Why Not `Semiring` Trait?
//!
//! String weights contain `Vec<u8>` which cannot be `Copy`. The `Semiring` trait
//! requires `Copy` for efficiency in numeric weights. String weights provide the
//! same API through inherent methods instead of trait implementations.
//!
//! # Use Cases
//!
//! - Computing common label prefixes/suffixes among paths
//! - Label disambiguation in determinization
//! - Output label accumulation in composition
//!
//! # Example
//!
//! ```
//! use lling_llang::semiring::LeftStringWeight;
//!
//! let abc = LeftStringWeight::from_str("abc");
//! let abx = LeftStringWeight::from_str("abx");
//!
//! // Longest common prefix: "ab"
//! let lcp = abc.plus(&abx);
//! assert_eq!(lcp.as_str(), Some("ab"));
//!
//! // Concatenation: "abcabx"
//! let concat = abc.times(&abx);
//! assert_eq!(concat.as_str(), Some("abcabx"));
//! ```

/// Left string weight using longest common prefix.
///
/// Uses `Option<Vec<u8>>` where:
/// - `None` = ∞ (infinite string, additive identity)
/// - `Some(vec![])` = ε (empty string, multiplicative identity)
///
/// This is left-distributive: `a ⊗ (b ⊕ c) = (a ⊗ b) ⊕ (a ⊗ c)`
///
/// # Note
///
/// This type does not implement the [`Semiring`](super::Semiring) trait because
/// it contains `Vec<u8>` which cannot be `Copy`. It provides semiring-like
/// operations through inherent methods instead.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct LeftStringWeight(Option<Vec<u8>>);

impl LeftStringWeight {
    /// Create a new string weight from bytes.
    #[inline]
    pub fn new(bytes: impl Into<Vec<u8>>) -> Self {
        LeftStringWeight(Some(bytes.into()))
    }

    /// Create from a string slice.
    #[inline]
    pub fn from_str(s: &str) -> Self {
        LeftStringWeight(Some(s.as_bytes().to_vec()))
    }

    /// Create the infinite string (additive identity, zero).
    #[inline]
    pub fn infinity() -> Self {
        LeftStringWeight(None)
    }

    /// Additive identity: infinite string.
    #[inline]
    pub fn zero() -> Self {
        Self::infinity()
    }

    /// Create the empty string (multiplicative identity, one).
    #[inline]
    pub fn epsilon() -> Self {
        LeftStringWeight(Some(Vec::new()))
    }

    /// Multiplicative identity: empty string.
    #[inline]
    pub fn one() -> Self {
        Self::epsilon()
    }

    /// Check if this is the infinite string (additive identity).
    #[inline]
    pub fn is_infinite(&self) -> bool {
        self.0.is_none()
    }

    /// Check if this is the zero element (infinite string).
    #[inline]
    pub fn is_zero(&self) -> bool {
        self.is_infinite()
    }

    /// Check if this is the empty string (multiplicative identity).
    #[inline]
    pub fn is_empty(&self) -> bool {
        matches!(&self.0, Some(v) if v.is_empty())
    }

    /// Check if this is the one element (empty string).
    #[inline]
    pub fn is_one(&self) -> bool {
        self.is_empty()
    }

    /// Get the bytes if not infinite.
    #[inline]
    pub fn as_bytes(&self) -> Option<&[u8]> {
        self.0.as_deref()
    }

    /// Get as a UTF-8 string if valid.
    pub fn as_str(&self) -> Option<&str> {
        self.0
            .as_ref()
            .and_then(|bytes| std::str::from_utf8(bytes).ok())
    }

    /// Get the length of the string (None for infinity).
    #[inline]
    pub fn len(&self) -> Option<usize> {
        self.0.as_ref().map(|v| v.len())
    }

    /// Compute the longest common prefix of two byte slices.
    pub fn longest_common_prefix(a: &[u8], b: &[u8]) -> Vec<u8> {
        let mut prefix = Vec::with_capacity(a.len().min(b.len()));
        for (&x, &y) in a.iter().zip(b.iter()) {
            if x == y {
                prefix.push(x);
            } else {
                break;
            }
        }
        prefix
    }

    /// Addition: longest common prefix.
    pub fn plus(&self, other: &Self) -> Self {
        match (&self.0, &other.0) {
            (None, _) => other.clone(),
            (_, None) => self.clone(),
            (Some(a), Some(b)) => LeftStringWeight(Some(Self::longest_common_prefix(a, b))),
        }
    }

    /// Multiplication: concatenation.
    pub fn times(&self, other: &Self) -> Self {
        match (&self.0, &other.0) {
            (None, _) | (_, None) => LeftStringWeight::infinity(),
            (Some(a), Some(b)) => {
                let mut result = a.clone();
                result.extend_from_slice(b);
                LeftStringWeight(Some(result))
            }
        }
    }

    /// Kleene closure for string semiring.
    ///
    /// For string semirings, star always converges to epsilon because:
    /// - ε* = ε (trivially)
    /// - For non-empty s: lcp(ε, s, ss, sss, ...) = ε
    pub fn star(&self) -> Self {
        // star(s) = ε for all s
        Self::one()
    }

    /// Check approximate equality (exact for strings).
    pub fn approx_eq(&self, other: &Self, _epsilon: f64) -> bool {
        self == other
    }

    /// Natural ordering: shorter strings are "better" (more specific).
    pub fn natural_less(&self, other: &Self) -> Option<bool> {
        match (&self.0, &other.0) {
            (None, None) => Some(false),
            (None, Some(_)) => Some(false), // infinity is "worse"
            (Some(_), None) => Some(true),  // finite is "better" than infinity
            (Some(a), Some(b)) => Some(a.len() < b.len()),
        }
    }

    /// Convert to bytes for serialization.
    pub fn to_bytes(&self) -> Vec<u8> {
        match &self.0 {
            None => vec![0xFF], // Special marker for infinity
            Some(bytes) => {
                let mut result = vec![0x00]; // Marker for finite string
                result.extend(bytes);
                result
            }
        }
    }
}

impl Default for LeftStringWeight {
    /// Default is epsilon (empty string, multiplicative identity).
    #[inline]
    fn default() -> Self {
        Self::one()
    }
}

impl From<&str> for LeftStringWeight {
    fn from(s: &str) -> Self {
        LeftStringWeight::from_str(s)
    }
}

impl From<String> for LeftStringWeight {
    fn from(s: String) -> Self {
        LeftStringWeight(Some(s.into_bytes()))
    }
}

impl From<Vec<u8>> for LeftStringWeight {
    fn from(bytes: Vec<u8>) -> Self {
        LeftStringWeight(Some(bytes))
    }
}

impl std::ops::Add for LeftStringWeight {
    type Output = Self;

    fn add(self, other: Self) -> Self {
        self.plus(&other)
    }
}

impl std::ops::Add<&LeftStringWeight> for LeftStringWeight {
    type Output = Self;

    fn add(self, other: &Self) -> Self {
        self.plus(other)
    }
}

impl std::ops::Mul for LeftStringWeight {
    type Output = Self;

    fn mul(self, other: Self) -> Self {
        self.times(&other)
    }
}

impl std::ops::Mul<&LeftStringWeight> for LeftStringWeight {
    type Output = Self;

    fn mul(self, other: &Self) -> Self {
        self.times(other)
    }
}

/// Right string weight using longest common suffix.
///
/// Uses `Option<Vec<u8>>` where:
/// - `None` = ∞ (infinite string, additive identity)
/// - `Some(vec![])` = ε (empty string, multiplicative identity)
///
/// This is right-distributive: `(a ⊕ b) ⊗ c = (a ⊗ c) ⊕ (b ⊗ c)`
///
/// # Note
///
/// This type does not implement the [`Semiring`](super::Semiring) trait because
/// it contains `Vec<u8>` which cannot be `Copy`. It provides semiring-like
/// operations through inherent methods instead.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct RightStringWeight(Option<Vec<u8>>);

impl RightStringWeight {
    /// Create a new string weight from bytes.
    #[inline]
    pub fn new(bytes: impl Into<Vec<u8>>) -> Self {
        RightStringWeight(Some(bytes.into()))
    }

    /// Create from a string slice.
    #[inline]
    pub fn from_str(s: &str) -> Self {
        RightStringWeight(Some(s.as_bytes().to_vec()))
    }

    /// Create the infinite string (additive identity, zero).
    #[inline]
    pub fn infinity() -> Self {
        RightStringWeight(None)
    }

    /// Additive identity: infinite string.
    #[inline]
    pub fn zero() -> Self {
        Self::infinity()
    }

    /// Create the empty string (multiplicative identity, one).
    #[inline]
    pub fn epsilon() -> Self {
        RightStringWeight(Some(Vec::new()))
    }

    /// Multiplicative identity: empty string.
    #[inline]
    pub fn one() -> Self {
        Self::epsilon()
    }

    /// Check if this is the infinite string (additive identity).
    #[inline]
    pub fn is_infinite(&self) -> bool {
        self.0.is_none()
    }

    /// Check if this is the zero element (infinite string).
    #[inline]
    pub fn is_zero(&self) -> bool {
        self.is_infinite()
    }

    /// Check if this is the empty string (multiplicative identity).
    #[inline]
    pub fn is_empty(&self) -> bool {
        matches!(&self.0, Some(v) if v.is_empty())
    }

    /// Check if this is the one element (empty string).
    #[inline]
    pub fn is_one(&self) -> bool {
        self.is_empty()
    }

    /// Get the bytes if not infinite.
    #[inline]
    pub fn as_bytes(&self) -> Option<&[u8]> {
        self.0.as_deref()
    }

    /// Get as a UTF-8 string if valid.
    pub fn as_str(&self) -> Option<&str> {
        self.0
            .as_ref()
            .and_then(|bytes| std::str::from_utf8(bytes).ok())
    }

    /// Get the length of the string (None for infinity).
    #[inline]
    pub fn len(&self) -> Option<usize> {
        self.0.as_ref().map(|v| v.len())
    }

    /// Compute the longest common suffix of two byte slices.
    pub fn longest_common_suffix(a: &[u8], b: &[u8]) -> Vec<u8> {
        let mut suffix = Vec::with_capacity(a.len().min(b.len()));
        for (&x, &y) in a.iter().rev().zip(b.iter().rev()) {
            if x == y {
                suffix.push(x);
            } else {
                break;
            }
        }
        suffix.reverse();
        suffix
    }

    /// Addition: longest common suffix.
    pub fn plus(&self, other: &Self) -> Self {
        match (&self.0, &other.0) {
            (None, _) => other.clone(),
            (_, None) => self.clone(),
            (Some(a), Some(b)) => RightStringWeight(Some(Self::longest_common_suffix(a, b))),
        }
    }

    /// Multiplication: concatenation.
    pub fn times(&self, other: &Self) -> Self {
        match (&self.0, &other.0) {
            (None, _) | (_, None) => RightStringWeight::infinity(),
            (Some(a), Some(b)) => {
                let mut result = a.clone();
                result.extend_from_slice(b);
                RightStringWeight(Some(result))
            }
        }
    }

    /// Kleene closure converges to epsilon for all strings.
    pub fn star(&self) -> Self {
        Self::one()
    }

    /// Check approximate equality (exact for strings).
    pub fn approx_eq(&self, other: &Self, _epsilon: f64) -> bool {
        self == other
    }

    /// Natural ordering: shorter strings are "better".
    pub fn natural_less(&self, other: &Self) -> Option<bool> {
        match (&self.0, &other.0) {
            (None, None) => Some(false),
            (None, Some(_)) => Some(false),
            (Some(_), None) => Some(true),
            (Some(a), Some(b)) => Some(a.len() < b.len()),
        }
    }

    /// Convert to bytes for serialization.
    pub fn to_bytes(&self) -> Vec<u8> {
        match &self.0 {
            None => vec![0xFF],
            Some(bytes) => {
                let mut result = vec![0x00];
                result.extend(bytes);
                result
            }
        }
    }
}

impl Default for RightStringWeight {
    /// Default is epsilon (empty string, multiplicative identity).
    #[inline]
    fn default() -> Self {
        Self::one()
    }
}

impl From<&str> for RightStringWeight {
    fn from(s: &str) -> Self {
        RightStringWeight::from_str(s)
    }
}

impl From<String> for RightStringWeight {
    fn from(s: String) -> Self {
        RightStringWeight(Some(s.into_bytes()))
    }
}

impl From<Vec<u8>> for RightStringWeight {
    fn from(bytes: Vec<u8>) -> Self {
        RightStringWeight(Some(bytes))
    }
}

impl std::ops::Add for RightStringWeight {
    type Output = Self;

    fn add(self, other: Self) -> Self {
        self.plus(&other)
    }
}

impl std::ops::Add<&RightStringWeight> for RightStringWeight {
    type Output = Self;

    fn add(self, other: &Self) -> Self {
        self.plus(other)
    }
}

impl std::ops::Mul for RightStringWeight {
    type Output = Self;

    fn mul(self, other: Self) -> Self {
        self.times(&other)
    }
}

impl std::ops::Mul<&RightStringWeight> for RightStringWeight {
    type Output = Self;

    fn mul(self, other: &Self) -> Self {
        self.times(other)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // ========== LeftStringWeight Tests ==========

    #[test]
    fn test_left_basic_operations() {
        let abc = LeftStringWeight::from_str("abc");
        let abx = LeftStringWeight::from_str("abx");
        let def = LeftStringWeight::from_str("def");

        // Longest common prefix
        let lcp = abc.plus(&abx);
        assert_eq!(lcp.as_str(), Some("ab"));

        // No common prefix
        let lcp2 = abc.plus(&def);
        assert_eq!(lcp2.as_str(), Some(""));

        // Concatenation
        let concat = abc.times(&def);
        assert_eq!(concat.as_str(), Some("abcdef"));
    }

    #[test]
    fn test_left_identities() {
        let abc = LeftStringWeight::from_str("abc");

        // Zero is additive identity
        let sum = abc.plus(&LeftStringWeight::zero());
        assert_eq!(sum, abc);

        let sum2 = LeftStringWeight::zero().plus(&abc);
        assert_eq!(sum2, abc);

        // One is multiplicative identity
        let prod = abc.times(&LeftStringWeight::one());
        assert_eq!(prod, abc);

        let prod2 = LeftStringWeight::one().times(&abc);
        assert_eq!(prod2, abc);
    }

    #[test]
    fn test_left_annihilation() {
        let abc = LeftStringWeight::from_str("abc");

        // Zero annihilates
        let prod = abc.times(&LeftStringWeight::zero());
        assert!(prod.is_zero());

        let prod2 = LeftStringWeight::zero().times(&abc);
        assert!(prod2.is_zero());
    }

    #[test]
    fn test_left_commutativity() {
        let abc = LeftStringWeight::from_str("abc");
        let abx = LeftStringWeight::from_str("abx");

        // Addition is commutative
        assert_eq!(abc.plus(&abx), abx.plus(&abc));
    }

    #[test]
    fn test_left_associativity() {
        let ab = LeftStringWeight::from_str("ab");
        let abc = LeftStringWeight::from_str("abc");
        let abcd = LeftStringWeight::from_str("abcd");

        // Additive associativity
        let left = ab.plus(&abc).plus(&abcd);
        let right = ab.plus(&abc.plus(&abcd));
        assert_eq!(left, right);

        // Multiplicative associativity
        let a = LeftStringWeight::from_str("a");
        let b = LeftStringWeight::from_str("b");
        let c = LeftStringWeight::from_str("c");
        let left = a.times(&b).times(&c);
        let right = a.times(&b.times(&c));
        assert_eq!(left, right);
        assert_eq!(left.as_str(), Some("abc"));
    }

    #[test]
    fn test_left_distributivity() {
        let a = LeftStringWeight::from_str("x");
        let b = LeftStringWeight::from_str("ab");
        let c = LeftStringWeight::from_str("ac");

        // Left distributivity: a * (b + c) = (a * b) + (a * c)
        let left = a.times(&b.plus(&c));
        let right = a.times(&b).plus(&a.times(&c));
        assert_eq!(left, right);
        // b + c = lcp("ab", "ac") = "a"
        // a * (b + c) = "x" * "a" = "xa"
        // a * b = "xab", a * c = "xac"
        // (a * b) + (a * c) = lcp("xab", "xac") = "xa"
    }

    #[test]
    fn test_left_star() {
        let abc = LeftStringWeight::from_str("abc");
        let eps = LeftStringWeight::epsilon();

        // star(ε) = ε
        assert_eq!(eps.star(), LeftStringWeight::one());

        // star(s) = ε for non-empty s
        assert_eq!(abc.star(), LeftStringWeight::one());
    }

    // ========== RightStringWeight Tests ==========

    #[test]
    fn test_right_basic_operations() {
        let abc = RightStringWeight::from_str("abc");
        let xbc = RightStringWeight::from_str("xbc");
        let def = RightStringWeight::from_str("def");

        // Longest common suffix
        let lcs = abc.plus(&xbc);
        assert_eq!(lcs.as_str(), Some("bc"));

        // No common suffix
        let lcs2 = abc.plus(&def);
        assert_eq!(lcs2.as_str(), Some(""));

        // Concatenation
        let concat = abc.times(&def);
        assert_eq!(concat.as_str(), Some("abcdef"));
    }

    #[test]
    fn test_right_identities() {
        let abc = RightStringWeight::from_str("abc");

        // Zero is additive identity
        let sum = abc.plus(&RightStringWeight::zero());
        assert_eq!(sum, abc);

        // One is multiplicative identity
        let prod = abc.times(&RightStringWeight::one());
        assert_eq!(prod, abc);
    }

    #[test]
    fn test_right_distributivity() {
        let a = RightStringWeight::from_str("ab");
        let b = RightStringWeight::from_str("cb");
        let c = RightStringWeight::from_str("x");

        // Right distributivity: (a + b) * c = (a * c) + (b * c)
        let left = a.plus(&b).times(&c);
        let right = a.times(&c).plus(&b.times(&c));
        assert_eq!(left, right);
        // a + b = lcs("ab", "cb") = "b"
        // (a + b) * c = "b" * "x" = "bx"
        // a * c = "abx", b * c = "cbx"
        // (a * c) + (b * c) = lcs("abx", "cbx") = "bx"
    }

    #[test]
    fn test_right_star() {
        let abc = RightStringWeight::from_str("abc");

        // star(s) = ε for any s
        assert_eq!(abc.star(), RightStringWeight::one());
    }

    // ========== Shared Property Tests ==========

    #[test]
    fn test_empty_string_lcp() {
        let empty = LeftStringWeight::epsilon();
        let abc = LeftStringWeight::from_str("abc");

        // lcp(ε, s) = ε
        assert_eq!(empty.plus(&abc), LeftStringWeight::epsilon());
    }

    #[test]
    fn test_empty_string_lcs() {
        let empty = RightStringWeight::epsilon();
        let abc = RightStringWeight::from_str("abc");

        // lcs(ε, s) = ε
        assert_eq!(empty.plus(&abc), RightStringWeight::epsilon());
    }

    #[test]
    fn test_bytes_conversion() {
        let bytes = vec![0x48, 0x65, 0x6c, 0x6c, 0x6f]; // "Hello"
        let left = LeftStringWeight::new(bytes.clone());
        let right = RightStringWeight::new(bytes.clone());

        assert_eq!(left.as_bytes(), Some(bytes.as_slice()));
        assert_eq!(left.as_str(), Some("Hello"));

        assert_eq!(right.as_bytes(), Some(bytes.as_slice()));
        assert_eq!(right.as_str(), Some("Hello"));
    }

    #[test]
    fn test_non_utf8_bytes() {
        let bytes = vec![0xFF, 0xFE]; // Invalid UTF-8
        let left = LeftStringWeight::new(bytes.clone());

        assert_eq!(left.as_bytes(), Some(bytes.as_slice()));
        assert_eq!(left.as_str(), None); // Not valid UTF-8
    }

    #[test]
    fn test_longest_common_prefix_function() {
        assert_eq!(
            LeftStringWeight::longest_common_prefix(b"abc", b"abx"),
            b"ab".to_vec()
        );
        assert_eq!(
            LeftStringWeight::longest_common_prefix(b"abc", b"abc"),
            b"abc".to_vec()
        );
        assert_eq!(
            LeftStringWeight::longest_common_prefix(b"abc", b"xyz"),
            b"".to_vec()
        );
        assert_eq!(
            LeftStringWeight::longest_common_prefix(b"", b"abc"),
            b"".to_vec()
        );
    }

    #[test]
    fn test_longest_common_suffix_function() {
        assert_eq!(
            RightStringWeight::longest_common_suffix(b"abc", b"xbc"),
            b"bc".to_vec()
        );
        assert_eq!(
            RightStringWeight::longest_common_suffix(b"abc", b"abc"),
            b"abc".to_vec()
        );
        assert_eq!(
            RightStringWeight::longest_common_suffix(b"abc", b"xyz"),
            b"".to_vec()
        );
        assert_eq!(
            RightStringWeight::longest_common_suffix(b"", b"abc"),
            b"".to_vec()
        );
    }

    #[test]
    fn test_operator_overloading() {
        let abc = LeftStringWeight::from_str("abc");
        let abx = LeftStringWeight::from_str("abx");
        let def = LeftStringWeight::from_str("def");

        // Addition via +
        let lcp = abc.clone() + abx.clone();
        assert_eq!(lcp.as_str(), Some("ab"));

        // Multiplication via *
        let concat = abc.clone() * def.clone();
        assert_eq!(concat.as_str(), Some("abcdef"));

        // With references
        let lcp_ref = abc.clone() + &abx;
        assert_eq!(lcp_ref.as_str(), Some("ab"));

        let concat_ref = abc.clone() * &def;
        assert_eq!(concat_ref.as_str(), Some("abcdef"));
    }
}