|
| 1 | +use std::result::Result as StdResult; |
| 2 | +use std::sync::Arc; |
| 3 | + |
| 4 | +use mlua::{ |
| 5 | + AnyUserData, Error as LuaError, ExternalResult, Function, Integer as LuaInteger, IntoLuaMulti, Lua, |
| 6 | + LuaSerdeExt, MetaMethod, MultiValue, Result, String as LuaString, Table, UserData, UserDataMethods, |
| 7 | + UserDataRefMut, Value, |
| 8 | +}; |
| 9 | +use ouroboros::self_referencing; |
| 10 | +use serde::{Serialize, Serializer}; |
| 11 | + |
| 12 | +use crate::bytes::StringOrBytes; |
| 13 | + |
| 14 | +/// Represents a native Json object in Lua. |
| 15 | +#[derive(Clone)] |
| 16 | +pub(crate) struct JsonObject { |
| 17 | + root: Arc<serde_json::Value>, |
| 18 | + current: *const serde_json::Value, |
| 19 | +} |
| 20 | + |
| 21 | +impl Serialize for JsonObject { |
| 22 | + fn serialize<S: Serializer>(&self, serializer: S) -> StdResult<S::Ok, S::Error> { |
| 23 | + self.current().serialize(serializer) |
| 24 | + } |
| 25 | +} |
| 26 | + |
| 27 | +impl JsonObject { |
| 28 | + /// Creates a new `JsonObject` from the given JSON value. |
| 29 | + /// |
| 30 | + /// SAFETY: |
| 31 | + /// The caller must ensure that `current` is a value inside `root`. |
| 32 | + unsafe fn new(root: &Arc<serde_json::Value>, current: &serde_json::Value) -> Self { |
| 33 | + let root = root.clone(); |
| 34 | + JsonObject { root, current } |
| 35 | + } |
| 36 | + |
| 37 | + /// Returns a reference to the current JSON value. |
| 38 | + #[inline(always)] |
| 39 | + fn current(&self) -> &serde_json::Value { |
| 40 | + unsafe { &*self.current } |
| 41 | + } |
| 42 | + |
| 43 | + /// Returns a new `JsonObject` which points to the value at the given key. |
| 44 | + /// |
| 45 | + /// This operation is cheap and does not clone the underlying data. |
| 46 | + fn get(&self, key: Value) -> Option<Self> { |
| 47 | + let value = match key { |
| 48 | + Value::Integer(index) if index > 0 => self.current().get(index as usize - 1), |
| 49 | + Value::String(key) => key.to_str().ok().and_then(|s| self.current().get(&*s)), |
| 50 | + _ => None, |
| 51 | + }?; |
| 52 | + unsafe { Some(Self::new(&self.root, value)) } |
| 53 | + } |
| 54 | + |
| 55 | + /// Returns a new `JsonObject` by following the given JSON Pointer path. |
| 56 | + fn pointer(&self, path: &str) -> Option<Self> { |
| 57 | + unsafe { Some(JsonObject::new(&self.root, self.root.pointer(path)?)) } |
| 58 | + } |
| 59 | + |
| 60 | + /// Converts this `JsonObject` into a Lua `Value`. |
| 61 | + fn into_lua(self, lua: &Lua) -> Result<Value> { |
| 62 | + match self.current() { |
| 63 | + serde_json::Value::Null => Ok(Value::NULL), |
| 64 | + serde_json::Value::Bool(b) => Ok(Value::Boolean(*b)), |
| 65 | + serde_json::Value::Number(n) => { |
| 66 | + if let Some(n) = n.as_i64() { |
| 67 | + Ok(Value::Integer(n as _)) |
| 68 | + } else if let Some(n) = n.as_f64() { |
| 69 | + Ok(Value::Number(n)) |
| 70 | + } else { |
| 71 | + Err(LuaError::ToLuaConversionError { |
| 72 | + from: "number".to_string(), |
| 73 | + to: "integer or float", |
| 74 | + message: Some("number is too big to fit in a Lua integer".to_owned()), |
| 75 | + }) |
| 76 | + } |
| 77 | + } |
| 78 | + serde_json::Value::String(s) => Ok(Value::String(lua.create_string(s)?)), |
| 79 | + value @ serde_json::Value::Array(_) | value @ serde_json::Value::Object(_) => { |
| 80 | + let obj_ud = lua.create_ser_userdata(unsafe { JsonObject::new(&self.root, value) })?; |
| 81 | + Ok(Value::UserData(obj_ud)) |
| 82 | + } |
| 83 | + } |
| 84 | + } |
| 85 | + |
| 86 | + fn lua_iterator(&self, lua: &Lua) -> Result<MultiValue> { |
| 87 | + match self.current() { |
| 88 | + serde_json::Value::Array(_) => { |
| 89 | + let next = Self::lua_array_iterator(lua)?; |
| 90 | + let iter_ud = AnyUserData::wrap(LuaJsonArrayIter { |
| 91 | + value: self.clone(), |
| 92 | + next: 1, // index starts at 1 |
| 93 | + }); |
| 94 | + (next, iter_ud).into_lua_multi(lua) |
| 95 | + } |
| 96 | + serde_json::Value::Object(_) => { |
| 97 | + let next = Self::lua_map_iterator(lua)?; |
| 98 | + let iter_builder = LuaJsonMapIterBuilder { |
| 99 | + value: self.clone(), |
| 100 | + iter_builder: |value| value.current().as_object().unwrap().iter(), |
| 101 | + }; |
| 102 | + let iter_ud = AnyUserData::wrap(iter_builder.build()); |
| 103 | + (next, iter_ud).into_lua_multi(lua) |
| 104 | + } |
| 105 | + _ => ().into_lua_multi(lua), |
| 106 | + } |
| 107 | + } |
| 108 | + |
| 109 | + /// Returns an iterator function for arrays. |
| 110 | + fn lua_array_iterator(lua: &Lua) -> Result<Function> { |
| 111 | + if let Ok(Some(f)) = lua.named_registry_value("__json_array_iterator") { |
| 112 | + return Ok(f); |
| 113 | + } |
| 114 | + |
| 115 | + let f = lua.create_function(|lua, mut it: UserDataRefMut<LuaJsonArrayIter>| { |
| 116 | + it.next += 1; |
| 117 | + match it.value.get(Value::Integer(it.next - 1)) { |
| 118 | + Some(next_value) => (it.next - 1, next_value.into_lua(lua)?).into_lua_multi(lua), |
| 119 | + None => ().into_lua_multi(lua), |
| 120 | + } |
| 121 | + })?; |
| 122 | + lua.set_named_registry_value("__json_array_iterator", &f)?; |
| 123 | + Ok(f) |
| 124 | + } |
| 125 | + |
| 126 | + /// Returns an iterator function for objects. |
| 127 | + fn lua_map_iterator(lua: &Lua) -> Result<Function> { |
| 128 | + if let Ok(Some(f)) = lua.named_registry_value("__json_map_iterator") { |
| 129 | + return Ok(f); |
| 130 | + } |
| 131 | + |
| 132 | + let f = lua.create_function(|lua, mut it: UserDataRefMut<LuaJsonMapIter>| { |
| 133 | + let root = it.borrow_value().root.clone(); |
| 134 | + it.with_iter_mut(move |iter| match iter.next() { |
| 135 | + Some((key, value)) => { |
| 136 | + let key = lua.create_string(key)?; |
| 137 | + let value = unsafe { JsonObject::new(&root, value) }.into_lua(lua)?; |
| 138 | + (key, value).into_lua_multi(lua) |
| 139 | + } |
| 140 | + None => ().into_lua_multi(lua), |
| 141 | + }) |
| 142 | + })?; |
| 143 | + lua.set_named_registry_value("__json_map_iterator", &f)?; |
| 144 | + Ok(f) |
| 145 | + } |
| 146 | +} |
| 147 | + |
| 148 | +impl From<serde_json::Value> for JsonObject { |
| 149 | + fn from(value: serde_json::Value) -> Self { |
| 150 | + let root = Arc::new(value); |
| 151 | + unsafe { Self::new(&root, &root) } |
| 152 | + } |
| 153 | +} |
| 154 | + |
| 155 | +impl UserData for JsonObject { |
| 156 | + fn register(registry: &mut mlua::UserDataRegistry<Self>) { |
| 157 | + registry.add_method("pointer", |lua, this, path: LuaString| { |
| 158 | + this.pointer(&path.to_str()?) |
| 159 | + .map(|obj| obj.into_lua(lua)) |
| 160 | + .unwrap_or(Ok(Value::Nil)) |
| 161 | + }); |
| 162 | + |
| 163 | + registry.add_method("dump", |lua, this, ()| lua.to_value(this)); |
| 164 | + |
| 165 | + registry.add_method("iter", |lua, this, ()| this.lua_iterator(lua)); |
| 166 | + |
| 167 | + registry.add_meta_method(MetaMethod::Index, |lua, this, key: Value| { |
| 168 | + this.get(key) |
| 169 | + .map(|obj| obj.into_lua(lua)) |
| 170 | + .unwrap_or(Ok(Value::Nil)) |
| 171 | + }); |
| 172 | + |
| 173 | + registry.add_meta_method(crate::METAMETHOD_ITER, |lua, this, ()| this.lua_iterator(lua)); |
| 174 | + } |
| 175 | +} |
| 176 | + |
| 177 | +struct LuaJsonArrayIter { |
| 178 | + value: JsonObject, |
| 179 | + next: LuaInteger, |
| 180 | +} |
| 181 | + |
| 182 | +#[self_referencing] |
| 183 | +struct LuaJsonMapIter { |
| 184 | + value: JsonObject, |
| 185 | + |
| 186 | + #[borrows(value)] |
| 187 | + #[covariant] |
| 188 | + iter: serde_json::map::Iter<'this>, |
| 189 | +} |
| 190 | + |
| 191 | +fn decode(lua: &Lua, data: StringOrBytes) -> Result<StdResult<Value, String>> { |
| 192 | + let json: serde_json::Value = lua_try!(serde_json::from_slice(&data.as_bytes_deref()).into_lua_err()); |
| 193 | + Ok(Ok(lua.to_value(&json)?)) |
| 194 | +} |
| 195 | + |
| 196 | +fn decode_native(lua: &Lua, data: StringOrBytes) -> Result<StdResult<Value, String>> { |
| 197 | + let json: serde_json::Value = lua_try!(serde_json::from_slice(&data.as_bytes_deref()).into_lua_err()); |
| 198 | + Ok(Ok(lua_try!(JsonObject::from(json).into_lua(lua)))) |
| 199 | +} |
| 200 | + |
| 201 | +fn encode(value: Value, options: Option<Table>) -> StdResult<String, String> { |
| 202 | + let mut value = value.to_serializable(); |
| 203 | + let options = options.as_ref(); |
| 204 | + |
| 205 | + if options.and_then(|t| t.get::<bool>("relaxed").ok()) == Some(true) { |
| 206 | + value = value.deny_recursive_tables(false).deny_unsupported_types(false); |
| 207 | + } |
| 208 | + |
| 209 | + if options.and_then(|t| t.get::<bool>("pretty").ok()) == Some(true) { |
| 210 | + value = value.sort_keys(true); |
| 211 | + return serde_json::to_string_pretty(&value).map_err(|e| e.to_string()); |
| 212 | + } |
| 213 | + |
| 214 | + serde_json::to_string(&value).map_err(|e| e.to_string()) |
| 215 | +} |
| 216 | + |
| 217 | +/// A loader for the `json` module. |
| 218 | +fn loader(lua: &Lua) -> Result<Table> { |
| 219 | + let t = lua.create_table()?; |
| 220 | + t.set("decode", lua.create_function(decode)?)?; |
| 221 | + t.set("decode_native", lua.create_function(decode_native)?)?; |
| 222 | + t.set("encode", Function::wrap_raw(encode))?; |
| 223 | + Ok(t) |
| 224 | +} |
| 225 | + |
| 226 | +/// Registers the `json` module in the given Lua state. |
| 227 | +pub fn register(lua: &Lua, name: Option<&str>) -> Result<Table> { |
| 228 | + let name = name.unwrap_or("@json"); |
| 229 | + let value = loader(lua)?; |
| 230 | + lua.register_module(name, &value)?; |
| 231 | + Ok(value) |
| 232 | +} |
0 commit comments