razeri-plugin-contract 0.13.0

The dialect contract Razeri plugins are written against — rendering traits, data types, platform identity
Documentation
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
// Copyright (C) 2026 Gabriel Shea
// Licensed under either of the Apache License, Version 2.0 or the MIT
// license, at your option.

//! **A version of an engine**, and the platform name that carries one.
//!
//! A platform is an engine at a version: `postgres`, or `postgres@17`. The
//! engine's name comes first, and after the last `@` the version the design is
//! for. A version is digits, with dots where the vendor uses them (`8.4`), and
//! letters only after the last digit, where the vendor's own name has them
//! (`23ai`).
//!
//! Two spellings are refused before anything else reads them, because the
//! scans that keep private names out of a release would refuse them too:
//!
//! - a dot before letters, `oracle@23.ai`, is the shape of a mail address, and
//!   the accepted spelling is shown: `oracle@23ai`;
//! - a colon, `postgres:17`, is the shape of a host and its port, and the
//!   accepted spelling is shown: `postgres@17`.

use std::cmp::Ordering;
use std::fmt;
use std::hash::{Hash, Hasher};

/// The most characters a version is written in.
const LONGEST: usize = 16;

/// The most numbers a version holds: `2.00.088` is three.
const MOST_NUMBERS: usize = 4;

/// **A version of an engine**: `17`, `8.4`, `2022`, `23ai`.
///
/// Ordered by its numbers, the missing ones read as zero, so `8.4` is newer
/// than `8` and the same as `8.4.0`. The letters after the last digit are
/// part of how the vendor writes it and not of its order: `23ai` and `23` are
/// one version, and a dialect that declares `23ai` answers to `oracle@23` too.
///
/// It is displayed as it was written, so a refusal and a manifest say the
/// version in the user's words.
///
/// ```
/// use razeri_plugin_contract::EngineVersion;
///
/// let floor = EngineVersion::declared("15");
/// let asked: EngineVersion = "17".parse().unwrap();
/// assert!(floor < asked);
/// assert_eq!(asked.to_string(), "17");
/// assert_eq!("23ai".parse::<EngineVersion>().unwrap(), "23".parse().unwrap());
/// ```
#[derive(Clone, Copy)]
pub struct EngineVersion {
    written: [u8; LONGEST],
    length: usize,
    numbers: [u32; MOST_NUMBERS],
}

/// **Why a spelling is not a version**, with the spelling that is, where there
/// is one.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EngineVersionError {
    /// Nothing after the `@`.
    Empty,
    /// A colon: the shape of a host and its port.
    Colon {
        /// The version with the colon taken out, or `None` when nothing is
        /// left.
        accepted: Option<String>,
    },
    /// Letters after a dot: the shape of a mail address.
    DotBeforeLetters {
        /// The same version with the dot before the letters taken out.
        accepted: String,
    },
    /// Anything else that is not digits, dots and trailing letters.
    NotAVersion,
}

impl fmt::Display for EngineVersionError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Empty => f.write_str("there is no version after the `@`"),
            Self::Colon { accepted: Some(accepted) } => write!(
                f,
                "a version never holds a colon, which is how a host and its port are written; \
                 write `{accepted}`"
            ),
            Self::Colon { accepted: None } => f.write_str(
                "a version never holds a colon, which is how a host and its port are written",
            ),
            Self::DotBeforeLetters { accepted } => write!(
                f,
                "a version has no dot before its letters, which is how a mail address is \
                 written; write `{accepted}`"
            ),
            Self::NotAVersion => f.write_str(
                "a version is digits, with dots where the vendor uses them and letters only after \
                 the last digit, like `17`, `8.4` or `23ai`",
            ),
        }
    }
}

impl std::error::Error for EngineVersionError {}

/// What [`EngineVersion::read`] found wrong, before the sentence is written.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Fault {
    Empty,
    Colon,
    DotBeforeLetters,
    NotAVersion,
}

impl EngineVersion {
    /// **A version a dialect declares**, read when the program is compiled.
    ///
    /// A spelling that is not a version stops the build, so a dialect's
    /// declared list can be a `const`:
    ///
    /// ```
    /// use razeri_plugin_contract::EngineVersion;
    ///
    /// const VERSIONS: &[EngineVersion] =
    ///     &[EngineVersion::declared("15"), EngineVersion::declared("17")];
    /// assert_eq!(VERSIONS[0].to_string(), "15");
    /// ```
    ///
    /// # Panics
    ///
    /// When `spelling` is not a version; in a `const`, that is a compile
    /// error.
    #[must_use]
    pub const fn declared(spelling: &str) -> Self {
        match Self::read(spelling) {
            Ok(version) => version,
            Err(_) => panic!("a declared version is digits, dots and trailing letters"),
        }
    }

