Skip to main content

lua_protobuf_rs/
runtime_type.rs

1use crate::descriptor::enum_descriptor::LuaEnumDescriptor;
2use crate::descriptor::message_descriptor::LuaMessageDescriptor;
3use derive_more::{Deref, From, Into};
4use mlua::UserDataMethods;
5use mlua::prelude::LuaUserData;
6use protobuf::reflect::RuntimeType;
7use std::ops::Deref;
8
9#[derive(Debug, Clone, Eq, PartialEq, Deref, From, Into)]
10pub struct LuaRuntimeType(pub RuntimeType);
11
12impl LuaUserData for LuaRuntimeType {
13    fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
14        methods.add_method("is_i32", |_, this, ()| {
15            Ok(matches!(this.deref(), RuntimeType::I32))
16        });
17
18        methods.add_method("is_i64", |_, this, ()| {
19            Ok(matches!(this.deref(), RuntimeType::I64))
20        });
21
22        methods.add_method("is_u32", |_, this, ()| {
23            Ok(matches!(this.deref(), RuntimeType::U32))
24        });
25
26        methods.add_method("is_u64", |_, this, ()| {
27            Ok(matches!(this.deref(), RuntimeType::U64))
28        });
29
30        methods.add_method("is_f32", |_, this, ()| {
31            Ok(matches!(this.deref(), RuntimeType::F32))
32        });
33
34        methods.add_method("is_f64", |_, this, ()| {
35            Ok(matches!(this.deref(), RuntimeType::F64))
36        });
37
38        methods.add_method("is_bool", |_, this, ()| {
39            Ok(matches!(this.deref(), RuntimeType::Bool))
40        });
41
42        methods.add_method("is_string", |_, this, ()| {
43            Ok(matches!(this.deref(), RuntimeType::String))
44        });
45
46        methods.add_method("is_vec_u8", |_, this, ()| {
47            Ok(matches!(this.deref(), RuntimeType::VecU8))
48        });
49
50        methods.add_method("is_enum", |_, this, ()| {
51            Ok(matches!(this.deref(), RuntimeType::Enum(_)))
52        });
53
54        methods.add_method("get_enum", |_, this, ()| {
55            if let RuntimeType::Enum(descriptor) = this.deref() {
56                let descriptor: LuaEnumDescriptor = From::from(descriptor.clone());
57                Ok(Some(descriptor))
58            } else {
59                Ok(None)
60            }
61        });
62
63        methods.add_method("is_message", |_, this, ()| {
64            Ok(matches!(this.deref(), RuntimeType::Message(_)))
65        });
66
67        methods.add_method("get_message", |_, this, ()| {
68            if let RuntimeType::Message(message) = this.deref() {
69                let descriptor: LuaMessageDescriptor = From::from(message.clone());
70                Ok(Some(descriptor))
71            } else {
72                Ok(None)
73            }
74        });
75    }
76}