inkling 0.12.5

Limited implementation of the Ink markup language.
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
//! Processing nested story content by following, or walking through, it.

use crate::{
    error::{runtime::internal::IncorrectNodeStackError, InternalError},
    follow::{ChoiceInfo, EncounteredEvent, FollowData, FollowResult, LineDataBuffer},
    knot::increment_num_visited,
    node::{Branch, NodeItem, RootNode},
    process::process_line,
};

use std::{fmt, slice::IterMut};

/// Represents the current stack of choices made from the tree root.
///
/// # Example
///
/// For example, for this tree:
///
/// Root
/// ```text
/// Line
/// Line
/// Branching Set
///     Branch 1
///     Branch 2
///         Line
///         Branching Set   <---- the user is here in the branched story
///             Branch 1
///                 ...
///             Branch 2
///                 ...
///     Branch 3
///         ...
/// ```
///
/// the current stack is [2, 1, 1]. When the user picks a choice the stack is used to
/// advance to the position of that choice set in the tree, then follow from there on.
///
/// Do note that every `Branch` adds a line of text to its children. Lines after this
/// choice start at index 1.
pub type Stack = Vec<usize>;

/// Trait which enables us to walk through the tree of content in a `Stitch`.
///
/// This trait is implemented on all constituent parts (nodes) of the tree. For every line
/// of content in the current node the text is processed and added to a supplied buffer.
///
/// When a branching choice is encountered it is returned and the story will halt until
/// the user supplies a branch to keep following the story from.
pub trait Follow: FollowInternal {
    /// Follow the content of the current node.
    ///
    /// The follow continues until the node runs out of content or a branching choice
    /// is encountered. This node should be the currently active node, representing
    /// the last stack position in a tree.
    ///
    /// The follow will resume from and update the current `Stack` as it walks through
    /// the node.
    ///
    /// # Notes
    ///  *  The method assumes that the last index of the stack belongs to this node,
    ///     since a `follow` will always be called on the deepest level that has been
    ///     reached in the tree.
    ///
    ///     Ensure that the stack is maintained before calling this method.
    fn follow(
        &mut self,
        stack: &mut Stack,
        buffer: &mut LineDataBuffer,
        data: &mut FollowData,
    ) -> FollowResult {
        let at_index = stack
            .last_mut()
            .ok_or(InternalError::from(IncorrectNodeStackError::EmptyStack))?;

        if *at_index > self.get_num_items() {
            return Err(InternalError::from(IncorrectNodeStackError::OutOfBounds {
                stack_index: stack.len() - 1,
                stack: stack.clone(),
                num_items: self.get_num_items(),
            })
            .into());
        } else if *at_index == 0 {
            self.increment_num_visited(data)?;
        }

        for item in self.iter_mut_items().skip(*at_index) {
            *at_index += 1;

            match item {
                NodeItem::Line(line) => {
                    let result =
                        process_line(line, buffer, data).map_err(|err| InternalError::from(err))?;

                    if let EncounteredEvent::Divert(..) = result {
                        return Ok(result);
                    }
                }
                NodeItem::BranchingPoint(branches) => {
                    *at_index -= 1;

                    let branching_choice_set = get_choices_from_branching_set(branches);

                    return Ok(EncounteredEvent::BranchingChoice(branching_choice_set));
                }
            }
        }

        Ok(EncounteredEvent::Done)
    }

    /// Resume the follow of content in the tree with a supplied choice.
    ///
    /// Will fast forward through the tree to reach the node where the choice was encountered.
    /// The `Stack` is used to accomplish this. The last index in the stack represents
    /// the `NodeItem` of the nested node where the choice was encountered. We advance to
    /// that node from a lower level by checking whether the current `stack_index` represents
    /// this level.
    ///
    /// If the `stack_index` is lower than the stack length - 1 we are not yet at the level
    /// in the tree where the choice was encountered. We recursively move to the next node
    /// by following the stack to it, updating the `stack_index` value when calling it
    /// until we reach the deepest level.
    ///
    /// When reaching the deepest level, `follow` is called on the selected branch of
    /// the choices. Diverts and new branching choices are returned through the stack
    /// if encountered.
    ///
    /// Finally, when we return from a deeper level due to running out of content in that node,
    /// we keep `follow`ing the content in the current node until its end.
    fn follow_with_choice(
        &mut self,
        selection: usize,
        stack_index: usize,
        stack: &mut Stack,
        buffer: &mut LineDataBuffer,
        data: &mut FollowData,
    ) -> FollowResult {
        let result = if let Some(next_branch) = self.get_next_level_branch(stack_index, stack)? {
            next_branch.follow_with_choice(selection, stack_index + 2, stack, buffer, data)
        } else {
            let selected_branch = self.get_selected_branch(selection, stack_index, stack)?;

            stack.extend_from_slice(&[selection, 0]);

            selected_branch.follow(stack, buffer, data)
        }?;

        match result {
            EncounteredEvent::Done => {
                stack.truncate(stack_index + 1);
                stack.last_mut().map(|i| *i += 1);

                self.follow(stack, buffer, data)
            }
            other => Ok(other),
        }
    }
}

