Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix unbounded memory growth in DoubleArrayConverter #6412

Merged
merged 2 commits into from
Dec 22, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// SPDX-FileCopyrightText: 2023 Demerzel Solutions Limited
// SPDX-License-Identifier: LGPL-3.0-only

using System;
using System.Text.Json;
using Nethermind.Serialization.Json;

using NUnit.Framework;

namespace Nethermind.Core.Test.Json;

[TestFixture]
public class DoubleArrayConverterTests : ConverterTestBase<double[]>
{
static readonly DoubleArrayConverter converter = new();

[Test]
public void Test_roundtrip()
{
TestConverter(new double[] { -0.5, 0.5, 1.0, 1.5, 2.0, 2.5 }, (a, b) => a.AsSpan().SequenceEqual(b), converter);
TestConverter(new double[] { 1, 1, 1, 1 }, (a, b) => a.AsSpan().SequenceEqual(b), converter);
TestConverter(new double[] { 0, 0, 0, 0 }, (a, b) => a.AsSpan().SequenceEqual(b), converter);
TestConverter(Array.Empty<double>(), (a, b) => a.AsSpan().SequenceEqual(b), converter);
}
}
16 changes: 9 additions & 7 deletions src/Nethermind/Nethermind.Serialization.Json/DoubleConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

namespace Nethermind.Serialization.Json
{
using System.Collections.Generic;
using Nethermind.Core.Collections;
using System.Runtime.CompilerServices;
using System.Text.Json;
using System.Text.Json.Serialization;
Expand Down Expand Up @@ -47,19 +47,21 @@ public override double[] Read(
{
throw new JsonException();
}
List<double> values = null;
reader.Read();
while (reader.TokenType == JsonTokenType.Number)
using ArrayPoolList<double> values = new ArrayPoolList<double>(16);
while (reader.Read() && reader.TokenType == JsonTokenType.Number)
{
values ??= new List<double>();
values.Add(reader.GetDouble());
}
if (reader.TokenType != JsonTokenType.EndArray)
{
throw new JsonException();
}
reader.Read();
return values?.ToArray() ?? Array.Empty<double>();

if (values.Count == 0) return Array.Empty<double>();

double[] result = new double[values.Count];
values.CopyTo(result, 0);
return result;
}

[SkipLocalsInit]
Expand Down
Loading