big_endian.cc 2.12 KB
Newer Older
1
// Copyright 2014 The Chromium Authors. All rights reserved.
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
#include "base/big_endian.h"
6

7
#include "base/strings/string_piece.h"
8

9
namespace base {
10

11 12
BigEndianReader::BigEndianReader(const char* buf, size_t len)
    : ptr_(buf), end_(ptr_ + len) {}
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45

bool BigEndianReader::Skip(size_t len) {
  if (ptr_ + len > end_)
    return false;
  ptr_ += len;
  return true;
}

bool BigEndianReader::ReadBytes(void* out, size_t len) {
  if (ptr_ + len > end_)
    return false;
  memcpy(out, ptr_, len);
  ptr_ += len;
  return true;
}

bool BigEndianReader::ReadPiece(base::StringPiece* out, size_t len) {
  if (ptr_ + len > end_)
    return false;
  *out = base::StringPiece(ptr_, len);
  ptr_ += len;
  return true;
}

template<typename T>
bool BigEndianReader::Read(T* value) {
  if (ptr_ + sizeof(T) > end_)
    return false;
  ReadBigEndian<T>(ptr_, value);
  ptr_ += sizeof(T);
  return true;
}

46
bool BigEndianReader::ReadU8(uint8_t* value) {
47 48 49
  return Read(value);
}

50
bool BigEndianReader::ReadU16(uint16_t* value) {
51 52 53
  return Read(value);
}

54
bool BigEndianReader::ReadU32(uint32_t* value) {
55 56 57
  return Read(value);
}

58
bool BigEndianReader::ReadU64(uint64_t* value) {
59 60 61
  return Read(value);
}

62 63
BigEndianWriter::BigEndianWriter(char* buf, size_t len)
    : ptr_(buf), end_(ptr_ + len) {}
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88

bool BigEndianWriter::Skip(size_t len) {
  if (ptr_ + len > end_)
    return false;
  ptr_ += len;
  return true;
}

bool BigEndianWriter::WriteBytes(const void* buf, size_t len) {
  if (ptr_ + len > end_)
    return false;
  memcpy(ptr_, buf, len);
  ptr_ += len;
  return true;
}

template<typename T>
bool BigEndianWriter::Write(T value) {
  if (ptr_ + sizeof(T) > end_)
    return false;
  WriteBigEndian<T>(ptr_, value);
  ptr_ += sizeof(T);
  return true;
}

89
bool BigEndianWriter::WriteU8(uint8_t value) {
90 91 92
  return Write(value);
}

93
bool BigEndianWriter::WriteU16(uint16_t value) {
94 95 96
  return Write(value);
}

97
bool BigEndianWriter::WriteU32(uint32_t value) {
98 99 100
  return Write(value);
}

101
bool BigEndianWriter::WriteU64(uint64_t value) {
102 103 104
  return Write(value);
}

105
}  // namespace base