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,19 @@ 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
99+ IndirectValue [ ] indirs = indirBuilder . ToArray ( ) ;
100+
99101 return new Bencodex . Types . List (
100- indirElements . ToImmutableArray ( ) ,
102+ indirs . AsSpan ( ) ,
101103 _indirectValueLoader
102104 ) ;
103105
@@ -255,15 +257,15 @@ private byte[] Read(byte[] buffer)
255257 return _lastRead ;
256258 }
257259
258- int read = _stream . Read ( _tinyBuffer , 0 , 1 ) ;
260+ int read = _stream . ReadByte ( ) ;
259261 if ( read > 0 )
260262 {
261- _lastRead = _tinyBuffer [ 0 ] ;
263+ _lastRead = ( byte ) read ;
262264 }
263265
264266 _offset ++ ;
265267 _didBack = false ;
266- return read == 0 ? ( byte ? ) null : _tinyBuffer [ 0 ] ;
268+ return read == - 1 ? ( byte ? ) null : _lastRead ;
267269 }
268270
269271 private void Back ( )
@@ -363,12 +365,7 @@ Func<string, IFormatProvider, T> converter
363365 )
364366 {
365367 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-
368+ var digits = Unsafe . As < byte [ ] , char [ ] > ( ref buffer ) ;
372369 return converter ( new string ( digits ) , CultureInfo . InvariantCulture ) ;
373370 }
374371
@@ -399,7 +396,7 @@ Func<string, IFormatProvider, T> converter
399396 private Binary ReadBinary ( )
400397 {
401398 ( byte [ ] bytes , _ ) = ReadByteArray ( ) ;
402- return new Binary ( bytes ) ;
399+ return new Binary ( bytes . AsSpan ( ) ) ;
403400 }
404401
405402 private Text ReadTextAfterPrefix ( )
0 commit comments