1 module dlangui.core.streams;
2 
3 private import std.stdio;
4 
5 interface Closeable {
6     void close();
7     @property bool isOpen();
8 }
9 
10 interface InputStream : Closeable {
11     size_t read(ubyte[] buffer);
12     @property bool eof();
13 }
14 
15 interface OutputStream : Closeable {
16     void write(ubyte[] data);
17 }
18 
19 class FileInputStream : InputStream {
20     std.stdio.File _file;
21     this(string filename) {
22         _file = std.stdio.File(filename, "rb");
23     }
24     void close() {
25         if (isOpen)
26             _file.close();
27     }
28     size_t read(ubyte[] buffer) {
29         ubyte[] res = _file.rawRead(buffer);
30         return res.length;
31     }
32     @property bool isOpen() {
33         return _file.isOpen;
34     }
35     @property bool eof() {
36         return _file.eof;
37     }
38 }
39 
40 class FileOutputStream : OutputStream {
41     std.stdio.File _file;
42     this(string filename) {
43         _file = std.stdio.File(filename, "wb");
44     }
45     void close() {
46         _file.close();
47     }
48     void write(ubyte[] data) {
49         _file.rawWrite(data);
50     }
51     @property bool isOpen() {
52         return _file.isOpen;
53     }
54 }
55 
56 class MemoryInputStream : InputStream {
57     private ubyte[] _data;
58     private size_t _pos;
59     private bool _closed;
60     this(ubyte[] data) {
61         _data = data;
62         _closed = false;
63         _pos = 0;
64     }
65     void close() {
66         _closed = true;
67     }
68     @property bool isOpen() {
69         return !_closed;
70     }
71     size_t read(ubyte[] buffer) {
72         size_t bytesRead = 0;
73         for (size_t i = 0; i < buffer.length && _pos < _data.length; bytesRead++) {
74             buffer[i++] = _data[_pos++];
75         }
76         return bytesRead;
77     }
78     @property bool eof() {
79         return _closed || (_pos >= _data.length);
80     }
81 }