    /// Read a version written by a user.
    ///
    /// # Errors
    ///
    /// [`EngineVersionError`] naming what is wrong and, where there is one,
    /// the spelling that is accepted.
    pub fn parse(spelling: &str) -> Result<Self, EngineVersionError> {
        match Self::read(spelling) {
            Ok(version) => Ok(version),
            Err(Fault::Empty) => Err(EngineVersionError::Empty),
            Err(Fault::Colon) => Err(EngineVersionError::Colon { accepted: None }),
            Err(Fault::NotAVersion) => Err(EngineVersionError::NotAVersion),
            Err(Fault::DotBeforeLetters) => {
                let accepted = without_dots_before_letters(spelling);
                if Self::read(&accepted).is_ok() {
                    Err(EngineVersionError::DotBeforeLetters { accepted })
                } else {
                    Err(EngineVersionError::NotAVersion)
                }
            }
        }
    }

    /// The reading both [`Self::declared`] and [`Self::parse`] share. It
    /// runs when a dialect is compiled, so what it says is wrong is a word,
    /// and [`Self::parse`] writes the sentence.
    const fn read(spelling: &str) -> Result<Self, Fault> {
        let bytes = spelling.as_bytes();
        if bytes.is_empty() {
            return Err(Fault::Empty);
        }
        let mut at = 0;
        while at < bytes.len() {
            if bytes[at] == b':' {
                return Err(Fault::Colon);
            }
            at += 1;
        }
        if bytes.len() > LONGEST {
            return Err(Fault::NotAVersion);
        }
        let mut written = [0u8; LONGEST];
        let mut numbers = [0u32; MOST_NUMBERS];
        let mut part = 0;
        let mut digits = 0;
        let mut lettered = false;
        let mut at = 0;
        while at < bytes.len() {
            let byte = bytes[at];
            written[at] = byte;
            if byte.is_ascii_digit() {
                if lettered || numbers[part] > (u32::MAX - 9) / 10 {
                    return Err(Fault::NotAVersion);
                }
                numbers[part] = numbers[part] * 10 + (byte - b'0') as u32;
                digits += 1;
            } else if byte == b'.' {
                if digits == 0 || lettered {
                    return Err(Fault::NotAVersion);
                }
                if at + 1 < bytes.len() && bytes[at + 1].is_ascii_alphabetic() {
                    return Err(Fault::DotBeforeLetters);
                }
                part += 1;
                digits = 0;
                if part == MOST_NUMBERS {
                    return Err(Fault::NotAVersion);
                }
            } else if byte.is_ascii_alphabetic() {
                if digits == 0 {
                    return Err(Fault::NotAVersion);
                }
                lettered = true;
            } else {
                return Err(Fault::NotAVersion);
            }
            at += 1;
        }
        if digits == 0 {
            return Err(Fault::NotAVersion);
        }
        Ok(Self { written, length: bytes.len(), numbers })
    }

    /// The version as it was written.
    #[must_use]
    pub fn as_str(&self) -> &str {
        // Only ASCII digits, dots and letters are ever written here.
        std::str::from_utf8(&self.written[..self.length]).unwrap_or_default()
    }

    /// The numbers of the version, the missing ones zero: `8.4` is
    /// `[8, 4, 0, 0]`.
    #[must_use]
    pub const fn numbers(&self) -> [u32; MOST_NUMBERS] {
        self.numbers
    }
}

impl std::str::FromStr for EngineVersion {
    type Err = EngineVersionError;

    fn from_str(spelling: &str) -> Result<Self, Self::Err> {
        Self::parse(spelling)
    }
}

impl PartialEq for EngineVersion {
    fn eq(&self, other: &Self) -> bool {
        self.numbers == other.numbers
    }
}

impl Eq for EngineVersion {}

impl PartialOrd for EngineVersion {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for EngineVersion {
    fn cmp(&self, other: &Self) -> Ordering {
        self.numbers.cmp(&other.numbers)
    }
}

impl Hash for EngineVersion {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.numbers.hash(state);
    }
}

impl fmt::Display for EngineVersion {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl fmt::Debug for EngineVersion {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "EngineVersion({})", self.as_str())
    }
}

impl serde::Serialize for EngineVersion {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(self.as_str())
    }
}

/// **A platform name, read into the engine and the version it is for.**
///
/// `postgres@17` is the engine `postgres` at version `17`; `postgres` is the
/// engine with no version named. The name is split on its last `@`, so the
/// engine's own name is never cut short.
///
/// Parameters:
/// - `platform`: the name as a design or a `--target` writes it.
///
/// # Errors
///
/// [`EngineVersionError`] when the version is not one, and
/// [`EngineVersionError::Colon`] for a colon anywhere in the name, with the
/// spelling that is accepted: `postgres:17` reads as `postgres@17`.
pub fn split_platform(platform: &str) -> Result<(&str, Option<EngineVersion>), EngineVersionError> {
    let platform = platform.trim();
    if platform.contains(':') {
        // `postgres:17` is the `@` written as a host's port; the fix is the
        // `@`, where that reads as a version.
        let accepted = match platform.split_once(':') {
            Some((engine, version))
                if !engine.contains('@') && EngineVersion::read(version).is_ok() =>
            {
                Some(format!("{engine}@{version}"))
            }
            _ => None,
        };
        return Err(EngineVersionError::Colon { accepted });
    }
    let Some((engine, version)) = platform.rsplit_once('@') else {
        return Ok((platform, None));
    };
    match EngineVersion::parse(version) {
        Ok(version) => Ok((engine, Some(version))),
        Err(EngineVersionError::DotBeforeLetters { accepted }) => {
            Err(EngineVersionError::DotBeforeLetters { accepted: format!("{engine}@{accepted}") })
        }
        Err(other) => Err(other),
    }
}

