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
//! String semiring implementation.
//!
//! This module provides the string semiring $`(\Sigma^*, \mathrm{lcp}, \cdot, \bot, \varepsilon)`$
//! where addition computes the longest common prefix (LCP) and multiplication
//! performs string concatenation.
//!
//! # Mathematical Definition
//!
//! | Operation | Definition |
//! |-----------|------------|
//! | $`a \oplus b`$ | $`\mathrm{lcp}(a, b)`$ (longest common prefix) |
//! | $`a \otimes b`$ | $`a \cdot b`$ (concatenation) |
//! | $`\bar{0}`$ | $`\bot`$ (special marker) |
//! | $`\bar{1}`$ | $`\varepsilon`$ (empty string) |
//!
//! # References
//!
//! - Mohri, M. (2002). Semiring frameworks and algorithms for shortest-distance problems.
//! *Journal of Automata, Languages and Combinatorics*, 7(3), 321-350.
//!
//! - Allauzen, C., & Mohri, M. (2003). Efficient algorithms for testing the twins property.
//! *Journal of Automata, Languages and Combinatorics*, 8(2), 117-144.
use *;
use fmt;
use ;
use ;
/// String semiring for sequence analysis and common subsequence computation.
///
/// The String semiring provides a mathematical framework for string operations
/// where addition computes the longest common prefix (LCP) and multiplication
/// performs string concatenation. This semiring is essential for pattern matching,
/// sequence alignment, string processing, and automata-based text analysis.
///
/// # Mathematical Definition
///
/// | Operation | Definition |
/// |-----------|------------|
/// | $`a \oplus b`$ | $`\mathrm{lcp}(a, b)`$ (longest common prefix) |
/// | $`a \otimes b`$ | $`a \cdot b`$ (concatenation) |
/// | $`\bar{0}`$ | $`\bot`$ (special marker) |
/// | $`\bar{1}`$ | $`\varepsilon`$ (empty string) |
///
/// # Algebraic Properties
///
/// - **Not Commutative:** $`a \otimes b \neq b \otimes a`$ in general
/// - **Idempotent:** $`a \oplus a = a`$
/// - **Not Path:** $`a \oplus b \notin \{a, b\}`$ in general
/// - **Left/Right Semiring:** Satisfies both distributivity laws
///
/// # Mathematical Semantics
///
/// - **Value Range:** Finite sequences over an alphabet $`\Sigma^*`$ (plus special zero element)
/// - **Addition ($`\oplus`$):** $`\mathrm{lcp}(a, b)`$ - longest common prefix of two strings
/// - **Multiplication ($`\otimes`$):** $`a \cdot b`$ - string concatenation
/// - **Zero ($`\bar{0}`$):** Special marker (represented as `[0xFF]`) - impossible/rejected string
/// - **One ($`\bar{1}`$):** Empty string $`\varepsilon`$ - identity for concatenation
///
/// # Key Properties
///
/// - **Non-Commutative:** String concatenation is order-dependent ($`ab \neq ba`$)
/// - **Idempotent:** LCP operation is idempotent ($`\mathrm{lcp}(a, a) = a`$)
/// - **Left/Right Semiring:** Satisfies distributivity laws
/// - **Path Tracking:** Can track actual string sequences through FST paths
///
/// # Use Cases
///
/// ## String Pattern Analysis
/// ```rust
/// use arcweight::prelude::*;
///
/// // Find common prefix patterns
/// let pattern1 = StringWeight::from_string("programming");
/// let pattern2 = StringWeight::from_string("program");
/// let pattern3 = StringWeight::from_string("progress");
///
/// // Longest common prefix across alternatives
/// let common = pattern1.plus(&pattern2).plus(&pattern3);
/// assert_eq!(common.to_string().unwrap(), "progr");
/// ```
///
/// ## Sequence Concatenation
/// ```rust
/// use arcweight::prelude::*;
///
/// // Build sequences through concatenation
/// let prefix = StringWeight::from_string("pre");
/// let root = StringWeight::from_string("process");
/// let suffix = StringWeight::from_string("ing");
///
/// // Sequential combination
/// let compound = prefix.times(&root).times(&suffix);
/// assert_eq!(compound.to_string().unwrap(), "preprocessing");
/// ```
///
/// ## Automata-Based Text Processing
/// ```rust
/// use arcweight::prelude::*;
///
/// // Build weighted FST for text transformation
/// let mut fst = VectorFst::<StringWeight>::new();
/// let s0 = fst.add_state();
/// let s1 = fst.add_state();
/// let s2 = fst.add_state();
///
/// fst.set_start(s0);
/// fst.set_final(s2, StringWeight::one());
///
/// // Transform "cat" -> "cats"
/// fst.add_arc(s0, Arc::new(
/// 'c' as u32,
/// 'c' as u32,
/// StringWeight::from_string("c"),
/// s1
/// ));
///
/// fst.add_arc(s1, Arc::new(
/// 'a' as u32,
/// 'a' as u32,
/// StringWeight::from_string("a"),
/// s1
/// ));
///
/// // Add suffix transformation
/// fst.add_arc(s1, Arc::new(
/// 't' as u32,
/// 0, // epsilon output
/// StringWeight::from_string("ts"), // Plural transformation
/// s2
/// ));
/// ```
///
/// ## Morphological Analysis
/// ```rust
/// use arcweight::prelude::*;
///
/// // Decompose words into morphological components
/// let stem = StringWeight::from_string("walk");
/// let suffix1 = StringWeight::from_string("ing"); // Progressive
/// let suffix2 = StringWeight::from_string("ed"); // Past tense
///
/// // Generate inflected forms
/// let walking = stem.clone().times(&suffix1);
/// let walked = stem.times(&suffix2);
///
/// assert_eq!(walking.to_string().unwrap(), "walking");
/// assert_eq!(walked.to_string().unwrap(), "walked");
///
/// // Find common stem (using addition for LCP)
/// let common_stem = walking.plus(&walked);
/// assert_eq!(common_stem.to_string().unwrap(), "walk");
/// ```
///
/// ## Phonological Rule Application
/// ```rust
/// use arcweight::prelude::*;
///
/// // Model phonological processes
/// let base_form = StringWeight::from_string("cat");
/// let plural_rule = StringWeight::from_string("s");
/// let liaison_rule = StringWeight::from_string("z"); // Voicing in context
///
/// // Apply phonological rules
/// let surface_form = base_form.times(&plural_rule);
/// let phonetic_form = base_form.times(&liaison_rule);
///
/// // Find common phonetic base
/// let common_base = surface_form.plus(&phonetic_form);
/// assert_eq!(common_base.to_string().unwrap(), "cat");
/// ```
///
/// # Working with FSTs
///
/// ```rust
/// use arcweight::prelude::*;
///
/// let string1 = StringWeight::from_string("hello");
/// let string2 = StringWeight::from_string("help");
///
/// // Addition computes longest common prefix
/// let lcp = string1.clone() + string2.clone(); // "hel"
/// assert_eq!(lcp.to_string().unwrap(), "hel");
///
/// // Multiplication concatenates strings
/// let concat = string1 * string2; // "hellohelp"
/// assert_eq!(concat.to_string().unwrap(), "hellohelp");
///
/// // Identity elements
/// assert_eq!(StringWeight::zero().as_bytes(), &[0xFF]); // Special zero marker
/// assert_eq!(StringWeight::one().as_bytes(), &[]); // Empty string
/// ```
///
/// # Advanced Applications
///
/// ## Edit Distance with String Tracking
/// ```rust
/// use arcweight::prelude::*;
///
/// // Track actual edit operations as strings
/// let insertion = StringWeight::from_string("i:"); // Insert operation
/// let deletion = StringWeight::from_string("d:"); // Delete operation
/// let substitution = StringWeight::from_string("s:"); // Substitute operation
///
/// // Build edit sequence
/// let edit_sequence = insertion
/// .times(&substitution)
/// .times(&deletion);
///
/// assert_eq!(edit_sequence.to_string().unwrap(), "i:s:d:");
/// ```
///
/// ## Longest Common Subsequence
/// ```rust
/// use arcweight::prelude::*;
///
/// // Find common subsequences using LCP
/// let seq1 = StringWeight::from_string("ABCDGH");
/// let seq2 = StringWeight::from_string("AEDFHR");
/// let seq3 = StringWeight::from_string("ABXDGY");
///
/// // Common prefix across all sequences
/// let common = seq1.plus(&seq2).plus(&seq3);
/// assert_eq!(common.to_string().unwrap(), "A"); // Common starting character
/// ```
///
/// ## DNA/RNA Sequence Analysis
/// ```rust
/// use arcweight::prelude::*;
///
/// // Genetic sequence analysis
/// let dna1 = StringWeight::from_string("ATCGATCG");
/// let dna2 = StringWeight::from_string("ATCGTTCG");
/// let dna3 = StringWeight::from_string("ATCGAACG");
///
/// // Find conserved regions (common prefix)
/// let conserved = dna1.plus(&dna2).plus(&dna3);
/// assert_eq!(conserved.to_string().unwrap(), "ATCG");
///
/// // Model sequence concatenation (gene assembly)
/// let gene_segment1 = StringWeight::from_string("ATCG");
/// let gene_segment2 = StringWeight::from_string("GCTA");
/// let assembled_gene = gene_segment1.times(&gene_segment2);
/// assert_eq!(assembled_gene.to_string().unwrap(), "ATCGGCTA");
/// ```
///
/// ## Compiler and Parser Applications
/// ```rust
/// use arcweight::prelude::*;
///
/// // Track syntax patterns
/// let keyword = StringWeight::from_string("if");
/// let condition = StringWeight::from_string("(x > 0)");
/// let block = StringWeight::from_string(" { ... }");
///
/// // Build syntax tree representations
/// let conditional = keyword
/// .times(&condition)
/// .times(&block);
///
/// assert_eq!(conditional.to_string().unwrap(), "if(x > 0) { ... }");
/// ```
///
/// # Byte-Level Operations
///
/// ```rust
/// use arcweight::prelude::*;
///
/// // Work with arbitrary byte sequences
/// let bytes1 = StringWeight::from_bytes(vec![0x41, 0x42, 0x43]); // "ABC"
/// let bytes2 = StringWeight::from_bytes(vec![0x41, 0x42, 0x44]); // "ABD"
///
/// // LCP works on byte level
/// let common_bytes = bytes1.plus(&bytes2);
/// assert_eq!(common_bytes.as_bytes(), &[0x41, 0x42]); // "AB"
///
/// // Concatenation preserves byte sequences
/// let combined = bytes1.times(&bytes2);
/// assert_eq!(combined.as_bytes(), &[0x41, 0x42, 0x43, 0x41, 0x42, 0x44]);
/// ```
///
/// # Performance Characteristics
///
/// - **LCP Computation:** O(min(|a|, |b|)) where |a|, |b| are string lengths
/// - **Concatenation:** O(|a| + |b|) with memory allocation for result
/// - **Memory:** Linear in total string length plus Vec overhead
/// - **Comparison:** Lexicographic ordering, O(min(|a|, |b|)) average case
/// - **Storage:** UTF-8 compatible, supports arbitrary byte sequences
///
/// # UTF-8 and Encoding Considerations
///
/// ```rust
/// use arcweight::prelude::*;
///
/// // Unicode support through UTF-8
/// let unicode_str = StringWeight::from_string("Hello 世界");
/// assert!(unicode_str.to_string().is_ok());
///
/// // Handle potential encoding errors
/// let invalid_utf8 = StringWeight::from_bytes(vec![0xFF, 0xFE]);
/// assert!(invalid_utf8.to_string().is_err());
///
/// // Graceful fallback for display
/// println!("{}", invalid_utf8); // Shows byte representation
/// ```
///
/// # Integration with FST Algorithms
///
/// String weights provide unique capabilities in FST algorithms:
/// - **Shortest Path:** Finds paths with specific string properties
/// - **Composition:** Combines string transformations
/// - **Determinization:** Maintains string output while removing nondeterminism
/// - **String-to-String Translation:** Direct implementation of string transducers
///
/// # Mathematical Properties
///
/// The String semiring exhibits important properties:
/// - **Associative:** Both LCP and concatenation are associative
/// - **Non-Commutative:** Order matters in concatenation
/// - **Idempotent Addition:** `lcp(s, s) = s` for any string s
/// - **Identity Elements:** Empty string for multiplication, special marker for addition
/// - **Distributive:** Left and right distributivity hold
///
/// # See Also
///
/// - [Core Concepts - String Semiring](../../docs/core-concepts/semirings.md#string-semiring) for mathematical background
/// - [`TropicalWeight`](crate::semiring::TropicalWeight) for optimization-based string processing
/// - [`compose()`](crate::algorithms::compose) for string-to-string transduction
;