helm-rs 0.1.2

Typed Rust API for Helm 4: swappable backends, native chart, values and release reading
Documentation
//! The timestamps `yaml.v3` resolves plain scalars to (`parseTimestamp` in `resolve.go`), and the
//! JSON Go writes for a `time.Time` (RFC 3339 with nanoseconds).

use std::fmt;

/// A parsed timestamp: a calendar date, optionally with a time of day and a UTC offset.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(in crate::schema::generate) struct Timestamp {
    year: u32,
    month: u32,
    day: u32,
    hour: u32,
    minute: u32,
    second: u32,
    nanos: u32,
    offset_seconds: i32,
}

impl Timestamp {
    /// Parses `s` with the four layouts `yaml.v3` tries, in its order:
    /// `2006-1-2T15:4:5.999999999Z07:00`, the same with a lower-case `t`,
    /// `2006-1-2 15:4:5.999999999` and `2006-1-2`.
    pub(in crate::schema::generate) fn parse(s: &str) -> Option<Self> {
        let digits = s.bytes().take_while(u8::is_ascii_digit).count();

        if digits != 4 || digits == s.len() || s.as_bytes()[digits] != b'-' {
            return None;
        }

        let bytes = s.as_bytes();
        let mut at = 0;
        let year = number(bytes, &mut at, 4, 4)?;

        expect(bytes, &mut at, b'-')?;

        let month = number(bytes, &mut at, 1, 2)?;

        expect(bytes, &mut at, b'-')?;

        let day = number(bytes, &mut at, 1, 2)?;
        let mut stamp = Self {
            year,
            month,
            day,
            hour: 0,
            minute: 0,
            second: 0,
            nanos: 0,
            offset_seconds: 0,
        };

        if !(1..=12).contains(&month) || day < 1 || day > days_in(month, year) {
            return None;
        }

        if at == bytes.len() {
            return Some(stamp);
        }

        let zoned = match bytes[at] {
            b'T' | b't' => true,
            b' ' => false,
            _ => return None,
        };

        at += 1;
        stamp.hour = number(bytes, &mut at, 1, 2)?;
        expect(bytes, &mut at, b':')?;
        stamp.minute = number(bytes, &mut at, 1, 2)?;
        expect(bytes, &mut at, b':')?;
        stamp.second = number(bytes, &mut at, 1, 2)?;

        if stamp.hour >= 24 || stamp.minute >= 60 || stamp.second >= 60 {
            return None;
        }

        if at + 1 < bytes.len() && bytes[at] == b'.' && bytes[at + 1].is_ascii_digit() {
            at += 1;

            let mut nanos = 0_u32;
            let mut seen = 0;

            while at < bytes.len() && bytes[at].is_ascii_digit() {
                if seen < 9 {
                    nanos = nanos * 10 + u32::from(bytes[at] - b'0');
                    seen += 1;
                }

                at += 1;
            }

            stamp.nanos = nanos * 10_u32.pow(9 - seen);
        }

        if !zoned {
            return (at == bytes.len()).then_some(stamp);
        }

        if &bytes[at..] == b"Z" {
            return Some(stamp);
        }

        let sign = match bytes.get(at)? {
            b'+' => 1,
            b'-' => -1,
            _ => return None,
        };

        at += 1;

        let hours = number(bytes, &mut at, 2, 2)?;

        expect(bytes, &mut at, b':')?;

        let minutes = number(bytes, &mut at, 2, 2)?;

        if at != bytes.len() || hours > 24 || minutes > 59 {
            return None;
        }

        stamp.offset_seconds = sign * i32::try_from(hours * 3600 + minutes * 60).ok()?;

        Some(stamp)
    }
}

impl fmt::Display for Timestamp {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}",
            self.year, self.month, self.day, self.hour, self.minute, self.second
        )?;

        if self.nanos != 0 {
            let fraction = format!("{:09}", self.nanos);

            write!(f, ".{}", fraction.trim_end_matches('0'))?;
        }

        if self.offset_seconds == 0 {
            return write!(f, "Z");
        }

        let sign = if self.offset_seconds < 0 { '-' } else { '+' };
        let magnitude = self.offset_seconds.unsigned_abs();

        write!(
            f,
            "{sign}{:02}:{:02}",
            magnitude / 3600,
            magnitude % 3600 / 60
        )
    }
}

/// Reads between `min` and `max` ASCII digits.
fn number(bytes: &[u8], at: &mut usize, min: usize, max: usize) -> Option<u32> {
    let mut value = 0;
    let mut count = 0;

    while count < max && *at < bytes.len() && bytes[*at].is_ascii_digit() {
        value = value * 10 + u32::from(bytes[*at] - b'0');
        *at += 1;
        count += 1;
    }

    (count >= min).then_some(value)
}

fn expect(bytes: &[u8], at: &mut usize, byte: u8) -> Option<()> {
    if bytes.get(*at) != Some(&byte) {
        return None;
    }

    *at += 1;

    Some(())
}

fn days_in(month: u32, year: u32) -> u32 {
    match month {
        2 if year.is_multiple_of(4) && (!year.is_multiple_of(100) || year.is_multiple_of(400)) => {
            29
        }
        2 => 28,
        4 | 6 | 9 | 11 => 30,
        _ => 31,
    }
}