unaligned_access.h 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. #ifndef Y_ABSL_BASE_INTERNAL_UNALIGNED_ACCESS_H_
  17. #define Y_ABSL_BASE_INTERNAL_UNALIGNED_ACCESS_H_
  18. #include <string.h>
  19. #include <cstdint>
  20. #include "y_absl/base/attributes.h"
  21. #include "y_absl/base/config.h"
  22. // unaligned APIs
  23. // Portable handling of unaligned loads, stores, and copies.
  24. // The unaligned API is C++ only. The declarations use C++ features
  25. // (namespaces, inline) which are absent or incompatible in C.
  26. #if defined(__cplusplus)
  27. namespace y_absl {
  28. Y_ABSL_NAMESPACE_BEGIN
  29. namespace base_internal {
  30. inline uint16_t UnalignedLoad16(const void *p) {
  31. uint16_t t;
  32. memcpy(&t, p, sizeof t);
  33. return t;
  34. }
  35. inline uint32_t UnalignedLoad32(const void *p) {
  36. uint32_t t;
  37. memcpy(&t, p, sizeof t);
  38. return t;
  39. }
  40. inline uint64_t UnalignedLoad64(const void *p) {
  41. uint64_t t;
  42. memcpy(&t, p, sizeof t);
  43. return t;
  44. }
  45. inline void UnalignedStore16(void *p, uint16_t v) { memcpy(p, &v, sizeof v); }
  46. inline void UnalignedStore32(void *p, uint32_t v) { memcpy(p, &v, sizeof v); }
  47. inline void UnalignedStore64(void *p, uint64_t v) { memcpy(p, &v, sizeof v); }
  48. } // namespace base_internal
  49. Y_ABSL_NAMESPACE_END
  50. } // namespace y_absl
  51. #define Y_ABSL_INTERNAL_UNALIGNED_LOAD16(_p) \
  52. (y_absl::base_internal::UnalignedLoad16(_p))
  53. #define Y_ABSL_INTERNAL_UNALIGNED_LOAD32(_p) \
  54. (y_absl::base_internal::UnalignedLoad32(_p))
  55. #define Y_ABSL_INTERNAL_UNALIGNED_LOAD64(_p) \
  56. (y_absl::base_internal::UnalignedLoad64(_p))
  57. #define Y_ABSL_INTERNAL_UNALIGNED_STORE16(_p, _val) \
  58. (y_absl::base_internal::UnalignedStore16(_p, _val))
  59. #define Y_ABSL_INTERNAL_UNALIGNED_STORE32(_p, _val) \
  60. (y_absl::base_internal::UnalignedStore32(_p, _val))
  61. #define Y_ABSL_INTERNAL_UNALIGNED_STORE64(_p, _val) \
  62. (y_absl::base_internal::UnalignedStore64(_p, _val))
  63. #endif // defined(__cplusplus), end of unaligned API
  64. #endif // Y_ABSL_BASE_INTERNAL_UNALIGNED_ACCESS_H_