From ea65c8dc32eedd3460a1c742aa1d5f93591aff0a Mon Sep 17 00:00:00 2001 From: Karchnu Date: Thu, 26 Nov 2020 06:51:29 +0100 Subject: [PATCH] Time: allow to use String representations, as produced by #to_json. --- src/cbor/from_cbor.cr | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/src/cbor/from_cbor.cr b/src/cbor/from_cbor.cr index e2610e7..4979fa8 100644 --- a/src/cbor/from_cbor.cr +++ b/src/cbor/from_cbor.cr @@ -134,18 +134,24 @@ end # # [1]: https://tools.ietf.org/html/rfc7049#section-2.4.1 def Time.new(decoder : CBOR::Decoder) - case tag = decoder.read_tag - when CBOR::Tag::RFC3339Time + # In case Time is formatted as a JSON#to_json String. + case decoder.current_token + when CBOR::Token::StringT Time::Format::RFC_3339.parse(decoder.read_string) - when CBOR::Tag::EpochTime - case num = decoder.read_num - when Int - Time.unix(num) - when Float - Time.unix_ms((BigFloat.new(num) * 1_000).to_u64) - end else - raise CBOR::ParseError.new("Expected tag to have value 0 or 1, got #{tag.value}") + case tag = decoder.read_tag + when CBOR::Tag::RFC3339Time + Time::Format::RFC_3339.parse(decoder.read_string) + when CBOR::Tag::EpochTime + case num = decoder.read_num + when Int + Time.unix(num) + when Float + Time.unix_ms((BigFloat.new(num) * 1_000).to_u64) + end + else + raise CBOR::ParseError.new("Expected tag to have value 0 or 1, got #{tag.value}") + end end end