net: socket system, high level api
[quarnos.git] / libs / buffer.h
blob7b6dc7b0c4401159a11b71cc1bc51d145e7e5d4e
1 /* Quarn OS
3 * Buffer
5 * Copyright (C) 2008-2009 Pawel Dziepak
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 #ifndef _BUFFER_H_
24 #define _BUFFER_H_
26 #include "pointer.h"
27 #include "math.h"
29 void *memcpy(void *,const void*,int);
31 class buffer {
32 private:
33 char *address;
34 int size;
36 public:
37 buffer() : address((char*)0), size(0) { }
39 buffer(unsigned int bytes) : address(new char[bytes]), size(bytes) { }
41 buffer(void *addr, int siz) : address((char*)addr), size(siz) { }
43 buffer(const buffer &x) : address(x.address), size(x.size) { }
45 buffer &operator=(const buffer &x) {
46 address = x.address;
47 size = x.size;
49 return *this;
52 operator void*() {
53 return address;
56 char &operator[](int i) {
57 if (i >= 0 && i < size)
58 return address[i];
61 const char &operator[](int i) const {
62 if (i >= 0 && i < size)
63 return address[i];
66 buffer &operator+=(const buffer &x) {
67 char *buf = new char[x.size + size];
68 memcpy(buf, address, size);
69 memcpy((void*)((unsigned int)buf + size), x.address, x.size);
71 delete address;
72 address = buf;
73 size += x.size;
75 return *this;
78 template<typename T>
79 p<T> cast() const {
80 if (size >= sizeof(T))
81 return p<T>(reinterpret_cast<T*>(address));
84 int get_size() const {
85 return size;
88 void *get_address() const {
89 return address;
92 buffer cut_first(unsigned int cut_size) const {
93 if (cut_size >= size)
94 throw cut_size;
96 return buffer(address + cut_size, size - cut_size);
99 buffer copy() const {
100 buffer buf(new char[size], size);
101 memcpy(buf.address, address, size);
102 return buf;
105 buffer copy_data(const buffer &buf) {
106 memcpy(address, buf.address, math::min(size, buf.size));
109 template<typename T>
110 static buffer to_mem(p<T> addr) {
111 return buffer((void*)addr, sizeof(T));
114 template<typename T>
115 static buffer to_mem(T &addr) {
116 return buffer((void*)&addr, sizeof(T));
120 #endif