From 35dd24f46f3335b8f152bcf20e86b30eb5ee49b4 Mon Sep 17 00:00:00 2001 From: Michael Davidsaver Date: Wed, 18 Dec 2019 18:25:11 -0800 Subject: [PATCH] Value::tryAs() tryFrom() --- src/data.cpp | 24 ++++++++++++++++++++++++ src/pvxs/data.h | 33 +++++++++++++++++++-------------- 2 files changed, 43 insertions(+), 14 deletions(-) diff --git a/src/data.cpp b/src/data.cpp index c6704b1..4c7fb67 100644 --- a/src/data.cpp +++ b/src/data.cpp @@ -241,6 +241,18 @@ void Value::copyOut(void *ptr, StoreType type) const throw NoConvert(); } +bool Value::tryCopyOut(void *ptr, StoreType type) const +{ + try { + copyOut(ptr, type); + return true; + }catch(NoField&){ + return false; + }catch(NoConvert&){ + return false; + } +} + namespace { // C-style cast between scalar storage types, and print to string (base 10) template @@ -342,6 +354,18 @@ void Value::copyIn(const void *ptr, StoreType type) mark(); } +bool Value::tryCopyIn(const void *ptr, StoreType type) +{ + try { + copyIn(ptr, type); + return true; + }catch(NoField&){ + return false; + }catch(NoConvert&){ + return false; + } +} + void Value::traverse(const std::string &expr, bool modify) { size_t pos=0; diff --git a/src/pvxs/data.h b/src/pvxs/data.h index db4ae65..5d6c747 100644 --- a/src/pvxs/data.h +++ b/src/pvxs/data.h @@ -286,14 +286,16 @@ public: // use with caution void copyOut(void *ptr, StoreType type) const; - //bool tryCopyOut(void *ptr, impl::StoreType type) const; + bool tryCopyOut(void *ptr, StoreType type) const; void copyIn(const void *ptr, StoreType type); - //bool tryCopyIn(const void *ptr, impl::StoreType type); + bool tryCopyIn(const void *ptr, StoreType type); -// template -// inline bool tryAs(T& val) const { -// return tryCopyOut(&val, std::type_index(typeid(std::decay::type))); -// } + template + inline bool tryAs(T& val) const { + typedef impl::StorageMap::type> map_t; + typename map_t::store_t ret; + return tryCopyOut(&ret, map_t::code); + } /** Extract value from field. */ @@ -304,15 +306,18 @@ public: copyOut(&ret, map_t::code); return ret; } -// template -// void as(T& val) const { -// copyOut(&val, std::type_index(typeid(typename std::decay::type))); -// } -// template -// inline bool tryFrom(const T& val) { -// return tryCopyIn(&val, std::type_index(typeid(std::decay::type))); -// } + template + inline void as(T& val) const { + val = this->as(); + } + + template + inline bool tryFrom(const T& val) { + typedef impl::StorageMap::type> map_t; + typename map_t::store_t norm(val); + return copyIn(&norm, map_t::code); + } template void from(const T& val) {