zshrs 0.11.5

The first compiled Unix shell — bytecode VM, worker pool, AOP intercept, Rkyv caching
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
//! Linked list implementation for zshrs
//!
//! Direct port from zsh/Src/linklist.c
//!
//! Get an empty linked list header                                          // c:99
//! Insert a node in a linked list after a given node                       // c:129
//! Remove a node from a linked list                                        // c:247
//! Free a linked list                                                      // c:283
//! Count the number of nodes in a linked list                              // c:300
//!
//! Provides the canonical `LinkList<T>` used everywhere a C source line
//! takes a `LinkList`. Backed by `VecDeque<T>` so index-based access used
//! by `Src/subst.c` walks (`firstnode` / `nextnode` / `incnode` /
//! `getdata` / `setdata`) is O(1) — same big-O as C's pointer walk over
//! `linknode->next`.
//!
//! Mirrors `struct linklist` from `Src/zsh.h:563` — `first` / `last` /
//! `flags`. Rust folds `first`/`last` into the `VecDeque`'s head/tail
//! pointers; the `flags` field is preserved as `u32`. Subst.c sets
//! `LF_ARRAY` (`Src/subst.c:33`) on the flag word.

use std::collections::VecDeque;

// ===========================================================
// Free-fn ports of `Src/linklist.c` (functions, not macros).
// ===========================================================

// Get an empty linked list header                                         // c:116
/// Port of `newlinklist()` (`Src/linklist.c:103`).
pub fn newlinklist() -> LinkList<String> {                                   // c:103
    LinkList::new()
}

impl<T> Default for LinkList<T> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T> LinkList<T> {
    // Get an empty linked list header                                        // c:99
    /// Port of `znewlinklist()` from Src/linklist.c:116 — heap-arena
    /// fresh empty list. Rust uses `LinkList::new()`.
    pub fn new() -> Self {                                                      // c:116
        LinkList { nodes: VecDeque::new(), flags: 0 }
    }

    /// Port of the C macro `empty(list)` (`Src/zsh.h:583`) —
    /// `firstnode(list) == NULL`.
    pub fn is_empty(&self) -> bool {                                            // c:zsh.h:583
        self.nodes.is_empty()
    }

    // Count the number of nodes in a linked list                             // c:300
    /// Port of `countlinknodes(LinkList list)` from Src/linklist.c:304.
    pub fn len(&self) -> usize {                                                // c:304
        self.nodes.len()
    }

    /// Push at the head. Port of the C macro `pushnode()` (`Src/zsh.h`).
    pub fn push_front(&mut self, data: T) {                                     // c:151
        self.nodes.push_front(data);
    }

    /// Push at the tail. Port of `addlinknode()` (`Src/zsh.h`) /
    /// `zaddlinknode()` (`Src/linklist.c:151`).
    pub fn push_back(&mut self, data: T) {                                      // c:151
        self.nodes.push_back(data);
    }

    /// Pop the head. Port of `getlinknode(LinkList list)` (`Src/linklist.c:210`).
    pub fn pop_front(&mut self) -> Option<T> {                                  // c:210
        self.nodes.pop_front()
    }

    /// Pop the tail. Port of `remnode(list, lastnode(list))` idiom.
    pub fn pop_back(&mut self) -> Option<T> {                                   // c:251
        self.nodes.pop_back()
    }

    /// Front-element ref, equivalent to `firstnode(list)->dat`
    /// (`Src/zsh.h:576,586`).
    pub fn front(&self) -> Option<&T> {
        self.nodes.front()
    }

    pub fn front_mut(&mut self) -> Option<&mut T> {
        self.nodes.front_mut()
    }

    /// Back-element ref, equivalent to `lastnode(list)->dat`
    /// (`Src/zsh.h:577,586`).
    pub fn back(&self) -> Option<&T> {
        self.nodes.back()
    }

    pub fn back_mut(&mut self) -> Option<&mut T> {
        self.nodes.back_mut()
    }

