summaryrefslogtreecommitdiff
path: root/serde_dhall/src/options/ser.rs
diff options
context:
space:
mode:
authorNadrieril2020-05-10 22:09:43 +0100
committerNadrieril2020-10-28 22:52:41 +0000
commite070270c3f1f10d46281ed7751ff95e15092e7f4 (patch)
tree46c22c75f209c5112030f3db6609ed64ff4888d3 /serde_dhall/src/options/ser.rs
parent5f3ca811f09dcf6f09fb9b60fcd2664d06762f39 (diff)
Implement serialization
Diffstat (limited to 'serde_dhall/src/options/ser.rs')
-rw-r--r--serde_dhall/src/options/ser.rs67
1 files changed, 67 insertions, 0 deletions
diff --git a/serde_dhall/src/options/ser.rs b/serde_dhall/src/options/ser.rs
new file mode 100644
index 0000000..026dd21
--- /dev/null
+++ b/serde_dhall/src/options/ser.rs
@@ -0,0 +1,67 @@
+use crate::{Result, SimpleType, StaticType, ToDhall};
+
+#[derive(Debug, Clone, Copy)]
+pub struct NoAnnot;
+#[derive(Debug, Clone, Copy)]
+pub struct ManualAnnot<'ty>(&'ty SimpleType);
+#[derive(Debug, Clone, Copy)]
+pub struct StaticAnnot;
+
+pub trait RequiredAnnot<A> {
+ fn get_annot(a: &A) -> SimpleType;
+}
+impl<'ty, T> RequiredAnnot<ManualAnnot<'ty>> for T {
+ fn get_annot(a: &ManualAnnot<'ty>) -> SimpleType {
+ a.0.clone()
+ }
+}
+impl<T: StaticType> RequiredAnnot<StaticAnnot> for T {
+ fn get_annot(_: &StaticAnnot) -> SimpleType {
+ T::static_type()
+ }
+}
+
+#[derive(Debug, Clone)]
+pub struct Serializer<'a, T, A> {
+ data: &'a T,
+ annot: A,
+}
+
+impl<'a, T> Serializer<'a, T, NoAnnot> {
+ pub fn type_annotation<'ty>(
+ self,
+ ty: &'ty SimpleType,
+ ) -> Serializer<'a, T, ManualAnnot<'ty>> {
+ Serializer {
+ annot: ManualAnnot(ty),
+ data: self.data,
+ }
+ }
+
+ pub fn static_type_annotation(self) -> Serializer<'a, T, StaticAnnot> {
+ Serializer {
+ annot: StaticAnnot,
+ data: self.data,
+ }
+ }
+}
+
+impl<'a, T, A> Serializer<'a, T, A> {
+ pub fn to_string(&self) -> Result<String>
+ where
+ T: ToDhall + RequiredAnnot<A>,
+ {
+ let val = self.data.to_dhall(&T::get_annot(&self.annot))?;
+ Ok(val.to_string())
+ }
+}
+
+pub fn serialize<'a, T>(data: &'a T) -> Serializer<'a, T, NoAnnot>
+where
+ T: ToDhall,
+{
+ Serializer {
+ data,
+ annot: NoAnnot,
+ }
+}