1 // Copyright 2016 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 namespace WTF {
6
7 template <typename To, typename From>
IsInBounds(From value)8 bool IsInBounds(From value) {
9 return true;
10 }
11
12 template <typename To, typename From>
SafeCast(From value)13 To SafeCast(From value) {
14 if (!IsInBounds<To>(value))
15 return 0;
16 return static_cast<To>(value);
17 }
18
19 template <typename T, typename OverflowHandler>
20 class Checked {
21 public:
22 template <typename U, typename V>
Checked(const Checked<U,V> & rhs)23 Checked(const Checked<U, V>& rhs) {
24 if (rhs.HasOverflowed())
25 this->Overflowed();
26 if (!IsInBounds<T>(rhs.value_))
27 this->Overflowed();
28 value_ = static_cast<T>(rhs.value_);
29 }
30
HasOverflowed() const31 bool HasOverflowed() const { return false; }
Overflowed()32 void Overflowed() {}
33
34 private:
35 T value_;
36 };
37
38 template <typename To, typename From>
bitwise_cast(From from)39 To bitwise_cast(From from) {
40 static_assert(sizeof(To) == sizeof(From), "msg");
41 return reinterpret_cast<To>(from);
42 }
43
44 } // namespace WTF
45
46 namespace mojo {
47
48 template <typename U>
49 struct ArrayTraits;
50
51 template <typename U>
52 struct ArrayTraits<WTF::Checked<U, int>> {
HasOverflowedmojo::ArrayTraits53 static bool HasOverflowed(WTF::Checked<U, int>& input) {
54 // |hasOverflowed| below should be rewritten to |HasOverflowed|
55 // (because this is a method of WTF::Checked; it doesn't matter
56 // that we are not in WTF namespace *here*).
57 return input.HasOverflowed();
58 }
59 };
60
61 } // namespace mojo
62
63 using WTF::bitwise_cast;
64 using WTF::SafeCast;
65