1 // Copyright (c) 2011 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. 4 5 #include "net/base/big_endian.h" 6 7 #include "base/strings/string_piece.h" 8 9 namespace net { 10 11 BigEndianReader::BigEndianReader(const void* buf, size_t len) 12 : ptr_(reinterpret_cast<const char*>(buf)), end_(ptr_ + len) {} 13 14 bool BigEndianReader::Skip(size_t len) { 15 if (ptr_ + len > end_) 16 return false; 17 ptr_ += len; 18 return true; 19 } 20 21 bool BigEndianReader::ReadBytes(void* out, size_t len) { 22 if (ptr_ + len > end_) 23 return false; 24 memcpy(out, ptr_, len); 25 ptr_ += len; 26 return true; 27 } 28 29 bool BigEndianReader::ReadPiece(base::StringPiece* out, size_t len) { 30 if (ptr_ + len > end_) 31 return false; 32 *out = base::StringPiece(ptr_, len); 33 ptr_ += len; 34 return true; 35 } 36 37 template<typename T> 38 bool BigEndianReader::Read(T* value) { 39 if (ptr_ + sizeof(T) > end_) 40 return false; 41 ReadBigEndian<T>(ptr_, value); 42 ptr_ += sizeof(T); 43 return true; 44 } 45 46 bool BigEndianReader::ReadU8(uint8* value) { 47 return Read(value); 48 } 49 50 bool BigEndianReader::ReadU16(uint16* value) { 51 return Read(value); 52 } 53 54 bool BigEndianReader::ReadU32(uint32* value) { 55 return Read(value); 56 } 57 58 BigEndianWriter::BigEndianWriter(void* buf, size_t len) 59 : ptr_(reinterpret_cast<char*>(buf)), end_(ptr_ + len) {} 60 61 bool BigEndianWriter::Skip(size_t len) { 62 if (ptr_ + len > end_) 63 return false; 64 ptr_ += len; 65 return true; 66 } 67 68 bool BigEndianWriter::WriteBytes(const void* buf, size_t len) { 69 if (ptr_ + len > end_) 70 return false; 71 memcpy(ptr_, buf, len); 72 ptr_ += len; 73 return true; 74 } 75 76 template<typename T> 77 bool BigEndianWriter::Write(T value) { 78 if (ptr_ + sizeof(T) > end_) 79 return false; 80 WriteBigEndian<T>(ptr_, value); 81 ptr_ += sizeof(T); 82 return true; 83 } 84 85 bool BigEndianWriter::WriteU8(uint8 value) { 86 return Write(value); 87 } 88 89 bool BigEndianWriter::WriteU16(uint16 value) { 90 return Write(value); 91 } 92 93 bool BigEndianWriter::WriteU32(uint32 value) { 94 return Write(value); 95 } 96 97 } // namespace net 98 99