Skip to content

Commit 31fa955

Browse files
authored
Merge pull request #1116 from Mr-Rm/fix-1115
fix #1115: беззнаковые типы для ЧтениеДанных/ЗаписьДанных
2 parents 43e0a4f + b91a93c commit 31fa955

File tree

12 files changed

+259
-32
lines changed

12 files changed

+259
-32
lines changed

src/ScriptEngine.HostedScript/Library/Binary/DataReader.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -472,10 +472,10 @@ private T FromBytes<T>(byte[] bytes, Func<byte[], int, T> leConverter, Func<byte
472472
/// <returns name="Number"/>
473473
///
474474
[ContextMethod("ПрочитатьЦелое16", "ReadInt16")]
475-
public int ReadInt16(IValue byteOrder = null)
475+
public uint ReadInt16(IValue byteOrder = null)
476476
{
477-
var bytes = _reader.ReadBytes(sizeof(short));
478-
return FromBytes(bytes, BitConversionFacility.LittleEndian.ToInt16, BitConversionFacility.BigEndian.ToInt16, byteOrder);
477+
var bytes = _reader.ReadBytes(sizeof(ushort));
478+
return FromBytes(bytes, BitConversionFacility.LittleEndian.ToUInt16, BitConversionFacility.BigEndian.ToUInt16, byteOrder);
479479
}
480480

481481

src/ScriptEngine.HostedScript/Library/Binary/DataWriter.cs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -379,7 +379,7 @@ private byte[] GetBytes<T>(T value, Converter<T, byte[]> leConverter, Converter<
379379
/// Значение по умолчанию: Неопределено. </param>
380380
///
381381
[ContextMethod("ЗаписатьЦелое16", "WriteInt16")]
382-
public void WriteInt16(short number, IValue byteOrder = null)
382+
public void WriteInt16(ushort number, IValue byteOrder = null)
383383
{
384384
var buffer = GetBytes(number, BitConversionFacility.LittleEndian.GetBytes, BitConversionFacility.BigEndian.GetBytes, byteOrder);
385385
_binaryWriter.Write(buffer, 0, buffer.Length);
@@ -397,7 +397,7 @@ public void WriteInt16(short number, IValue byteOrder = null)
397397
/// Значение по умолчанию: Неопределено. </param>
398398
///
399399
[ContextMethod("ЗаписатьЦелое32", "WriteInt32")]
400-
public void WriteInt32(int number, IValue byteOrder = null)
400+
public void WriteInt32(uint number, IValue byteOrder = null)
401401
{
402402
var buffer = GetBytes(number, BitConversionFacility.LittleEndian.GetBytes, BitConversionFacility.BigEndian.GetBytes, byteOrder);
403403
_binaryWriter.Write(buffer, 0, buffer.Length);
@@ -406,7 +406,7 @@ public void WriteInt32(int number, IValue byteOrder = null)
406406

407407
/// <summary>
408408
///
409-
/// Записывает целое 16-битное число в целевой поток.
409+
/// Записывает целое 64-битное число в целевой поток.
410410
/// </summary>
411411
///
412412
/// <param name="number">
@@ -416,7 +416,7 @@ public void WriteInt32(int number, IValue byteOrder = null)
416416
/// Значение по умолчанию: Неопределено. </param>
417417
///
418418
[ContextMethod("ЗаписатьЦелое64", "WriteInt64")]
419-
public void WriteInt64(long number, IValue byteOrder = null)
419+
public void WriteInt64(ulong number, IValue byteOrder = null)
420420
{
421421
var buffer = GetBytes(number, BitConversionFacility.LittleEndian.GetBytes, BitConversionFacility.BigEndian.GetBytes, byteOrder);
422422
_binaryWriter.Write(buffer, 0, buffer.Length);

src/ScriptEngine.HostedScript/Library/Binary/GenericStream.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ public GenericStream(Stream underlyingStream, bool readOnly)
4747
}
4848

4949
public bool IsReadOnly => !CanWrite;
50-
50+
5151
/// <summary>
5252
///
5353
/// Признак доступности записи в поток.

src/ScriptEngine.HostedScript/Library/Binary/MemoryStreamContext.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ public class MemoryStreamContext : AutoContext<MemoryStreamContext>, IDisposable
4141
_underlyingStream = new MemoryStream(capacity);
4242
_commonImpl = new GenericStreamImpl(_underlyingStream);
4343
}
44-
44+
4545
/// <summary>
4646
///
4747
/// Создает поток, в качестве нижележащего хранилища для которого используется заданный байтовый буфер. Ёмкость потока ограничена размером буфера. При выходе за границы буфера будет сгенерировано исключение.

src/ScriptEngine.HostedScript/Library/ConsoleContext.cs

Lines changed: 88 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ This Source Code Form is subject to the terms of the
55
at http://mozilla.org/MPL/2.0/.
66
----------------------------------------------------------*/
77
using System;
8+
using System.IO;
9+
using ScriptEngine.HostedScript.Library.Binary;
810
using ScriptEngine.Machine;
911
using ScriptEngine.Machine.Contexts;
1012

@@ -168,6 +170,24 @@ public IValue InputEncoding
168170
Console.InputEncoding = TextEncodingEnum.GetEncoding(value);
169171
}
170172
}
173+
174+
/// <summary>
175+
/// Возвращает или задает кодировку консоли, используемую при чтении входных данных.
176+
/// </summary>
177+
/// <returns>КодировкаТекста</returns>
178+
[ContextProperty("КодировкаВыходногоПотока", "InputEncoding")]
179+
public IValue OutputEncoding
180+
{
181+
get
182+
{
183+
var encodingEnum = GlobalsManager.GetEnum<TextEncodingEnum>();
184+
return encodingEnum.GetValue(Console.OutputEncoding);
185+
}
186+
set
187+
{
188+
Console.OutputEncoding = TextEncodingEnum.GetEncoding(value);
189+
}
190+
}
171191

172192
/// <summary>
173193
/// Воспроизводит звуковой сигнал.
@@ -178,10 +198,77 @@ public void Beep()
178198
Console.Beep();
179199
}
180200