impl Follow for RootNode {}
impl Follow for Branch {}

/// Internal utilities required to implement `Follow`.
///
/// Separated from that trait to simplify the scope of functions that are made available
/// when importing `Follow`.
pub trait FollowInternal: fmt::Debug {
    fn get_next_level_branch(
        &mut self,
        stack_index: usize,
        stack: &Stack,
    ) -> Result<Option<&mut Branch>, InternalError> {
        if stack_index < stack.len() - 1 {
            self.get_branches_at_stack_index(stack_index, stack)
                .and_then(|branches| {
                    let branch_index = stack.get(stack_index + 1).ok_or(
                        IncorrectNodeStackError::MissingBranchIndex {
                            stack_index,
                            stack: stack.clone(),
                        },
                    )?;

                    Ok((branch_index, branches))
                })
                .and_then(|(branch_index, branches)| {
                    let num_items = branches.len();

                    Some(
                        branches.get_mut(*branch_index).ok_or(
                            IncorrectNodeStackError::OutOfBounds {
                                stack_index: stack_index + 1,
                                stack: stack.clone(),
                                num_items,
                            }
                            .into(),
                        ),
                    )
                    .transpose()
                })
        } else {
            Ok(None)
        }
    }

    fn get_selected_branch(
        &mut self,
        branch_index: usize,
        stack_index: usize,
        stack: &Stack,
    ) -> Result<&mut Branch, InternalError> {
        self.get_branches_at_stack_index(stack_index, stack)
            .map_err(|err| err.into())
            .and_then(|branches| {
                let branch_choices = get_choices_from_branching_set(branches);

                branches
                    .get_mut(branch_index)
                    .ok_or(InternalError::IncorrectChoiceIndex {
                        selection: branch_index,
                        available_choices: branch_choices,
                        stack_index,
                        stack: stack.clone(),
                    })
            })
    }

    fn get_branches_at_stack_index(
        &mut self,
        stack_index: usize,
        stack: &Stack,
    ) -> Result<&mut Vec<Branch>, InternalError> {
        let num_items = self.get_num_items();

        stack
            .get(stack_index)
            .and_then(move |i| self.get_item_mut(*i))
            .ok_or(
                IncorrectNodeStackError::OutOfBounds {
                    stack_index,
                    stack: stack.clone(),
                    num_items,
                }
                .into(),
            )
            .and_then(|item| match item {
                NodeItem::BranchingPoint(branches) => Ok(branches),
                NodeItem::Line(..) => Err(IncorrectNodeStackError::ExpectedBranchingPoint {
                    stack_index,
                    stack: stack.clone(),
                }
                .into()),
            })
    }

    fn get_item(&self, index: usize) -> Option<&NodeItem>;
    fn get_item_mut(&mut self, index: usize) -> Option<&mut NodeItem>;
    fn get_num_items(&self) -> usize;
    fn increment_num_visited(&mut self, data: &mut FollowData) -> Result<(), InternalError>;
    fn iter_mut_items(&mut self) -> IterMut<NodeItem>;
}

impl FollowInternal for RootNode {
    fn get_item(&self, index: usize) -> Option<&NodeItem> {
        self.items.get(index)
    }

    fn get_item_mut(&mut self, index: usize) -> Option<&mut NodeItem> {
        self.items.get_mut(index)
    }

    fn get_num_items(&self) -> usize {
        self.items.len()
    }

    fn increment_num_visited(&mut self, data: &mut FollowData) -> Result<(), InternalError> {
        increment_num_visited(&self.address, data)
    }

