44using System . Globalization ;
55using System . IO ;
66using System . Numerics ;
7+ using System . Runtime . CompilerServices ;
78using System . Text ;
89using Bencodex . Misc ;
910using Bencodex . Types ;
@@ -12,7 +13,6 @@ namespace Bencodex
1213{
1314 internal sealed class Decoder
1415 {
15- private readonly byte [ ] _tinyBuffer = new byte [ 1 ] ;
1616 private readonly Stream _stream ;
1717 private readonly IndirectValue . Loader ? _indirectValueLoader ;
1818 private byte _lastRead ;
@@ -74,7 +74,7 @@ private IValue DecodeValue()
7474 return ReadTextAfterPrefix ( ) ;
7575
7676 case 0x6c : // 'l'
77- var indirElements = new List < IndirectValue > ( ) ;
77+ var indirBuilder = ImmutableArray . CreateBuilder < IndirectValue > ( ) ;
7878 while ( true )
7979 {
8080 byte b = ReadByte ( ) ?? throw new DecodingException (
@@ -87,17 +87,17 @@ private IValue DecodeValue()
8787 else if ( b == indir )
8888 {
8989 Fingerprint fp = DecodeFingerprint ( ) ;
90- indirElements . Add ( new IndirectValue ( fp ) ) ;
90+ indirBuilder . Add ( new IndirectValue ( fp ) ) ;
9191 continue ;
9292 }
9393
9494 Back ( ) ;
9595 IValue element = DecodeValue ( ) ;
96- indirElements . Add ( new IndirectValue ( element ) ) ;
96+ indirBuilder . Add ( new IndirectValue ( element ) ) ;
9797 }
9898
9999 return new Bencodex . Types . List (
100- indirElements . ToImmutableArray ( ) ,
100+ indirBuilder . MoveToImmutable ( ) . AsSpan ( ) ,
101101 _indirectValueLoader
102102 ) ;
103103
@@ -255,15 +255,15 @@ private byte[] Read(byte[] buffer)
255255 return _lastRead ;
256256 }
257257
258- int read = _stream . Read ( _tinyBuffer , 0 , 1 ) ;
258+ int read = _stream . ReadByte ( ) ;
259259 if ( read > 0 )
260260 {
261- _lastRead = _tinyBuffer [ 0 ] ;
261+ _lastRead = ( byte ) read ;
262262 }
263263
264264 _offset ++ ;
265265 _didBack = false ;
266- return read == 0 ? ( byte ? ) null : _tinyBuffer [ 0 ] ;
266+ return read == - 1 ? ( byte ? ) null : _lastRead ;
267267 }
268268
269269 private void Back ( )
@@ -363,12 +363,7 @@ Func<string, IFormatProvider, T> converter
363363 )
364364 {
365365 byte [ ] buffer = ReadDigits ( takeMinusSign , delimiter ) ;
366- var digits = new char [ buffer . Length ] ;
367- for ( int i = 0 ; i < buffer . Length ; i ++ )
368- {
369- digits [ i ] = ( char ) buffer [ i ] ;
370- }
371-
366+ var digits = Unsafe . As < byte [ ] , char [ ] > ( ref buffer ) ;
372367 return converter ( new string ( digits ) , CultureInfo . InvariantCulture ) ;
373368 }
374369
@@ -399,7 +394,7 @@ Func<string, IFormatProvider, T> converter
399394 private Binary ReadBinary ( )
400395 {
401396 ( byte [ ] bytes , _ ) = ReadByteArray ( ) ;
402- return new Binary ( bytes ) ;
397+ return new Binary ( bytes . AsSpan ( ) ) ;
403398 }
404399
405400 private Text ReadTextAfterPrefix ( )
0 commit comments