    pub fn iter(&self) -> std::collections::vec_deque::Iter<'_, T> {
        self.nodes.iter()
    }

    pub fn iter_mut(&mut self) -> std::collections::vec_deque::IterMut<'_, T> {
        self.nodes.iter_mut()
    }

    /// Append `other` onto the tail; drains `other`. Port of
    /// `joinlists()` (`Src/linklist.c:360`).
    pub fn append(&mut self, other: &mut LinkList<T>) {                         // c:360
        self.nodes.append(&mut other.nodes);
    }

    /// Drop every node. Port of `freelinklist(list, NULL)`
    /// (`Src/linklist.c:287`).
    pub fn clear(&mut self) {                                                   // c:287
        self.nodes.clear();
    }

    pub fn to_vec(self) -> Vec<T>
    where
        T: Clone,
    {
        self.nodes.into_iter().collect()
    }

    // ===== C-macro accessors (Src/zsh.h:576-590) =====

    /// Port of `firstnode(X)` macro (`Src/zsh.h:576`) — head node
    /// handle. Rust uses `usize` indices since the `VecDeque` backing
    /// gives O(1) random access matching C's pointer walk.
    pub fn firstnode(&self) -> Option<usize> {                                  // c:zsh.h:576
        if self.nodes.is_empty() { None } else { Some(0) }
    }

    /// Port of `lastnode(X)` macro (`Src/zsh.h:577`).
    pub fn lastnode(&self) -> Option<usize> {                                   // c:zsh.h:577
        if self.nodes.is_empty() { None } else { Some(self.nodes.len() - 1) }
    }

    /// Port of `nextnode(X)` macro (`Src/zsh.h:588`).
    pub fn nextnode(&self, idx: usize) -> Option<usize> {                       // c:zsh.h:588
        if idx + 1 < self.nodes.len() { Some(idx + 1) } else { None }
    }

    /// Port of `prevnode(X)` macro (`Src/zsh.h:589`).
    pub fn prevnode(&self, idx: usize) -> Option<usize> {                       // c:zsh.h:589
        if idx > 0 && idx <= self.nodes.len() { Some(idx - 1) } else { None }
    }

    /// Port of `getdata(X)` macro (`Src/zsh.h:586`).
    pub fn getdata(&self, idx: usize) -> Option<&T> {                           // c:zsh.h:586
        self.nodes.get(idx)
    }

    /// Port of `setdata(X,Y)` macro (`Src/zsh.h:587`).
    pub fn setdata(&mut self, idx: usize, data: T) {                            // c:zsh.h:587
        if let Some(slot) = self.nodes.get_mut(idx) {
            *slot = data;
        }
    }

    /// Port of `empty(X)` macro (`Src/zsh.h:583`).
    pub fn empty(&self) -> bool {                                               // c:zsh.h:583
        self.nodes.is_empty()
    }

    /// Port of `insertlinknode(list, after, dat)` macro
    /// (`Src/zsh.h:580`) and the function form (`Src/linklist.c:133`)
    /// — insert after the supplied node index, return the index of the
    /// inserted node.
    /// WARNING: param names don't match C — Rust=(after_idx, data) vs C=(list, node, dat)
    pub fn insertlinknode(&mut self, after_idx: usize, data: T) -> usize {      // c:linklist.c:133
        let new_idx = after_idx + 1;
        if new_idx >= self.nodes.len() {
            self.nodes.push_back(data);
            self.nodes.len() - 1
        } else {
            self.nodes.insert(new_idx, data);
            new_idx
        }
    }

    /// Remove + free a node. Port of `remnode(LinkList list, LinkNode nd)` (`Src/linklist.c:251`).
    pub fn delete_node(&mut self, idx: usize) -> Option<T> {                    // c:251
        self.nodes.remove(idx)
    }

    /// Port of `pushlinknode(list, val)` head-insert helper.
    pub fn insert_at(&mut self, idx: usize, data: T) {
        if idx >= self.nodes.len() {
            self.nodes.push_back(data);
        } else {
            self.nodes.insert(idx, data);
        }
    }
}

