source: git/Singular/dyn_modules/systhreads/bytebuf.h

spielwiese
Last change on this file was b2e2b0, checked in by Max Horn <max@…>, 4 years ago
Fix a bunch of warnings
  • Property mode set to 100644
File size: 1.4 KB
Line 
1#ifndef _SINGULAR_LIBTHREAD_BYTEBUFFER_H
2#define _SINGULAR_LIBTHREAD_BYTEBUFFER_H
3
4#include <cstddef>
5#include <cstdlib>
6#include <cstring>
7
8namespace LibThread {
9
10using namespace std;
11
12char *allocate_space (size_t n);
13void free_space(size_t n, char *p);
14
15class ByteBuf {
16private:
17  size_t count;
18  size_t cap;
19  size_t pos;
20  char *buf;
21public:
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  }
37  ~ByteBuf() {
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
Note: See TracBrowser for help on using the repository browser.