My Project
bytebuf.h
Go to the documentation of this file.
1 #ifndef _SINGULAR_LIBTHREAD_BYTEBUFFER_H
2 #define _SINGULAR_LIBTHREAD_BYTEBUFFER_H
3 
4 #include <cstddef>
5 #include <cstdlib>
6 #include <cstring>
7 
8 namespace LibThread {
9 
10 using namespace std;
11 
12 char *allocate_space (size_t n);
13 void free_space(size_t n, char *p);
14 
15 class ByteBuf {
16 private:
17  size_t count;
18  size_t cap;
19  size_t pos;
20  char *buf;
21 public:
22  ByteBuf() : pos(0), count(0), cap(0) { }
23  ByteBuf(const ByteBuf &other) :
24  count(other.count), cap(other.cap), pos(0)
25  {
26  buf = allocate_space(cap);
27  memcpy(buf, other.buf, count);
28  }
29  ByteBuf &operator=(const ByteBuf &other) {
30  count = other.count;
31  cap = other.cap;
32  pos = 0;
33  buf = allocate_space(cap);
34  memcpy(buf, other.buf, count);
35  return *this;
36  }
38  free_space(cap, buf);
39  }
40  size_t size() { return count; }
41  void write_bytes(char *p, size_t n) {
42  if (pos + n >= cap) {
43  char *newbuf = allocate_space(2 * cap);
44  memcpy(newbuf, buf, count);
45  free_space(cap, buf);
46  cap *= 2;
47  }
48  memcpy(buf+pos, p, n);
49  pos += n;
50  if (pos >= count)
51  count = pos;
52  }
53  void read_bytes(char *p, size_t n) {
54  memcpy(p, buf+pos, n);
55  pos += n;
56  }
57  template <typename T>
58  void write(T &value) {
59  write_bytes((char *)&value, sizeof(T));
60  }
61  template <typename T>
62  void read(T &value) {
63  read_bytes((char *)&value, sizeof(T));
64  }
65  void seek(size_t p) {
66  pos = p;
67  }
68 };
69 
70 }
71 
72 #endif // _SINGULAR_LIBTHREAD_BYTEBUFFER_H
int p
Definition: cfModGcd.cc:4080
ByteBuf & operator=(const ByteBuf &other)
Definition: bytebuf.h:29
size_t size()
Definition: bytebuf.h:40
ByteBuf(const ByteBuf &other)
Definition: bytebuf.h:23
void seek(size_t p)
Definition: bytebuf.h:65
void write_bytes(char *p, size_t n)
Definition: bytebuf.h:41
void write(T &value)
Definition: bytebuf.h:58
void read_bytes(char *p, size_t n)
Definition: bytebuf.h:53
void read(T &value)
Definition: bytebuf.h:62
STATIC_VAR jList * T
Definition: janet.cc:30
void free_space(size_t n, char *p)
char * allocate_space(size_t n)
int status int void size_t count
Definition: si_signals.h:59
int status int void * buf
Definition: si_signals.h:59