-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileObserver.cs
More file actions
63 lines (55 loc) · 1.43 KB
/
Copy pathFileObserver.cs
File metadata and controls
63 lines (55 loc) · 1.43 KB
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
namespace Rule110;
public class FileObserver : IObserver
{
private FileStream _fs;
private BinaryWriter _bw;
private int _width;
private static byte[] _mask = [
1 << 7,
1 << 6,
1 << 5,
1 << 4,
1 << 3,
1 << 2,
1 << 1,
1 << 0,
];
public FileObserver(int size, string filePath)
: this(size, size, filePath)
{
}
public FileObserver(int width, int height, string filePath)
{
if (File.Exists(filePath))
File.Delete(filePath);
_width = width;
_fs = new FileStream(filePath, new FileStreamOptions {
Mode = FileMode.Create,
Access = FileAccess.Write,
PreallocationSize = DivCeil(width, 8) * height + 8
});
_bw = new BinaryWriter(_fs);
_bw.Write(width);
_bw.Write(height);
}
public void Next(int lvl, int[] tape)
{
var bytesTotal = DivCeil(_width, 8);
for (int i = 0; i < bytesTotal; i++)
{
byte b = 0;
for (int j = i * 8, ind = 0; j < Math.Min(_width, (i + 1) * 8); j++, ind++)
{
if (tape[j] == 1)
b |= _mask[ind];
}
_bw.Write(b);
}
}
public void Complete()
{
_fs.Dispose();
_bw.Dispose();
}
private static int DivCeil(int n, int i) => n / i + (n % i != 0 ? 1 : 0);
}