1
use std::{fmt::Display, str::FromStr};
2

            
3
use jetstream_wireformat::{JetStreamWireFormat, WireFormat};
4

            
5
use crate::Framer;
6

            
7
pub const TVERSION: u8 = 100;
8
pub const RVERSION: u8 = TVERSION + 1;
9

            
10
/// version -- negotiate protocol version
11
///
12
/// ```text
13
/// size[4] Tversion tag[2] msize[4] version[s]
14
/// ```
15
///
16
/// version establishes the msize, which is the maximum message size inclusive of the size value that can be handled by both client and server.
17
///
18
/// It also establishes the protocol version. For 9P2000.L version must be the string 9P2000.L.
19
///
20
/// See the Plan 9 manual page for [version(5)](http://9p.io/magic/man2html/5/version).
21
#[derive(Debug, JetStreamWireFormat)]
22
pub struct Tversion {
23
    pub msize: u32,
24
    pub version: String,
25
}
26

            
27
/// version -- negotiate protocol version
28
///
29
/// ```text
30
/// size[4] Rversion tag[2] msize[4] version[s]
31
/// ```
32
///
33
/// version establishes the msize, which is the maximum message size inclusive of the size value that can be handled by both client and server.
34
///
35
/// It also establishes the protocol version. For 9P2000.L version must be the string 9P2000.L.
36
///
37
/// See the Plan 9 manual page for [version(5)](http://9p.io/magic/man2html/5/version).
38
#[derive(Debug, JetStreamWireFormat)]
39
pub struct Rversion {
40
    pub msize: u32,
41
    pub version: String,
42
}
43

            
44
#[derive(Debug)]
45
pub enum VersionFrame {
46
    Tversion(Tversion),
47
    Rversion(Rversion),
48
}
49

            
50
impl Framer for VersionFrame {
51
28
    fn message_type(&self) -> u8 {
52
28
        match self {
53
            VersionFrame::Tversion(_) => TVERSION,
54
28
            VersionFrame::Rversion(_) => RVERSION,
55
        }
56
28
    }
57

            
58
28
    fn byte_size(&self) -> u32 {
59
28
        match self {
60
            VersionFrame::Tversion(tversion) => tversion.byte_size(),
61
28
            VersionFrame::Rversion(rversion) => rversion.byte_size(),
62
        }
63
28
    }
64

            
65
26
    fn encode<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()> {
66
26
        match self {
67
            VersionFrame::Tversion(tversion) => tversion.encode(writer),
68
26
            VersionFrame::Rversion(rversion) => rversion.encode(writer),
69
        }
70
26
    }
71

            
72
26
    fn decode<R: std::io::Read>(
73
26
        reader: &mut R,
74
26
        ty: u8,
75
26
    ) -> std::io::Result<Self> {
76
26
        match ty {
77
            TVERSION => {
78
26
                let tversion = Tversion::decode(reader)?;
79
26
                Ok(VersionFrame::Tversion(tversion))
80
            }
81
            RVERSION => {
82
                let rversion = Rversion::decode(reader)?;
83
                Ok(VersionFrame::Rversion(rversion))
84
            }
85
            _ => Err(std::io::Error::new(
86
                std::io::ErrorKind::InvalidData,
87
                format!("Invalid version frame type: {}", ty),
88
            )),
89
        }
90
26
    }
91
}
92

            
93
#[derive(Debug, PartialEq, Eq)]
94
pub enum Version {
95
    V9P2000L,
96
    V9P2000,
97
    /// example rs.jetstream.proto/echohttp/15.0.0+bfd7d20e
98
    JetStream {
99
        name: String,
100
        version: semver::Version,
101
    },
102
}
103

            
104
impl Display for Version {
105
28
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
106
28
        match self {
107
            Version::V9P2000L => write!(f, "9P2000.L"),
108
            Version::V9P2000 => write!(f, "9P2000"),
109
            Version::JetStream { name, version } => {
110
28
                write!(f, "rs.jetstream.proto/{}/{}", name, version)
111
            }
112
        }
113
28
    }
114
}
115

            
116
impl TryFrom<VersionFrame> for Version {
117
    type Error = String;
118

            
119
    fn try_from(value: VersionFrame) -> Result<Self, Self::Error> {
120
        match value {
121
            VersionFrame::Tversion(tversion) => {
122
                Version::from_str(&tversion.version)
123
            }
124
            VersionFrame::Rversion(rversion) => {
125
                Version::from_str(&rversion.version)
126
            }
127
        }
128
    }
129
}
130

            
131
impl FromStr for Version {
132
    type Err = String;
133

            
134
28
    fn from_str(s: &str) -> Result<Self, Self::Err> {
135
28
        match s {
136
            "9P2000.L" => Ok(Version::V9P2000L),
137
            "9P2000" => Ok(Version::V9P2000),
138
            //example rs.jetstream.proto/echohttp/15.0.0+bfd7d20e
139
28
            s if s.starts_with("rs.jetstream.proto") => {
140
28
                let parts: Vec<&str> = s.split('/').collect();
141
28
                if parts.len() != 3 {
142
                    return Err(format!(
143
                        "Invalid JetStream version format: {}",
144
                        s
145
                    ));
146
28
                }
147
28
                let name = parts[1].to_string();
148
28
                let version_str = parts[2];
149
28
                let version = semver::Version::parse(version_str).map_err(|e| {
150
                    format!("Invalid semver version in JetStream version: {}: {}", version_str, e)
151
                })?;
152
28
                Ok(Version::JetStream { name, version })
153
            }
154
            _ => Err(format!("Unknown version string: {}", s)),
155
        }
156
28
    }
157
}
158

            
159
#[cfg(test)]
160
mod tests {
161
    use super::*;
162

            
163
    #[test]
164
    fn version_from_str() {
165
        assert_eq!(Version::from_str("9P2000.L").unwrap(), Version::V9P2000L);
166
        assert_eq!(Version::from_str("9P2000").unwrap(), Version::V9P2000);
167
        assert_eq!(
168
            Version::from_str("rs.jetstream.proto/echohttp/15.0.0+bfd7d20e")
169
                .unwrap(),
170
            Version::JetStream {
171
                name: "echohttp".to_string(),
172
                version: semver::Version::parse("15.0.0+bfd7d20e").unwrap(),
173
            }
174
        );
175

            
176
        assert!(Version::from_str("invalid").is_err());
177
    }
178
}