-
Notifications
You must be signed in to change notification settings - Fork 714
/
Copy pathsafe_any.hpp
715 lines (617 loc) · 20.8 KB
/
safe_any.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
/* Copyright (C) 2022 Davide Faconti - All Rights Reserved
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#pragma once
#if __has_include(<charconv>)
#include <charconv>
#endif
#include <string>
#include <type_traits>
#include <typeindex>
#include "behaviortree_cpp/contrib/any.hpp"
#include "behaviortree_cpp/contrib/expected.hpp"
#include "behaviortree_cpp/utils/demangle_util.h"
#include "behaviortree_cpp/utils/convert_impl.hpp"
#include "behaviortree_cpp/utils/strcat.hpp"
namespace BT
{
static std::type_index UndefinedAnyType = typeid(nullptr);
template <typename T>
struct any_cast_base
{
using type = void; // Default: no base known, fallback to default any storage
};
// Trait to detect std::shared_ptr types.
template <typename T>
struct is_shared_ptr : std::false_type
{
};
template <typename U>
struct is_shared_ptr<std::shared_ptr<U>> : std::true_type
{
};
// Trait to detect if a type is complete
template <typename T, typename = void>
struct is_complete : std::false_type
{
};
template <typename T>
struct is_complete<T, decltype(void(sizeof(T)))> : std::true_type
{
};
// Trait to detect if a trait is complete and polymorphic
template <typename T, typename = void>
struct is_polymorphic_safe : std::false_type
{
};
// Specialization only enabled if T is complete
template <typename T>
struct is_polymorphic_safe<T, std::enable_if_t<is_complete<T>::value>>
: std::integral_constant<bool, std::is_polymorphic<T>::value>
{
};
template <typename T>
inline constexpr bool is_polymorphic_safe_v = is_polymorphic_safe<T>::value;
// Rational: since type erased numbers will always use at least 8 bytes
// it is faster to cast everything to either double, uint64_t or int64_t.
class Any
{
template <typename T>
using EnableIntegral = typename std::enable_if<std::is_integral<T>::value ||
std::is_enum<T>::value>::type*;
template <typename T>
using EnableNonIntegral = typename std::enable_if<!std::is_integral<T>::value &&
!std::is_enum<T>::value>::type*;
template <typename T>
using EnableString =
typename std::enable_if<std::is_same<T, std::string>::value>::type*;
template <typename T>
using EnableArithmetic = typename std::enable_if<std::is_arithmetic<T>::value>::type*;
template <typename T>
using EnableEnum = typename std::enable_if<std::is_enum<T>::value>::type*;
template <typename T>
using EnableUnknownType =
typename std::enable_if<!std::is_arithmetic<T>::value && !std::is_enum<T>::value &&
!std::is_same<T, std::string>::value>::type*;
template <typename T>
nonstd::expected<T, std::string> stringToNumber() const;
public:
Any() : _original_type(UndefinedAnyType)
{}
~Any() = default;
Any(const Any& other) : _any(other._any), _original_type(other._original_type)
{}
Any(Any&& other) : _any(std::move(other._any)), _original_type(other._original_type)
{}
explicit Any(const double& value) : _any(value), _original_type(typeid(double))
{}
explicit Any(const uint64_t& value) : _any(value), _original_type(typeid(uint64_t))
{}
explicit Any(const float& value) : _any(double(value)), _original_type(typeid(float))
{}
explicit Any(const std::string& str)
: _any(SafeAny::SimpleString(str)), _original_type(typeid(std::string))
{}
explicit Any(const char* str)
: _any(SafeAny::SimpleString(str)), _original_type(typeid(std::string))
{}
explicit Any(const SafeAny::SimpleString& str)
: _any(str), _original_type(typeid(std::string))
{}
explicit Any(const std::string_view& str)
: _any(SafeAny::SimpleString(str)), _original_type(typeid(std::string))
{}
// all the other integrals are casted to int64_t
template <typename T>
explicit Any(const T& value, EnableIntegral<T> = 0)
: _any(int64_t(value)), _original_type(typeid(T))
{}
Any(const std::type_index& type) : _original_type(type)
{}
// default for shared pointers
template <typename T>
explicit Any(const std::shared_ptr<T>& value)
: _original_type(typeid(std::shared_ptr<T>))
{
using Base = typename any_cast_base<T>::type;
// store as base class if specialized
if constexpr(!std::is_same_v<Base, void>)
{
static_assert(is_polymorphic_safe_v<Base>, "Any Base trait specialization must be "
"polymorphic");
_any = std::static_pointer_cast<Base>(value);
}
else
{
_any = value;
}
}
// default for other custom types
template <typename T>
explicit Any(const T& value, EnableNonIntegral<T> = 0)
: _any(value), _original_type(typeid(T))
{
static_assert(!std::is_reference<T>::value, "Any can not contain references");
}
Any& operator=(const Any& other);
[[nodiscard]] bool isNumber() const;
[[nodiscard]] bool isIntegral() const;
[[nodiscard]] bool isString() const
{
return _any.type() == typeid(SafeAny::SimpleString);
}
// check is the original type is equal to T
template <typename T>
[[nodiscard]] bool isType() const
{
return _original_type == typeid(T);
}
// copy the value (casting into dst). We preserve the destination type.
void copyInto(Any& dst);
// this is different from any_cast, because if allows safe
// conversions between arithmetic values and from/to string.
template <typename T>
nonstd::expected<T, std::string> tryCast() const;
// same as tryCast, but throws if fails
template <typename T>
[[nodiscard]] T cast() const
{
if(auto res = tryCast<T>())
{
return res.value();
}
else
{
throw std::runtime_error(res.error());
}
}
// Method to access the value by pointer.
// It will return nullptr, if the user try to cast it to a
// wrong type or if Any was empty.
//
// WARNING: The returned pointer may alias internal cache and be invalidated by subsequent castPtr() calls.
// Do not store it long-term. Applies only to shared_ptr<Derived> where Derived is polymorphic and base-registered.
template <typename T>
[[nodiscard]] T* castPtr()
{
static_assert(!std::is_same_v<T, float>, "The value has been casted internally to "
"[double]. "
"Use that instead");
static_assert(!SafeAny::details::is_integer<T>() || std::is_same_v<T, uint64_t>, "The"
" va"
"lue"
" ha"
"s "
"bee"
"n "
"cas"
"ted"
" in"
"ter"
"nal"
"ly "
"to "
"[in"
"t64"
"_t]"
". "
"Use"
" th"
"at "
"ins"
"tea"
"d");
// Special case: applies only when requesting shared_ptr<Derived> and Derived is polymorphic
// with a registered base via any_cast_base.
if constexpr(is_shared_ptr<T>::value)
{
using Derived = typename T::element_type;
using Base = typename any_cast_base<Derived>::type;
if constexpr(is_polymorphic_safe_v<Derived> && !std::is_same_v<Base, void>)
{
try
{
// Attempt to retrieve the stored shared_ptr<Base> from the Any container
auto base_ptr = linb::any_cast<std::shared_ptr<Base>>(&_any);
if(!base_ptr)
return nullptr;
// Case 1: If Base and Derived are the same, no casting is needed
if constexpr(std::is_same_v<Base, Derived>)
{
return reinterpret_cast<T*>(base_ptr);
}
// Case 2: Originally stored as shared_ptr<Derived>
if(_original_type == typeid(std::shared_ptr<Derived>))
{
_cached_derived_ptr = std::static_pointer_cast<Derived>(*base_ptr);
return reinterpret_cast<T*>(&_cached_derived_ptr);
}
// Case 3: Fallback to dynamic cast
auto derived_ptr = std::dynamic_pointer_cast<Derived>(*base_ptr);
if(derived_ptr)
{
_cached_derived_ptr = derived_ptr;
return reinterpret_cast<T*>(&_cached_derived_ptr);
}
}
catch(...)
{
return nullptr;
}
return nullptr;
}
}
return _any.empty() ? nullptr : linb::any_cast<T>(&_any);
}
// This is the original type
[[nodiscard]] const std::type_index& type() const noexcept
{
return _original_type;
}
// This is the type we casted to, internally
[[nodiscard]] const std::type_info& castedType() const noexcept
{
return _any.type();
}
[[nodiscard]] bool empty() const noexcept
{
return _any.empty();
}
private:
linb::any _any;
std::type_index _original_type;
mutable std::shared_ptr<void> _cached_derived_ptr = nullptr;
//----------------------------
template <typename DST>
nonstd::expected<DST, std::string> convert(EnableString<DST> = 0) const;
template <typename DST>
nonstd::expected<DST, std::string> convert(EnableArithmetic<DST> = nullptr) const;
template <typename DST>
nonstd::expected<DST, std::string> convert(EnableEnum<DST> = 0) const;
template <typename DST>
nonstd::expected<DST, std::string> convert(EnableUnknownType<DST> = 0) const
{
return nonstd::make_unexpected(errorMsg<DST>());
}
template <typename T>
std::string errorMsg() const
{
return StrCat("[Any::convert]: no known safe conversion between [", demangle(type()),
"] and [", demangle(typeid(T)), "]");
}
};
//-------------------------------------------------------------
//-------------------------------------------------------------
//-------------------------------------------------------------
template <typename SRC, typename TO>
inline bool ValidCast(const SRC& val)
{
// First check numeric limits
if constexpr(std::is_arithmetic_v<SRC> && std::is_arithmetic_v<TO>)
{
// Handle conversion to floating point
if constexpr(std::is_floating_point_v<TO>)
{
if constexpr(std::is_integral_v<SRC>)
{
// For integral to float, check if we can represent the value exactly
TO as_float = static_cast<TO>(val);
SRC back_conv = static_cast<SRC>(as_float);
return back_conv == val;
}
}
// Handle conversion to integral
else if constexpr(std::is_integral_v<TO>)
{
if(val > static_cast<SRC>(std::numeric_limits<TO>::max()) ||
val < static_cast<SRC>(std::numeric_limits<TO>::lowest()))
{
return false;
}
}
}
TO as_target = static_cast<TO>(val);
SRC back_to_source = static_cast<SRC>(as_target);
return val == back_to_source;
}
template <typename T>
inline bool isCastingSafe(const std::type_index& type, const T& val)
{
if(type == typeid(T))
{
return true;
}
if(std::type_index(typeid(uint8_t)) == type)
{
return ValidCast<T, uint8_t>(val);
}
if(std::type_index(typeid(uint16_t)) == type)
{
return ValidCast<T, uint16_t>(val);
}
if(std::type_index(typeid(uint32_t)) == type)
{
return ValidCast<T, uint32_t>(val);
}
if(std::type_index(typeid(uint64_t)) == type)
{
return ValidCast<T, uint64_t>(val);
}
//------------
if(std::type_index(typeid(int8_t)) == type)
{
return ValidCast<T, int8_t>(val);
}
if(std::type_index(typeid(int16_t)) == type)
{
return ValidCast<T, int16_t>(val);
}
if(std::type_index(typeid(int32_t)) == type)
{
return ValidCast<T, int32_t>(val);
}
if(std::type_index(typeid(int64_t)) == type)
{
return ValidCast<T, int64_t>(val);
}
//------------
if(std::type_index(typeid(float)) == type)
{
return ValidCast<T, float>(val);
}
if(std::type_index(typeid(double)) == type)
{
return ValidCast<T, double>(val);
}
return false;
}
inline Any& Any::operator=(const Any& other)
{
this->_any = other._any;
this->_original_type = other._original_type;
return *this;
}
inline bool Any::isNumber() const
{
return _any.type() == typeid(int64_t) || _any.type() == typeid(uint64_t) ||
_any.type() == typeid(double);
}
inline bool Any::isIntegral() const
{
return _any.type() == typeid(int64_t) || _any.type() == typeid(uint64_t);
}
inline void Any::copyInto(Any& dst)
{
if(dst.empty())
{
dst = *this;
return;
}
const auto& dst_type = dst.castedType();
if((castedType() == dst_type) || (isString() && dst.isString()))
{
dst._any = _any;
}
else if(isNumber() && dst.isNumber())
{
if(dst_type == typeid(int64_t))
{
dst._any = cast<int64_t>();
}
else if(dst_type == typeid(uint64_t))
{
dst._any = cast<uint64_t>();
}
else if(dst_type == typeid(double))
{
dst._any = cast<double>();
}
else
{
throw std::runtime_error("Any::copyInto fails");
}
}
else
{
throw std::runtime_error("Any::copyInto fails");
}
}
template <typename DST>
inline nonstd::expected<DST, std::string> Any::convert(EnableString<DST>) const
{
const auto& type = _any.type();
if(type == typeid(SafeAny::SimpleString))
{
return linb::any_cast<SafeAny::SimpleString>(_any).toStdString();
}
else if(type == typeid(int64_t))
{
return std::to_string(linb::any_cast<int64_t>(_any));
}
else if(type == typeid(uint64_t))
{
return std::to_string(linb::any_cast<uint64_t>(_any));
}
else if(type == typeid(double))
{
return std::to_string(linb::any_cast<double>(_any));
}
return nonstd::make_unexpected(errorMsg<DST>());
}
template <typename T>
inline nonstd::expected<T, std::string> Any::stringToNumber() const
{
static_assert(std::is_arithmetic_v<T> && !std::is_same_v<T, bool>, "Expecting a "
"numeric type");
const auto str = linb::any_cast<SafeAny::SimpleString>(_any);
#if __cpp_lib_to_chars >= 201611L
T out;
auto [ptr, err] = std::from_chars(str.data(), str.data() + str.size(), out);
if(err == std::errc())
{
return out;
}
else
{
return nonstd::make_unexpected("Any failed string to number conversion");
}
#else
try
{
if constexpr(std::is_same_v<T, uint16_t>)
{
return std::stoul(str.toStdString());
}
if constexpr(std::is_integral_v<T>)
{
const int64_t val = std::stol(str.toStdString());
Any temp_any(val);
return temp_any.convert<T>();
}
if constexpr(std::is_floating_point_v<T>)
{
return std::stod(str.toStdString());
}
}
catch(...)
{
return nonstd::make_unexpected("Any failed string to number conversion");
}
#endif
return nonstd::make_unexpected("Any conversion from string failed");
}
template <typename DST>
inline nonstd::expected<DST, std::string> Any::convert(EnableEnum<DST>) const
{
using SafeAny::details::convertNumber;
const auto& type = _any.type();
if(type == typeid(int64_t))
{
auto out = linb::any_cast<int64_t>(_any);
return static_cast<DST>(out);
}
else if(type == typeid(uint64_t))
{
auto out = linb::any_cast<uint64_t>(_any);
return static_cast<DST>(out);
}
return nonstd::make_unexpected(errorMsg<DST>());
}
template <typename DST>
inline nonstd::expected<DST, std::string> Any::convert(EnableArithmetic<DST>) const
{
using SafeAny::details::convertNumber;
DST out;
const auto& type = _any.type();
if(type == typeid(int64_t))
{
convertNumber<int64_t, DST>(linb::any_cast<int64_t>(_any), out);
}
else if(type == typeid(uint64_t))
{
convertNumber<uint64_t, DST>(linb::any_cast<uint64_t>(_any), out);
}
else if(type == typeid(double))
{
convertNumber<double, DST>(linb::any_cast<double>(_any), out);
}
else
{
return nonstd::make_unexpected(errorMsg<DST>());
}
return out;
}
template <typename T>
inline nonstd::expected<T, std::string> Any::tryCast() const
{
static_assert(!std::is_reference<T>::value, "Any::cast uses value semantic, "
"can not cast to reference");
if(_any.empty())
{
throw std::runtime_error("Any::cast failed because it is empty");
}
// special case: T is a shared_ptr to a registered polymorphic type.
// The stored value is a shared_ptr<Base>, but the user is requesting shared_ptr<Derived>.
// Perform safe downcasting (static or dynamic) from Base to Derived if applicable.
if constexpr(is_shared_ptr<T>::value)
{
using Derived = typename T::element_type;
using Base = typename any_cast_base<Derived>::type;
if constexpr(is_polymorphic_safe_v<Derived> && !std::is_same_v<Base, void>)
{
// Attempt to retrieve the stored shared_ptr<Base> from the Any container
auto base_ptr = linb::any_cast<std::shared_ptr<Base>>(_any);
if(!base_ptr)
{
throw std::runtime_error("Any::cast cannot cast to shared_ptr<Base> class");
}
// Case 1: If Base and Derived are the same, no casting is needed
if constexpr(std::is_same_v<T, std::shared_ptr<Base>>)
{
return base_ptr;
}
// Case 2: If the original stored type was shared_ptr<Derived>, we can safely static_cast
if(_original_type == typeid(std::shared_ptr<Derived>))
{
return std::static_pointer_cast<Derived>(base_ptr);
}
// Case 3: Otherwise, attempt a dynamic cast from Base to Derived
auto derived_ptr = std::dynamic_pointer_cast<Derived>(base_ptr);
if(!derived_ptr)
throw std::runtime_error("Any::cast Dynamic cast failed, types are not related");
return derived_ptr;
}
}
if(castedType() == typeid(T))
{
return linb::any_cast<T>(_any);
}
// special case when the output is an enum.
// We will try first a int convertion
if constexpr(std::is_enum_v<T>)
{
if(isNumber())
{
return static_cast<T>(convert<int>().value());
}
if(isString())
{
if(auto out = stringToNumber<int64_t>())
{
return static_cast<T>(out.value());
}
}
return nonstd::make_unexpected("Any::cast failed to cast to enum type");
}
if(isString())
{
if constexpr(std::is_arithmetic_v<T> && !std::is_same_v<T, bool>)
{
if(auto out = stringToNumber<T>())
{
return out.value();
}
else
{
return out;
}
}
}
if(auto res = convert<T>())
{
return res.value();
}
else
{
return res;
}
}
} // end namespace BT