1 package frost.io
2
3 uses frost.unsafe.Pointer
4
5 ====================================================================================================
6 An `OutputStream` which stores the data written to it in a memory buffer.
7 ====================================================================================================
8 class MemoryOutputStream : OutputStream {
9 @private
10 constant DEFAULT_CAPACITY := 1024
11
12 @private
13 var data:MutableString
14
15 ================================================================================================
16 Creates a new `MemoryOutputStream`.
17 ================================================================================================
18 init() {
19 init(DEFAULT_CAPACITY)
20 }
21
22 ================================================================================================
23 Creates a new `MemoryOutputStream` with the specified capacity.
24 ================================================================================================
25 init(capacity:Int) {
26 data := MutableString(capacity)
27 super.init()
28 }
29
30 @override
31 method write(i:UInt8):Error? {
32 data.append(Char8(i))
33 return null
34 }
35
36 @override
37 method write(ptr:Pointer<UInt8>, count:Int):Error? {
38 data.append(ptr->Pointer<Char8>, count)
39 return null
40 }
41
42 ================================================================================================
43 Clears all data written to the stream.
44 ================================================================================================
45 method clear() {
46 data.clear()
47 }
48
49 ================================================================================================
50 Returns an immutable copy of the data written to this stream. Typically it is better to use
51 [finish()] for performance reasons, as that does not make a copy.
52 ================================================================================================
53 @override
54 function get_toString():String {
55 return data.toString
56 }
57
58 ================================================================================================
59 Invalidates this stream and returns its contents as an immutable `String`. This is generally
60 preferable to [toString], as it does not copy the stream's contents. Interacting in any way
61 with a `MemoryOutputStream` after `finish`ing it will cause precondition violations (or, if
62 safety checks are disabled, undefined behavior).
63 ================================================================================================
64 method finish():String {
65 return data.finish()
66 }
67 }