From 7d33f1519f2ab1835d84987b4c90523ed58ae9d7 Mon Sep 17 00:00:00 2001 From: Didactic Drunk <1479616+didactic-drunk@users.noreply.github.com> Date: Fri, 30 Aug 2019 22:30:21 -0700 Subject: [PATCH] Sodium::Nonce add JSON and Yaml converters. --- src/sodium/nonce.cr | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/src/sodium/nonce.cr b/src/sodium/nonce.cr index 33deab9..67156cd 100644 --- a/src/sodium/nonce.cr +++ b/src/sodium/nonce.cr @@ -41,5 +41,24 @@ module Sodium raise Error::Reused.new("attempted nonce reuse") if @used @used = true unless @reusable end + + module SerializeConverter + def self.to_json(value : Nonce, json : JSON::Builder) + json.string Base64.strict_encode(value.to_slice) + end + + def self.from_json(value : JSON::PullParser) : Nonce + Nonce.new Base64.decode(value.read_string) + end + + def self.to_yaml(value : Nonce, yaml : YAML::Nodes::Builder) + yaml.scalar Base64.strict_encode(value.to_slice) + end + + def self.from_yaml(ctx : YAML::ParseContext, node : YAML::Nodes::Node) : Nonce + node.raise "Expected scalar, not #{node.class}" unless node.is_a?(YAML::Nodes::Scalar) + Nonce.new Base64.decode(node.value) + end + end end end