201+
/// <summary>
202+
/// Получает системный поток ввода stdin
203+
/// </summary>
204+
/// <returns>Поток</returns>
205+
[ContextMethod("ОткрытьСтандартныйПотокВвода", "OpenStandardInput")]
206+
public GenericStream OpenStandardInput()
207+
{
208+
var stream = Console.OpenStandardInput();
209+
return new GenericStream(stream, true);
210+
}
211+
212+
/// <summary>
213+
/// Получает системный поток вывода ошибок stderr
214+
/// </summary>
215+
/// <returns>Поток</returns>
216+
[ContextMethod("ОткрытьСтандартныйПотокОшибок", "OpenStandardError")]
217+
public GenericStream OpenStandardError()
218+
{
219+
var stream = Console.OpenStandardError();
220+
return new GenericStream(stream);
221+
}
222+
223+
/// <summary>
224+
/// Получает системный поток вывода stdout
225+
/// </summary>
226+
/// <returns>Поток</returns>
227+
[ContextMethod("ОткрытьСтандартныйПотокВывода", "OpenStandardOutput")]
228+
public GenericStream OpenStandardOutput()
229+
{
230+
var stream = Console.OpenStandardOutput();
231+
return new GenericStream(stream);
232+
}
233+
234+
/// <summary>
235+
/// Глобально переопределяет стандартный вывод и направляет в другой поток
236+
/// </summary>
237+
/// <param name="target">Поток назначения</param>
238+
[ContextMethod("УстановитьПотокВывода", "SetOutput")]
239+
public void SetOutput(IValue target)
240+
{
241+
if (!(target.AsObject() is IStreamWrapper stream))
242+
throw RuntimeException.InvalidArgumentType(nameof(target));
243+
244+
var writer = new StreamWriter(stream.GetUnderlyingStream(), Console.OutputEncoding)
245+
{
246+
AutoFlush = true,
247+
};
248+
Console.SetOut(writer);
249+
}
250+
251+
/// <summary>
252+
/// Глобально переопределяет стандартный поток ошибок и направляет в другой поток
253+
/// </summary>
254+
/// <param name="target">Поток назначения</param>
255+
[ContextMethod("УстановитьПотокОшибок", "SetError")]
256+
public void SetError(IValue target)
257+
{
258+
if (!(target.AsObject() is IStreamWrapper stream))
259+
throw RuntimeException.InvalidArgumentType(nameof(target));
260+
261+
var writer = new StreamWriter(stream.GetUnderlyingStream());
262+
Console.SetError(writer);
263+
}
264+
181265
[ScriptConstructor]
182266
public static ConsoleContext Constructor()
183267
{
184-
return new ConsoleContext();
268+
var provider = GlobalsManager.GetGlobalContext<ConsoleProvider>();
269+
SystemLogger.Write("WARNING: Constructor of Console is obsolete. Use global property Консоль/Console");
270+
271+
return provider.Console;
185272
}
186273
}
187274

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/*----------------------------------------------------------
2+
This Source Code Form is subject to the terms of the
3+
Mozilla Public License, v.2.0. If a copy of the MPL
4+
was not distributed with this file, You can obtain one
5+
at http://mozilla.org/MPL/2.0/.
6+
----------------------------------------------------------*/
7+
8+
using System;
9+
using ScriptEngine.Machine;
10+
using ScriptEngine.Machine.Contexts;
11+
12+
namespace ScriptEngine.HostedScript.Library
13+
{
14+
[GlobalContext(Category = "Работа с консолью")]
15+
public class ConsoleProvider : GlobalContextBase<ConsoleProvider>
16+
{
17+
private readonly ConsoleContext _console = new ConsoleContext();
18+
19+
private ConsoleProvider()
20+
{
21+
}
22+
23+
public override void OnAttach(MachineInstance machine, out IVariable[] variables, out MethodInfo[] methods)
24+
{
25+
variables = new [] {Variable.CreateContextPropertyReference(this, 0, GetPropName(0))};
26+
methods = new MethodInfo[0];
27+
}
28+
29+
[ContextProperty("Консоль", "Console")]
30+
public ConsoleContext Console => _console;
31+
32+
public override bool IsPropWritable(int propNum)
33+
{
34+
// обратная совместимость. Присваивание Консоль = Новый Консоль не должно ругаться на недоступность записи
35+
return true;
36+
}
37+
38+
public override void SetPropValue(int propNum, IValue newVal)
39+
{
40+
// обратная совместимость. Присваивание Консоль = Новый Консоль не должно ничего делать
41+
if (!ReferenceEquals(newVal.GetRawValue(), _console))
42+
{
43+
throw new InvalidOperationException("Can't assign to global property Console");
44+
}
45+
}
46+
47+
public static ConsoleProvider CreateInstance()
48+
{
49+
return new ConsoleProvider();
50+
}
51+
}
52+
}