impl<T: Clone> Clone for LinkList<T> {
    fn clone(&self) -> Self {
        LinkList { nodes: self.nodes.clone(), flags: self.flags }
    }
}

impl<T: std::fmt::Debug> std::fmt::Debug for LinkList<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("LinkList")
            .field("nodes", &self.nodes)
            .field("flags", &self.flags)
            .finish()
    }
}

impl<T> FromIterator<T> for LinkList<T> {
    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
        let mut list = LinkList::new();
        for item in iter {
            list.push_back(item);
        }
        list
    }
}

impl<T> IntoIterator for LinkList<T> {
    type Item = T;
    type IntoIter = std::collections::vec_deque::IntoIter<T>;

    fn into_iter(self) -> Self::IntoIter {
        self.nodes.into_iter()
    }
}

impl<'a, T> IntoIterator for &'a LinkList<T> {
    type Item = &'a T;
    type IntoIter = std::collections::vec_deque::Iter<'a, T>;

    fn into_iter(self) -> Self::IntoIter {
        self.nodes.iter()
    }
}

/// Port of `znewlinklist()` (`Src/linklist.c:116`).
pub fn znewlinklist() -> LinkList<String> {                                  // c:116
    LinkList::new()
}

// Insert a node in a linked list after a given node                       // c:151
/// Port of `insertlinknode(LinkList list, LinkNode node, void *dat)` (`Src/linklist.c:133`).
pub fn insertlinknode<T>(list: &mut LinkList<T>, node: usize, dat: T) -> usize { // c:133
    list.insertlinknode(node, dat)
}

/// Port of `zinsertlinknode(LinkList list, LinkNode node, void *dat)` (`Src/linklist.c:151`).
pub fn zinsertlinknode<T>(list: &mut LinkList<T>, node: usize, dat: T) -> usize {
    list.insertlinknode(node, dat)
}

/// Port of `uinsertlinknode(LinkList list, LinkNode node, LinkNode new)` (`Src/linklist.c:173`).
pub fn uinsertlinknode(list: &mut LinkList<String>, node: usize, new: String) -> Option<usize> {
    if list.iter().any(|s| s == &new) {
        None
    } else {
        Some(list.insertlinknode(node, new))
    }
}

// Insert a list in another list                                           // c:210
/// Port of `insertlinklist(LinkList l, LinkNode where, LinkList x)` from
/// `Src/linklist.c:190`. **C semantics: `l` is the SOURCE list, `where`
/// is the position in DEST list `x`, and `x` is the DESTINATION**. All
/// nodes of `l` get spliced into `x` right after node `where` —
/// equivalent to inserting the contents of `l` between `where` and
/// `where->next` in `x`. Empty `l` is a no-op (c:194 `if (!firstnode(l))
/// return;`). Param names + positions match C exactly so callers
/// reading `insertlinklist(sub.in, lastnode(result->in), result->in)`
/// (the canonical zutil.c:1324 pattern) translate 1:1.
pub fn insertlinklist<T: Clone>(                                              // c:190
    l: &LinkList<T>,
    where_idx: usize,
    x: &mut LinkList<T>,
) {
    if l.is_empty() {                                                         // c:194
        return;
    }
    let mut idx = where_idx;
    for v in l.iter() {                                                       // c:196 walk l, splice into x
        idx = x.insertlinknode(idx, v.clone());
    }
}

// Pop the top node off a linked list and free it.                         // c:210
/// Port of `getlinknode(LinkList list)` (`Src/linklist.c:210`).
pub fn getlinknode<T>(list: &mut LinkList<T>) -> Option<T> {                 // c:210
    list.pop_front()
}

// Pop the top node off a linked list without freeing it.                  // c:251
/// Port of `ugetnode(LinkList list)` (`Src/linklist.c:231`).
pub fn ugetnode<T>(list: &mut LinkList<T>) -> Option<T> {                    // c:231
    list.pop_front()
}

// Remove a node from a linked list                                        // c:270
/// Port of `remnode(LinkList list, LinkNode nd)` (`Src/linklist.c:251`).
pub fn remnode<T>(list: &mut LinkList<T>, nd: usize) -> Option<T> {         // c:251
    list.delete_node(nd)
}

