vector_core/event/lua/
util.rs1use chrono::{DateTime, Datelike, TimeZone, Timelike, Utc};
2use mlua::prelude::*;
3
4pub 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
25pub 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#[allow(clippy::needless_pass_by_value)] pub 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}