-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBuffer.m
90 lines (76 loc) · 2.21 KB
/
Buffer.m
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
% "Buffered cell array"
classdef Buffer < handle
properties (Constant)
DEF_BUFFER_SIZE = 24;
end
properties
Pool
Size
Len
FFlag
end
methods
function obj = Buffer(size)
if nargin >= 1
obj.Pool = cell(1, size);
else
obj.Pool = cell(1, Buffer.DEF_BUFFER_SIZE);
end
obj.Size = length(obj.Pool);
obj.Len = 0;
obj.FFlag = 0;
end
% "Get length"
function l = len(obj)
l = obj.Len;
end
% "Get pool"
function p = pool(obj)
p = obj.Pool(1:obj.Len);
end
% "Expand buffer if needed"
% If at max length, exponentially increase buffer (x2).
% Call this prior to adding any items.
function cbin(obj)
if obj.FFlag
error("Buffer flushed and cannot be used.");
end
if obj.Len >= obj.Size
obj.Pool = [ obj.Pool, cell(1, obj.Size) ];
obj.Size = obj.Size * 2;
% fprintf("Buffer changed size from %i to %i — consider new defsize.\n", obj.BufferSize / 2, obj.BufferSize);
end
end
% "Add item"
function a(obj, item)
if obj.FFlag
error("Buffer flushed and cannot be used.");
end
obj.cbin();
obj.Pool{obj.Len + 1} = unwrap(item, 1);
obj.Len = obj.Len + 1;
end
% "Add all items"
function aa(obj, items)
if obj.FFlag
error("Buffer flushed and cannot be used.");
end
for item = items
obj.a(item);
end
end
% "Flush buffer"
% The buffer shouldn't be used after flushing.
% For regular array, simply cell2mat the result.
function cellarr = flush(obj)
if obj.FFlag
error("Buffer flushed and cannot be used.");
end
cellarr = obj.Pool(1:obj.Len);
obj.Pool = {};
obj.Size = -1;
obj.Len = -1;
obj.FFlag = 1;
end
end
end