awsim-cloudformation 0.4.0

AWS CloudFormation emulator for AWSim
Documentation
use uuid::Uuid;

/// Generate a UUID v4 string.
pub fn new_uuid() -> String {
    Uuid::new_v4().to_string()
}

/// Generate a stack ARN.
pub fn stack_arn(region: &str, account_id: &str, stack_name: &str) -> String {
    let uid = new_uuid();
    format!("arn:aws:cloudformation:{region}:{account_id}:stack/{stack_name}/{uid}")
}

/// Generate a change set ARN.
pub fn change_set_arn(
    region: &str,
    account_id: &str,
    _stack_name: &str,
    change_set_name: &str,
) -> String {
    let uid = new_uuid();
    format!("arn:aws:cloudformation:{region}:{account_id}:changeSet/{change_set_name}/{uid}")
}

/// Current UTC timestamp in ISO 8601 format.
pub fn now_iso8601() -> String {
    use std::time::{SystemTime, UNIX_EPOCH};
    let secs = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs();
    let (y, mo, d, h, min, s) = unix_to_ymd_hms(secs);
    format!("{y:04}-{mo:02}-{d:02}T{h:02}:{min:02}:{s:02}Z")
}

fn unix_to_ymd_hms(secs: u64) -> (u64, u64, u64, u64, u64, u64) {
    let s = secs % 60;
    let mins = secs / 60;
    let min = mins % 60;
    let hours = mins / 60;
    let h = hours % 24;
    let days = hours / 24;
    let (y, doy) = days_to_year(days);
    let (mo, d) = doy_to_month_day(doy, is_leap(y));
    (y, mo, d, h, min, s)
}

fn is_leap(y: u64) -> bool {
    (y.is_multiple_of(4) && !y.is_multiple_of(100)) || y.is_multiple_of(400)
}

fn days_to_year(mut days: u64) -> (u64, u64) {
    let mut y = 1970u64;
    loop {
        let dy = if is_leap(y) { 366 } else { 365 };
        if days < dy {
            return (y, days);
        }
        days -= dy;
        y += 1;
    }
}

fn doy_to_month_day(doy: u64, leap: bool) -> (u64, u64) {
    let months: &[u64] = if leap {
        &[31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    } else {
        &[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    };
    let mut rem = doy;
    for (i, &days) in months.iter().enumerate() {
        if rem < days {
            return ((i + 1) as u64, rem + 1);
        }
        rem -= days;
    }
    (12, 31)
}