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
//! Constant (immutable) FST implementation optimized for read-only operations.
//!
//! This module provides [`ConstFst`], an immutable FST representation with contiguous
//! memory layout designed for optimal cache performance during traversal. The design
//! follows the OpenFst library's `ConstFst` implementation, providing significant
//! memory savings and access speed improvements over mutable representations.
//!
//! # Architecture
//!
//! `ConstFst` uses a two-array storage model where states contain offsets into a
//! global arc array, enabling cache-friendly sequential access:
//!
//! ```text
//! ConstFst<W>
//! +------------------+ ConstState<W> Arc Array
//! | states: Box<[]> | +---------------+ +----------+
//! | [0] ---------> |---> | final_weight | | Arc 0 |
//! | [1] ... | | arcs_start: 0 |---> | Arc 1 |
//! +------------------+ | num_arcs: 2 | | Arc 2 |
//! | arcs: Box<[]> ----+--> +---------------+ | ... |
//! | start: Option | +----------+
//! | properties |
//! +------------------+
//! ```
//!
//! # References
//!
//! - Allauzen, C., Riley, M., Schalkwyk, J., Skut, W., & Mohri, M. (2007).
//! OpenFst: A General and Efficient Weighted Finite-State Transducer Library.
//! In *Proc. CIAA 2007*, LNCS 4783, pp. 11-23. Springer.
use *;
use crate;
use crateFstProperties;
use crateSemiring;
use crateResult;
use slice;
/// Immutable FST implementation optimized for memory efficiency and fast read-only access
///
/// `ConstFst` is an immutable FST implementation that provides excellent performance for
/// read-only operations. Once constructed, it cannot be modified, but offers superior
/// memory efficiency and access speed compared to mutable alternatives. This makes it
/// ideal for production use cases where FSTs are built once and queried many times.
///
/// # Design Characteristics
///
/// - **Immutability:** Cannot be modified after construction - read-only operations only
/// - **Memory Layout:** Compact memory representation with excellent cache locality
/// - **Storage Format:** States and arcs stored in separate contiguous arrays
/// - **Random Access:** O(1) access to any state, O(1) arc range lookup per state
/// - **Space Efficiency:** Minimal memory overhead, optimal for large FSTs
///
/// # Performance Profile
///
/// | Operation | Time Complexity | Notes |
/// |-----------|----------------|-------|
/// | State Access | O(1) | Direct array indexing |
/// | Arc Range Access | O(1) | Precomputed arc ranges |
/// | Arc Iteration | O(k) | k = number of arcs, excellent cache locality |
/// | Memory Footprint | Minimal | ~20% less memory than VectorFst |
/// | Construction | O(V + E) | One-time cost from source FST |
///
/// # Memory Layout
///
/// ```text
/// ConstFst Memory Structure:
/// ┌─────────────────┐
/// │ States Array │ ← Box<[ConstState]>: metadata per state
/// │ [State 0] │ - final_weight: Option<W>
/// │ [State 1] │ - arcs_start: u32 (offset into arcs array)
/// │ [State ...] │ - num_arcs: u32 (count of arcs)
/// └─────────────────┘
/// ┌─────────────────┐
/// │ Arcs Array │ ← Box<[Arc<W>]>: all arcs in order
/// │ [State 0 arcs] │ Grouped by source state for cache locality
/// │ [State 1 arcs] │
/// │ [State ... arcs]│
/// └─────────────────┘
/// ```
///
/// # Memory Characteristics
///
/// - **State Storage:** Fixed-size array with 16 bytes per state + weight size
/// - **Arc Storage:** Contiguous array with ~32 bytes per arc
/// - **No Growth Overhead:** No unused capacity, exact memory allocation
/// - **Cache Friendly:** Sequential arc access has excellent spatial locality
/// - **Memory Savings:** 15-25% less memory than equivalent VectorFst
///
/// # Use Cases
///
/// ## Production FST Deployment
/// ```rust
/// use arcweight::prelude::*;
///
/// // Build FST during application startup or offline
/// fn build_and_optimize_fst() -> Result<ConstFst<TropicalWeight>> {
/// // Build mutable FST with complex construction logic
/// let mut builder = VectorFst::new();
///
/// // ... complex FST construction ...
/// let s0 = builder.add_state();
/// let s1 = builder.add_state();
/// builder.set_start(s0);
/// builder.add_arc(s0, Arc::new(1, 1, TropicalWeight::new(0.5), s1));
/// builder.set_final(s1, TropicalWeight::one());
///
/// // Convert to optimized read-only format
/// ConstFst::from_fst(&builder)
/// }
///
/// // Use optimized FST for all subsequent operations
/// let production_fst = build_and_optimize_fst()?;
///
/// // High-performance lookups
/// if let Some(start) = production_fst.start() {
/// for arc in production_fst.arcs(start) {
/// // Process arcs with optimal cache performance
/// println!("Arc: {} -> {} / {}", arc.ilabel, arc.olabel, arc.weight);
/// }
/// }
/// # Ok::<(), arcweight::Error>(())
/// ```
///
/// ## Large-Scale Language Models
/// ```rust
/// use arcweight::prelude::*;
///
/// // Convert large language model FST to const format
/// fn optimize_language_model(
/// mutable_lm: &VectorFst<LogWeight>
/// ) -> Result<ConstFst<LogWeight>> {
/// // Verify FST is complete and valid
/// println!("Optimizing LM with {} states, {} arcs",
/// mutable_lm.num_states(), mutable_lm.num_arcs_total());
///
/// // Convert to space-efficient immutable format
/// let const_lm = ConstFst::from_fst(mutable_lm)?;
///
/// // Memory usage comparison
/// println!("Memory optimization complete");
/// // Note: Actual memory usage would need external measurement
///
/// Ok(const_lm)
/// }
/// ```
///
/// ## Pronunciation Dictionary Deployment
/// ```rust
/// use arcweight::prelude::*;
///
/// // Deploy pronunciation dictionary for speech recognition
/// fn create_pronunciation_dict() -> Result<ConstFst<TropicalWeight>> {
/// let mut dict = VectorFst::new();
///
/// // Build dictionary structure (simplified example)
/// let root = dict.add_state();
/// dict.set_start(root);
///
/// // Add word: "hello" -> "heh low"
/// let mut current = root;
/// for &ch in b"hello" {
/// let next = dict.add_state();
/// dict.add_arc(current, Arc::new(
/// ch as u32, 0, // Input letter, epsilon output
/// TropicalWeight::one(), next
/// ));
/// current = next;
/// }
///
/// // Add phoneme outputs
/// let phonemes = [b'h', b'e', b'h', b' ', b'l', b'o', b'w'];
/// for &ph in &phonemes {
/// let next = dict.add_state();
/// dict.add_arc(current, Arc::new(
/// 0, ph as u32, // Epsilon input, phoneme output
/// TropicalWeight::one(), next
/// ));
/// current = next;
/// }
///
/// dict.set_final(current, TropicalWeight::one());
///
/// // Optimize for deployment
/// ConstFst::from_fst(&dict)
/// }
/// ```
///
/// ## Multi-FST Algorithm Input
/// ```rust
/// use arcweight::prelude::*;
///
/// // Prepare FSTs for composition operations
/// fn prepare_composition_inputs(
/// input_fst: &VectorFst<LogWeight>,
/// output_fst: &VectorFst<LogWeight>
/// ) -> Result<(ConstFst<LogWeight>, ConstFst<LogWeight>)> {
/// // Convert both FSTs to optimized format for composition
/// let const_input = ConstFst::from_fst(input_fst)?;
/// let const_output = ConstFst::from_fst(output_fst)?;
///
/// // Both FSTs now have optimal memory layout for composition algorithm
/// Ok((const_input, const_output))
/// }
/// ```
///
/// # Construction Patterns
///
/// ## From Existing FST
/// ```rust
/// use arcweight::prelude::*;
///
/// // Standard construction pattern
/// let mut builder = VectorFst::<TropicalWeight>::new();
/// // ... build FST structure ...
/// let optimized = ConstFst::from_fst(&builder)?;
/// # Ok::<(), arcweight::Error>(())
/// ```
///
/// ## Validation During Construction
/// ```rust
/// use arcweight::prelude::*;
///
/// fn safe_const_fst_creation(
/// source: &VectorFst<TropicalWeight>
/// ) -> Result<ConstFst<TropicalWeight>> {
/// // Validate source FST before conversion
/// if source.num_states() == 0 {
/// return Err(arcweight::Error::InvalidOperation("FST is empty".to_string()));
/// }
///
/// if source.start().is_none() {
/// return Err(arcweight::Error::InvalidOperation("FST has no start state".to_string()));
/// }
///
/// // Proceed with conversion
/// ConstFst::from_fst(source)
/// }
/// ```
///
/// # Performance Optimization Guidelines
///
/// ## When to Use ConstFst
/// - ✅ FST structure is finalized and won't change
/// - ✅ Memory efficiency is important
/// - ✅ Read-heavy workloads with many traversals
/// - ✅ Production deployment of large FSTs
/// - ✅ Multi-threaded read access patterns
///
/// ## When to Use VectorFst Instead
/// - ❌ FST needs to be modified after construction
/// - ❌ Incremental construction with unknown final size
/// - ❌ Debugging and development phases
/// - ❌ Single-use FSTs with minimal reuse
///
/// ## Memory Optimization Tips
/// 1. **Build Efficiently:** Construct in VectorFst, then convert
/// 2. **Batch Conversion:** Convert multiple FSTs together if memory allows
/// 3. **Size Validation:** Check memory requirements before conversion
/// 4. **Timing:** Convert during application startup, not critical paths
///
/// # Thread Safety
///
/// `ConstFst` is fully thread-safe for read operations:
/// - **Immutable Data:** No risk of data races during concurrent reads
/// - **Send + Sync:** Can be shared between threads safely
/// - **Arc-Compatible:** Wrap in `Arc<ConstFst<W>>` for shared ownership
/// - **Lock-Free:** No synchronization overhead for read operations
///
/// # Algorithm Integration
///
/// ConstFst works with all FST algorithms that accept the `Fst` trait:
/// - **Composition:** Excellent performance as composition input
/// - **Search:** Optimal for shortest path and traversal algorithms
/// - **Analysis:** Efficient for property computation and validation
/// - **Determinization:** Can serve as input to determinization algorithms
///
/// # Limitations
///
/// - **No Modification**: Cannot add/remove states or arcs after construction
/// - **Construction Cost**: $`O(V + E)`$ conversion time from source FST
/// - **Memory Spike**: Temporarily requires memory for both source and result
/// - **Clone Requirement**: Semiring weights must implement `Clone`
///
/// # References
///
/// - Allauzen, C., Riley, M., Schalkwyk, J., Skut, W., & Mohri, M. (2007).
/// OpenFst: A General and Efficient Weighted Finite-State Transducer Library.
/// In *Proc. CIAA 2007*, LNCS 4783, pp. 11-23. Springer.
///
/// - Mohri, M., Pereira, F., & Riley, M. (2000). The Design Principles of a
/// Weighted Finite-State Transducer Library. *Theoretical Computer Science*,
/// 231(1), 17-32.
///
/// # See Also
///
/// - [`VectorFst`] for mutable FST operations
/// - [`CacheFst`] for lazy evaluation patterns
/// - [`CompactFst`] for maximum memory compression
/// - [`CsrFst`] for SIMD-optimized access patterns
///
/// [`VectorFst`]: crate::fst::VectorFst
/// [`CacheFst`]: crate::fst::CacheFst
/// [`CompactFst`]: crate::fst::CompactFst
/// [`CsrFst`]: crate::fst::CsrFst
/// Compact state representation for ConstFst
///
/// Stores minimal state information with precomputed arc range offsets
/// for optimal memory usage and cache performance.
/// High-performance arc iterator for ConstFst with optimal cache locality
///
/// Provides iterator access to arcs from a specific state in a ConstFst.
/// The iterator works directly with a contiguous slice of arcs, providing
/// excellent memory access patterns and cache performance.
///
/// # Performance Characteristics
///
/// - **Memory Access:** Sequential access to contiguous arc array
/// - **Cache Locality:** Excellent - arcs are stored together
/// - **Allocation:** Zero allocations during iteration
/// - **Overhead:** Minimal iterator state (single slice iterator)
///
/// # Usage
///
/// This iterator is created automatically by `ConstFst::arcs()` and should
/// not be constructed directly. It implements the standard Iterator trait
/// for integration with Rust iteration patterns.
///
/// ```rust
/// use arcweight::prelude::*;
///
/// # fn example() -> Result<()> {
/// let mut builder = VectorFst::<TropicalWeight>::new();
/// let s0 = builder.add_state();
/// let s1 = builder.add_state();
/// builder.set_start(s0);
/// builder.add_arc(s0, Arc::new(1, 1, TropicalWeight::new(0.5), s1));
/// builder.add_arc(s0, Arc::new(2, 2, TropicalWeight::new(1.0), s1));
///
/// let const_fst = ConstFst::from_fst(&builder)?;
///
/// // High-performance iteration
/// for arc in const_fst.arcs(s0) {
/// println!("Label: {}, Weight: {}", arc.ilabel, arc.weight);
/// }
/// # Ok(())
/// # }
/// ```