Skip to content

fix #1679: добавлен метод ОткрытьПоток() объекта ЧтениеJSON#1680

Open
Mr-Rm wants to merge 4 commits into
EvilBeaver:developfrom
Mr-Rm:v2/fix-1679
Open

fix #1679: добавлен метод ОткрытьПоток() объекта ЧтениеJSON#1680
Mr-Rm wants to merge 4 commits into
EvilBeaver:developfrom
Mr-Rm:v2/fix-1679

Conversation

@Mr-Rm
Copy link
Copy Markdown
Collaborator

@Mr-Rm Mr-Rm commented May 13, 2026

Summary by CodeRabbit

  • New Features

    • JSON reader can open and read from stream-based inputs with optional encoding; streams can be reopened and reused.
  • Tests

    • Added tests verifying opening a stream, reopening the same stream, and reusing a stream after closing the reader.
  • Refactor

    • Minor public declaration order adjusted with no behavioral change.

Review Change Stack

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 13, 2026

📝 Walkthrough

Walkthrough

Adds JSONReader.OpenStream to initialize the internal JSON reader from an IStreamWrapper (optional encoding, default UTF-8), makes OpenFile/SetString always call Close() before opening, reorders FileStreamContext interfaces, and adds tests that read JSON {"ответ":42} from a memory stream (including repeated open and reopen-after-close scenarios).

Changes

JSON stream reading support

Layer / File(s) Summary
Imports, docs, properties
src/OneScript.StandardLibrary/Json/JSONReader.cs
Updates using directives, adjusts XML doc regions, and refactors CurrentPosition/CurrentLine to expression-bodied ternary properties.
Close docs and whitespace
src/OneScript.StandardLibrary/Json/JSONReader.cs
Whitespace and XML documentation adjustments around CurrentValue/ReaderValue/CurrentValueType and Close() (no behavior change).
OpenFile / OpenStream / SetString
src/OneScript.StandardLibrary/Json/JSONReader.cs
OpenFile and SetString now unconditionally call Close() before initializing a new JsonReaderInternal. Adds OpenStream(IStreamWrapper streamContext, IValue encoding = null) (ОткрытьПоток) which extracts the underlying Stream (throws if null), chooses encoding (default UTF‑8), constructs StreamReader(..., leaveOpen:true), and initializes JsonReaderInternal with SupportMultipleContent = true.
FileStreamContext declaration
src/OneScript.StandardLibrary/Binary/FileStreamContext.cs
Reorders implemented interfaces in the FileStreamContext class declaration (swap IDisposable and IStreamWrapper).
Stream reading test coverage
tests/json/test-json_reader.os
Adds three exported tests: Тест_Должен_ПроверитьОткрытиеПотока, Тест_Должен_ПроверитьПовторноеОткрытиеПотока, Тест_Должен_ПроверитьСохранениеПотокаПослеЗакрытияЧтения. Each uses a memory stream over {"ответ":42}, opens via the JSON reader (including repeated opens and reopen after Close), reads JSON, and asserts Ответ == 42.

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant JSONReader
  participant IStreamWrapper
  participant Stream as StreamReader
  participant JsonReaderInternal
  Caller->>JSONReader: OpenStream(streamContext, encoding?)
  JSONReader->>IStreamWrapper: Get underlying Stream
  IStreamWrapper-->>JSONReader: Stream (not null)
  JSONReader->>Stream: new StreamReader(Stream, encoding, leaveOpen:true)
  JSONReader->>JsonReaderInternal: new JsonReaderInternal(StreamReader) (SupportMultipleContent = true)
  JSONReader-->>Caller: ready to Read/Parse
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • EvilBeaver/OneScript#1408: Related prior changes to JSONReader and its reader lifecycle that overlap with OpenStream and tests.

