-
Notifications
You must be signed in to change notification settings - Fork 7
/
MetafileReader.cs
77 lines (66 loc) · 2.32 KB
/
MetafileReader.cs
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
using System;
using System.IO;
using CgmInfo.Commands;
using CgmInfo.Traversal;
using BinaryMetafileReader = CgmInfo.BinaryEncoding.MetafileReader;
using TextMetafileReader = CgmInfo.TextEncoding.MetafileReader;
namespace CgmInfo
{
public abstract class MetafileReader : IDisposable
{
private readonly MetafilePropertyVisitor _propertyVisitor = new MetafilePropertyVisitor();
private readonly FileStream? _fileStream;
public MetafileDescriptor Descriptor { get; } = new MetafileDescriptor();
public MetafileProperties Properties { get; }
protected MetafileReader(string fileName, bool isBinaryEncoding)
{
_fileStream = File.OpenRead(fileName);
Properties = new MetafileProperties(isBinaryEncoding, _fileStream.Length);
}
protected MetafileReader(MetafileReader other)
{
if (other == null)
throw new ArgumentNullException(nameof(other));
Descriptor = other.Descriptor;
Properties = other.Properties;
}
public Command? Read()
{
if (_fileStream == null)
throw new InvalidOperationException("Attempted to read a Command from a Sub-Buffer reader.");
var command = ReadCommand(_fileStream);
command?.Accept(_propertyVisitor, Properties);
return command;
}
protected abstract Command? ReadCommand(Stream stream);
public static MetafileReader Create(string fileName)
{
bool isBinary;
using (var fs = File.OpenRead(fileName))
isBinary = BinaryMetafileReader.IsBinaryMetafile(fs);
if (isBinary)
return new BinaryMetafileReader(fileName);
else
return new TextMetafileReader(fileName);
}
#region IDisposable
private bool _isDisposed = false;
protected virtual void Dispose(bool disposing)
{
if (!_isDisposed)
{
if (disposing)
{
_fileStream?.Dispose();
}
_isDisposed = true;
}
}
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
#endregion
}
}