Skip to main content

stateknot_core/
version.rs

1// Copyright 2026 StateKnot contributors
2// SPDX-License-Identifier: Apache-2.0
3
4//! Canonical semantic versions used to pin durable `StateKnot` contracts.
5
6use std::{fmt, str::FromStr};
7
8use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
9use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
10use thiserror::Error;
11
12const VERSION_PATTERN: &str = "^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)$";
13
14/// A canonical three-component semantic version.
15///
16/// `StateKnot` contract versions intentionally exclude pre-release and build
17/// metadata. Their wire form is exactly `major.minor.patch`, with three `u64`
18/// components and no leading zeroes except for the value zero itself.
19#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
20pub struct Version {
21    major: u64,
22    minor: u64,
23    patch: u64,
24}
25
26impl Version {
27    /// Maximum length of the canonical text representation in bytes.
28    pub const MAX_LEN: usize = 62;
29
30    /// Constructs a version from its numeric components.
31    #[must_use]
32    pub const fn new(major: u64, minor: u64, patch: u64) -> Self {
33        Self {
34            major,
35            minor,
36            patch,
37        }
38    }
39
40    /// Returns the major component.
41    #[must_use]
42    pub const fn major(self) -> u64 {
43        self.major
44    }
45
46    /// Returns the minor component.
47    #[must_use]
48    pub const fn minor(self) -> u64 {
49        self.minor
50    }
51
52    /// Returns the patch component.
53    #[must_use]
54    pub const fn patch(self) -> u64 {
55        self.patch
56    }
57}
58
59impl fmt::Display for Version {
60    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
61        write!(formatter, "{}.{}.{}", self.major, self.minor, self.patch)
62    }
63}
64
65impl FromStr for Version {
66    type Err = VersionError;
67
68    fn from_str(value: &str) -> Result<Self, Self::Err> {
69        if value.len() > Self::MAX_LEN {
70            return Err(VersionError::TooLong {
71                max: Self::MAX_LEN,
72                actual: value.len(),
73            });
74        }
75
76        let mut parts = value.split('.');
77        let major = parse_component(parts.next(), VersionComponent::Major)?;
78        let minor = parse_component(parts.next(), VersionComponent::Minor)?;
79        let patch = parse_component(parts.next(), VersionComponent::Patch)?;
80        if parts.next().is_some() {
81            return Err(VersionError::InvalidFormat);
82        }
83
84        Ok(Self::new(major, minor, patch))
85    }
86}
87
88impl From<(u64, u64, u64)> for Version {
89    fn from((major, minor, patch): (u64, u64, u64)) -> Self {
90        Self::new(major, minor, patch)
91    }
92}
93
94impl From<Version> for (u64, u64, u64) {
95    fn from(value: Version) -> Self {
96        (value.major, value.minor, value.patch)
97    }
98}
99
100impl Serialize for Version {
101    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
102    where
103        S: Serializer,
104    {
105        serializer.collect_str(self)
106    }
107}
108
109impl<'de> Deserialize<'de> for Version {
110    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
111    where
112        D: Deserializer<'de>,
113    {
114        deserializer.deserialize_str(VersionVisitor)
115    }
116}
117
118impl JsonSchema for Version {
119    fn schema_name() -> std::borrow::Cow<'static, str> {
120        "Version".into()
121    }
122
123    fn schema_id() -> std::borrow::Cow<'static, str> {
124        concat!(module_path!(), "::Version").into()
125    }
126
127    fn json_schema(_: &mut SchemaGenerator) -> Schema {
128        json_schema!({
129            "type": "string",
130            "minLength": 5,
131            "maxLength": 62,
132            "pattern": VERSION_PATTERN
133        })
134    }
135
136    fn inline_schema() -> bool {
137        true
138    }
139}
140
141/// The component of a [`Version`] that failed validation.
142#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
143pub enum VersionComponent {
144    /// The major component.
145    Major,
146    /// The minor component.
147    Minor,
148    /// The patch component.
149    Patch,
150}
151
152impl fmt::Display for VersionComponent {
153    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
154        formatter.write_str(match self {
155            Self::Major => "major",
156            Self::Minor => "minor",
157            Self::Patch => "patch",
158        })
159    }
160}
161
162/// Parse failure for a canonical [`Version`].
163#[derive(Clone, Debug, Eq, Error, PartialEq)]
164#[non_exhaustive]
165pub enum VersionError {
166    /// The encoded version exceeded [`Version::MAX_LEN`].
167    #[error("version is {actual} bytes; maximum is {max}")]
168    TooLong {
169        /// Maximum accepted byte length.
170        max: usize,
171        /// Observed byte length.
172        actual: usize,
173    },
174
175    /// The value was not exactly three decimal components.
176    #[error("version must contain exactly three decimal components")]
177    InvalidFormat,
178
179    /// A component used a leading zero.
180    #[error("version {component} component is not canonical")]
181    NonCanonical {
182        /// Component containing the leading zero.
183        component: VersionComponent,
184    },
185
186    /// A component exceeded the `u64` range.
187    #[error("version {component} component exceeds the supported range")]
188    ComponentOverflow {
189        /// Component that overflowed.
190        component: VersionComponent,
191    },
192}
193
194struct VersionVisitor;
195
196impl de::Visitor<'_> for VersionVisitor {
197    type Value = Version;
198
199    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
200        formatter.write_str("a canonical three-component StateKnot version")
201    }
202
203    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
204    where
205        E: de::Error,
206    {
207        value.parse().map_err(E::custom)
208    }
209}
210
211fn parse_component(value: Option<&str>, component: VersionComponent) -> Result<u64, VersionError> {
212    let value = value.ok_or(VersionError::InvalidFormat)?;
213    if value.is_empty() || !value.bytes().all(|byte| byte.is_ascii_digit()) {
214        return Err(VersionError::InvalidFormat);
215    }
216    if value.len() > 1 && value.starts_with('0') {
217        return Err(VersionError::NonCanonical { component });
218    }
219    value
220        .parse()
221        .map_err(|_| VersionError::ComponentOverflow { component })
222}
223
224#[cfg(test)]
225mod tests {
226    use super::*;
227    use serde_json::{Value, from_str, from_value, to_string};
228
229    #[test]
230    fn versions_round_trip_at_numeric_boundaries() {
231        for value in [0, 1, 9, 10, u64::MAX] {
232            let version = Version::new(value, value, value);
233            assert_eq!(version.to_string().parse::<Version>().unwrap(), version);
234            assert_eq!(<(u64, u64, u64)>::from(version), (value, value, value));
235        }
236
237        assert!(Version::new(1, 10, 0) < Version::new(2, 0, 0));
238        assert_eq!(Version::new(1, 2, 3).to_string(), "1.2.3");
239    }
240
241    #[test]
242    fn versions_reject_noncanonical_or_unsupported_forms() {
243        for value in [
244            "",
245            "1",
246            "1.2",
247            "1.2.3.4",
248            "1..3",
249            ".1.2",
250            "1.2.",
251            "v1.2.3",
252            "1.2.3-alpha",
253            "1.2.3+build",
254            "1. 2.3",
255        ] {
256            assert_eq!(value.parse::<Version>(), Err(VersionError::InvalidFormat));
257        }
258
259        assert_eq!(
260            "01.2.3".parse::<Version>(),
261            Err(VersionError::NonCanonical {
262                component: VersionComponent::Major,
263            })
264        );
265        assert_eq!(
266            "1.02.3".parse::<Version>(),
267            Err(VersionError::NonCanonical {
268                component: VersionComponent::Minor,
269            })
270        );
271        assert_eq!(
272            "1.2.03".parse::<Version>(),
273            Err(VersionError::NonCanonical {
274                component: VersionComponent::Patch,
275            })
276        );
277        assert_eq!(
278            "18446744073709551616.0.0".parse::<Version>(),
279            Err(VersionError::ComponentOverflow {
280                component: VersionComponent::Major,
281            })
282        );
283
284        let too_long = format!("{}.0.0", "1".repeat(Version::MAX_LEN));
285        assert_eq!(
286            too_long.parse::<Version>(),
287            Err(VersionError::TooLong {
288                max: Version::MAX_LEN,
289                actual: too_long.len(),
290            })
291        );
292    }
293
294    #[test]
295    fn version_serde_uses_and_enforces_canonical_text() {
296        let version = Version::new(12, 34, 56);
297        let encoded = to_string(&version).unwrap();
298        assert_eq!(encoded, "\"12.34.56\"");
299        assert_eq!(from_str::<Version>(&encoded).unwrap(), version);
300        assert!(from_value::<Version>(Value::Array(Vec::new())).is_err());
301        assert!(from_str::<Version>("\"12.034.56\"").is_err());
302    }
303
304    #[test]
305    fn version_schema_matches_runtime_bounds() {
306        let schema = serde_json::to_value(schemars::schema_for!(Version)).unwrap();
307        assert_eq!(schema["type"], "string");
308        assert_eq!(schema["minLength"], 5);
309        assert_eq!(schema["maxLength"], Version::MAX_LEN);
310        assert_eq!(schema["pattern"], VERSION_PATTERN);
311    }
312}