"I nibbled bytes from a buffered brook, 🐇
Opened streams where tiny JSONs look,
Memory wrapped, encodings set right,
OneScript reads softly through the night."

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Docstring Coverage ✅ Passed Docstring coverage is 87.50% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The pull request title accurately describes the main change: adding an OpenStream() method to the JSONReader object, which aligns with the primary additions in the code (new OpenStream method and related tests).

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (2)
tests/json/test-json_reader.os (1)

225-233: ⚖️ Poor tradeoff

Consider expanding test coverage.

The test correctly validates the basic happy path with ПотокВПамяти (MemoryStreamContext). To improve robustness, consider adding tests for:

  • The optional encoding parameter with non-UTF-8 encodings
  • Error cases: invalid stream context type, null argument
  • Other stream context types (FileStreamContext or GenericStream)
  • Stream state after reading (verify Close() behavior)

These additions would help ensure the implementation handles edge cases correctly.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/json/test-json_reader.os` around lines 225 - 233, Add additional test
cases alongside Тест_Должен_ПроверитьОткрытиеПотока to cover edge cases: create
a test that passes a ПотокВПамяти with a non-UTF8 encoding and assert correct
parsing using ЧтениеJSON and ПрочитатьJSON; add tests that call
Чтение.ОткрытьПоток with an invalid stream context type and with null and assert
that the right exceptions are raised; add a test using FileStreamContext or
GenericStream to ensure file-backed streams parse the same way; and add a test
that reads then checks stream state/Close() behavior after ПрочитатьJSON to
verify the stream is closed or left open as intended.
src/OneScript.StandardLibrary/Json/JSONReader.cs (1)

280-300: ⚡ Quick win

Add exception handling for consistency with OpenFile.

The OpenFile method (lines 252-262) wraps all file and encoding operations in a try-catch block and converts exceptions to RuntimeException. For API consistency, OpenStream should follow the same pattern, since GetUnderlyingStream(), TextEncodingEnum.GetEncoding(), and the StreamReader constructor can all throw exceptions.

🔄 Proposed exception handling
 public void OpenStream(IValue streamContext, IValue encoding = null)
 {
     if (IsOpen())
         Close();
 
+    try
+    {
         var stream = streamContext switch
         {
             GenericStream s => s.GetUnderlyingStream(),
             FileStreamContext s => s.GetUnderlyingStream(),
             MemoryStreamContext s => s.GetUnderlyingStream(),
 
             _ => throw RuntimeException.InvalidNthArgumentType(1)
         };
 
         var enc = encoding != null ? TextEncodingEnum.GetEncoding(encoding) : System.Text.Encoding.UTF8;
 
         _reader = new JsonReaderInternal(new StreamReader(stream, enc))
         {
             SupportMultipleContent = true
         };
+    }
+    catch (Exception e)
+    {
+        throw new RuntimeException(e.Message, e);
+    }
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/OneScript.StandardLibrary/Json/JSONReader.cs` around lines 280 - 300,
OpenStream lacks the try-catch used in OpenFile, so exceptions from
GetUnderlyingStream, TextEncodingEnum.GetEncoding or
StreamReader/JsonReaderInternal are not converted to RuntimeException; wrap the
body of OpenStream in a try-catch that mirrors OpenFile: catch any Exception and
rethrow as RuntimeException (use the same message/format used in OpenFile),
while keeping the same behavior of closing an already open reader via
IsOpen()/Close() and preserving SupportMultipleContent on JsonReaderInternal.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@src/OneScript.StandardLibrary/Json/JSONReader.cs`:
- Around line 280-300: OpenStream lacks the try-catch used in OpenFile, so
exceptions from GetUnderlyingStream, TextEncodingEnum.GetEncoding or
StreamReader/JsonReaderInternal are not converted to RuntimeException; wrap the
body of OpenStream in a try-catch that mirrors OpenFile: catch any Exception and
rethrow as RuntimeException (use the same message/format used in OpenFile),
while keeping the same behavior of closing an already open reader via
IsOpen()/Close() and preserving SupportMultipleContent on JsonReaderInternal.

In `@tests/json/test-json_reader.os`:
- Around line 225-233: Add additional test cases alongside
Тест_Должен_ПроверитьОткрытиеПотока to cover edge cases: create a test that
passes a ПотокВПамяти with a non-UTF8 encoding and assert correct parsing using
ЧтениеJSON and ПрочитатьJSON; add tests that call Чтение.ОткрытьПоток with an
invalid stream context type and with null and assert that the right exceptions
are raised; add a test using FileStreamContext or GenericStream to ensure
file-backed streams parse the same way; and add a test that reads then checks
stream state/Close() behavior after ПрочитатьJSON to verify the stream is closed
or left open as intended.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: a309e50b-9baa-46fc-8be3-1f4f577b6437

📥 Commits

Reviewing files that changed from the base of the PR and between a541e3e and 777fac1.

📒 Files selected for processing (2)
  • src/OneScript.StandardLibrary/Json/JSONReader.cs
  • tests/json/test-json_reader.os

@nixel2007
Copy link
Copy Markdown
Collaborator

Огонь огонь!

if (IsOpen())
Close();

var stream = streamContext switch
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

а просто IStreamWrapper не пойдет? Они все его реализуют

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
src/OneScript.StandardLibrary/Json/JSONReader.cs (2)

285-291: ⚡ Quick win

Consider whether to add error handling to OpenStream for consistency with OpenFile.

The OpenFile method (lines 252-262) wraps stream operations in a try-catch block to convert exceptions to RuntimeException. However, the OpenStream method (lines 280-292) lacks similar error handling for operations like GetUnderlyingStream(), TextEncodingEnum.GetEncoding(), or the StreamReader constructor, creating inconsistency between the two public API methods.

Note: Other similar OpenStream methods in the codebase (e.g., TextReadImpl, TextWriteImpl) do not include try-catch blocks around stream operations, suggesting this may be an intentional design choice. Adding error handling would improve intra-class consistency but would diverge from the broader codebase pattern for OpenStream methods.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/OneScript.StandardLibrary/Json/JSONReader.cs` around lines 285 - 291,
OpenStream currently calls streamContext.GetUnderlyingStream(),
TextEncodingEnum.GetEncoding(encoding) and new StreamReader(...) to create
JsonReaderInternal without guarding exceptions; make it consistent with OpenFile
by wrapping those operations in a try-catch that catches Exception and rethrows
a RuntimeException with a clear message (include the original exception as
inner/innerException) so callers get the same RuntimeException behavior as
OpenFile; update the block that constructs _reader (the JsonReaderInternal(new
StreamReader(...)) assignment) to be inside this try-catch and reference the
same symbols: OpenStream, streamContext.GetUnderlyingStream(),
TextEncodingEnum.GetEncoding, StreamReader, JsonReaderInternal and
RuntimeException.

