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
/*
    Appellation: moves <module>
    Contrib: FL03 <jo3mccain@icloud.com>
    Description:
        The Move enum is used to represent the direction of a Turing machine's
        head. It is used in the instruction set to determine the next state of
        the machine.
*/
use crate::{Symbolic, Tape};
use contained_core::ArrayLike;
use serde::{Deserialize, Serialize};
use strum::{Display, EnumString, EnumVariantNames};

#[derive(
    Clone,
    Copy,
    Debug,
    Default,
    Deserialize,
    Display,
    EnumString,
    EnumVariantNames,
    Eq,
    Hash,
    Ord,
    PartialEq,
    PartialOrd,
    Serialize,
)]
#[repr(i64)]
#[strum(serialize_all = "snake_case")]
pub enum Move {
    Left = -1,
    Right = 1,
    #[default]
    Stay = 0,
}

impl Move {
    pub fn invert(&self) -> Self {
        match self {
            Self::Left => Self::Right,
            Self::Right => Self::Left,
            Self::Stay => Self::Stay,
        }
    }
    pub fn apply<S: Symbolic>(
        &self,
        mut index: usize,
        mut tape: Tape<S>,
        elem: S,
    ) -> (usize, Tape<S>) {
        match *self {
            // If the current position is 0, insert a new element at the top of the vector
            Move::Left if index == 0 => {
                tape[index] = elem;
            }
            Move::Left => {
                index -= 1;
            }
            Move::Right => {
                index += 1;

                if index == tape.len() {
                    tape[index] = elem;
                }
            }
            Move::Stay => {}
        };
        (index, tape.clone())
    }
    pub fn shift(&self, pos: usize) -> usize {
        (pos as i64 + *self as i64) as usize
    }
}

impl std::ops::Mul<Move> for usize {
    type Output = usize;

    fn mul(self, rhs: Move) -> Self::Output {
        rhs.shift(self)
    }
}

impl From<i64> for Move {
    fn from(d: i64) -> Self {
        match d % 2 {
            -1 => Self::Left,
            1 => Self::Right,
            _ => Self::Stay,
        }
    }
}

impl From<Move> for i64 {
    fn from(d: Move) -> i64 {
        d as i64
    }
}

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

    #[test]
    fn test_move_default() {
        let a = Move::default();
        assert_eq!(a.clone(), Move::Stay);
    }
}