forked from EvilBeaver/OneScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTextReadImpl.cs
More file actions
266 lines (237 loc) · 10.4 KB
/
TextReadImpl.cs
File metadata and controls
266 lines (237 loc) · 10.4 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
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
/*----------------------------------------------------------
This Source Code Form is subject to the terms of the
Mozilla Public License, v.2.0. If a copy of the MPL
was not distributed with this file, You can obtain one
at http://mozilla.org/MPL/2.0/.
----------------------------------------------------------*/
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using OneScript.Commons;
using OneScript.Contexts;
using OneScript.Exceptions;
using OneScript.StandardLibrary.Binary;
using OneScript.Values;
using ScriptEngine.Machine;
using ScriptEngine.Machine.Contexts;
namespace OneScript.StandardLibrary.Text
{
/// <summary>
/// Предназначен для последовательного чтения файлов, в том числе большого размера.
/// </summary>
[ContextClass("ЧтениеТекста", "TextReader")]
public class TextReadImpl : AutoContext<TextReadImpl>, IDisposable
{
// TextReader _reader;
CustomLineFeedStreamReader _reader;
string _lineDelimiter = "\n";
public TextReadImpl ()
{
AnalyzeDefaultLineFeed = true;
}
/// <summary>
/// Открывает текстовый файл для чтения. Ранее открытый файл закрывается.
/// </summary>
/// <param name="input">Путь к файлу или поток</param>
/// <param name="encoding">Кодировка</param>
/// <param name="lineDelimiter">Раздедитель строк</param>
/// <param name="eolDelimiter">Разделитель строк в файле</param>
/// <param name="monopoly">Открывать монопольно</param>
[ContextMethod("Открыть", "Open")]
public void Open(IValue input, IValue encoding = null, string lineDelimiter = "\n", string eolDelimiter = null,
bool? monopoly = null)
{
Close();
if(IsStream(input, out var wrapper))
{
OpenStream(wrapper, encoding, lineDelimiter, eolDelimiter);
}
else
{
OpenFile(
ContextValuesMarshaller.ConvertValueStrict<string>(input),
encoding,
lineDelimiter,
eolDelimiter,
monopoly);
}
}
private void OpenStream(IStreamWrapper streamObj, IValue encoding = null, string lineDelimiter = "\n", string eolDelimiter = null)
{
TextReader imReader;
if (encoding == null)
{
imReader = FileOpener.OpenReader(streamObj.GetUnderlyingStream(), Encoding.Default);
}
else
{
var enc = TextEncodingEnum.GetEncoding(encoding);
imReader = FileOpener.OpenReader(streamObj.GetUnderlyingStream(), enc);
}
_reader = GetCustomLineFeedReader(imReader, lineDelimiter, eolDelimiter, AnalyzeDefaultLineFeed);
}
private void OpenFile(string path, IValue encoding = null, string lineDelimiter = "\n", string eolDelimiter = null,
bool? monopoly = null)
{
TextReader imReader;
var shareMode = (monopoly ?? true) ? FileShare.None : FileShare.ReadWrite;
if (encoding == null)
{
imReader = FileOpener.OpenReader(path, shareMode);
}
else
{
var enc = TextEncodingEnum.GetEncoding(encoding);
imReader = FileOpener.OpenReader(path, shareMode, enc);
}
_reader = GetCustomLineFeedReader(imReader, lineDelimiter, eolDelimiter, AnalyzeDefaultLineFeed);
}
private bool AnalyzeDefaultLineFeed { get; set; }
private int ReadNext()
{
return _reader.Read ();
}
/// <summary>
/// Считывает строку указанной длины или до конца файла.
/// </summary>
/// <param name="size">Размер строки. Если не задан, текст считывается до конца файла</param>
/// <returns>Строка - считанная строка, Неопределено - в файле больше нет данных</returns>
[ContextMethod("Прочитать", "Read")]
public IValue ReadAll(int size = 0)
{
RequireOpen();
var sb = new StringBuilder();
var read = 0;
do {
var ic = ReadNext();
if (ic == -1)
break;
sb.Append((char)ic);
++read;
} while (size == 0 || read < size);
if (sb.Length == 0)
return ValueFactory.Create ();
return ValueFactory.Create(sb.ToString());
}
/// <summary>
/// Считывает очередную строку текстового файла.
/// </summary>
/// <param name="overridenLineDelimiter">Подстрока, считающаяся концом строки. Переопределяет РазделительСтрок,
/// переданный в конструктор или в метод Открыть</param>
/// <returns>Строка - в случае успешного чтения, Неопределено - больше нет данных</returns>
[ContextMethod("ПрочитатьСтроку", "ReadLine")]
public IValue ReadLine(string overridenLineDelimiter = null)
{
RequireOpen();
string l = _reader.ReadLine (overridenLineDelimiter ?? _lineDelimiter);
if (l == null)
return ValueFactory.Create();
return ValueFactory.Create(l);
}
/// <summary>
/// Закрывает открытый текстовый файл. Если файл был открыт монопольно, то после закрытия он становится доступен.
/// </summary>
[ContextMethod("Закрыть", "Close")]
public void Close()
{
Dispose();
}
private void RequireOpen()
{
if (_reader == null)
{
throw new RuntimeException("Файл не открыт");
}
}
/// <summary>
/// Открывает текстовый файл для чтения.
/// </summary>
/// <param name="input">Путь к файлу или поток</param>
/// <returns>ЧтениеТекста</returns>
[ScriptConstructor(Name = "На основании файла или потока без кодировки")]
public static TextReadImpl Constructor (IValue input)
{
var reader = new TextReadImpl ();
reader.AnalyzeDefaultLineFeed = false;
reader.Open (input, null, "\n", "\r\n");
return reader;
}
/// <summary>
/// Создаёт неинициализированный объект. Для инициализации необходимо открыть файл методом Открыть.
/// </summary>
/// <returns>ЧтениеТекста</returns>
[ScriptConstructor(Name = "Формирование неинициализированного объекта")]
public static TextReadImpl Constructor()
{
var reader = new TextReadImpl();
reader.AnalyzeDefaultLineFeed = false;
return reader;
}
/// <summary>
/// Открывает текстовый файл или поток для чтения. Работает аналогично методу Открыть.
/// </summary>
/// <param name="input">Путь к файлу или поток</param>
/// <param name="encoding">Кодировка</param>
/// <param name="lineDelimiter">Разделитель строк</param>
/// <param name="eolDelimiter">Разделитель строк в файле</param>
/// <param name="monopoly">Открывать файл монопольно</param>
/// <returns>ЧтениеТекста</returns>
[ScriptConstructor(Name = "На основании потока или файла")]
public static TextReadImpl ConstructorWithEncoding(IValue input, IValue encoding = null,
string lineDelimiter = null, string eolDelimiter = null, bool monopoly = true)
{
var reader = new TextReadImpl();
if (lineDelimiter != null)
reader.AnalyzeDefaultLineFeed = false;
if(IsStream(input, out var wrapper))
{
reader.OpenStream(
wrapper,
encoding,
lineDelimiter ?? "\n",
eolDelimiter);
}
else
{
reader.OpenFile(
ContextValuesMarshaller.ConvertValueStrict<string>(input),
encoding,
lineDelimiter ?? "\n",
eolDelimiter,
monopoly);
}
return reader;
}
private static bool IsStream(IValue input, out IStreamWrapper wrapper)
{
Debug.Assert(!(input is IValueReference));
wrapper = null;
if (input is IStreamWrapper wrap)
{
wrapper = wrap;
return true;
}
return false;
}
private CustomLineFeedStreamReader GetCustomLineFeedReader(TextReader imReader, string lineDelimiter,
string eolDelimiter, bool AnalyzeDefaultLineFeed)
{
_lineDelimiter = lineDelimiter ?? "\n";
if (eolDelimiter != null)
return new CustomLineFeedStreamReader(imReader, eolDelimiter, AnalyzeDefaultLineFeed);
else
return new CustomLineFeedStreamReader(imReader, "\r\n", AnalyzeDefaultLineFeed);
}
#region IDisposable Members
public void Dispose()
{
if (_reader != null)
{
_reader.Dispose();
_reader = null;
}
}
#endregion
}
}