270-292: ⚖️ Poor tradeoff

Document that OpenStream takes ownership of the provided stream and will dispose it.

When Close() is called (line 230), it calls _reader.Close() on the JsonTextReader, which closes its underlying StreamReader (created at line 288). This disposes the stream obtained from IStreamWrapper.GetUnderlyingStream(), preventing the caller from reusing it.

While this behavior mirrors OpenFile, which also closes its underlying stream, the disposal semantics differ: OpenFile owns resources it creates, whereas OpenStream disposes a caller-provided resource. Add a remark to the XML documentation clarifying that the stream is taken over and will be disposed when the reader closes.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/OneScript.StandardLibrary/Json/JSONReader.cs` around lines 270 - 292,
OpenStream currently takes the stream returned by
IStreamWrapper.GetUnderlyingStream(), wraps it in a StreamReader for
JsonReaderInternal stored in _reader, and Close() calls on this reader will
dispose that underlying stream; update the XML documentation for OpenStream
(method OpenStream) to explicitly state that the provided stream is taken
ownership of by the JSONReader and will be disposed when the reader is closed
(e.g., when Close() is called), referencing that _reader
(JsonReaderInternal/JsonTextReader) closes the underlying StreamReader and
stream so callers should not expect the stream to remain usable after calling
Close().
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/OneScript.StandardLibrary/Json/JSONReader.cs`:
- Around line 280-285: The OpenStream method lacks a null check for its
streamContext parameter; before calling streamContext.GetUnderlyingStream() add
a defensive validation that throws an ArgumentNullException (or returns an
appropriate error) when streamContext is null. Locate OpenStream in
JSONReader.cs and insert the null check at the top (after the IsOpen/Close
handling if desired) so the call to GetUnderlyingStream() is only made on a
non-null streamContext. Ensure the exception message names the parameter
("streamContext") to aid callers.

