From d863068322ef1404cd5b95a8f21b3d2836f942bf Mon Sep 17 00:00:00 2001 From: David Kerkeslager Date: Tue, 11 Apr 2017 16:10:03 -0400 Subject: [PATCH] Start implementing string deserialization --- don/binary.py | 2 +- don/string.py | 39 ++++++++++++++++++++++++++++++++++++++- test_don.py | 36 ++++++++++++++++++------------------ 3 files changed, 57 insertions(+), 20 deletions(-) diff --git a/don/binary.py b/don/binary.py index 295a218..d270f93 100644 --- a/don/binary.py +++ b/don/binary.py @@ -185,7 +185,7 @@ _TAGS_TO_PARSERS = { def _object_parser(source): return _TAGS_TO_PARSERS[source[0]](source[1:]) -def _parse(parser, source, consume_all = True): +def _parse(parser, source): result = parser(source) if result.success and result.remaining == b'': diff --git a/don/string.py b/don/string.py index c791387..15ffc10 100644 --- a/don/string.py +++ b/don/string.py @@ -58,5 +58,42 @@ def serialize(o): return _STRING_SERIALIZERS[o.tag](o.value) +def _make_constant_parser(constant, value): + def parser(s): + if s.startswith(constant): + result = _shared.ParseResult( + success = True, + value = value, + remaining = s[len(constant):], + ) + return result + + return _shared._FAILED_PARSE_RESULT + + return parser + +_PARSERS = [ + _make_constant_parser('null', None), + _make_constant_parser('true', True), + _make_constant_parser('false', False), +] + +def _object_parser(source): + for parser in _PARSERS: + result = parser(source) + + if result.success: + return result + + return _shared._FAILED_PARSE_RESULT + +def _parse(parser, source): + result = parser(source) + + if result.success and result.remaining.strip() == '': + return result.value + + raise Exception('Unparsed trailing characters: "{}"'.format(result.remaining)) + def deserialize(s): - pass + return _parse(_object_parser, s) diff --git a/test_don.py b/test_don.py index 3e830c0..df91309 100644 --- a/test_don.py +++ b/test_don.py @@ -173,23 +173,23 @@ class TestStringSerialize(unittest.TestCase): '{ "foo"utf8: 1i32, "bar"utf8: "baz"utf8 }' ) -# class TestStringDeserialize(unittest.TestCase): -# def test_deserializes_null(self): -# self.assertEqual( -# None, -# string.deserialize('null'), -# ) -# -# def test_deserializes_null(self): -# self.assertEqual( -# True, -# string.deserialize('true'), -# ) -# -# def test_deserializes_null(self): -# self.assertEqual( -# False, -# string.deserialize('false'), -# ) +class TestStringDeserialize(unittest.TestCase): + def test_deserializes_null(self): + self.assertEqual( + None, + string.deserialize('null'), + ) + + def test_deserializes_null(self): + self.assertEqual( + True, + string.deserialize('true'), + ) + + def test_deserializes_null(self): + self.assertEqual( + False, + string.deserialize('false'), + ) unittest.main() -- 2.20.1