git.delta.rocks / jrsonnet / refs/commits / 219e52af0b17

difftreelog

feat create Val from Serializable value

Yaroslav Bolyukin2023-01-20parent: #2cecfb0.patch.diff
in: master

1 file changed

modifiedcrates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth
1use std::borrow::Cow;1use std::borrow::Cow;
22
3use jrsonnet_interner::IStr;
3use serde::{4use serde::{
4 de::Visitor,5 de::Visitor,
5 ser::{Error, SerializeMap, SerializeSeq},6 ser::{
7 Error, SerializeMap, SerializeSeq, SerializeStruct, SerializeStructVariant, SerializeTuple,
8 SerializeTupleStruct, SerializeTupleVariant,
9 },
6 Deserialize, Serialize,10 Deserialize, Serialize, Serializer,
7};11};
812
9use crate::{arr::ArrValue, error::Result, val::StrValue, ObjValueBuilder, State, Val};13use crate::{
14 arr::ArrValue,
15 error::{Error as JrError, ErrorKind, Result},
16 val::StrValue,
17 ObjValue, ObjValueBuilder, State, Val,
18};
1019
11impl<'de> Deserialize<'de> for Val {20impl<'de> Deserialize<'de> for Val {
205 }214 }
206}215}
216
217struct IntoVecValSerializer {
218 variant: Option<IStr>,
219 data: Vec<Val>,
220}
221impl IntoVecValSerializer {
222 fn new() -> Self {
223 Self {
224 variant: None,
225 data: Vec::new(),
226 }
227 }
228 fn with_capacity(capacity: usize) -> Self {
229 Self {
230 variant: None,
231 data: Vec::with_capacity(capacity),
232 }
233 }
234 fn variant_with_capacity(variant: impl Into<IStr>, capacity: usize) -> Self {
235 Self {
236 variant: Some(variant.into()),
237 data: Vec::with_capacity(capacity),
238 }
239 }
240}
241impl SerializeSeq for IntoVecValSerializer {
242 type Ok = Val;
243 type Error = JrError;
244
245 fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<()>
246 where
247 T: Serialize,
248 {
249 let value = value.serialize(IntoValSerializer)?;
250 self.data.push(value);
251 Ok(())
252 }
253
254 fn end(self) -> Result<Val> {
255 let inner = Val::Arr(ArrValue::eager(self.data));
256 if let Some(variant) = self.variant {
257 let mut out = ObjValue::builder_with_capacity(1);
258 out.member(variant).value_unchecked(inner);
259 Ok(Val::Obj(out.build()))
260 } else {
261 Ok(inner)
262 }
263 }
264}
265impl SerializeTuple for IntoVecValSerializer {
266 type Ok = Val;
267 type Error = JrError;
268
269 fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<()>
270 where
271 T: Serialize,
272 {
273 SerializeSeq::serialize_element(self, value)
274 }
275
276 fn end(self) -> Result<Val> {
277 SerializeSeq::end(self)
278 }
279}
280impl SerializeTupleVariant for IntoVecValSerializer {
281 type Ok = Val;
282 type Error = JrError;
283
284 fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<()>
285 where
286 T: Serialize,
287 {
288 SerializeSeq::serialize_element(self, value)
289 }
290
291 fn end(self) -> Result<Val> {
292 SerializeSeq::end(self)
293 }
294}
295impl SerializeTupleStruct for IntoVecValSerializer {
296 type Ok = Val;
297 type Error = JrError;
298
299 fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<()>
300 where
301 T: Serialize,
302 {
303 SerializeSeq::serialize_element(self, value)
304 }
305
306 fn end(self) -> Result<Val> {
307 SerializeSeq::end(self)
308 }
309}
310
311struct IntoObjValueSerializer {
312 variant: Option<IStr>,
313 data: ObjValueBuilder,
314 key: Option<IStr>,
315}
316impl IntoObjValueSerializer {
317 fn new() -> Self {
318 Self {
319 variant: None,
320 data: ObjValue::builder(),
321 key: None,
322 }
323 }
324 fn with_capacity(capacity: usize) -> Self {
325 Self {
326 variant: None,
327 data: ObjValue::builder_with_capacity(capacity),
328 key: None,
329 }
330 }
331 fn variant_with_capacity(variant: impl Into<IStr>, capacity: usize) -> Self {
332 Self {
333 variant: Some(variant.into()),
334 data: ObjValue::builder_with_capacity(capacity),
335 key: None,
336 }
337 }
338}
339impl SerializeMap for IntoObjValueSerializer {
340 type Ok = Val;
341 type Error = JrError;
342
343 fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<()>
344 where
345 T: Serialize,
346 {
347 let key = key.serialize(IntoValSerializer)?;
348 let key = key.to_string()?;
349 self.key = Some(key);
350 Ok(())
351 }
352
353 fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<()>
354 where
355 T: Serialize,
356 {
357 let key = self.key.take().expect("no serialize_key called");
358 let value = value.serialize(IntoValSerializer)?;
359 self.data.member(key).value(value)?;
360 Ok(())
361 }
362
363 // TODO: serialize_key/serialize_value
364 fn serialize_entry<K: ?Sized, V: ?Sized>(&mut self, key: &K, value: &V) -> Result<()>
365 where
366 K: Serialize,
367 V: Serialize,
368 {
369 let key = key.serialize(IntoValSerializer)?;
370 let key = key.to_string()?;
371 let value = value.serialize(IntoValSerializer)?;
372 self.data.member(key).value(value)?;
373 Ok(())
374 }
375
376 fn end(self) -> Result<Val> {
377 let inner = Val::Obj(self.data.build());
378 if let Some(variant) = self.variant {
379 let mut out = ObjValue::builder_with_capacity(1);
380 out.member(variant).value_unchecked(inner);
381 Ok(Val::Obj(out.build()))
382 } else {
383 Ok(inner)
384 }
385 }
386}
387impl SerializeStruct for IntoObjValueSerializer {
388 type Ok = Val;
389 type Error = JrError;
390
391 fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<()>
392 where
393 T: Serialize,
394 {
395 SerializeMap::serialize_entry(self, key, value)?;
396 Ok(())
397 }
398
399 fn end(self) -> Result<Val> {
400 SerializeMap::end(self)
401 }
402}
403impl SerializeStructVariant for IntoObjValueSerializer {
404 type Ok = Val;
405
406 type Error = JrError;
407
408 fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<()>
409 where
410 T: Serialize,
411 {
412 SerializeMap::serialize_entry(self, key, value)?;
413 Ok(())
414 }
415
416 fn end(self) -> Result<Val> {
417 SerializeMap::end(self)
418 }
419}
420
421struct IntoValSerializer;
422impl Serializer for IntoValSerializer {
423 type Ok = Val;
424
425 type Error = JrError;
426
427 type SerializeSeq = IntoVecValSerializer;
428
429 type SerializeTuple = IntoVecValSerializer;
430
431 type SerializeTupleStruct = IntoVecValSerializer;
432
433 type SerializeTupleVariant = IntoVecValSerializer;
434
435 type SerializeMap = IntoObjValueSerializer;
436
437 type SerializeStruct = IntoObjValueSerializer;
438
439 type SerializeStructVariant = IntoObjValueSerializer;
440
441 fn serialize_bool(self, v: bool) -> Result<Val> {
442 Ok(Val::Bool(v))
443 }
444
445 fn serialize_i8(self, v: i8) -> Result<Val> {
446 Ok(Val::Num(f64::from(v)))
447 }
448
449 fn serialize_i16(self, v: i16) -> Result<Val> {
450 Ok(Val::Num(f64::from(v)))
451 }
452
453 fn serialize_i32(self, v: i32) -> Result<Val> {
454 Ok(Val::Num(f64::from(v)))
455 }
456
457 fn serialize_i64(self, v: i64) -> Result<Val> {
458 Ok(Val::Str(v.to_string().into()))
459 }
460
461 fn serialize_u8(self, v: u8) -> Result<Val> {
462 Ok(Val::Num(f64::from(v)))
463 }
464
465 fn serialize_u16(self, v: u16) -> Result<Val> {
466 Ok(Val::Num(f64::from(v)))
467 }
468
469 fn serialize_u32(self, v: u32) -> Result<Val> {
470 Ok(Val::Num(f64::from(v)))
471 }
472
473 fn serialize_u64(self, v: u64) -> Result<Val> {
474 Ok(Val::Str(v.to_string().into()))
475 }
476
477 fn serialize_f32(self, v: f32) -> Result<Val> {
478 Ok(Val::Num(f64::from(v)))
479 }
480
481 fn serialize_f64(self, v: f64) -> Result<Val> {
482 Ok(Val::Num(v))
483 }
484
485 fn serialize_char(self, v: char) -> Result<Val> {
486 Ok(Val::Str(v.to_string().into()))
487 }
488
489 fn serialize_str(self, v: &str) -> Result<Val> {
490 Ok(Val::Str(v.into()))
491 }
492
493 fn serialize_bytes(self, v: &[u8]) -> Result<Val> {
494 Ok(Val::Arr(ArrValue::bytes(v.into())))
495 }
496
497 fn serialize_none(self) -> Result<Val> {
498 Ok(Val::Null)
499 }
500
501 fn serialize_some<T: ?Sized>(self, value: &T) -> Result<Val>
502 where
503 T: Serialize,
504 {
505 value.serialize(self)
506 }
507
508 fn serialize_unit(self) -> Result<Val> {
509 Ok(Val::Null)
510 }
511
512 fn serialize_unit_struct(self, _name: &'static str) -> Result<Val> {
513 Ok(Val::Null)
514 }
515
516 fn serialize_unit_variant(
517 self,
518 _name: &'static str,
519 _variant_index: u32,
520 variant: &'static str,
521 ) -> Result<Val> {
522 Ok(Val::Str(variant.into()))
523 }
524
525 fn serialize_newtype_struct<T: ?Sized>(self, _name: &'static str, value: &T) -> Result<Val>
526 where
527 T: Serialize,
528 {
529 value.serialize(self)
530 }
531
532 fn serialize_newtype_variant<T: ?Sized>(
533 self,
534 _name: &'static str,
535 _variant_index: u32,
536 variant: &'static str,
537 value: &T,
538 ) -> Result<Val>
539 where
540 T: Serialize,
541 {
542 let mut out = ObjValue::builder_with_capacity(1);
543 let value = value.serialize(self)?;
544 out.member(variant.into()).value_unchecked(value);
545 Ok(Val::Obj(out.build()))
546 }
547
548 fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
549 Ok(len.map_or_else(
550 IntoVecValSerializer::new,
551 IntoVecValSerializer::with_capacity,
552 ))
553 }
554
555 fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error> {
556 Ok(IntoVecValSerializer::with_capacity(len))
557 }
558
559 fn serialize_tuple_struct(
560 self,
561 _name: &'static str,
562 len: usize,
563 ) -> Result<Self::SerializeTupleStruct, Self::Error> {
564 Ok(IntoVecValSerializer::with_capacity(len))
565 }
566
567 fn serialize_tuple_variant(
568 self,
569 _name: &'static str,
570 _variant_index: u32,
571 variant: &'static str,
572 len: usize,
573 ) -> Result<Self::SerializeTupleVariant, Self::Error> {
574 Ok(IntoVecValSerializer::variant_with_capacity(variant, len))
575 }
576
577 fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
578 Ok(len.map_or_else(
579 IntoObjValueSerializer::new,
580 IntoObjValueSerializer::with_capacity,
581 ))
582 }
583
584 fn serialize_struct(
585 self,
586 _name: &'static str,
587 len: usize,
588 ) -> Result<Self::SerializeStruct, Self::Error> {
589 Ok(IntoObjValueSerializer::with_capacity(len))
590 }
591
592 fn serialize_struct_variant(
593 self,
594 _name: &'static str,
595 _variant_index: u32,
596 variant: &'static str,
597 len: usize,
598 ) -> Result<Self::SerializeStructVariant, Self::Error> {
599 Ok(IntoObjValueSerializer::variant_with_capacity(variant, len))
600 }
601}
602
603impl Val {
604 pub fn from_serde(v: impl Serialize) -> Result<Val, JrError> {
605 v.serialize(IntoValSerializer)
606 }
607}
608
609impl serde::ser::Error for JrError {
610 fn custom<T>(msg: T) -> Self
611 where
612 T: std::fmt::Display,
613 {
614 JrError::new(ErrorKind::RuntimeError(format!("serde: {msg}").into()))
615 }
616}
207617