---

Nitpick comments:
In `@src/OneScript.StandardLibrary/Json/JSONReader.cs`:
- Around line 285-291: OpenStream currently calls
streamContext.GetUnderlyingStream(), TextEncodingEnum.GetEncoding(encoding) and
new StreamReader(...) to create JsonReaderInternal without guarding exceptions;
make it consistent with OpenFile by wrapping those operations in a try-catch
that catches Exception and rethrows a RuntimeException with a clear message
(include the original exception as inner/innerException) so callers get the same
RuntimeException behavior as OpenFile; update the block that constructs _reader
(the JsonReaderInternal(new StreamReader(...)) assignment) to be inside this
try-catch and reference the same symbols: OpenStream,
streamContext.GetUnderlyingStream(), TextEncodingEnum.GetEncoding, StreamReader,
JsonReaderInternal and RuntimeException.
- Around line 270-292: OpenStream currently takes the stream returned by
IStreamWrapper.GetUnderlyingStream(), wraps it in a StreamReader for
JsonReaderInternal stored in _reader, and Close() calls on this reader will
dispose that underlying stream; update the XML documentation for OpenStream
(method OpenStream) to explicitly state that the provided stream is taken
ownership of by the JSONReader and will be disposed when the reader is closed
(e.g., when Close() is called), referencing that _reader
(JsonReaderInternal/JsonTextReader) closes the underlying StreamReader and
stream so callers should not expect the stream to remain usable after calling
Close().
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 38b2e98e-4bdd-4294-a3fe-90a0effac490

📥 Commits

Reviewing files that changed from the base of the PR and between 777fac1 and 0297f46.

📒 Files selected for processing (2)
  • src/OneScript.StandardLibrary/Binary/FileStreamContext.cs
  • src/OneScript.StandardLibrary/Json/JSONReader.cs
✅ Files skipped from review due to trivial changes (1)
  • src/OneScript.StandardLibrary/Binary/FileStreamContext.cs

Comment thread src/OneScript.StandardLibrary/Json/JSONReader.cs Outdated
@EvilBeaver
Copy link
Copy Markdown
Owner

@Mr-Rm вижу WIP, еще нельзя вливать?

@Mr-Rm
Copy link
Copy Markdown
Collaborator Author

Mr-Rm commented May 14, 2026

Пока WIP, есть проблемы с закрытием-открытием потока

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
tests/json/test-json_reader.os (1)

227-235: 💤 Low value

Consider fixing indentation consistency.

