File: BufStream.cpp

package info (click to toggle)
storm-lang 0.7.4-1
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 52,004 kB
  • sloc: ansic: 261,462; cpp: 140,405; sh: 14,891; perl: 9,846; python: 2,525; lisp: 2,504; asm: 860; makefile: 678; pascal: 70; java: 52; xml: 37; awk: 12
file content (93 lines) | stat: -rw-r--r-- 2,018 bytes parent folder | download | duplicates (3)
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
81
82
83
84
85
86
87
88
89
90
91
92
93
#include "stdafx.h"
#include "BufStream.h"
#include "Core/CloneEnv.h"

namespace storm {
	namespace server {

		BufStream::BufStream() {}

		BufStream::BufStream(const BufStream &o) : data(o.data), pos(o.pos) {}

		void BufStream::deepCopy(CloneEnv *env) {
			cloned(data, env);
		}

		Bool BufStream::more() {
			return pos < data.filled();
		}

		Buffer BufStream::read(Buffer to) {
			Nat start = to.filled();
			Nat copy = min(to.count() - to.filled(), data.filled() - pos);
			memcpy(to.dataPtr() + start, data.dataPtr() + pos, copy);
			pos += copy;
			to.filled(start + copy);
			return to;
		}

		Buffer BufStream::peek(Buffer to) {
			Nat oldPos = pos;
			Buffer r = read(to);
			pos = oldPos;
			return r;
		}

		void BufStream::seek(Word to) {
			pos = min(Nat(to), data.filled());
		}

		Word BufStream::tell() {
			return pos;
		}

		Word BufStream::length() {
			return data.filled();
		}

		RIStream *BufStream::randomAccess() {
			return this;
		}

		void BufStream::toS(StrBuf *to) const {
			data.outputMark(to, pos);
		}

		Nat BufStream::findByte(Byte b) const {
			Nat count = data.filled();
			for (Nat i = pos; i < count; i++)
				if (data[i] == b)
					return i - pos;
			return count - pos;
		}

		void BufStream::append(Buffer src) {
			Nat copy = src.filled();
			if (data.filled() + copy >= data.count())
				realloc(copy);

			Nat start = data.filled();
			memcpy(data.dataPtr() + start, src.dataPtr(), copy);
			data.filled(start + copy);
		}

		void BufStream::realloc(Nat count) {
			Nat currentCap = data.filled() - pos;
			Nat newCap = currentCap + count;

			// Is it possible to just discard data and fit the new data?
			if (newCap <= data.count()) {
				memmove(data.dataPtr(), data.dataPtr() + pos, currentCap);
			} else {
				// No, we need to allocate a new array.
				Buffer newData = buffer(engine(), max(newCap, 2 * data.count()));
				memcpy(newData.dataPtr(), data.dataPtr() + pos, currentCap);
				data = newData;
			}

			data.filled(currentCap);
			pos = 0;
		}

	}
}