@@ -198,15 +198,21 @@ public static void Write(this Stream stream, ReadOnlySpan<byte> buffer)
198
198
/// <typeparam name="T">The type of value to read.</typeparam>
199
199
/// <param name="stream">The source <see cref="Stream"/> instance to read from.</param>
200
200
/// <returns>The <typeparamref name="T"/> value read from <paramref name="stream"/>.</returns>
201
- /// <exception cref="InvalidOperationException ">Thrown if <paramref name="stream"/> reaches the end.</exception>
201
+ /// <exception cref="EndOfStreamException ">Thrown if <paramref name="stream"/> reaches the end.</exception>
202
202
#if NETSTANDARD2_1_OR_GREATER
203
203
[ MethodImpl ( MethodImplOptions . AggressiveInlining ) ]
204
204
#endif
205
205
public static unsafe T Read < T > ( this Stream stream )
206
206
where T : unmanaged
207
207
{
208
- #if NETSTANDARD2_1_OR_GREATER
209
- T result = default ;
208
+ #if NET7_0_OR_GREATER
209
+ T result ;
210
+
211
+ stream . ReadExactly ( new Span < byte > ( & result , sizeof ( T ) ) ) ;
212
+
213
+ return result ;
214
+ #elif NETSTANDARD2_1_OR_GREATER
215
+ T result ;
210
216
int bytesOffset = 0 ;
211
217
212
218
// As per Stream.Read's documentation:
@@ -220,7 +226,7 @@ public static unsafe T Read<T>(this Stream stream)
220
226
// A return value of 0 indicates that the end of the stream has been reached
221
227
if ( bytesRead == 0 )
222
228
{
223
- ThrowInvalidOperationExceptionForEndOfStream ( ) ;
229
+ ThrowEndOfStreamException ( ) ;
224
230
}
225
231
226
232
bytesOffset += bytesRead ;
@@ -240,7 +246,7 @@ public static unsafe T Read<T>(this Stream stream)
240
246
241
247
if ( bytesRead == 0 )
242
248
{
243
- ThrowInvalidOperationExceptionForEndOfStream ( ) ;
249
+ ThrowEndOfStreamException ( ) ;
244
250
}
245
251
246
252
bytesOffset += bytesRead ;
@@ -293,11 +299,13 @@ public static unsafe void Write<T>(this Stream stream, in T value)
293
299
#endif
294
300
}
295
301
302
+ #if ! NET7_0_OR_GREATER
296
303
/// <summary>
297
- /// Throws an <see cref="InvalidOperationException "/> when <see cref="Read{T}"/> fails.
304
+ /// Throws an <see cref="EndOfStreamException "/> when <see cref="Read{T}"/> fails.
298
305
/// </summary>
299
- private static void ThrowInvalidOperationExceptionForEndOfStream ( )
306
+ private static void ThrowEndOfStreamException ( )
300
307
{
301
- throw new InvalidOperationException ( "The stream didn't contain enough data to read the requested item." ) ;
308
+ throw new EndOfStreamException ( "The stream didn't contain enough data to read the requested item." ) ;
302
309
}
310
+ #endif
303
311
}
0 commit comments