1use config::{any_err, get_or_create_sub_module};
2use mlua::{Lua, MetaMethod, UserData, UserDataFields, UserDataMethods};
3use uuid::Uuid;
4
5struct WrappedUuid(Uuid);
6
7impl UserData for WrappedUuid {
8 fn add_fields<F: UserDataFields<Self>>(fields: &mut F) {
9 fields.add_field_method_get("hyphenated", |_, this| {
10 Ok(format!("{}", this.0.as_hyphenated()))
11 });
12 fields.add_field_method_get("simple", |_, this| Ok(format!("{}", this.0.as_simple())));
13 fields.add_field_method_get("braced", |_, this| Ok(format!("{}", this.0.as_braced())));
14 fields.add_field_method_get("urn", |_, this| Ok(format!("{}", this.0.as_urn())));
15 fields.add_field_method_get("bytes", |lua, this| lua.create_string(this.0.as_bytes()));
16 }
17
18 fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
19 methods.add_meta_method(MetaMethod::ToString, |_, this, _: ()| {
20 Ok(format!("{}", this.0.as_hyphenated()))
21 });
22 }
23}
24
25pub fn register(lua: &Lua) -> anyhow::Result<()> {
26 let uuid_mod = get_or_create_sub_module(lua, "uuid")?;
27
28 uuid_mod.set(
29 "parse",
30 lua.create_function(|_, s: String| Ok(WrappedUuid(Uuid::try_parse(&s).map_err(any_err)?)))?,
31 )?;
32
33 uuid_mod.set(
34 "new_v1",
35 lua.create_function(|_, _: ()| Ok(WrappedUuid(uuid_helper::now_v1())))?,
36 )?;
37 uuid_mod.set(
38 "new_v4",
39 lua.create_function(|_, _: ()| Ok(WrappedUuid(Uuid::new_v4())))?,
40 )?;
41 uuid_mod.set(
42 "new_v6",
43 lua.create_function(|_, _: ()| {
44 Ok(WrappedUuid(Uuid::now_v6(uuid_helper::get_mac_address())))
45 })?,
46 )?;
47 uuid_mod.set(
48 "new_v7",
49 lua.create_function(|_, _: ()| Ok(WrappedUuid(Uuid::now_v7())))?,
50 )?;
51
52 Ok(())
53}