src/ScriptEngine.HostedScript/Library/SystemGlobalContext.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ public SystemGlobalContext()
3838
RegisterProperty("ФайловыеПотоки", () => FileStreams);
3939
RegisterProperty("FileStreams", () => FileStreams);
4040

41-
RegisterProperty("Символы", () => (IValue)Chars);
41+
RegisterProperty("Символы", () => (IValue)Chars);
4242
RegisterProperty("Chars", () => (IValue)Chars);
4343
}
4444

src/ScriptEngine.HostedScript/Library/TextReadImpl.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ private void OpenStream(IStreamWrapper streamObj, IValue encoding = null, string
5656
TextReader imReader;
5757
if (encoding == null)
5858
{
59-
imReader = Environment.FileOpener.OpenReader(streamObj.GetUnderlyingStream());
59+
imReader = Environment.FileOpener.OpenReader(streamObj.GetUnderlyingStream(), Encoding.Default);
6060
}
6161
else
6262
{

src/ScriptEngine/Machine/Contexts/ContextValuesMarshaller.cs

Lines changed: 12 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -14,42 +14,36 @@ public static class ContextValuesMarshaller
1414
{
1515
public static T ConvertParam<T>(IValue value)
1616
{
17-
var type = typeof(T);
18-
object valueObj = ConvertParam(value, type);
19-
if (valueObj == null)
20-
{
21-
return default(T);
22-
}
23-
2417
try
2518
{
26-
return (T)valueObj;
19+
object valueObj = ConvertParam(value, typeof(T));
20+
return valueObj != null ? (T)valueObj : default;
2721
}
2822
catch (InvalidCastException)
2923
{
3024
throw RuntimeException.InvalidArgumentType();
3125
}
32-
26+
catch (OverflowException)
27+
{
28+
throw RuntimeException.InvalidArgumentValue();
29+
}
3330
}
3431

3532
public static T ConvertParam<T>(IValue value, T defaultValue)
3633
{
37-
var type = typeof(T);
38-
object valueObj = ConvertParam(value, type);
39-
if (valueObj == null)
40-
{
41-
return defaultValue;
42-
}
43-
4434
try
4535
{
46-
return (T)valueObj;
36+
object valueObj = ConvertParam(value, typeof(T));
37+
return valueObj != null ? (T)valueObj : defaultValue;
4738
}
4839
catch (InvalidCastException)
4940
{
5041
throw RuntimeException.InvalidArgumentType();
5142
}
52-
43+
catch (OverflowException)
44+
{
45+
throw RuntimeException.InvalidArgumentValue();
46+
}
5347
}
5448

5549
public static object ConvertParam(IValue value, Type type)

0 commit comments

Comments
 (0)