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
use {
    crate::{
        errors::NetError,
        command::Sequence,
    },
    std::{
        io::{
            self,
            BufRead,
            Write,
        },
    },
};

/// A message which may be sent by a client or server to the other part
#[derive(Debug)]
pub enum Message {
    Command(String),
    Hi,
    GetRoot,
    Root(String),
    Sequence(Sequence),
}

fn read_line<BR: BufRead>(r: &mut BR) -> Result<String, NetError> {
    let mut line = String::new();
    r.read_line(&mut line)?;
    debug!("read line => {:?}", &line);
    while line.ends_with('\n') || line.ends_with('\r') {
        line.pop();
    }
    Ok(line)
}

impl Message {
    pub fn read<BR: BufRead>(r: &mut BR) -> Result<Self, NetError> {
        // the first line gives the type of message
        match read_line(r)?.as_ref() {
            "CMD" => Ok(Self::Command(read_line(r)?)),
            "GET_ROOT" => Ok(Self::GetRoot),
            "ROOT" => Ok(Self::Root(read_line(r)?)),
            "SEQ" => Ok(Self::Sequence(Sequence::new(
                read_line(r)?,
                Some(read_line(r)?),
            ))),
            _ => Err(NetError::InvalidMessage),
        }
    }
    pub fn write<W: Write>(&self, w: &mut W) -> io::Result<()> {
        match self {
            Self::Command(c) => {
                writeln!(w, "CMD")?;
                writeln!(w, "{c}")
            }
            Self::GetRoot => {
                writeln!(w, "GET_ROOT")
            }
            Self::Hi => {
                writeln!(w, "HI")
            }
            Self::Root(path) => {
                writeln!(w, "ROOT")?;
                writeln!(w, "{path}")
            }
            Self::Sequence(Sequence { separator, raw }) => {
                writeln!(w, "SEQ")?;
                writeln!(w, "{raw}")?;
                writeln!(w, "{separator}")
            }
        }
    }
}