1 /*
2 * Copyright 2006 The Android Open Source Project
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8 #ifndef SkUtils_DEFINED
9 #define SkUtils_DEFINED
10
11 #include "include/core/SkTypes.h"
12
13 #include <type_traits> // is_trivially_copyable
14
15 namespace SkHexadecimalDigits {
16 extern const char gUpper[16]; // 0-9A-F
17 extern const char gLower[16]; // 0-9a-f
18 } // namespace SkHexadecimalDigits
19
20 ///////////////////////////////////////////////////////////////////////////////
21
22 // If T is an 8-byte GCC or Clang vector extension type, it would naturally
23 // pass or return in the MMX mm0 register on 32-bit x86 builds. This has the
24 // fun side effect of clobbering any state in the x87 st0 register. (There is
25 // no ABI governing who should preserve mm?/st? registers, so no one does!)
26 //
27 // We force-inline sk_unaligned_load() and sk_unaligned_store() to avoid that,
28 // making them safe to use for all types on all platforms, thus solving the
29 // problem once and for all!
30
31 template <typename T, typename P>
sk_unaligned_load(const P * ptr)32 static SK_ALWAYS_INLINE T sk_unaligned_load(const P* ptr) {
33 static_assert(std::is_trivially_copyable<T>::value);
34 static_assert(std::is_trivially_copyable<P>::value);
35 T val;
36 memcpy(&val, ptr, sizeof(val));
37 return val;
38 }
39
40 template <typename T, typename P>
sk_unaligned_store(P * ptr,T val)41 static SK_ALWAYS_INLINE void sk_unaligned_store(P* ptr, T val) {
42 static_assert(std::is_trivially_copyable<T>::value);
43 static_assert(std::is_trivially_copyable<P>::value);
44 memcpy(ptr, &val, sizeof(val));
45 }
46
47 template <typename Dst, typename Src>
sk_bit_cast(const Src & src)48 static SK_ALWAYS_INLINE Dst sk_bit_cast(const Src& src) {
49 static_assert(sizeof(Dst) == sizeof(Src));
50 return sk_unaligned_load<Dst>(&src);
51 }
52
53 #endif
54