/// Port of `uremnode(LinkList list, LinkNode nd)` (`Src/linklist.c:270`).
pub fn uremnode<T>(list: &mut LinkList<T>, nd: usize) -> Option<T> {        // c:270
    list.delete_node(nd)
}

// Free a linked list                                                       // c:304
/// Port of `freelinklist(LinkList list, FreeFunc freefunc)` (`Src/linklist.c:287`).
/// WARNING: param names don't match C — Rust=(list) vs C=(list, freefunc)
pub fn freelinklist<T>(list: &mut LinkList<T>) {                             // c:287
    list.clear();
}

// Count the number of nodes in a linked list                              // c:317
/// Port of `countlinknodes(LinkList list)` (`Src/linklist.c:304`).
pub fn countlinknodes<T>(list: &LinkList<T>) -> usize {                      // c:304
    list.len()
}

// Make specified node first, moving preceding nodes to end                // c:317
/// Port of `rolllist(LinkList l, LinkNode nd)` (`Src/linklist.c:317`).
pub fn rolllist<T>(l: &mut LinkList<T>, nd: usize) {                       // c:317
    let len = l.len();
    if len > 0 {
        let nd = nd % len;
        for _ in 0..nd {
            if let Some(v) = l.pop_front() {
                l.push_back(v);
            }
        }
    }
}

// Create linklist of specified size. node->dats are not initialized.      // c:331
/// Port of `newsizedlist(int size)` from `Src/linklist.c:331-348`.
///
/// C body allocates a header + `size` pre-linked placeholder nodes
/// with uninitialized data; the C `for` loop wires prev/next
/// pointers (c:339-341). Callers iterate and fill data into each
/// slot.
///
/// The previous Rust port returned an empty list (ignoring `size`),
/// so any caller expecting `size` placeholder slots would iterate
/// over nothing. Fix by pushing `size` default-constructed nodes.
pub fn newsizedlist<T: Default>(size: usize) -> LinkList<T> {                // c:331
    let mut list = LinkList::new();
    for _ in 0..size {                                                       // c:339-341
        list.push_back(T::default());
    }
    list
}

/// Port of `joinlists(LinkList first, LinkList second)` (`Src/linklist.c:360`).
pub fn joinlists<T>(first: &mut LinkList<T>, second: &mut LinkList<T>) {              // c:360
    first.append(second);
}

/// Port of `linknodebydatum(LinkList list, void *dat)` (`Src/linklist.c:386`).
pub fn linknodebydatum<T: PartialEq>(list: &LinkList<T>, dat: &T) -> Option<usize> { // c:386
    list.iter().position(|v| v == dat)
}

/// Port of `linknodebystring(LinkList list, char *dat)` (`Src/linklist.c:403`).
pub fn linknodebystring(list: &LinkList<String>, dat: &str) -> Option<usize> { // c:403
    list.iter().position(|v| v == dat)
}

/// Convert a linked list of strings to a `Vec`. Port of
/// `hlinklist2array()` (`Src/linklist.c:423`).
pub fn hlinklist2array(list: &LinkList<String>) -> Vec<String> {                // c:423
    list.iter().cloned().collect()
}

/// Port of `zlinklist2array(LinkList list, int copy)` (`Src/linklist.c:449`).
/// WARNING: param names don't match C — Rust=(list) vs C=(list, copy)
pub fn zlinklist2array(list: &LinkList<String>) -> Vec<String> {             // c:449
    list.iter().cloned().collect()
}

