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 #include "base/big_endian.h"
9 #include "base/numerics/checked_math.h"
10 #include "base/strings/string_piece.h"
14 BigEndianReader::BigEndianReader(const char* buf, size_t len)
15 : ptr_(buf), end_(ptr_ + len) {}
17 bool BigEndianReader::Skip(size_t len) {
18 if (ptr_ + len > end_)
24 bool BigEndianReader::ReadBytes(void* out, size_t len) {
25 if (ptr_ + len > end_)
27 memcpy(out, ptr_, len);
32 bool BigEndianReader::ReadPiece(base::StringPiece* out, size_t len) {
33 if (ptr_ + len > end_)
35 *out = base::StringPiece(ptr_, len);
41 bool BigEndianReader::Read(T* value) {
42 if (ptr_ + sizeof(T) > end_)
44 ReadBigEndian<T>(ptr_, value);
49 bool BigEndianReader::ReadU8(uint8_t* value) {
53 bool BigEndianReader::ReadU16(uint16_t* value) {
57 bool BigEndianReader::ReadU32(uint32_t* value) {
61 bool BigEndianReader::ReadU64(uint64_t* value) {
66 bool BigEndianReader::ReadLengthPrefixed(base::StringPiece* out) {
70 size_t len = strict_cast<size_t>(t_len);
71 const char* original_ptr = ptr_;
76 *out = base::StringPiece(original_ptr, len);
80 bool BigEndianReader::ReadU8LengthPrefixed(base::StringPiece* out) {
81 return ReadLengthPrefixed<uint8_t>(out);
84 bool BigEndianReader::ReadU16LengthPrefixed(base::StringPiece* out) {
85 return ReadLengthPrefixed<uint16_t>(out);
88 BigEndianWriter::BigEndianWriter(char* buf, size_t len)
89 : ptr_(buf), end_(ptr_ + len) {}
91 bool BigEndianWriter::Skip(size_t len) {
92 if (ptr_ + len > end_)
98 bool BigEndianWriter::WriteBytes(const void* buf, size_t len) {
99 if (ptr_ + len > end_)
101 memcpy(ptr_, buf, len);
107 bool BigEndianWriter::Write(T value) {
108 if (ptr_ + sizeof(T) > end_)
110 WriteBigEndian<T>(ptr_, value);
115 bool BigEndianWriter::WriteU8(uint8_t value) {
119 bool BigEndianWriter::WriteU16(uint16_t value) {
123 bool BigEndianWriter::WriteU32(uint32_t value) {
127 bool BigEndianWriter::WriteU64(uint64_t value) {