Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions src/OneScript.StandardLibrary/Binary/DataReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -69,21 +69,22 @@ private DataReader(Stream stream, IValue textEncoding, ByteOrderEnum? byteOrder,
/// Определяет разделение строк в файле для конвертации в стандартный перевод строк ПС.
/// Значение по умолчанию: ВК + ПС. </param>
[ScriptConstructor(Name = "На основании двоичных данных или имени файла")]
public static DataReader Constructor(IValue dataSource, IValue textEncoding = null, ByteOrderEnum? byteOrder = null, string lineSplitter = "\n", string convertibleSplitterOfLines = null)
public static DataReader Constructor(IValue dataSource, IValue textEncoding = null, ByteOrderEnum? byteOrder = null,
string lineSplitter = "\n", string convertibleSplitterOfLines = null)
{
Stream stream;
if (dataSource.SystemType == BasicTypes.String)
if (dataSource?.SystemType == BasicTypes.String)
{
stream = new FileStream(dataSource.ToString()!, FileMode.Open, FileAccess.Read, FileShare.Read);
}
else
{
stream = dataSource.AsObject() switch
stream = dataSource switch
{
BinaryDataContext binaryData => binaryData.GetStream(),
IStreamWrapper wrapper => wrapper.GetUnderlyingStream(),

_ => throw RuntimeException.InvalidArgumentType("dataSource")
_ => throw RuntimeException.InvalidNthArgumentType(1)
};
}

Expand Down
50 changes: 9 additions & 41 deletions src/OneScript.StandardLibrary/Binary/DataWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -104,60 +104,28 @@ public DataWriter(IStreamWrapper streamObj, IValue textEncoding, ByteOrderEnum?
/// Значение по умолчанию: Ложь. </param>
///
[ScriptConstructor]
public static DataWriter Constructor(IValue file_stream, IValue textEncoding = null, ByteOrderEnum? byteOrder = null, string lineSplitter = null, IValue param5 = null, IValue param6 = null, IValue param7 = null)
public static DataWriter Constructor(IValue file_stream, IValue textEncoding = null, ByteOrderEnum? byteOrder = null,
string lineSplitter = null, IValue param5 = null, IValue param6 = null, IValue param7 = null)
{
if (file_stream.SystemType == BasicTypes.String)
return new DataWriter(file_stream.ToString(),
if (file_stream?.SystemType == BasicTypes.String)
return new DataWriter(file_stream.ToString()!,
textEncoding,
byteOrder,
lineSplitter,
ContextValuesMarshaller.ConvertValueStrict<bool>(param5),
ContextValuesMarshaller.ConvertValueStrict<string>(param6),
ContextValuesMarshaller.ConvertValueStrict<bool>(param7));
else
return ConstructorByStream(
file_stream,
else if (file_stream is IStreamWrapper stream)
return new DataWriter(stream,
textEncoding,
byteOrder,
lineSplitter,
ContextValuesMarshaller.ConvertValueStrict<string>(param5),
ContextValuesMarshaller.ConvertValueStrict<bool>(param6));
}

/// <summary>
///
/// Объект создается для записи в заданный поток.
/// После завершения работы с объектом, до закрытия потока, переданного в конструктор, объект необходимо закрыть с помощью метода Закрыть или НачатьЗакрытие.
/// </summary>
///
/// <param name="stream">
/// Поток, в который производится запись данных. Типы: Поток (Stream), ПотокВПамяти (MemoryStream), ФайловыйПоток (FileStream) </param>
/// <param name="textEncoding">
/// Устанавливает кодировку текста для создаваемого экземпляра ЗаписьДанных. Если не задано, используется кодировка UTF-8.
/// Значение по умолчанию: UTF8. Типы: КодировкаТекста (TextEncoding), Строка (String) </param>
/// <param name="byteOrder">
/// Порядок байтов, используемый по умолчанию для кодирования целых чисел при записи в поток.
/// Значение по умолчанию: LittleEndian. </param>
/// <param name="lineSplitter">
/// Разделитель по умолчанию для строк, записываемых в поток. Если разделитель строк не задан, то используется строка ПС.
/// Значение по умолчанию: ПС. </param>
/// <param name="convertibleSplitterOfLines">
/// Определяет разделение строк в файле для конвертации в стандартный перевод строк ПС.
/// Значение по умолчанию: ВК + ПС. </param>
/// <param name="writeBOM">
/// Если в начало файла или потока требуется записать метку порядка байтов (BOM) для используемой кодировки текста, то данный параметр должен иметь значение Истина.
/// Значение по умолчанию: Ложь. </param>
///
//[ScriptConstructor(Name = "На основании потока")]
public static DataWriter ConstructorByStream(IValue stream, IValue textEncoding = null, ByteOrderEnum? byteOrder = null, string lineSplitter = null, string convertibleSplitterOfLines = null, bool writeBOM = false)
{
var streamObj = stream.AsObject() as IStreamWrapper;
if (streamObj == null)
{
throw RuntimeException.InvalidArgumentType(nameof(stream));
}
else
throw RuntimeException.InvalidNthArgumentType(1);

return new DataWriter(streamObj, textEncoding, byteOrder, lineSplitter, convertibleSplitterOfLines, writeBOM);
}

/// <summary>
Expand Down
6 changes: 4 additions & 2 deletions src/OneScript.StandardLibrary/Text/TextReadImpl.cs
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ private void RequireOpen()
[ScriptConstructor(Name = "На основании файла или потока без кодировки")]
public static TextReadImpl Constructor (IValue input)
{
var reader = new TextReadImpl ();
var reader = new TextReadImpl();
reader.Open(input);
return reader;
}
Expand Down Expand Up @@ -210,7 +210,7 @@ public static TextReadImpl ConstructorWithEncoding(IValue input, IValue encoding
lineDelimiter ?? "\n",
eolDelimiter);
}
else
else if (input is not null)
{
reader.OpenFile(
ContextValuesMarshaller.ConvertValueStrict<string>(input),
Expand All @@ -219,6 +219,8 @@ public static TextReadImpl ConstructorWithEncoding(IValue input, IValue encoding
eolDelimiter,
monopoly);
}
else
throw RuntimeException.InvalidNthArgumentType(1);

return reader;
}
Expand Down
6 changes: 4 additions & 2 deletions src/OneScript.StandardLibrary/Text/TextWriteImpl.cs
Original file line number Diff line number Diff line change
Expand Up @@ -83,15 +83,17 @@ public void Open(IValue fileOrStream, IValue encoding = null, string lineDelimit
ContextValuesMarshaller.ConvertValueStrict<string>(param4),
ContextValuesMarshaller.ConvertValueStrict<bool>(param5));
}
else
else if (fileOrStream is not null)
{
OpenFile(
fileOrStream.ToString(),
fileOrStream.ToString()!,
encoding,
lineDelimiter,
ContextValuesMarshaller.ConvertValueStrict<bool>(param4),
ContextValuesMarshaller.ConvertValueStrict<string>(param5));
}
else
throw RuntimeException.InvalidNthArgumentType(1);
}

[ContextMethod("Закрыть","Close")]
Expand Down
10 changes: 4 additions & 6 deletions src/OneScript.StandardLibrary/Zip/ZipReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,17 +54,17 @@ public void Open(IValue filenameOrStream, string password = null, FileNamesEncod
// fuck non-russian encodings on non-ascii files
DotNetZipEncoding.SetDefault(Encoding.GetEncoding(866));

if (filenameOrStream.SystemType == BasicTypes.String)
if (filenameOrStream?.SystemType == BasicTypes.String)
{
_zip = ZipFile.Read(filenameOrStream.ToString(), new ReadOptions { Encoding = ChooseEncoding(encoding) });
_zip = ZipFile.Read(filenameOrStream.ToString()!, new ReadOptions { Encoding = ChooseEncoding(encoding) });
}
else if (filenameOrStream is IStreamWrapper stream)
{
_zip = ZipFile.Read(stream.GetUnderlyingStream(), new ReadOptions { Encoding = ChooseEncoding(encoding) });
}
else
{
throw RuntimeException.InvalidArgumentType(nameof(filenameOrStream));
throw RuntimeException.InvalidNthArgumentType(1);
}

_zip.Password = password;
Expand Down Expand Up @@ -156,9 +156,7 @@ public static ZipReader Construct()
[ScriptConstructor(Name = "На основании имени файла или потока")]
public static ZipReader Constructor(IValue dataSource, string password = null)
{
var dataSourceRawValue = dataSource ?? ValueFactory.CreateInvalidValueMarker();

return new ZipReader(dataSourceRawValue, password);
return new ZipReader(dataSource, password);
}

public void Dispose()
Expand Down
6 changes: 5 additions & 1 deletion src/oscript/Web/Multipart/PostRequestData.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ This Source Code Form is subject to the terms of the
using System;
using System.IO;
using System.Text;
using OneScript.Exceptions;
using OneScript.Contexts;
using OneScript.StandardLibrary.Binary;
using OneScript.StandardLibrary.Collections;
Expand Down Expand Up @@ -93,7 +94,10 @@ public FixedMapImpl Files
[ScriptConstructor(Name = "Из двоичных данных")]
public static PostRequestData Constructor(BinaryDataContext data, IValue boundary)
{
return new PostRequestData(data.GetStream(), boundary.ToString());
if (data is null)
throw RuntimeException.InvalidNthArgumentType(1);

return new PostRequestData(data.GetStream(), boundary?.ToString());
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

[ScriptConstructor(Name = "Из строки запроса")]
Expand Down
48 changes: 48 additions & 0 deletions tests/constructor.os
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
ВсеТесты.Добавить("ТестДолжен_ПроверитьПолучениеЗначенияПоУмолчанию");
ВсеТесты.Добавить("ТестДолжен_ПроверитьКорректностьПроверкиУказанияФактическихПараметров");
ВсеТесты.Добавить("ТестДолжен_ПроверитьПропускНеобязательныхПараметров");
ВсеТесты.Добавить("ТестДолжен_ПроверитьПропускОбязательныхПараметровБезNRE");

Возврат ВсеТесты;

Expand Down Expand Up @@ -130,4 +131,51 @@
Ожидаем.Что(НовыйОбъект.П1, "Параметр 1 заполнился верно").Равно("1");
Ожидаем.Что(НовыйОбъект.П2, "Параметр 2 заполнился верно").Равно(23);

КонецПроцедуры

Процедура ТестДолжен_ПроверитьПропускОбязательныхПараметровБезNRE() Экспорт

Попытка
НовыйОбъект = Новый ЧтениеДанных(,);
Ожидаем.Что(Ложь,"Объект не должен быть создан").ЭтоИстина();
Исключение
Ожидаем.Что(ОписаниеОшибки(), "для ЧтениеДанных").Не_().Содержит("NullReferenceException");
Comment thread
Mr-Rm marked this conversation as resolved.
Resolved
КонецПопытки;

Попытка
НовыйОбъект = Новый ЗаписьДанных(,);
Ожидаем.Что(Ложь,"Объект не должен быть создан").ЭтоИстина();
Исключение
Ожидаем.Что(ОписаниеОшибки(), "для ЗаписьДанных").Не_().Содержит("NullReferenceException");
КонецПопытки;

Попытка
НовыйОбъект = Новый ЧтениеТекста(,);
Ожидаем.Что(Ложь,"Объект не должен быть создан").ЭтоИстина();
Исключение
Ожидаем.Что(ОписаниеОшибки(), "для ЧтениеТекста").Не_().Содержит("NullReferenceException");
КонецПопытки;

Попытка
НовыйОбъект = Новый ЗаписьТекста(,);
Ожидаем.Что(Ложь,"Объект не должен быть создан").ЭтоИстина();
Исключение
Ожидаем.Что(ОписаниеОшибки(), "для ЗаписьТекста").Не_().Содержит("NullReferenceException");
КонецПопытки;

Попытка
НовыйОбъект = Новый ЧтениеZipФайла(,);
Ожидаем.Что(Ложь,"Объект не должен быть создан").ЭтоИстина();
Исключение
Ожидаем.Что(ОписаниеОшибки(), "для ЧтениеZipФайла").Не_().Содержит("NullReferenceException");
КонецПопытки;

Попытка
НовыйОбъект = Новый ЗаписьZipФайла(,);
Ожидаем.Что(Ложь,"Объект не должен быть создан").ЭтоИстина();
Исключение
Ожидаем.Что(ОписаниеОшибки(), "для ЗаписьZipФайла").Не_().Содержит("NullReferenceException");
КонецПопытки;


КонецПроцедуры
Loading