From 0db3188a4968d35e5b00c3618ec73cfc9b2fe83b Mon Sep 17 00:00:00 2001 From: Danny Robson Date: Mon, 16 Feb 2015 23:34:50 +1100 Subject: [PATCH] j/tree: add as_{uint,float,double} --- json/tree.cpp | 30 ++++++++++++++++++++++++++++++ json/tree.hpp | 4 ++++ 2 files changed, 34 insertions(+) diff --git a/json/tree.cpp b/json/tree.cpp index fe15118e..0f6a601e 100644 --- a/json/tree.cpp +++ b/json/tree.cpp @@ -26,6 +26,7 @@ #include "debug.hpp" #include "io.hpp" #include "maths.hpp" +#include "types/casts.hpp" #include #include @@ -235,6 +236,35 @@ json::tree::node::as_null (void) const { throw json::type_error ("node is not a null"); } +/////////////////////////////////////////////////////////////////////////////// +float +json::tree::node::as_float (void) const +{ + return static_cast (as_number ().native ()); +} + + +//----------------------------------------------------------------------------- +double +json::tree::node::as_double (void) const +{ + return as_number ().native (); +} + + +//----------------------------------------------------------------------------- +size_t +json::tree::node::as_uint (void) const +{ + auto val = as_number ().native (); + if (!is_integer (val)) + throw json::type_error ("cast fractional value to uint"); + + // TODO: use trunc_cast + return static_cast (val); +} + + //----------------------------------------------------------------------------- // Global operatoers diff --git a/json/tree.hpp b/json/tree.hpp index 368e85c4..8f5d8d81 100644 --- a/json/tree.hpp +++ b/json/tree.hpp @@ -60,6 +60,10 @@ namespace json { namespace tree { virtual const boolean& as_boolean (void) const; virtual const null& as_null (void) const; + virtual float as_float (void) const; + virtual double as_double (void) const; + virtual size_t as_uint (void) const; + virtual bool is_object (void) const { return false; } virtual bool is_array (void) const { return false; } virtual bool is_string (void) const { return false; }