/// A doubly-ended list, port of `struct linklist` (`Src/zsh.h:563`).
/// `flags` carries `LF_ARRAY` and friends from `Src/subst.c:33`.
pub struct LinkList<T> {
    pub nodes: VecDeque<T>,                                                 // c:zsh.h:565,566
    pub flags: u32,                                                          // c:zsh.h:567
}

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

    #[test]
    fn test_new_list() {
        let list: LinkList<i32> = LinkList::new();
        assert!(list.is_empty());
        assert_eq!(list.len(), 0);
        assert_eq!(list.flags, 0);
    }

    /// Pin `newsizedlist(N)` to canonical C body at
    /// `Src/linklist.c:339-341`: pre-allocates N placeholder nodes
    /// with uninitialized data, ready for callers to fill in.
    /// The previous Rust port returned an empty list, ignoring `size`.
    #[test]
    fn newsizedlist_preallocates_n_slots() {
        let list: LinkList<i32> = newsizedlist(5);
        assert_eq!(list.len(), 5,
            "c:339-341 — newsizedlist(5) must pre-allocate 5 nodes");
        // Default-constructed i32 is 0; every slot ready for assign.
        for v in list.iter() {
            assert_eq!(*v, 0, "pre-allocated slots default to 0");
        }

        let zero_list: LinkList<String> = newsizedlist(0);
        assert_eq!(zero_list.len(), 0,
            "newsizedlist(0) is the same as new()");
    }

    #[test]
    fn test_push_front_back() {
        let mut list = LinkList::new();
        list.push_back(1);
        list.push_back(2);
        list.push_front(0);
        assert_eq!(list.front(), Some(&0));
        assert_eq!(list.back(), Some(&2));
        assert_eq!(list.len(), 3);
    }

    #[test]
    fn test_pop_front_back() {
        let mut list = LinkList::new();
        list.push_back(1);
        list.push_back(2);
        list.push_back(3);
        assert_eq!(list.pop_front(), Some(1));
        assert_eq!(list.pop_back(), Some(3));
        assert_eq!(list.pop_front(), Some(2));
        assert_eq!(list.pop_front(), None);
    }

    #[test]
    fn test_iter() {
        let mut list = LinkList::new();
        list.push_back(1);
        list.push_back(2);
        list.push_back(3);
        let v: Vec<_> = list.iter().copied().collect();
        assert_eq!(v, vec![1, 2, 3]);
    }

    #[test]
    fn test_macro_methods() {
        let mut list: LinkList<String> = LinkList::new();
        list.push_back("a".to_string());
        list.push_back("b".to_string());
        list.push_back("c".to_string());

        assert_eq!(list.firstnode(), Some(0));
        assert_eq!(list.lastnode(), Some(2));
        assert_eq!(list.nextnode(0), Some(1));
        assert_eq!(list.nextnode(2), None);
        assert_eq!(list.getdata(1).map(String::as_str), Some("b"));
        list.setdata(1, "B".to_string());
        assert_eq!(list.getdata(1).map(String::as_str), Some("B"));
        let new_idx = list.insertlinknode(1, "X".to_string());
        assert_eq!(new_idx, 2);
        assert_eq!(list.getdata(2).map(String::as_str), Some("X"));
        assert_eq!(list.delete_node(2).as_deref(), Some("X"));
        assert_eq!(list.getdata(2).map(String::as_str), Some("c"));
    }

    #[test]
    fn test_append() {
        let mut a: LinkList<i32> = vec![1, 2].into_iter().collect();
        let mut b: LinkList<i32> = vec![3, 4].into_iter().collect();
        a.append(&mut b);
        assert!(b.is_empty());
        assert_eq!(a.to_vec(), vec![1, 2, 3, 4]);
    }

    #[test]
    fn test_clear() {
        let mut list: LinkList<i32> = vec![1, 2, 3].into_iter().collect();
        list.clear();
        assert!(list.is_empty());
    }

    #[test]
    fn test_uinsertlinknode_dedups() {
        let mut list: LinkList<String> = LinkList::new();
        list.push_back("a".to_string());
        assert!(uinsertlinknode(&mut list, 0, "b".to_string()).is_some());
        assert!(uinsertlinknode(&mut list, 0, "a".to_string()).is_none());
        assert_eq!(list.len(), 2);
    }

    /// c:360 — `joinlists(first, second)` moves all of `second` onto
    /// the end of `first`, draining second. A regression where second
    /// isn't drained would let the caller iterate doubled entries.
    #[test]
    fn joinlists_drains_second_into_first() {
        let mut a: LinkList<i32> = vec![1, 2].into_iter().collect();
        let mut b: LinkList<i32> = vec![3, 4, 5].into_iter().collect();
        joinlists(&mut a, &mut b);
        assert_eq!(a.to_vec(), vec![1, 2, 3, 4, 5]);
        assert!(b.is_empty(), "second list must be drained after join");
    }

    /// c:360 — joining an empty `second` is a no-op. Catches a
    /// regression that adds phantom empty sentinels.
    #[test]
    fn joinlists_empty_second_is_noop() {
        let mut a: LinkList<i32> = vec![1, 2].into_iter().collect();
        let mut b: LinkList<i32> = LinkList::new();
        joinlists(&mut a, &mut b);
        assert_eq!(a.to_vec(), vec![1, 2]);
        assert!(b.is_empty());
    }

    /// c:360 — joining INTO an empty `first` transfers second
    /// cleanly. The empty-head edge case in the C body has a
    /// dedicated branch — regression there would lose the data.
    #[test]
    fn joinlists_empty_first_receives_all_of_second() {
        let mut a: LinkList<i32> = LinkList::new();
        let mut b: LinkList<i32> = vec![1, 2, 3].into_iter().collect();
        joinlists(&mut a, &mut b);
        assert_eq!(a.to_vec(), vec![1, 2, 3]);
        assert!(b.is_empty());
    }

    /// c:386 — `linknodebydatum` returns Some(idx) for the first
    /// matching entry, None for miss. Used by `unhash -d` lookups.
    #[test]
    fn linknodebydatum_finds_first_match() {
        let list: LinkList<i32> = vec![10, 20, 30, 20].into_iter().collect();
        assert_eq!(linknodebydatum(&list, &20), Some(1),
            "must return FIRST match index");
        assert_eq!(linknodebydatum(&list, &99), None);
    }

    /// c:403 — `linknodebystring` is the string-specialised variant.
    /// Verifies same FIRST-match contract for the alias-table walks.
    #[test]
    fn linknodebystring_finds_first_match() {
        let list: LinkList<String> = vec!["a".into(), "b".into(), "a".into()].into_iter().collect();
        assert_eq!(linknodebystring(&list, "a"), Some(0));
        assert_eq!(linknodebystring(&list, "b"), Some(1));
        assert_eq!(linknodebystring(&list, "x"), None);
    }

    /// c:423 — `hlinklist2array` flattens to Vec preserving order.
    /// Used by `${(@k)hash}` array materialisation.
    #[test]
    fn hlinklist2array_preserves_order() {
        let list: LinkList<String> = vec!["a".into(), "b".into(), "c".into()].into_iter().collect();
        let arr = hlinklist2array(&list);
        assert_eq!(arr, vec!["a".to_string(), "b".to_string(), "c".to_string()]);
    }

    /// `Src/linklist.c:302-311` — `countlinknodes(list)` walks the
    /// `next` chain incrementing a counter. Empty list → 0.
    #[test]
    fn countlinknodes_returns_len_for_arbitrary_lists() {
        let empty: LinkList<i32> = LinkList::new();
        assert_eq!(countlinknodes(&empty), 0,
            "c:309 — empty list traversal yields 0");
        let one: LinkList<i32> = vec![42].into_iter().collect();
        assert_eq!(countlinknodes(&one), 1);
        let many: LinkList<i32> = (0..100).collect();
        assert_eq!(countlinknodes(&many), 100);
    }

    /// `Src/linklist.c:316-325` — `rolllist(l, nd)` makes `nd` first,
    /// moving preceding nodes to end (circular rotation). The Rust
    /// port treats `nd` as a 0-indexed position to rotate to the
    /// front; rotate-by-0 is a no-op, rotate-by-N wraps via modulo.
    #[test]
    fn rolllist_rotates_to_index() {
        // c:319-324 — rotate so nd-th element becomes first.
        let mut list: LinkList<i32> = vec![10, 20, 30, 40].into_iter().collect();
        rolllist(&mut list, 2);
        assert_eq!(list.to_vec(), vec![30, 40, 10, 20],
            "c:321 — `list.first = nd` then preceding nodes append at end");
    }

    /// c:316-325 — rolllist by 0 is the identity. Pin so an off-by-one
    /// regression doesn't silently rotate every caller by 1.
    #[test]
    fn rolllist_zero_index_is_identity() {
        let mut list: LinkList<i32> = vec![1, 2, 3].into_iter().collect();
        rolllist(&mut list, 0);
        assert_eq!(list.to_vec(), vec![1, 2, 3]);
    }

    /// c:316-325 — rolllist with index >= len wraps via modulo. Pins
    /// the implementation choice (C version is UB on out-of-range —
    /// Rust port chose modulo defensively).
    #[test]
    fn rolllist_wraps_index_modulo_length() {
        let mut list: LinkList<i32> = vec![1, 2, 3].into_iter().collect();
        // index 4 mod 3 == 1 → rotate by 1.
        rolllist(&mut list, 4);
        assert_eq!(list.to_vec(), vec![2, 3, 1]);
    }

    /// `Src/linklist.c:188-206` — `insertlinklist(l, where, x)` splices
    /// the contents of SOURCE list `l` into DESTINATION list `x` right
    /// after node `where`. Canonical caller pattern (per
    /// `Src/Modules/zutil.c:1324`):
    ///     `insertlinklist(sub.in, lastnode(result->in), result->in);`
    /// which appends every node from `sub.in` to the end of `result->in`.
    /// The Rust port previously had the param roles inverted (l mutated
    /// = treated as DEST), silently inserting in the wrong direction.
    /// Pin C semantics: source unchanged, dest grows by source's length,
    /// inserted in the right span and in source order.
    #[test]
    fn insertlinklist_splices_source_into_dest_after_position() {
        // dest: [10, 20, 30], source: [A, B, C], where=0 (after first).
        // Expected: [10, A, B, C, 20, 30] — source appears AFTER 10.
        let source: LinkList<i32> = vec![100, 200, 300].into_iter().collect();
        let mut dest: LinkList<i32> = vec![10, 20, 30].into_iter().collect();
        insertlinklist(&source, 0, &mut dest);
        assert_eq!(dest.to_vec(), vec![10, 100, 200, 300, 20, 30],
            "c:194-202 — source spliced into dest after node 0");
        assert_eq!(source.to_vec(), vec![100, 200, 300],
            "c:188-206 — source list is NOT modified (read-only)");
    }

    /// `Src/linklist.c:193-194` — `if (!firstnode(l)) return;` — empty
    /// source is a no-op. Pins so a regression doesn't accidentally
    /// insert a phantom sentinel.
    #[test]
    fn insertlinklist_empty_source_is_noop() {
        let source: LinkList<i32> = LinkList::new();
        let mut dest: LinkList<i32> = vec![1, 2, 3].into_iter().collect();
        insertlinklist(&source, 1, &mut dest);
        assert_eq!(dest.to_vec(), vec![1, 2, 3],
            "c:193-194 — empty l returns early; dest unchanged");
    }

    /// `Src/linklist.c:188-206` — canonical zutil.c:1324 pattern:
    /// `insertlinklist(sub.in, lastnode(result->in), result->in)` —
    /// append entire source list at end of dest. The Rust port's
    /// `lastnode_index()` is `len()-1`; passing that as `where_idx`
    /// inserts after the last node, producing dest++source.
    #[test]
    fn insertlinklist_lastnode_append_pattern() {
        let source: LinkList<&str> = vec!["x", "y"].into_iter().collect();
        let mut dest: LinkList<&str> = vec!["a", "b", "c"].into_iter().collect();
        let last = dest.len() - 1;
        insertlinklist(&source, last, &mut dest);
        assert_eq!(dest.to_vec(), vec!["a", "b", "c", "x", "y"],
            "c:188-206 zutil.c:1324 — lastnode anchor → tail-append");
    }
}