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
/*
 * ‌
 * Hedera Rust SDK
 * ​
 * Copyright (C) 2022 - 2023 Hedera Hashgraph, LLC
 * ​
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ‍
 */

use std::fmt;
use std::str::FromStr;

use hedera_proto::services;

use crate::protobuf::{
    FromProtobuf,
    ToProtobuf,
};
use crate::Error;

#[cfg(test)]
mod tests;

/// Hedera follows [semantic versioning](https://semver.org) for both the HAPI protobufs and
/// the Services software.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "ffi", derive(serde::Serialize))]
#[cfg_attr(feature = "ffi", serde(rename_all = "camelCase"))]
pub struct SemanticVersion {
    /// Increases with incompatible API changes
    pub major: u32,

    /// Increases with backwards-compatible new functionality
    pub minor: u32,

    /// Increases with backwards-compatible bug fixes]
    pub patch: u32,

    /// A pre-release version MAY be denoted by appending a hyphen and a series of dot separated identifiers (<https://semver.org/#spec-item-9>);
    /// so given a semver 0.14.0-alpha.1+21AF26D3, this field would contain ‘alpha.1’
    #[cfg_attr(feature = "ffi", serde(skip_serializing_if = "String::is_empty"))]
    pub prerelease: String,

    /// Build metadata MAY be denoted by appending a plus sign and a series of dot separated identifiers
    /// immediately following the patch or pre-release version (<https://semver.org/#spec-item-10>);
    /// so given a semver 0.14.0-alpha.1+21AF26D3, this field would contain ‘21AF26D3’
    #[cfg_attr(feature = "ffi", serde(skip_serializing_if = "String::is_empty"))]
    pub build: String,
}

impl fmt::Display for SemanticVersion {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}.{}.{}", self.major, self.minor, self.patch)?;
        if !self.prerelease.is_empty() {
            write!(f, "-{}", &self.prerelease)?;
        }

        if !self.build.is_empty() {
            write!(f, "+{}", &self.build)?;
        }

        Ok(())
    }
}

fn is_valid_ident_char(ch: char) -> bool {
    ch.is_ascii_alphanumeric() || ch == '-'
}

/// Returns true if this is a numeric string, and it starts with `"0"`, and isn't exactly `"0"`
fn is_numeric_with_leading_zero(s: &str) -> bool {
    s.strip_prefix('0')
        .map_or(false, |rest| !rest.is_empty() && rest.chars().all(|it| it.is_ascii_digit()))
}

fn parse_version(s: &str, name: &str) -> crate::Result<u32> {
    if is_numeric_with_leading_zero(s) {
        return Err(Error::basic_parse(format!(
            "semver section `{name}` starts with leading 0: `{s}`"
        )));
    }

    s.parse().map_err(Error::basic_parse)
}

fn parse_prerelease(s: &str) -> crate::Result<String> {
    if s.is_empty() {
        return Err(Error::basic_parse("semver with empty rerelease"));
    }

    for identifier in s.split('.') {
        if identifier.is_empty() {
            return Err(Error::basic_parse("semver with empty -pre identifier"));
        }

        if !identifier.chars().all(is_valid_ident_char) {
            return Err(Error::basic_parse(
                "semver with invalid identifier for the -pre section: `{identifier}`",
            ));
        }

        if is_numeric_with_leading_zero(identifier) {
            return Err(Error::basic_parse(
                "numeric pre-release identifier has leading zero: `{identifier}`",
            ));
        }
    }

    Ok(s.to_owned())
}

fn parse_build(s: &str) -> crate::Result<String> {
    if s.is_empty() {
        return Err(Error::basic_parse("semver with empty build"));
    }

    for identifier in s.split('.') {
        if identifier.is_empty() {
            return Err(Error::basic_parse("semver with empty build-section identifier"));
        }

        if !identifier.chars().all(is_valid_ident_char) {
            return Err(Error::basic_parse(
                "semver with invalid identifier for the build section: `{identifier}",
            ));
        }
    }

    Ok(s.to_owned())
}

impl FromStr for SemanticVersion {
    type Err = Error;

    // its probably useless doing strict parsing when Hedera probably accepts loose parsing anyway, but lets at least *try* not to make it worse.
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let parts: Vec<&str> = s.splitn(3, '.').collect();

        match &*parts {
            [major, minor, rest] => {
                let (patch, pre, build) = {
                    // while it seems like this is a weird order,
                    // it actually makes more sense than `pre` first,
                    // because `pre` is in the middle of the string.
                    let (rest, build) = match rest.split_once('+') {
                        Some((rest, build)) => (rest, Some(build)),
                        None => (*rest, None),
                    };

                    let (patch, pre) = match rest.split_once('-') {
                        Some((patch, pre)) => (patch, Some(pre)),
                        None => (rest, None),
                    };

                    (patch, pre, build)
                };

                let major = parse_version(major, "major")?;
                let minor = parse_version(minor, "minor")?;
                let patch = parse_version(patch, "patch")?;

                let prerelease = match pre {
                    Some(it) => parse_prerelease(it)?,
                    None => String::new(),
                };

                let build = match build {
                    Some(it) => parse_build(it)?,
                    None => String::new(),
                };

                Ok(Self { major, minor, patch, prerelease, build })
            }
            _ => Err(Error::basic_parse("expected major.minor.patch for semver")),
        }
    }
}

impl SemanticVersion {
    /// Create a new `SemanticVersion` from protobuf-encoded `bytes`.
    ///
    /// # Errors
    /// - [`Error::FromProtobuf`](crate::Error::FromProtobuf) if decoding the bytes fails to produce a valid protobuf.
    /// - [`Error::FromProtobuf`](crate::Error::FromProtobuf) if decoding the protobuf fails.
    pub fn from_bytes(bytes: &[u8]) -> crate::Result<Self> {
        FromProtobuf::from_bytes(bytes)
    }

    /// Convert `self` to a protobuf-encoded [`Vec<u8>`].
    #[must_use]
    pub fn to_bytes(&self) -> Vec<u8> {
        ToProtobuf::to_bytes(self)
    }
}

impl FromProtobuf<services::SemanticVersion> for SemanticVersion {
    fn from_protobuf(pb: services::SemanticVersion) -> crate::Result<Self>
    where
        Self: Sized,
    {
        Ok(Self {
            major: pb.major as u32,
            minor: pb.minor as u32,
            patch: pb.patch as u32,
            prerelease: pb.pre,
            build: pb.build,
        })
    }
}

impl ToProtobuf for SemanticVersion {
    type Protobuf = services::SemanticVersion;
    fn to_protobuf(&self) -> Self::Protobuf {
        Self::Protobuf {
            major: self.major as i32,
            minor: self.minor as i32,
            patch: self.patch as i32,
            pre: self.prerelease.clone(),
            build: self.build.clone(),
        }
    }
}