| | | 1 | | // ----------------------------------------------------------------------- |
| | | 2 | | // <copyright file="StreamExtensions.cs" company="Stéphane ANDRE"> |
| | | 3 | | // Copyright (c) Stéphane ANDRE. All rights reserved. |
| | | 4 | | // </copyright> |
| | | 5 | | // ----------------------------------------------------------------------- |
| | | 6 | | |
| | | 7 | | using System; |
| | | 8 | | using System.Diagnostics.CodeAnalysis; |
| | | 9 | | using System.IO; |
| | | 10 | | using System.Text; |
| | | 11 | | using System.Threading; |
| | | 12 | | using System.Threading.Tasks; |
| | | 13 | | using System.Xml; |
| | | 14 | | using System.Xml.Serialization; |
| | | 15 | | |
| | | 16 | | #pragma warning disable IDE0130 // Namespace does not match folder structure |
| | | 17 | | namespace MyNet.Utilities; |
| | | 18 | | #pragma warning restore IDE0130 // Namespace does not match folder structure |
| | | 19 | | |
| | | 20 | | [SuppressMessage("Reliability", "CA2007:Consider calling ConfigureAwait on the awaited task", Justification = "Library c |
| | | 21 | | public static class StreamExtensions |
| | | 22 | | { |
| | | 23 | | private const int DefaultBufferSize = 81920; |
| | | 24 | | |
| | | 25 | | extension(Stream stream) |
| | | 26 | | { |
| | | 27 | | /// <summary> |
| | | 28 | | /// Writes the specified byte array to the stream. |
| | | 29 | | /// </summary> |
| | | 30 | | /// <param name="buffer">The buffer to write.</param> |
| | | 31 | | public void WriteBytes(byte[] buffer) |
| | | 32 | | { |
| | 9 | 33 | | ArgumentNullException.ThrowIfNull(buffer); |
| | | 34 | | |
| | 6 | 35 | | if (buffer.Length == 0) |
| | 3 | 36 | | return; |
| | | 37 | | |
| | 3 | 38 | | stream.Write(buffer); |
| | 3 | 39 | | } |
| | | 40 | | |
| | | 41 | | /// <summary> |
| | | 42 | | /// Writes the specified byte array to the stream asynchronously. |
| | | 43 | | /// </summary> |
| | | 44 | | /// <param name="buffer">The buffer to write.</param> |
| | | 45 | | /// <param name="cancellationToken">The cancellation token.</param> |
| | | 46 | | /// <returns>A task representing the asynchronous operation.</returns> |
| | | 47 | | public async ValueTask WriteBytesAsync( |
| | | 48 | | byte[] buffer, |
| | | 49 | | CancellationToken cancellationToken = default) |
| | | 50 | | { |
| | 3 | 51 | | ArgumentNullException.ThrowIfNull(buffer); |
| | | 52 | | |
| | 3 | 53 | | if (buffer.Length == 0) |
| | 0 | 54 | | return; |
| | | 55 | | |
| | 3 | 56 | | await stream |
| | 3 | 57 | | .WriteAsync(buffer, cancellationToken) |
| | 3 | 58 | | .ConfigureAwait(false); |
| | 3 | 59 | | } |
| | | 60 | | |
| | | 61 | | /// <summary> |
| | | 62 | | /// Reads the entire stream into a byte array. |
| | | 63 | | /// </summary> |
| | | 64 | | /// <returns>The stream content as a byte array.</returns> |
| | | 65 | | public byte[] ReadAllBytes() |
| | | 66 | | { |
| | 6 | 67 | | if (stream is MemoryStream memoryStream && |
| | 6 | 68 | | memoryStream.TryGetBuffer(out var segment)) |
| | | 69 | | { |
| | 0 | 70 | | return segment.Array is not null |
| | 0 | 71 | | ? segment.Array.AsSpan(0, (int)memoryStream.Length).ToArray() |
| | 0 | 72 | | : memoryStream.ToArray(); |
| | | 73 | | } |
| | | 74 | | |
| | 6 | 75 | | using var ms = new MemoryStream(); |
| | | 76 | | |
| | 6 | 77 | | stream.CopyTo(ms, DefaultBufferSize); |
| | | 78 | | |
| | 6 | 79 | | return ms.ToArray(); |
| | | 80 | | } |
| | | 81 | | |
| | | 82 | | /// <summary> |
| | | 83 | | /// Reads the entire stream into a byte array asynchronously. |
| | | 84 | | /// </summary> |
| | | 85 | | /// <param name="cancellationToken">The cancellation token.</param> |
| | | 86 | | /// <returns>The stream content as a byte array.</returns> |
| | | 87 | | public async ValueTask<byte[]> ReadAllBytesAsync( |
| | | 88 | | CancellationToken cancellationToken = default) |
| | | 89 | | { |
| | 6 | 90 | | if (stream is MemoryStream memoryStream && |
| | 6 | 91 | | memoryStream.TryGetBuffer(out var segment)) |
| | | 92 | | { |
| | 0 | 93 | | return segment.Array is not null |
| | 0 | 94 | | ? segment.Array.AsSpan(0, (int)memoryStream.Length).ToArray() |
| | 0 | 95 | | : memoryStream.ToArray(); |
| | | 96 | | } |
| | | 97 | | |
| | 6 | 98 | | await using var ms = new MemoryStream(); |
| | | 99 | | |
| | 6 | 100 | | await stream |
| | 6 | 101 | | .CopyToAsync(ms, DefaultBufferSize, cancellationToken) |
| | 6 | 102 | | .ConfigureAwait(false); |
| | | 103 | | |
| | 6 | 104 | | return ms.ToArray(); |
| | 6 | 105 | | } |
| | | 106 | | |
| | | 107 | | /// <summary> |
| | | 108 | | /// Writes the specified string to the stream using UTF8 encoding. |
| | | 109 | | /// </summary> |
| | | 110 | | /// <param name="value">The string to write.</param> |
| | | 111 | | /// <param name="encoding">The encoding to use.</param> |
| | | 112 | | /// <param name="leaveOpen">Whether to leave the stream open.</param> |
| | | 113 | | public void WriteString( |
| | | 114 | | string value, |
| | | 115 | | Encoding? encoding = null, |
| | | 116 | | bool leaveOpen = true) |
| | | 117 | | { |
| | 6 | 118 | | ArgumentNullException.ThrowIfNull(value); |
| | | 119 | | |
| | 3 | 120 | | using var writer = new StreamWriter( |
| | 3 | 121 | | stream, |
| | 3 | 122 | | encoding ?? Encoding.UTF8, |
| | 3 | 123 | | DefaultBufferSize, |
| | 3 | 124 | | leaveOpen); |
| | | 125 | | |
| | 3 | 126 | | writer.Write(value); |
| | 3 | 127 | | writer.Flush(); |
| | 3 | 128 | | } |
| | | 129 | | |
| | | 130 | | /// <summary> |
| | | 131 | | /// Writes the specified string to the stream asynchronously using UTF8 encoding. |
| | | 132 | | /// </summary> |
| | | 133 | | /// <param name="value">The string to write.</param> |
| | | 134 | | /// <param name="encoding">The encoding to use.</param> |
| | | 135 | | /// <param name="leaveOpen">Whether to leave the stream open.</param> |
| | | 136 | | /// <param name="cancellationToken">The cancellation token.</param> |
| | | 137 | | public async ValueTask WriteStringAsync( |
| | | 138 | | string value, |
| | | 139 | | Encoding? encoding = null, |
| | | 140 | | bool leaveOpen = true, |
| | | 141 | | CancellationToken cancellationToken = default) |
| | | 142 | | { |
| | 3 | 143 | | ArgumentNullException.ThrowIfNull(value); |
| | | 144 | | |
| | 3 | 145 | | await using var writer = new StreamWriter( |
| | 3 | 146 | | stream, |
| | 3 | 147 | | encoding ?? Encoding.UTF8, |
| | 3 | 148 | | DefaultBufferSize, |
| | 3 | 149 | | leaveOpen); |
| | | 150 | | |
| | 3 | 151 | | await writer |
| | 3 | 152 | | .WriteAsync(value.AsMemory(), cancellationToken) |
| | 3 | 153 | | .ConfigureAwait(false); |
| | | 154 | | |
| | 3 | 155 | | await writer |
| | 3 | 156 | | .FlushAsync(cancellationToken) |
| | 3 | 157 | | .ConfigureAwait(false); |
| | 3 | 158 | | } |
| | | 159 | | |
| | | 160 | | /// <summary> |
| | | 161 | | /// Reads the entire stream as a string. |
| | | 162 | | /// </summary> |
| | | 163 | | /// <param name="encoding">The encoding to use.</param> |
| | | 164 | | /// <param name="leaveOpen">Whether to leave the stream open.</param> |
| | | 165 | | /// <returns>The stream content as a string.</returns> |
| | | 166 | | public string ReadAsString( |
| | | 167 | | Encoding? encoding = null, |
| | | 168 | | bool leaveOpen = true) |
| | | 169 | | { |
| | 3 | 170 | | using var reader = new StreamReader( |
| | 3 | 171 | | stream, |
| | 3 | 172 | | encoding ?? Encoding.UTF8, |
| | 3 | 173 | | detectEncodingFromByteOrderMarks: true, |
| | 3 | 174 | | DefaultBufferSize, |
| | 3 | 175 | | leaveOpen); |
| | | 176 | | |
| | 3 | 177 | | return reader.ReadToEnd(); |
| | | 178 | | } |
| | | 179 | | |
| | | 180 | | /// <summary> |
| | | 181 | | /// Reads the entire stream as a string asynchronously. |
| | | 182 | | /// </summary> |
| | | 183 | | /// <param name="encoding">The encoding to use.</param> |
| | | 184 | | /// <param name="leaveOpen">Whether to leave the stream open.</param> |
| | | 185 | | /// <param name="cancellationToken">The cancellation token.</param> |
| | | 186 | | /// <returns>The stream content as a string.</returns> |
| | | 187 | | public async ValueTask<string> ReadAsStringAsync( |
| | | 188 | | Encoding? encoding = null, |
| | | 189 | | bool leaveOpen = true, |
| | | 190 | | CancellationToken cancellationToken = default) |
| | | 191 | | { |
| | 3 | 192 | | using var reader = new StreamReader( |
| | 3 | 193 | | stream, |
| | 3 | 194 | | encoding ?? Encoding.UTF8, |
| | 3 | 195 | | detectEncodingFromByteOrderMarks: true, |
| | 3 | 196 | | DefaultBufferSize, |
| | 3 | 197 | | leaveOpen); |
| | | 198 | | |
| | 3 | 199 | | return await reader |
| | 3 | 200 | | .ReadToEndAsync(cancellationToken) |
| | 3 | 201 | | .ConfigureAwait(false); |
| | 3 | 202 | | } |
| | | 203 | | |
| | | 204 | | /// <summary> |
| | | 205 | | /// Serializes an object as XML into the stream. |
| | | 206 | | /// </summary> |
| | | 207 | | /// <typeparam name="T">The object type.</typeparam> |
| | | 208 | | /// <param name="value">The object to serialize.</param> |
| | | 209 | | /// <param name="leaveOpen">Whether to leave the stream open.</param> |
| | | 210 | | public void WriteXml<T>( |
| | | 211 | | T value, |
| | | 212 | | bool leaveOpen = true) |
| | | 213 | | { |
| | 6 | 214 | | ArgumentNullException.ThrowIfNull(value); |
| | | 215 | | |
| | 3 | 216 | | var serializer = XmlSerializerCache<T>.Instance; |
| | | 217 | | |
| | 3 | 218 | | var settings = new XmlWriterSettings { Async = false, Indent = true, Encoding = Encoding.UTF8, CloseOutput = |
| | | 219 | | |
| | 3 | 220 | | using var writer = XmlWriter.Create(stream, settings); |
| | | 221 | | |
| | 3 | 222 | | serializer.Serialize(writer, value); |
| | 3 | 223 | | } |
| | | 224 | | |
| | | 225 | | /// <summary> |
| | | 226 | | /// Serializes an object as XML into the stream asynchronously. |
| | | 227 | | /// </summary> |
| | | 228 | | /// <typeparam name="T">The object type.</typeparam> |
| | | 229 | | /// <param name="value">The object to serialize.</param> |
| | | 230 | | /// <param name="leaveOpen">Whether to leave the stream open.</param> |
| | | 231 | | /// <param name="cancellationToken">The cancellation token.</param> |
| | | 232 | | public async ValueTask WriteXmlAsync<T>( |
| | | 233 | | T value, |
| | | 234 | | bool leaveOpen = true, |
| | | 235 | | CancellationToken cancellationToken = default) |
| | | 236 | | { |
| | 3 | 237 | | ArgumentNullException.ThrowIfNull(value); |
| | | 238 | | |
| | 3 | 239 | | var serializer = XmlSerializerCache<T>.Instance; |
| | | 240 | | |
| | 3 | 241 | | var settings = new XmlWriterSettings { Async = true, Indent = true, Encoding = Encoding.UTF8, CloseOutput = |
| | | 242 | | |
| | 3 | 243 | | await using var writer = XmlWriter.Create(stream, settings); |
| | | 244 | | |
| | 3 | 245 | | serializer.Serialize(writer, value); |
| | | 246 | | |
| | 3 | 247 | | await writer |
| | 3 | 248 | | .FlushAsync() |
| | 3 | 249 | | .ConfigureAwait(false); |
| | | 250 | | |
| | 3 | 251 | | cancellationToken.ThrowIfCancellationRequested(); |
| | 3 | 252 | | } |
| | | 253 | | |
| | | 254 | | /// <summary> |
| | | 255 | | /// Deserializes an object from XML. |
| | | 256 | | /// </summary> |
| | | 257 | | /// <typeparam name="T">The object type.</typeparam> |
| | | 258 | | /// <param name="leaveOpen">Whether to leave the stream open.</param> |
| | | 259 | | /// <returns>The deserialized object.</returns> |
| | | 260 | | public T? ReadXml<T>(bool leaveOpen = true) |
| | | 261 | | { |
| | 3 | 262 | | var serializer = XmlSerializerCache<T>.Instance; |
| | | 263 | | |
| | 3 | 264 | | var settings = new XmlReaderSettings { Async = false, CloseInput = !leaveOpen }; |
| | | 265 | | |
| | 3 | 266 | | using var reader = XmlReader.Create(stream, settings); |
| | | 267 | | |
| | 3 | 268 | | return serializer.Deserialize(reader) is T result |
| | 3 | 269 | | ? result |
| | 3 | 270 | | : default; |
| | | 271 | | } |
| | | 272 | | |
| | | 273 | | /// <summary> |
| | | 274 | | /// Deserializes an object from XML asynchronously. |
| | | 275 | | /// </summary> |
| | | 276 | | /// <typeparam name="T">The object type.</typeparam> |
| | | 277 | | /// <param name="leaveOpen">Whether to leave the stream open.</param> |
| | | 278 | | /// <param name="cancellationToken">The cancellation token.</param> |
| | | 279 | | /// <returns>The deserialized object.</returns> |
| | | 280 | | public async ValueTask<T?> ReadXmlAsync<T>( |
| | | 281 | | bool leaveOpen = true, |
| | | 282 | | CancellationToken cancellationToken = default) |
| | | 283 | | { |
| | 3 | 284 | | var serializer = XmlSerializerCache<T>.Instance; |
| | | 285 | | |
| | 3 | 286 | | var settings = new XmlReaderSettings { Async = true, CloseInput = !leaveOpen }; |
| | | 287 | | |
| | 3 | 288 | | using var reader = XmlReader.Create(stream, settings); |
| | | 289 | | |
| | 3 | 290 | | await reader |
| | 3 | 291 | | .MoveToContentAsync() |
| | 3 | 292 | | .ConfigureAwait(false); |
| | | 293 | | |
| | 3 | 294 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 295 | | |
| | 3 | 296 | | return serializer.Deserialize(reader) is T result |
| | 3 | 297 | | ? result |
| | 3 | 298 | | : default; |
| | 3 | 299 | | } |
| | | 300 | | |
| | | 301 | | /// <summary> |
| | | 302 | | /// Rewinds the stream to the beginning if seekable. |
| | | 303 | | /// </summary> |
| | | 304 | | public void Rewind() |
| | | 305 | | { |
| | 6 | 306 | | if (!stream.CanSeek) |
| | 3 | 307 | | return; |
| | | 308 | | |
| | 3 | 309 | | stream.Position = 0; |
| | 3 | 310 | | } |
| | | 311 | | } |
| | | 312 | | |
| | | 313 | | private static class XmlSerializerCache<T> |
| | | 314 | | { |
| | 3 | 315 | | public static readonly XmlSerializer Instance = |
| | 3 | 316 | | new(typeof(T)); |
| | | 317 | | } |
| | | 318 | | } |
| | | 319 | | |