The first line of the procedure body (line 228) appears to use spaces for indentation instead of tabs, which is inconsistent with the rest of the file's indentation style.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/json/test-json_reader.os` around lines 227 - 235, The procedure
Тест_Должен_ПроверитьОткрытиеПотока() has inconsistent indentation: the first
line of the body uses spaces instead of tabs; update the leading whitespace for
the body lines (e.g., the line starting with БДД =
ПолучитьБуферДвоичныхДанныхИзСтроки(...)) to use the same tab indentation style
as the rest of the file so all lines inside Тест_Должен_ПроверитьОткрытиеПотока
and its subsequent statements (Поток, Чтение, Чтение.ОткрытьПоток, Json,
юТест.ПроверитьРавенство) are consistently indented with tabs.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@tests/json/test-json_reader.os`:
- Around line 248-257: Rename and rewrite the
Тест_Должен_ПроверитьСохранениеПотокаПослеЗакрытияЧтения test so it actually
verifies the stream remains open after closing the reader: instantiate Поток =
Новый ПотокВПамяти(...), call Чтение.ОткрытьПоток(Поток) (optionally read via
ПрочитатьJSON to advance), then call Чтение.Закрыть(), assert the Поток is still
usable by setting Поток.Позиция = 0 (or reading again) and reopening/using the
reader (ОткрытьПоток/ПрочитатьJSON) to confirm data can still be read; ensure
you reference the existing methods ОткрытьПоток, Закрыть, ПрочитатьJSON and
class ПотокВПамяти, and fix indentation to match file style.

---

Nitpick comments:
In `@tests/json/test-json_reader.os`:
- Around line 227-235: The procedure Тест_Должен_ПроверитьОткрытиеПотока() has
inconsistent indentation: the first line of the body uses spaces instead of
tabs; update the leading whitespace for the body lines (e.g., the line starting
with БДД = ПолучитьБуферДвоичныхДанныхИзСтроки(...)) to use the same tab
indentation style as the rest of the file so all lines inside
Тест_Должен_ПроверитьОткрытиеПотока and its subsequent statements (Поток,
Чтение, Чтение.ОткрытьПоток, Json, юТест.ПроверитьРавенство) are consistently
indented with tabs.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 0af6ca48-f64e-423d-ac76-be975ad2cfe4

📥 Commits

Reviewing files that changed from the base of the PR and between 0297f46 and 0ca87f7.

📒 Files selected for processing (2)
  • src/OneScript.StandardLibrary/Json/JSONReader.cs
  • tests/json/test-json_reader.os
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/OneScript.StandardLibrary/Json/JSONReader.cs

Comment thread tests/json/test-json_reader.os
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/OneScript.StandardLibrary/Json/JSONReader.cs`:
- Around line 214-216: OpenFile and SetString (and the other public methods
around lines 294-297 that accept concrete string parameters) currently assume
non-null inputs; add explicit null checks at the start of each such public
method to guard against direct C# callers passing null by either throwing
ArgumentNullException(nameof(param)) or otherwise handling null
deterministically (e.g., treat as empty string) — locate the methods by name
(OpenFile, SetString and the similarly patterned public string-accepting
methods) and add a clear null-guard for each string parameter with the parameter
name in the exception to provide immediate, unambiguous diagnostics.
- Around line 253-258: OpenStream currently allows .NET exceptions from
TextEncodingEnum.GetEncoding and new JsonReaderInternal to leak; mirror OpenFile
by wrapping the encoding resolution and _reader initialization in a try/catch
and throw a RuntimeException instead. Specifically, surround the calls to
TextEncodingEnum.GetEncoding(encoding) and the JsonReaderInternal/StreamReader
creation that assigns _reader with a try block, catch Exception ex, and rethrow
a new RuntimeException (include a clear message and set ex as the inner
exception) so OpenStream behavior matches OpenFile.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: e7bd23c7-d51c-4fc4-99a8-fce6699a4bd0

📥 Commits

Reviewing files that changed from the base of the PR and between 0ca87f7 and 021d90f.

📒 Files selected for processing (2)
  • src/OneScript.StandardLibrary/Json/JSONReader.cs
  • tests/json/test-json_reader.os
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/json/test-json_reader.os

