vector_core/event/lua/
util.rs

1use chrono::{DateTime, Datelike, TimeZone, Timelike, Utc};
2use mlua::prelude::*;
3
4/// Convert a `DateTime<Utc>` to a `LuaTable`
5///
6/// # Errors
7///
8/// This function will fail insertion into the table fails.
9pub fn timestamp_to_table(lua: &Lua, ts: DateTime<Utc>) -> LuaResult<LuaTable> {
10    let table = lua.create_table()?;
11    table.raw_set("year", ts.year())?;
12    table.raw_set("month", ts.month())?;
13    table.raw_set("day", ts.day())?;
14    table.raw_set("hour", ts.hour())?;
15    table.raw_set("min", ts.minute())?;
16    table.raw_set("sec", ts.second())?;
17    table.raw_set("nanosec", ts.nanosecond())?;
18    table.raw_set("yday", ts.ordinal())?;
19    table.raw_set("wday", ts.weekday().number_from_sunday())?;
20    table.raw_set("isdst", false)?;
21
22    Ok(table)
23}
24
25/// Determines if a `LuaTable` is a timestamp.
26///
27/// # Errors
28///
29/// This function will fail if the table is malformed.
30pub fn table_is_timestamp(t: &LuaTable) -> LuaResult<bool> {
31    for &key in &["year", "month", "day", "hour", "min", "sec"] {
32        if !t.contains_key(key)? {
33            return Ok(false);
34        }
35    }
36    Ok(true)
37}
38
39/// Convert a `LuaTable` to a `DateTime<Utc>`
40///
41/// # Errors
42///
43/// This function will fail if the table is malformed.
44///
45/// # Panics
46///
47/// Panics if the resulting timestamp is invalid.
48#[allow(clippy::needless_pass_by_value)] // constrained by mlua types
49pub fn table_to_timestamp(t: LuaTable) -> LuaResult<DateTime<Utc>> {
50    let year = t.raw_get("year")?;
51    let month = t.raw_get("month")?;
52    let day = t.raw_get("day")?;
53    let hour = t.raw_get("hour")?;
54    let min = t.raw_get("min")?;
55    let sec = t.raw_get("sec")?;
56    let nano = t.raw_get::<Option<u32>>("nanosec")?.unwrap_or(0);
57    Ok(Utc
58        .with_ymd_and_hms(year, month, day, hour, min, sec)
59        .single()
60        .and_then(|t| t.with_nanosecond(nano))
61        .expect("invalid timestamp"))
62}