/// `23.ai` written `23ai`: every dot that comes before a letter taken out.
fn without_dots_before_letters(spelling: &str) -> String {
    let mut out = String::with_capacity(spelling.len());
    let mut chars = spelling.chars().peekable();
    while let Some(c) = chars.next() {
        if c == '.' && chars.peek().is_some_and(char::is_ascii_alphabetic) {
            continue;
        }
        out.push(c);
    }
    out
}
#[cfg(test)]
mod tests {
    use super::*;

    fn read(spelling: &str) -> EngineVersion {
        EngineVersion::parse(spelling).unwrap_or_else(|e| panic!("{spelling}: {e}"))
    }

    #[test]
    fn the_four_shapes_a_vendor_writes_are_versions_and_display_as_written() {
        for spelling in ["17", "8.4", "2022", "23ai", "2.00.088"] {
            assert_eq!(read(spelling).to_string(), spelling);
        }
    }

    #[test]
    fn versions_are_ordered_by_their_numbers() {
        assert!(read("15") < read("16"));
        assert!(read("16") < read("17"));
        assert!(read("8") < read("8.4"));
        assert!(read("8.4") < read("8.10"));
        assert!(read("19") < read("23ai"));
        assert_eq!(read("8.4"), read("8.4.0"));
    }

    #[test]
    fn the_letters_are_how_the_vendor_writes_it_and_not_its_order() {
        assert_eq!(read("23ai"), read("23"));
        assert_eq!(read("23ai").to_string(), "23ai");
    }

    #[test]
    fn a_declared_version_reads_the_same_as_a_written_one() {
        const FLOOR: EngineVersion = EngineVersion::declared("15");
        assert_eq!(FLOOR, read("15"));
        assert_eq!(FLOOR.to_string(), "15");
    }

    #[test]
    fn a_dot_before_letters_is_refused_showing_the_accepted_spelling() {
        assert_eq!(
            EngineVersion::parse("23.ai"),
            Err(EngineVersionError::DotBeforeLetters { accepted: "23ai".to_owned() })
        );
        let said = EngineVersion::parse("23.ai").unwrap_err().to_string();
        assert!(said.contains("`23ai`"), "{said}");
        assert!(said.contains("mail address"), "{said}");
    }

    #[test]
    fn a_colon_is_refused() {
        assert!(matches!(EngineVersion::parse("17:5432"), Err(EngineVersionError::Colon { .. })));
    }

    #[test]
    fn what_is_not_a_version_is_refused() {
        for spelling in ["latest", "v17", "17-beta", "17 ", ".17", "17.", "1..2", "1.2.3.4.5"] {
            assert_eq!(
                EngineVersion::parse(spelling),
                Err(EngineVersionError::NotAVersion),
                "{spelling}"
            );
        }
        assert_eq!(EngineVersion::parse(""), Err(EngineVersionError::Empty));
        assert_eq!(
            EngineVersion::parse("12345678901234567"),
            Err(EngineVersionError::NotAVersion),
            "longer than any vendor writes one"
        );
    }

    #[test]
    fn a_platform_name_splits_on_its_last_at() {
        assert_eq!(split_platform("postgres"), Ok(("postgres", None)));
        assert_eq!(split_platform("postgres@17"), Ok(("postgres", Some(read("17")))));
        assert_eq!(split_platform(" oracle@23ai "), Ok(("oracle", Some(read("23ai")))));
        assert_eq!(split_platform("my@db@8.4"), Ok(("my@db", Some(read("8.4")))));
    }

    #[test]
    fn a_platform_name_with_a_colon_is_refused_showing_the_at() {
        assert_eq!(
            split_platform("postgres:17"),
            Err(EngineVersionError::Colon { accepted: Some("postgres@17".to_owned()) })
        );
        assert!(matches!(split_platform("postgres@17:1"), Err(EngineVersionError::Colon { .. })));
    }

    #[test]
    fn a_platform_name_with_a_dot_before_letters_is_refused_showing_the_accepted_name() {
        assert_eq!(
            split_platform("oracle@23.ai"),
            Err(EngineVersionError::DotBeforeLetters { accepted: "oracle@23ai".to_owned() })
        );
    }

    #[test]
    fn a_version_serializes_as_it_was_written() {
        let json = serde_json::to_string(&[read("15"), read("23ai")]).unwrap();
        assert_eq!(json, r#"["15","23ai"]"#);
    }
}