• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/private/base/SkAttributes.h"
12 
13 #include <cstring>
14 #include <type_traits> // is_trivially_copyable
15 
16 namespace SkHexadecimalDigits {
17     extern const char gUpper[16];  // 0-9A-F
18     extern const char gLower[16];  // 0-9a-f
19 }  // namespace SkHexadecimalDigits
20 
21 ///////////////////////////////////////////////////////////////////////////////
22 
23 // If T is an 8-byte GCC or Clang vector extension type, it would naturally
24 // pass or return in the MMX mm0 register on 32-bit x86 builds.  This has the
25 // fun side effect of clobbering any state in the x87 st0 register.  (There is
26 // no ABI governing who should preserve mm?/st? registers, so no one does!)
27 //
28 // We force-inline sk_unaligned_load() and sk_unaligned_store() to avoid that,
29 // making them safe to use for all types on all platforms, thus solving the
30 // problem once and for all!
31 
32 template <typename T, typename P>
sk_unaligned_load(const P * ptr)33 static SK_ALWAYS_INLINE T sk_unaligned_load(const P* ptr) {
34     static_assert(std::is_trivially_copyable<T>::value);
35     static_assert(std::is_trivially_copyable<P>::value);
36     T val;
37     memcpy(&val, ptr, sizeof(val));
38     return val;
39 }
40 
41 template <typename T, typename P>
sk_unaligned_store(P * ptr,T val)42 static SK_ALWAYS_INLINE void sk_unaligned_store(P* ptr, T val) {
43     static_assert(std::is_trivially_copyable<T>::value);
44     static_assert(std::is_trivially_copyable<P>::value);
45     memcpy(ptr, &val, sizeof(val));
46 }
47 
48 // Copy the bytes from src into an instance of type Dst and return it.
49 template <typename Dst, typename Src>
sk_bit_cast(const Src & src)50 static SK_ALWAYS_INLINE Dst sk_bit_cast(const Src& src) {
51     static_assert(sizeof(Dst) == sizeof(Src));
52     return sk_unaligned_load<Dst>(&src);
53 }
54 
55 #endif
56