From e973422ee107dce597d332b25d88caa10375fc3d Mon Sep 17 00:00:00 2001 From: Michael Davidsaver Date: Sun, 8 Apr 2018 15:14:19 -0700 Subject: [PATCH] anyscalar.h: add ctor from type code and void* also helper bufferUnsafe() to get storage pointer or c_str(). --- src/misc/pv/anyscalar.h | 22 ++++++++++++++++++++++ testApp/misc/testanyscalar.cpp | 20 +++++++++++++++++++- 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/src/misc/pv/anyscalar.h b/src/misc/pv/anyscalar.h index e115062..f46f13b 100644 --- a/src/misc/pv/anyscalar.h +++ b/src/misc/pv/anyscalar.h @@ -112,6 +112,18 @@ public: _stype = (ScalarType)ScalarTypeID::value; } + AnyScalar(ScalarType type, const void *buf) + { + if(type==pvString) { + new (_wrap.blob) std::string(*static_cast(buf)); + + } else { + memcpy(_wrap.blob, buf, ScalarTypeFunc::elementSize(type)); + } + + _stype = type; + } + AnyScalar(const AnyScalar& o) :_stype(o._stype) { @@ -269,6 +281,16 @@ public: operator bool_type() const { return !empty() ? &AnyScalar::swap : 0; } #endif + //! Provide read-only access to underlying buffer. + //! For a string this is std::string::c_str(). + const void* bufferUnsafe() const { + if(_stype==pvString) { + return as().c_str(); + } else { + return _wrap.blob; + } + } + /** Return reference to wrapped value */ template // T -> strip_const -> map to storage type -> add reference diff --git a/testApp/misc/testanyscalar.cpp b/testApp/misc/testanyscalar.cpp index b60f5e3..3aa1d14 100644 --- a/testApp/misc/testanyscalar.cpp +++ b/testApp/misc/testanyscalar.cpp @@ -42,6 +42,23 @@ void test_ctor() testEqual(D.ref(), "bar"); } +void test_ctor_void() +{ + testDiag("test_ctor_void()"); + + pvd::int32 i = 42; + pvd::AnyScalar A(pvd::pvInt, (void*)&i); + + testEqual(A.type(), pvd::pvInt); + testEqual(A.ref(), 42); + + std::string s("hello"); + pvd::AnyScalar B(pvd::pvString, (void*)&s); + + testEqual(B.type(), pvd::pvString); + testEqual(B.ref(), "hello"); +} + void test_basic() { testDiag("test_basic()"); @@ -213,10 +230,11 @@ void test_move() MAIN(testanyscalar) { - testPlan(66); + testPlan(70); try { test_empty(); test_ctor(); + test_ctor_void(); test_basic(); test_swap(); test_move();