    fn iter_mut_items(&mut self) -> IterMut<NodeItem> {
        self.items.iter_mut()
    }
}

impl FollowInternal for Branch {
    fn get_item(&self, index: usize) -> Option<&NodeItem> {
        self.items.get(index)
    }

    fn get_item_mut(&mut self, index: usize) -> Option<&mut NodeItem> {
        self.items.get_mut(index)
    }

    fn get_num_items(&self) -> usize {
        self.items.len()
    }

    fn increment_num_visited(&mut self, _: &mut FollowData) -> Result<(), InternalError> {
        self.num_visited += 1;

        Ok(())
    }

    fn iter_mut_items(&mut self) -> IterMut<NodeItem> {
        self.items.iter_mut()
    }
}

/// Collect the `ChoiceInfo` from a given set of branches.
fn get_choices_from_branching_set(branches: &[Branch]) -> Vec<ChoiceInfo> {
    branches
        .iter()
        .map(|branch| ChoiceInfo::from_choice(&branch.choice, branch.num_visited))
        .collect::<Vec<_>>()
}

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

    use crate::{
        error::InklingError,
        knot::{get_num_visited, Address},
        line::{InternalChoice, LineChunkBuilder},
        node::builders::{BranchBuilder, BranchingPointBuilder, RootNodeBuilder},
    };

    use std::collections::HashMap;

    fn mock_follow_data(node: &RootNode) -> FollowData {
        let (knot, stitch) = node.address.get_knot_and_stitch().unwrap();

        let mut stitch_count = HashMap::new();
        stitch_count.insert(stitch.to_string(), 0);

        let mut knot_visit_counts = HashMap::new();
        knot_visit_counts.insert(knot.to_string(), stitch_count);

        FollowData {
            knot_visit_counts,
            variables: HashMap::new(),
        }
    }

    #[test]
    fn stack_that_points_to_line_instead_of_branching_choice_returns_error() {
        let mut node = RootNodeBuilder::empty()
            .with_text_line_chunk("Line 1")
            .build();

        let mut buffer = Vec::new();
        let mut stack = vec![0];
        let mut data = mock_follow_data(&node);

        match node.follow_with_choice(0, 0, &mut stack, &mut buffer, &mut data) {
            Err(InklingError::Internal(InternalError::IncorrectNodeStack(err))) => match err {
                IncorrectNodeStackError::ExpectedBranchingPoint { .. } => (),
                _ => unreachable!(),
            },
            _ => unreachable!(),
        }
    }

    #[test]
    fn out_of_bounds_stack_indices_return_stack_error() {
        let mut node = RootNodeBuilder::empty().build();

        let mut buffer = Vec::new();
        let mut stack = vec![0];
        let mut data = mock_follow_data(&node);

        match node.follow_with_choice(0, 0, &mut stack, &mut buffer, &mut data) {
            Err(InklingError::Internal(InternalError::IncorrectNodeStack(err))) => match err {
                IncorrectNodeStackError::OutOfBounds { .. } => (),
                _ => unreachable!(),
            },
            _ => unreachable!(),
        }
    }

    #[test]
    fn out_of_bounds_stack_indices_return_stack_error_when_checking_branches() {
        let mut node = RootNodeBuilder::empty()
            .with_branching_choice(BranchingPointBuilder::new().build())
            .build();

        let mut buffer = Vec::new();
        let mut stack = vec![0, 0, 0];
        let mut data = mock_follow_data(&node);

        match node.follow_with_choice(0, 0, &mut stack, &mut buffer, &mut data) {
            Err(InklingError::Internal(InternalError::IncorrectNodeStack(err))) => match err {
                IncorrectNodeStackError::OutOfBounds { .. } => (),
                _ => unreachable!(),
            },
            _ => unreachable!(),
        }
    }

    #[test]
    fn branch_choices_are_collected_when_supplying_an_incorrect_index_for_a_choice() {
        let internal_choice = InternalChoice::from_string("Choice");

        let mut node = RootNodeBuilder::empty()
            .with_branching_choice(
                BranchingPointBuilder::new()
                    .with_branch(BranchBuilder::from_choice(internal_choice.clone()).build())
                    .build(),
            )
            .build();

        let mut buffer = Vec::new();
        let mut stack = vec![0];
        let mut data = mock_follow_data(&node);

        match node.follow_with_choice(1, 0, &mut stack, &mut buffer, &mut data) {
            Err(InklingError::Internal(InternalError::IncorrectChoiceIndex {
                selection,
                available_choices,
                ..
            })) => {
                assert_eq!(selection, 1);
                assert_eq!(available_choices.len(), 1);
                assert_eq!(available_choices[0].choice_data, internal_choice);
            }
            other => panic!("expected `InklingError::InvalidChoice` but got {:?}", other),
        }
    }

    #[test]
    fn following_items_in_a_node_adds_lines_to_buffer() {
        let mut node = RootNodeBuilder::empty()
            .with_text_line_chunk("Line 1")
            .with_text_line_chunk("Line 2")
            .build();

        let mut buffer = Vec::new();
        let mut stack = vec![0];
        let mut data = mock_follow_data(&node);

        assert_eq!(
            node.follow(&mut stack, &mut buffer, &mut data).unwrap(),
            EncounteredEvent::Done
        );

        assert_eq!(buffer.len(), 2);
        assert_eq!(&buffer[0].text, "Line 1");
        assert_eq!(&buffer[1].text, "Line 2");
    }

    #[test]
    fn following_into_a_node_increments_number_of_visits() {
        let mut node = RootNodeBuilder::empty()
            .with_text_line_chunk("Line 1")
            .build();

        let mut buffer = Vec::new();
        let mut data = mock_follow_data(&node);

        assert_eq!(get_num_visited(&node.address, &data).unwrap(), 0);

        node.follow(&mut vec![0], &mut buffer, &mut data).unwrap();
        node.follow(&mut vec![0], &mut buffer, &mut data).unwrap();

        assert_eq!(get_num_visited(&node.address, &data).unwrap(), 2);
    }

    #[test]
    fn following_items_updates_stack() {
        let mut node = RootNodeBuilder::empty()
            .with_text_line_chunk("Line 1")
            .with_text_line_chunk("Line 2")
            .build();

        let mut buffer = Vec::new();
        let mut stack = vec![0];
        let mut data = mock_follow_data(&node);

        node.follow(&mut stack, &mut buffer, &mut data).unwrap();
        assert_eq!(stack[0], 2);
    }

    #[test]
    fn following_items_starts_from_stack() {
        let mut node = RootNodeBuilder::empty()
            .with_text_line_chunk("Line 1")
            .with_text_line_chunk("Line 2")
            .build();

        let mut buffer = Vec::new();
        let mut stack = vec![1];
        let mut data = mock_follow_data(&node);

        node.follow(&mut stack, &mut buffer, &mut data).unwrap();

        assert_eq!(&buffer[0].text, "Line 2");
        assert_eq!(stack[0], 2);
    }

    #[test]
    fn follow_always_uses_last_position_in_stack() {
        let mut node = RootNodeBuilder::empty()
            .with_text_line_chunk("Line 1")
            .with_text_line_chunk("Line 2")
            .with_text_line_chunk("Line 3")
            .build();

        let mut buffer = Vec::new();

        let mut stack = vec![0, 2, 1];
        let mut data = mock_follow_data(&node);

        node.follow(&mut stack, &mut buffer, &mut data).unwrap();

        assert_eq!(buffer.len(), 2);
        assert_eq!(&buffer[0].text, "Line 2");
        assert_eq!(&buffer[1].text, "Line 3");
    }

    #[test]
    fn following_into_a_node_does_not_increment_number_of_visits_if_stack_is_non_zero() {
        let mut node = RootNodeBuilder::empty()
            .with_text_line_chunk("Line 1")
            .with_text_line_chunk("Line 2")
            .build();

        let mut buffer = Vec::new();
        let mut data = mock_follow_data(&node);

        assert_eq!(get_num_visited(&node.address, &data).unwrap(), 0);

        node.follow(&mut vec![1], &mut buffer, &mut data).unwrap();

        assert_eq!(get_num_visited(&node.address, &data).unwrap(), 0);
    }

    #[test]
    fn following_into_line_with_divert_immediately_returns_it() {
        let mut node = RootNodeBuilder::empty()
            .with_text_line_chunk("Line 1")
            .with_line_chunk(
                LineChunkBuilder::new()
                    .with_text("Divert")
                    .with_divert("divert")
                    .build(),
            )
            .with_text_line_chunk("Line 2")
            .build();

        let mut buffer = Vec::new();
        let mut stack = vec![0];
        let mut data = mock_follow_data(&node);

        assert_eq!(
            node.follow(&mut stack, &mut buffer, &mut data).unwrap(),
            EncounteredEvent::Divert(Address::Raw("divert".to_string()))
        );

        assert_eq!(buffer.len(), 2);
        assert_eq!(&buffer[0].text, "Line 1");
        assert_eq!(buffer[1].text.trim(), "Divert");
    }

    #[test]
    fn encountering_a_branching_choice_returns_the_choice_data() {
        let choice1 = InternalChoice::from_string("Choice 1");
        let choice2 = InternalChoice::from_string("Choice 2");

        let branching_choice_set = BranchingPointBuilder::new()
            .with_branch(BranchBuilder::from_choice(choice1.clone()).build())
            .with_branch(BranchBuilder::from_choice(choice2.clone()).build())
            .build();

        let mut node = RootNodeBuilder::empty()
            .with_branching_choice(branching_choice_set)
            .build();

        let mut buffer = Vec::new();
        let mut stack = vec![0];
        let mut data = mock_follow_data(&node);

        match node.follow(&mut stack, &mut buffer, &mut data).unwrap() {
            EncounteredEvent::BranchingChoice(choice_set) => {
                assert_eq!(choice_set.len(), 2);
                assert_eq!(choice_set[0].choice_data, choice1);
                assert_eq!(choice_set[1].choice_data, choice2);
            }
            other => panic!(
                "expected a `EncounteredEvent::BranchingChoice` but got {:?}",
                other
            ),
        }
    }

    #[test]
    fn encountering_a_branching_choice_keeps_stack_at_that_index() {
        let choice1 = InternalChoice::from_string("Choice 1");
        let choice2 = InternalChoice::from_string("Choice 2");

        let branching_choice_set = BranchingPointBuilder::new()
            .with_branch(BranchBuilder::from_choice(choice1.clone()).build())
            .with_branch(BranchBuilder::from_choice(choice2.clone()).build())
            .build();

        let mut node = RootNodeBuilder::empty()
            .with_text_line_chunk("Line 1")
            .with_branching_choice(branching_choice_set)
            .build();

        let mut buffer = Vec::new();
        let mut stack = vec![0];
        let mut data = mock_follow_data(&node);

        node.follow(&mut stack, &mut buffer, &mut data).unwrap();

        assert_eq!(stack[0], 1);
    }

    #[test]
    fn following_with_choice_follows_from_last_position_in_stack() {
        let choice = InternalChoice::from_string("Choice");
        let empty_choice = InternalChoice::from_string("");

        let empty_branch = BranchBuilder::from_choice(empty_choice.clone()).build();

        let nested_branching_choice = BranchingPointBuilder::new()
            .with_branch(empty_branch.clone())
            .with_branch(
                BranchBuilder::from_choice(choice.clone()) // Stack: [1, 2, 2], Choice: 1
                    .with_text_line_chunk("Line 3")
                    .with_text_line_chunk("Line 4")
                    .build(),
            )
            .with_branch(empty_branch.clone())
            .build();

        let nested_branch = BranchBuilder::from_choice(choice.clone())
            .with_text_line_chunk("Line 2")
            .with_branching_choice(nested_branching_choice) // Stack: [1, 2, 1]
            .build();

        let root_branching_choice = BranchingPointBuilder::new()
            .with_branch(empty_branch.clone())
            .with_branch(empty_branch.clone())
            .with_branch(nested_branch) // Stack: [1, 2]
            .build();

        let mut node = RootNodeBuilder::empty()
            .with_text_line_chunk("Line 1")
            .with_branching_choice(root_branching_choice) // Stack: [1]
            .with_text_line_chunk("Line 5")
            .build();

        let mut buffer = Vec::new();
        let mut stack = vec![1, 2, 2];
        let mut data = mock_follow_data(&node);

        node.follow_with_choice(1, 0, &mut stack, &mut buffer, &mut data)
            .unwrap();

        assert_eq!(&buffer[1].text, "Line 3");
        assert_eq!(&buffer[2].text, "Line 4");
    }

    #[test]
    fn after_finishing_with_a_branch_lower_nodes_return_to_their_content() {
        let choice = InternalChoice::from_string("Choice");

        let mut node = RootNodeBuilder::empty()
            .with_branching_choice(
                BranchingPointBuilder::new()
                    .with_branch(BranchBuilder::from_choice(choice).build())
                    .build(),
            )
            .with_text_line_chunk("Line 1")
            .build();

        let mut buffer = Vec::new();
        let mut stack = vec![0];
        let mut data = mock_follow_data(&node);

        node.follow_with_choice(0, 0, &mut stack, &mut buffer, &mut data)
            .unwrap();

        assert_eq!(buffer.len(), 2);
        assert_eq!(&buffer[1].text, "Line 1");

        assert_eq!(&stack, &[2]);
    }

    #[test]
    fn selected_branches_have_their_number_of_visits_number_incremented() {
        let choice = InternalChoice::from_string("Choice");

        let mut node = RootNodeBuilder::empty()
            .with_branching_choice(
                BranchingPointBuilder::new()
                    .with_branch(BranchBuilder::from_choice(choice.clone()).build())
                    .with_branch(BranchBuilder::from_choice(choice.clone()).build())
                    .with_branch(BranchBuilder::from_choice(choice.clone()).build())
                    .build(),
            )
            .build();

        let mut buffer = Vec::new();
        let mut stack = vec![0];
        let mut data = mock_follow_data(&node);

        node.follow_with_choice(1, 0, &mut stack, &mut buffer, &mut data)
            .unwrap();

        match &node.items[0] {
            NodeItem::BranchingPoint(branches) => {
                assert_eq!(branches[0].num_visited, 0);
                assert_eq!(branches[1].num_visited, 1);
                assert_eq!(branches[2].num_visited, 0);
            }
            _ => unreachable!(),
        }
    }

    #[test]
    fn encountered_choices_return_with_their_number_of_visits_counter() {
        let choice = InternalChoice::from_string("Choice");

        let mut node = RootNodeBuilder::empty()
            .with_branching_choice(
                BranchingPointBuilder::new()
                    .with_branch(BranchBuilder::from_choice(choice.clone()).build())
                    .build(),
            )
            .build();

        let mut buffer = Vec::new();
        let mut data = mock_follow_data(&node);

        node.follow_with_choice(0, 0, &mut vec![0], &mut buffer, &mut data)
            .unwrap();
        node.follow_with_choice(0, 0, &mut vec![0], &mut buffer, &mut data)
            .unwrap();
        node.follow_with_choice(0, 0, &mut vec![0], &mut buffer, &mut data)
            .unwrap();

        match node.follow(&mut vec![0], &mut buffer, &mut data).unwrap() {
            EncounteredEvent::BranchingChoice(branches) => {
                assert_eq!(branches[0].num_visited, 3);
            }
            other => panic!(
                "expected a `EncounteredEvent::BranchingChoice` but got {:?}",
                other
            ),
        }
    }

    #[test]
    fn selected_branches_adds_line_text_to_line_buffer() {
        let choice = InternalChoice::from_string("Choice");

        let mut node = RootNodeBuilder::empty()
            .with_branching_choice(
                BranchingPointBuilder::new()
                    .with_branch(BranchBuilder::from_choice(choice.clone()).build())
                    .build(),
            )
            .build();

        let mut buffer = Vec::new();
        let mut stack = vec![0];
        let mut data = mock_follow_data(&node);

        node.follow_with_choice(0, 0, &mut stack, &mut buffer, &mut data)
            .unwrap();

        assert_eq!(&buffer[0].text, "Choice");
    }

    #[test]
    fn diverts_found_after_selections_are_returned() {
        let choice = InternalChoice::from_string("Choice -> divert");

        let mut node = RootNodeBuilder::empty()
            .with_branching_choice(
                BranchingPointBuilder::new()
                    .with_branch(BranchBuilder::from_choice(choice.clone()).build())
                    .build(),
            )
            .build();

        let mut buffer = Vec::new();
        let mut stack = vec![0];
        let mut data = mock_follow_data(&node);

        assert_eq!(
            node.follow_with_choice(0, 0, &mut stack, &mut buffer, &mut data)
                .unwrap(),
            EncounteredEvent::Divert(Address::Raw("divert".to_string()))
        );
    }

    #[test]
    fn following_into_nested_branches_works() {
        let choice = InternalChoice::from_string("Choice");

        let nested_branch = BranchingPointBuilder::new()
            .with_branch(BranchBuilder::from_choice(choice.clone()).build())
            .build();

        let branch_set = BranchingPointBuilder::new()
            .with_branch(
                BranchBuilder::from_choice(choice.clone())
                    .with_branching_choice(nested_branch)
                    .build(),
            )
            .build();

        let mut node = RootNodeBuilder::empty()
            .with_branching_choice(branch_set)
            .build();

        let mut buffer = Vec::new();
        let mut stack = vec![0];
        let mut data = mock_follow_data(&node);

        match node
            .follow_with_choice(0, 0, &mut stack, &mut buffer, &mut data)
            .unwrap()
        {
            EncounteredEvent::BranchingChoice(branches) => assert_eq!(branches.len(), 1),
            other => panic!("expected a `BranchingChoice` but got {:?}", other),
        }
    }

    #[test]
    fn after_a_followed_choice_returns_the_caller_nodes_always_follow_into_their_next_lines() {
        let choice = InternalChoice::from_string("Choice");

        let mut node = RootNodeBuilder::empty()
            .with_branching_choice(
                BranchingPointBuilder::new()
                    .with_branch(
                        BranchBuilder::from_choice(choice.clone())
                            .with_branching_choice(
                                BranchingPointBuilder::new()
                                    .with_branch(
                                        BranchBuilder::from_choice(choice.clone())
                                            .with_branching_choice(
                                                BranchingPointBuilder::new()
                                                    .with_branch(
                                                        BranchBuilder::from_choice(choice.clone())
                                                            .with_text_line_chunk("Line 1")
                                                            .build(),
                                                    )
                                                    .build(),
                                            )
                                            .with_text_line_chunk("Line 2")
                                            .build(),
                                    )
                                    .build(),
                            )
                            .with_text_line_chunk("Line 3")
                            .build(),
                    )
                    .build(),
            )
            .with_text_line_chunk("Line 4")
            .build();

        let mut buffer = Vec::new();
        let mut stack = vec![0];
        let mut data = mock_follow_data(&node);

        node.follow_with_choice(0, 0, &mut stack, &mut buffer, &mut data)
            .unwrap();
        node.follow_with_choice(0, 0, &mut stack, &mut buffer, &mut data)
            .unwrap();
        node.follow_with_choice(0, 0, &mut stack, &mut buffer, &mut data)
            .unwrap();

        assert_eq!(buffer.len(), 7);
        assert_eq!(&buffer[3].text, "Line 1");
        assert_eq!(&buffer[4].text, "Line 2");
        assert_eq!(&buffer[5].text, "Line 3");
        assert_eq!(&buffer[6].text, "Line 4");
    }

    #[test]
    fn following_with_stack_that_has_too_large_index_raises_error() {
        let mut node = RootNodeBuilder::empty()
            .with_text_line_chunk("Line 1")
            .build();

        let mut buffer = Vec::new();
        let mut data = mock_follow_data(&node);

        match node.follow(&mut vec![2], &mut buffer, &mut data) {
            Err(InklingError::Internal(InternalError::IncorrectNodeStack(err))) => match err {
                IncorrectNodeStackError::OutOfBounds { .. } => (),
                err => panic!(
                    "expected `IncorrectNodeStackError::OutOfBounds` but got {:?}",
                    err
                ),
            },
            err => panic!(
                "expected `IncorrectNodeStackError::OutOfBounds` but got {:?}",
                err
            ),
        }
    }

    #[test]
    fn following_with_empty_stack_raises_error() {
        let mut node = RootNodeBuilder::empty()
            .with_text_line_chunk("Line 1")
            .build();

        let mut buffer = Vec::new();
        let mut data = mock_follow_data(&node);

        match node.follow(&mut vec![], &mut buffer, &mut data) {
            Err(InklingError::Internal(InternalError::IncorrectNodeStack(err))) => match err {
                IncorrectNodeStackError::EmptyStack => (),
                err => panic!(
                    "expected `IncorrectNodeStackError::EmptyStack` but got {:?}",
                    err
                ),
            },
            err => panic!(
                "expected `IncorrectNodeStackError::EmptyStack` but got {:?}",
                err
            ),
        }
    }
}