DASH Media Packaging SDK
 All Classes Namespaces Functions Variables Typedefs
buffer_reader.cc
1 // Copyright 2014 Google Inc. All rights reserved.
2 //
3 // Use of this source code is governed by a BSD-style
4 // license that can be found in the LICENSE file or at
5 // https://developers.google.com/open-source/licenses/bsd
6 
7 #include "packager/media/base/buffer_reader.h"
8 
9 #include "packager/base/logging.h"
10 
11 namespace edash_packager {
12 namespace media {
13 
14 bool BufferReader::Read1(uint8_t* v) {
15  DCHECK(v != NULL);
16  if (!HasBytes(1))
17  return false;
18  *v = buf_[pos_++];
19  return true;
20 }
21 
22 bool BufferReader::Read2(uint16_t* v) {
23  return Read(v);
24 }
25 bool BufferReader::Read2s(int16_t* v) {
26  return Read(v);
27 }
28 bool BufferReader::Read4(uint32_t* v) {
29  return Read(v);
30 }
31 bool BufferReader::Read4s(int32_t* v) {
32  return Read(v);
33 }
34 bool BufferReader::Read8(uint64_t* v) {
35  return Read(v);
36 }
37 bool BufferReader::Read8s(int64_t* v) {
38  return Read(v);
39 }
40 bool BufferReader::ReadNBytesInto8(uint64_t* v, size_t num_bytes) {
41  return ReadNBytes(v, num_bytes);
42 }
43 bool BufferReader::ReadNBytesInto8s(int64_t* v, size_t num_bytes) {
44  return ReadNBytes(v, num_bytes);
45 }
46 
47 bool BufferReader::ReadToVector(std::vector<uint8_t>* vec, size_t count) {
48  DCHECK(vec != NULL);
49  if (!HasBytes(count))
50  return false;
51  vec->assign(buf_ + pos_, buf_ + pos_ + count);
52  pos_ += count;
53  return true;
54 }
55 
56 bool BufferReader::SkipBytes(size_t num_bytes) {
57  if (!HasBytes(num_bytes))
58  return false;
59  pos_ += num_bytes;
60  return true;
61 }
62 
63 template <typename T>
64 bool BufferReader::Read(T* v) {
65  return ReadNBytes(v, sizeof(*v));
66 }
67 
68 template <typename T>
69 bool BufferReader::ReadNBytes(T* v, size_t num_bytes) {
70  DCHECK(v != NULL);
71  DCHECK_LE(num_bytes, sizeof(*v));
72  if (!HasBytes(num_bytes))
73  return false;
74 
75  // Sign extension is required only if
76  // |num_bytes| is less than size of T, and
77  // T is a signed type.
78  const bool sign_extension_required =
79  num_bytes < sizeof(*v) && static_cast<T>(-1) < 0;
80  // Perform sign extension by casting the byte value to int8_t, which will be
81  // sign extended automatically when it is implicitly converted to T.
82  T tmp = sign_extension_required ? static_cast<int8_t>(buf_[pos_++])
83  : buf_[pos_++];
84  for (size_t i = 1; i < num_bytes; ++i) {
85  tmp <<= 8;
86  tmp |= buf_[pos_++];
87  }
88  *v = tmp;
89  return true;
90 }
91 
92 } // namespace media
93 } // namespace edash_packager
bool Read1(uint8_t *v) WARN_UNUSED_RESULT
bool SkipBytes(size_t num_bytes) WARN_UNUSED_RESULT
bool ReadNBytesInto8(uint64_t *v, size_t num_bytes) WARN_UNUSED_RESULT