1use std::borrow::Cow;23use jrsonnet_interner::IStr;4use serde::{5 de::{self, Visitor},6 ser::{7 Error, SerializeMap, SerializeSeq, SerializeStruct, SerializeStructVariant, SerializeTuple,8 SerializeTupleStruct, SerializeTupleVariant,9 },10 Deserialize, Serialize, Serializer,11};1213use crate::{14 arr::ArrValue, in_description_frame, runtime_error, val::NumValue, Error as JrError, ObjValue,15 ObjValueBuilder, Result, Val,16};1718impl<'de> Deserialize<'de> for Val {19 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>20 where21 D: serde::Deserializer<'de>,22 {23 struct ValVisitor;2425 26 27 28 29 30 31 32 33 34 3536 impl<'de> Visitor<'de> for ValVisitor {37 type Value = Val;3839 fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>40 where41 E: de::Error,42 {43 Ok(Val::Bool(v))44 }45 fn visit_f64<E>(self, v: f64) -> Result<Self::Value, E>46 where47 E: de::Error,48 {49 Ok(Val::Num(NumValue::new(v).ok_or_else(|| {50 E::custom("only finite numbers are supported")51 })?))52 }53 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>54 where55 E: de::Error,56 {57 Ok(Val::string(v))58 }5960 61 62 63 64 65 66 67 68 fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>69 where70 E: de::Error,71 {72 Ok(Val::Num(NumValue::new(v as f64).expect("no overflow")))73 }74 fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>75 where76 E: de::Error,77 {78 Ok(Val::Num(NumValue::new(v as f64).expect("no overflow")))79 }8081 fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>82 where83 E: de::Error,84 {85 Ok(Val::Arr(ArrValue::bytes(v.into())))86 }8788 fn visit_none<E>(self) -> Result<Self::Value, E>89 where90 E: de::Error,91 {92 Ok(Val::Null)93 }94 fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>95 where96 D: serde::Deserializer<'de>,97 {98 deserializer.deserialize_any(self)99 }100101 fn visit_unit<E>(self) -> Result<Self::Value, E>102 where103 E: de::Error,104 {105 Ok(Val::Null)106 }107108 fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>109 where110 D: serde::Deserializer<'de>,111 {112 deserializer.deserialize_any(self)113 }114115 fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>116 where117 A: de::SeqAccess<'de>,118 {119 let mut out = seq.size_hint().map_or_else(Vec::new, Vec::with_capacity);120121 while let Some(val) = seq.next_element::<Val>()? {122 out.push(val);123 }124125 Ok(Val::Arr(ArrValue::eager(out)))126 }127128 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>129 where130 A: de::MapAccess<'de>,131 {132 let mut out = map133 .size_hint()134 .map_or_else(ObjValueBuilder::new, ObjValueBuilder::with_capacity);135136 while let Some((k, v)) = map.next_entry::<Cow<'de, str>, Val>()? {137 138 out.field(k).value(v);139 }140141 Ok(Val::Obj(out.build()))142 }143144 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {145 write!(formatter, "any valid jsonnet value")146 }147 }148 deserializer.deserialize_any(ValVisitor)149 }150}151152impl Serialize for Val {153 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>154 where155 S: serde::Serializer,156 {157 match self {158 Self::Bool(v) => serializer.serialize_bool(*v),159 Self::Null => serializer.serialize_none(),160 Self::Str(s) => serializer.serialize_str(&s.clone().into_flat()),161 Self::Num(n) => {162 let n = n.get();163 if n.fract() == 0.0 {164 let n = n as i64;165 serializer.serialize_i64(n)166 } else {167 serializer.serialize_f64(n)168 }169 }170 #[cfg(feature = "exp-bigint")]171 Self::BigInt(b) => b.serialize(serializer),172 Self::Arr(arr) => {173 let mut seq = serializer.serialize_seq(Some(arr.len()))?;174 for (i, element) in arr.iter().enumerate() {175 let mut serde_error = None;176 in_description_frame(177 || format!("array index [{i}]"),178 || {179 let e = element?;180 if let Err(e) = seq.serialize_element(&e) {181 serde_error = Some(e);182 }183 Ok(())184 },185 )186 .map_err(|e| S::Error::custom(e.to_string()))?;187 if let Some(e) = serde_error {188 return Err(e);189 }190 }191 seq.end()192 }193 Self::Obj(obj) => {194 let mut map = serializer.serialize_map(Some(obj.len()))?;195 for (field, value) in obj.iter(196 #[cfg(feature = "exp-preserve-order")]197 true,198 ) {199 let mut serde_error = None;200 201 in_description_frame(202 || format!("object field {field:?}"),203 || {204 let v = value?;205 if let Err(e) = map.serialize_entry(field.as_str(), &v) {206 serde_error = Some(e);207 }208 Ok(())209 },210 )211 .map_err(|e| S::Error::custom(e.to_string()))?;212 if let Some(e) = serde_error {213 return Err(e);214 }215 }216 map.end()217 }218 Self::Func(_) => Err(S::Error::custom("tried to manifest function")),219 }220 }221}222223struct IntoVecValSerializer {224 variant: Option<IStr>,225 data: Vec<Val>,226}227impl IntoVecValSerializer {228 fn new() -> Self {229 Self {230 variant: None,231 data: Vec::new(),232 }233 }234 fn with_capacity(capacity: usize) -> Self {235 Self {236 variant: None,237 data: Vec::with_capacity(capacity),238 }239 }240 fn variant_with_capacity(variant: impl Into<IStr>, capacity: usize) -> Self {241 Self {242 variant: Some(variant.into()),243 data: Vec::with_capacity(capacity),244 }245 }246}247impl SerializeSeq for IntoVecValSerializer {248 type Ok = Val;249 type Error = JrError;250251 fn serialize_element<T>(&mut self, value: &T) -> Result<()>252 where253 T: ?Sized + Serialize,254 {255 let value = value.serialize(IntoValSerializer)?;256 self.data.push(value);257 Ok(())258 }259260 fn end(self) -> Result<Val> {261 let inner = Val::Arr(ArrValue::eager(self.data));262 if let Some(variant) = self.variant {263 let mut out = ObjValue::builder_with_capacity(1);264 out.field(variant).value(inner);265 Ok(Val::Obj(out.build()))266 } else {267 Ok(inner)268 }269 }270}271impl SerializeTuple for IntoVecValSerializer {272 type Ok = Val;273 type Error = JrError;274275 fn serialize_element<T>(&mut self, value: &T) -> Result<()>276 where277 T: ?Sized + Serialize,278 {279 SerializeSeq::serialize_element(self, value)280 }281282 fn end(self) -> Result<Val> {283 SerializeSeq::end(self)284 }285}286impl SerializeTupleVariant for IntoVecValSerializer {287 type Ok = Val;288 type Error = JrError;289290 fn serialize_field<T>(&mut self, value: &T) -> Result<()>291 where292 T: ?Sized + Serialize,293 {294 SerializeSeq::serialize_element(self, value)295 }296297 fn end(self) -> Result<Val> {298 SerializeSeq::end(self)299 }300}301impl SerializeTupleStruct for IntoVecValSerializer {302 type Ok = Val;303 type Error = JrError;304305 fn serialize_field<T>(&mut self, value: &T) -> Result<()>306 where307 T: ?Sized + Serialize,308 {309 SerializeSeq::serialize_element(self, value)310 }311312 fn end(self) -> Result<Val> {313 SerializeSeq::end(self)314 }315}316317struct IntoObjValueSerializer {318 variant: Option<IStr>,319 data: ObjValueBuilder,320 key: Option<IStr>,321}322impl IntoObjValueSerializer {323 fn new() -> Self {324 Self {325 variant: None,326 data: ObjValue::builder(),327 key: None,328 }329 }330 fn with_capacity(capacity: usize) -> Self {331 Self {332 variant: None,333 data: ObjValue::builder_with_capacity(capacity),334 key: None,335 }336 }337 fn variant_with_capacity(variant: impl Into<IStr>, capacity: usize) -> Self {338 Self {339 variant: Some(variant.into()),340 data: ObjValue::builder_with_capacity(capacity),341 key: None,342 }343 }344}345impl SerializeMap for IntoObjValueSerializer {346 type Ok = Val;347 type Error = JrError;348349 fn serialize_key<T>(&mut self, key: &T) -> Result<()>350 where351 T: ?Sized + Serialize,352 {353 let key = key.serialize(IntoValSerializer)?;354 let key = key.to_string()?;355 self.key = Some(key);356 Ok(())357 }358359 fn serialize_value<T>(&mut self, value: &T) -> Result<()>360 where361 T: ?Sized + Serialize,362 {363 let key = self.key.take().expect("no serialize_key called");364 let value = value.serialize(IntoValSerializer)?;365 self.data.field(key).try_value(value)?;366 Ok(())367 }368369 370 fn serialize_entry<K, V>(&mut self, key: &K, value: &V) -> Result<()>371 where372 K: ?Sized + Serialize,373 V: ?Sized + Serialize,374 {375 let key = key.serialize(IntoValSerializer)?;376 let key = key.to_string()?;377 let value = value.serialize(IntoValSerializer)?;378 self.data.field(key).try_value(value)?;379 Ok(())380 }381382 fn end(self) -> Result<Val> {383 let inner = Val::Obj(self.data.build());384 if let Some(variant) = self.variant {385 let mut out = ObjValue::builder_with_capacity(1);386 out.field(variant).value(inner);387 Ok(Val::Obj(out.build()))388 } else {389 Ok(inner)390 }391 }392}393impl SerializeStruct for IntoObjValueSerializer {394 type Ok = Val;395 type Error = JrError;396397 fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>398 where399 T: ?Sized + Serialize,400 {401 SerializeMap::serialize_entry(self, key, value)?;402 Ok(())403 }404405 fn end(self) -> Result<Val> {406 SerializeMap::end(self)407 }408}409impl SerializeStructVariant for IntoObjValueSerializer {410 type Ok = Val;411412 type Error = JrError;413414 fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>415 where416 T: ?Sized + Serialize,417 {418 SerializeMap::serialize_entry(self, key, value)?;419 Ok(())420 }421422 fn end(self) -> Result<Val> {423 SerializeMap::end(self)424 }425}426427struct IntoValSerializer;428impl Serializer for IntoValSerializer {429 type Ok = Val;430431 type Error = JrError;432433 type SerializeSeq = IntoVecValSerializer;434435 type SerializeTuple = IntoVecValSerializer;436437 type SerializeTupleStruct = IntoVecValSerializer;438439 type SerializeTupleVariant = IntoVecValSerializer;440441 type SerializeMap = IntoObjValueSerializer;442443 type SerializeStruct = IntoObjValueSerializer;444445 type SerializeStructVariant = IntoObjValueSerializer;446447 fn serialize_bool(self, v: bool) -> Result<Val> {448 Ok(Val::Bool(v))449 }450451 fn serialize_i8(self, v: i8) -> Result<Val> {452 Ok(Val::Num(v.into()))453 }454455 fn serialize_i16(self, v: i16) -> Result<Val> {456 Ok(Val::Num(v.into()))457 }458459 fn serialize_i32(self, v: i32) -> Result<Val> {460 Ok(Val::Num(v.into()))461 }462463 fn serialize_i64(self, v: i64) -> Result<Val> {464 Ok(Val::Str(v.to_string().into()))465 }466467 fn serialize_u8(self, v: u8) -> Result<Val> {468 Ok(Val::Num(v.into()))469 }470471 fn serialize_u16(self, v: u16) -> Result<Val> {472 Ok(Val::Num(v.into()))473 }474475 fn serialize_u32(self, v: u32) -> Result<Val> {476 Ok(Val::Num(v.into()))477 }478479 fn serialize_u64(self, v: u64) -> Result<Val> {480 Ok(Val::Str(v.to_string().into()))481 }482483 fn serialize_f32(self, v: f32) -> Result<Val> {484 Ok(Val::try_num(f64::from(v))?)485 }486487 fn serialize_f64(self, v: f64) -> Result<Val> {488 Ok(Val::try_num(v)?)489 }490491 fn serialize_char(self, v: char) -> Result<Val> {492 Ok(Val::Str(v.to_string().into()))493 }494495 fn serialize_str(self, v: &str) -> Result<Val> {496 Ok(Val::Str(v.into()))497 }498499 fn serialize_bytes(self, v: &[u8]) -> Result<Val> {500 Ok(Val::Arr(ArrValue::bytes(v.into())))501 }502503 fn serialize_none(self) -> Result<Val> {504 Ok(Val::Null)505 }506507 fn serialize_some<T>(self, value: &T) -> Result<Val>508 where509 T: ?Sized + Serialize,510 {511 value.serialize(self)512 }513514 fn serialize_unit(self) -> Result<Val> {515 Ok(Val::Null)516 }517518 fn serialize_unit_struct(self, _name: &'static str) -> Result<Val> {519 Ok(Val::Null)520 }521522 fn serialize_unit_variant(523 self,524 _name: &'static str,525 _variant_index: u32,526 variant: &'static str,527 ) -> Result<Val> {528 Ok(Val::Str(variant.into()))529 }530531 fn serialize_newtype_struct<T>(self, _name: &'static str, value: &T) -> Result<Val>532 where533 T: ?Sized + Serialize,534 {535 value.serialize(self)536 }537538 fn serialize_newtype_variant<T>(539 self,540 _name: &'static str,541 _variant_index: u32,542 variant: &'static str,543 value: &T,544 ) -> Result<Val>545 where546 T: ?Sized + Serialize,547 {548 let mut out = ObjValue::builder_with_capacity(1);549 let value = value.serialize(self)?;550 out.field(variant).value(value);551 Ok(Val::Obj(out.build()))552 }553554 fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {555 Ok(len.map_or_else(556 IntoVecValSerializer::new,557 IntoVecValSerializer::with_capacity,558 ))559 }560561 fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error> {562 Ok(IntoVecValSerializer::with_capacity(len))563 }564565 fn serialize_tuple_struct(566 self,567 _name: &'static str,568 len: usize,569 ) -> Result<Self::SerializeTupleStruct, Self::Error> {570 Ok(IntoVecValSerializer::with_capacity(len))571 }572573 fn serialize_tuple_variant(574 self,575 _name: &'static str,576 _variant_index: u32,577 variant: &'static str,578 len: usize,579 ) -> Result<Self::SerializeTupleVariant, Self::Error> {580 Ok(IntoVecValSerializer::variant_with_capacity(variant, len))581 }582583 fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {584 Ok(len.map_or_else(585 IntoObjValueSerializer::new,586 IntoObjValueSerializer::with_capacity,587 ))588 }589590 fn serialize_struct(591 self,592 _name: &'static str,593 len: usize,594 ) -> Result<Self::SerializeStruct, Self::Error> {595 Ok(IntoObjValueSerializer::with_capacity(len))596 }597598 fn serialize_struct_variant(599 self,600 _name: &'static str,601 _variant_index: u32,602 variant: &'static str,603 len: usize,604 ) -> Result<Self::SerializeStructVariant, Self::Error> {605 Ok(IntoObjValueSerializer::variant_with_capacity(variant, len))606 }607}608609impl Val {610 pub fn from_serde(v: impl Serialize) -> Result<Self, JrError> {611 v.serialize(IntoValSerializer)612 }613}614615impl serde::ser::Error for JrError {616 fn custom<T>(msg: T) -> Self617 where618 T: std::fmt::Display,619 {620 runtime_error!("serde: {msg}")621 }622}