Skip to content

Commit 565374e

Browse files
authored
Use Stream buffer (#3730)
Forward port of b75271d
1 parent 7ce1133 commit 565374e

File tree

2 files changed

+23
-4
lines changed

2 files changed

+23
-4
lines changed

src/Elasticsearch.Net/Extensions/Extensions.cs

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
using System;
22
using System.Collections.Generic;
33
using System.Globalization;
4+
using System.IO;
45
using System.Linq;
56
using System.Text;
67

@@ -11,11 +12,22 @@ internal static class Extensions
1112
private const long MillisecondsInAWeek = MillisecondsInADay * 7;
1213
private const long MillisecondsInADay = MillisecondsInAnHour * 24;
1314
private const long MillisecondsInAnHour = MillisecondsInAMinute * 60;
14-
15-
internal static string Utf8String(this byte[] bytes) => bytes == null ? null : Encoding.UTF8.GetString(bytes, 0, bytes.Length);
1615
private const long MillisecondsInAMinute = MillisecondsInASecond * 60;
1716
private const long MillisecondsInASecond = 1000;
1817

18+
internal static string Utf8String(this byte[] bytes) => bytes == null ? null : Encoding.UTF8.GetString(bytes, 0, bytes.Length);
19+
20+
internal static string Utf8String(this MemoryStream ms)
21+
{
22+
if (ms is null)
23+
return null;
24+
25+
if (!ms.TryGetBuffer(out ArraySegment<byte> buffer) || buffer.Array is null)
26+
return Encoding.UTF8.GetString(ms.ToArray());
27+
28+
return Encoding.UTF8.GetString(buffer.Array, buffer.Offset, buffer.Count);
29+
}
30+
1931
internal static byte[] Utf8Bytes(this string s) => s.IsNullOrEmpty() ? null : Encoding.UTF8.GetBytes(s);
2032

2133
internal static string NotNull(this string @object, string parameterName)

src/Elasticsearch.Net/Serialization/IElasticsearchSerializer.cs

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,14 @@ public static string SerializeToString<T>(
4444
T data,
4545
IMemoryStreamFactory memoryStreamFactory = null,
4646
SerializationFormatting formatting = SerializationFormatting.Indented
47-
) =>
48-
serializer.SerializeToBytes(data, memoryStreamFactory, formatting).Utf8String();
47+
)
48+
{
49+
memoryStreamFactory = memoryStreamFactory ?? RecyclableMemoryStreamFactory.Default;
50+
using (var ms = memoryStreamFactory.Create())
51+
{
52+
serializer.Serialize(data, ms, formatting);
53+
return ms.Utf8String();
54+
}
55+
}
4956
}
5057
}

0 commit comments

Comments
 (0)