• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.
4 
5 #include "base/big_endian.h"
6 
7 #include "base/strings/string_piece.h"
8 
9 namespace base {
10 
BigEndianReader(const char * buf,size_t len)11 BigEndianReader::BigEndianReader(const char* buf, size_t len)
12     : ptr_(buf), end_(ptr_ + len) {}
13 
Skip(size_t len)14 bool BigEndianReader::Skip(size_t len) {
15   if (ptr_ + len > end_)
16     return false;
17   ptr_ += len;
18   return true;
19 }
20 
ReadBytes(void * out,size_t len)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 
ReadPiece(base::StringPiece * out,size_t len)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>
Read(T * value)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 
ReadU8(uint8 * value)46 bool BigEndianReader::ReadU8(uint8* value) {
47   return Read(value);
48 }
49 
ReadU16(uint16 * value)50 bool BigEndianReader::ReadU16(uint16* value) {
51   return Read(value);
52 }
53 
ReadU32(uint32 * value)54 bool BigEndianReader::ReadU32(uint32* value) {
55   return Read(value);
56 }
57 
ReadU64(uint64 * value)58 bool BigEndianReader::ReadU64(uint64* value) {
59   return Read(value);
60 }
61 
BigEndianWriter(char * buf,size_t len)62 BigEndianWriter::BigEndianWriter(char* buf, size_t len)
63     : ptr_(buf), end_(ptr_ + len) {}
64 
Skip(size_t len)65 bool BigEndianWriter::Skip(size_t len) {
66   if (ptr_ + len > end_)
67     return false;
68   ptr_ += len;
69   return true;
70 }
71 
WriteBytes(const void * buf,size_t len)72 bool BigEndianWriter::WriteBytes(const void* buf, size_t len) {
73   if (ptr_ + len > end_)
74     return false;
75   memcpy(ptr_, buf, len);
76   ptr_ += len;
77   return true;
78 }
79 
80 template<typename T>
Write(T value)81 bool BigEndianWriter::Write(T value) {
82   if (ptr_ + sizeof(T) > end_)
83     return false;
84   WriteBigEndian<T>(ptr_, value);
85   ptr_ += sizeof(T);
86   return true;
87 }
88 
WriteU8(uint8 value)89 bool BigEndianWriter::WriteU8(uint8 value) {
90   return Write(value);
91 }
92 
WriteU16(uint16 value)93 bool BigEndianWriter::WriteU16(uint16 value) {
94   return Write(value);
95 }
96 
WriteU32(uint32 value)97 bool BigEndianWriter::WriteU32(uint32 value) {
98   return Write(value);
99 }
100 
WriteU64(uint64 value)101 bool BigEndianWriter::WriteU64(uint64 value) {
102   return Write(value);
103 }
104 
105 }  // namespace base
106