File: data_reader.cc

package info (click to toggle)
xsettingsd 1.0.2-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, forky, sid, trixie
  • size: 204 kB
  • sloc: cpp: 2,135; makefile: 19; sh: 6
file content (80 lines) | stat: -rw-r--r-- 1,772 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// Copyright 2009 Daniel Erat <dan@erat.org>
// All rights reserved.

#include "data_reader.h"

#include <arpa/inet.h>

using std::string;

namespace xsettingsd {

DataReader::DataReader(const char* buffer, size_t buf_len)
    : buffer_(buffer),
      buf_len_(buf_len),
      bytes_read_(0),
      reverse_bytes_(false) {
}

bool DataReader::ReadBytes(string* out, size_t size) {
  if (bytes_read_ + size > buf_len_ ||
      bytes_read_ + size < bytes_read_) {
    return false;
  }
  if (out)
    out->assign(buffer_ + bytes_read_, size);
  bytes_read_ += size;
  return true;
}

bool DataReader::ReadInt8(int8_t* out) {
  if (bytes_read_ + sizeof(int8_t) > buf_len_ ||
      bytes_read_ + sizeof(int8_t) < bytes_read_) {
    return false;
  }

  if (out)
    *out = *reinterpret_cast<const int8_t*>(buffer_ + bytes_read_);
  bytes_read_ += sizeof(int8_t);
  return true;
}

bool DataReader::ReadInt16(int16_t* out) {
  if (bytes_read_ + sizeof(int16_t) > buf_len_ ||
      bytes_read_ + sizeof(int16_t) < bytes_read_) {
    return false;
  }

  if (out) {
    *out = *reinterpret_cast<const int16_t*>(buffer_ + bytes_read_);
    if (reverse_bytes_) {
      if (IsLittleEndian())
        *out = ntohs(*out);
      else
        *out = htons(*out);
    }
  }
  bytes_read_ += sizeof(int16_t);
  return true;
}

bool DataReader::ReadInt32(int32_t* out) {
  if (bytes_read_ + sizeof(int32_t) > buf_len_ ||
      bytes_read_ + sizeof(int32_t) < bytes_read_) {
    return false;
  }

  if (out) {
    *out = *reinterpret_cast<const int32_t*>(buffer_ + bytes_read_);
    if (reverse_bytes_) {
      if (IsLittleEndian())
        *out = ntohl(*out);
      else
        *out = htonl(*out);
    }
  }
  bytes_read_ += sizeof(int32_t);
  return true;
}

}  // namespace xsettingsd