1 //
2 // Copyright 2017 The Abseil Authors.
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 //      https://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 //
16 
17 #ifndef ABSL_BASE_INTERNAL_UNALIGNED_ACCESS_H_
18 #define ABSL_BASE_INTERNAL_UNALIGNED_ACCESS_H_
19 
20 #include <string.h>
21 
22 #include <cstdint>
23 
24 #include "absl/base/attributes.h"
25 #include "absl/base/config.h"
26 
27 // unaligned APIs
28 
29 // Portable handling of unaligned loads, stores, and copies.
30 
31 // The unaligned API is C++ only.  The declarations use C++ features
32 // (namespaces, inline) which are absent or incompatible in C.
33 #if defined(__cplusplus)
34 namespace absl {
35 ABSL_NAMESPACE_BEGIN
36 namespace base_internal {
37 
UnalignedLoad16(const void * p)38 inline uint16_t UnalignedLoad16(const void* p) {
39   uint16_t t;
40   memcpy(&t, p, sizeof t);
41   return t;
42 }
43 
UnalignedLoad32(const void * p)44 inline uint32_t UnalignedLoad32(const void* p) {
45   uint32_t t;
46   memcpy(&t, p, sizeof t);
47   return t;
48 }
49 
UnalignedLoad64(const void * p)50 inline uint64_t UnalignedLoad64(const void* p) {
51   uint64_t t;
52   memcpy(&t, p, sizeof t);
53   return t;
54 }
55 
UnalignedStore16(void * p,uint16_t v)56 inline void UnalignedStore16(void* p, uint16_t v) { memcpy(p, &v, sizeof v); }
57 
UnalignedStore32(void * p,uint32_t v)58 inline void UnalignedStore32(void* p, uint32_t v) { memcpy(p, &v, sizeof v); }
59 
UnalignedStore64(void * p,uint64_t v)60 inline void UnalignedStore64(void* p, uint64_t v) { memcpy(p, &v, sizeof v); }
61 
62 }  // namespace base_internal
63 ABSL_NAMESPACE_END
64 }  // namespace absl
65 
66 #  define ABSL_INTERNAL_UNALIGNED_LOAD16(_p) \
67     (absl::base_internal::UnalignedLoad16(_p))
68 #  define ABSL_INTERNAL_UNALIGNED_LOAD32(_p) \
69     (absl::base_internal::UnalignedLoad32(_p))
70 #  define ABSL_INTERNAL_UNALIGNED_LOAD64(_p) \
71     (absl::base_internal::UnalignedLoad64(_p))
72 
73 #  define ABSL_INTERNAL_UNALIGNED_STORE16(_p, _val) \
74     (absl::base_internal::UnalignedStore16(_p, _val))
75 #  define ABSL_INTERNAL_UNALIGNED_STORE32(_p, _val) \
76     (absl::base_internal::UnalignedStore32(_p, _val))
77 #  define ABSL_INTERNAL_UNALIGNED_STORE64(_p, _val) \
78     (absl::base_internal::UnalignedStore64(_p, _val))
79 
80 #endif  // defined(__cplusplus), end of unaligned API
81 
82 #endif  // ABSL_BASE_INTERNAL_UNALIGNED_ACCESS_H_
83