1 // Copyright 2014 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.
5 #ifndef BASE_BIG_ENDIAN_H_
6 #define BASE_BIG_ENDIAN_H_
11 #include "base/base_export.h"
12 #include "base/strings/string_piece.h"
16 // Read an integer (signed or unsigned) from |buf| in Big Endian order.
17 // Note: this loop is unrolled with -O1 and above.
18 // NOTE(szym): glibc dns-canon.c use ntohs(*(uint16_t*)ptr) which is
19 // potentially unaligned.
20 // This would cause SIGBUS on ARMv5 or earlier and ARMv6-M.
22 inline void ReadBigEndian(const char buf[], T* out) {
24 for (size_t i = 1; i < sizeof(T); ++i) {
26 // Must cast to uint8_t to avoid clobbering by sign extension.
27 *out |= static_cast<uint8_t>(buf[i]);
31 // Write an integer (signed or unsigned) |val| to |buf| in Big Endian order.
32 // Note: this loop is unrolled with -O1 and above.
34 inline void WriteBigEndian(char buf[], T val) {
35 for (size_t i = 0; i < sizeof(T); ++i) {
36 buf[sizeof(T)-i-1] = static_cast<char>(val & 0xFF);
41 // Specializations to make clang happy about the (dead code) shifts above.
43 inline void ReadBigEndian<uint8_t>(const char buf[], uint8_t* out) {
48 inline void WriteBigEndian<uint8_t>(char buf[], uint8_t val) {
49 buf[0] = static_cast<char>(val);
52 // Allows reading integers in network order (big endian) while iterating over
53 // an underlying buffer. All the reading functions advance the internal pointer.
54 class BASE_EXPORT BigEndianReader {
56 BigEndianReader(const char* buf, size_t len);
58 const char* ptr() const { return ptr_; }
59 size_t remaining() const { return end_ - ptr_; }
61 bool Skip(size_t len);
62 bool ReadBytes(void* out, size_t len);
63 // Creates a StringPiece in |out| that points to the underlying buffer.
64 bool ReadPiece(base::StringPiece* out, size_t len);
65 bool ReadU8(uint8_t* value);
66 bool ReadU16(uint16_t* value);
67 bool ReadU32(uint32_t* value);
68 bool ReadU64(uint64_t* value);
71 // Hidden to promote type safety.
79 // Allows writing integers in network order (big endian) while iterating over
80 // an underlying buffer. All the writing functions advance the internal pointer.
81 class BASE_EXPORT BigEndianWriter {
83 BigEndianWriter(char* buf, size_t len);
85 char* ptr() const { return ptr_; }
86 size_t remaining() const { return end_ - ptr_; }
88 bool Skip(size_t len);
89 bool WriteBytes(const void* buf, size_t len);
90 bool WriteU8(uint8_t value);
91 bool WriteU16(uint16_t value);
92 bool WriteU32(uint32_t value);
93 bool WriteU64(uint64_t value);
96 // Hidden to promote type safety.
106 #endif // BASE_BIG_ENDIAN_H_