Comment on lines 214 to +216
public void OpenFile(string JSONFileName, IValue encoding = null)
{
if (IsOpen())
Close();
Close();
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Add explicit null guards for concrete string inputs.

OpenFile and SetString accept string parameters but don’t explicitly handle null. Direct C# calls can still pass null, and failures then happen deeper with less clear diagnostics.

Proposed fix
 public void OpenFile(string JSONFileName, IValue encoding = null)
 {
+    if (JSONFileName == null)
+        throw new ArgumentNullException(nameof(JSONFileName));
+
     Close();

     StreamReader _fileReader;
 public void SetString(string JSONString)
 {
+    if (JSONString == null)
+        throw new ArgumentNullException(nameof(JSONString));
+
     Close();

     _reader = new JsonReaderInternal(new StringReader(JSONString))

Based on learnings: when script-side calls omit concrete string arguments they may become "", while direct calls may pass null, so public methods should explicitly handle null.

Also applies to: 294-297

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/OneScript.StandardLibrary/Json/JSONReader.cs` around lines 214 - 216,
OpenFile and SetString (and the other public methods around lines 294-297 that
accept concrete string parameters) currently assume non-null inputs; add
explicit null checks at the start of each such public method to guard against
direct C# callers passing null by either throwing
ArgumentNullException(nameof(param)) or otherwise handling null
deterministically (e.g., treat as empty string) — locate the methods by name
(OpenFile, SetString and the similarly patterned public string-accepting
methods) and add a clear null-guard for each string parameter with the parameter
name in the exception to provide immediate, unambiguous diagnostics.

Comment on lines +253 to +258
var enc = encoding != null ? TextEncodingEnum.GetEncoding(encoding) : System.Text.Encoding.UTF8;

_reader = new JsonReaderInternal(new StreamReader(stream, enc, leaveOpen:true))
{
SupportMultipleContent = true
};
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Align OpenStream open/init exception behavior with OpenFile.

OpenFile wraps initialization failures into RuntimeException, while OpenStream currently leaks raw .NET exceptions from encoding resolution/reader creation. Keeping this consistent improves script-facing behavior.

Proposed fix
-            var enc = encoding != null ? TextEncodingEnum.GetEncoding(encoding) : System.Text.Encoding.UTF8;
-
-            _reader = new JsonReaderInternal(new StreamReader(stream, enc, leaveOpen:true))
-            {
-                SupportMultipleContent = true
-            };
+            try
+            {
+                var enc = encoding != null ? TextEncodingEnum.GetEncoding(encoding) : System.Text.Encoding.UTF8;
+
+                _reader = new JsonReaderInternal(new StreamReader(stream, enc, leaveOpen: true))
+                {
+                    SupportMultipleContent = true
+                };
+            }
+            catch (Exception e)
+            {
+                throw new RuntimeException(e.Message, e);
+            }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
var enc = encoding != null ? TextEncodingEnum.GetEncoding(encoding) : System.Text.Encoding.UTF8;
_reader = new JsonReaderInternal(new StreamReader(stream, enc, leaveOpen:true))
{
SupportMultipleContent = true
};
try
{
var enc = encoding != null ? TextEncodingEnum.GetEncoding(encoding) : System.Text.Encoding.UTF8;
_reader = new JsonReaderInternal(new StreamReader(stream, enc, leaveOpen: true))
{
SupportMultipleContent = true
};
}
catch (Exception e)
{
throw new RuntimeException(e.Message, e);
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/OneScript.StandardLibrary/Json/JSONReader.cs` around lines 253 - 258,
OpenStream currently allows .NET exceptions from TextEncodingEnum.GetEncoding
and new JsonReaderInternal to leak; mirror OpenFile by wrapping the encoding
resolution and _reader initialization in a try/catch and throw a
RuntimeException instead. Specifically, surround the calls to
TextEncodingEnum.GetEncoding(encoding) and the JsonReaderInternal/StreamReader
creation that assigns _reader with a try block, catch Exception ex, and rethrow
a new RuntimeException (include a clear message and set ex as the inner
exception) so OpenStream behavior matches OpenFile.

@Mr-Rm Mr-Rm changed the title [WIP] fix #1679: добавлен метод ОткрытьПоток() объекта ЧтениеJSON fix #1679: добавлен метод ОткрытьПоток() объекта ЧтениеJSON May 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants