@@ -47,7 +47,7 @@ protected PositionAwareStreamReaderBase (Stream stream, EncodingOptions encoding
4747
4848 MaximumLineLength = maximumLineLength ;
4949
50- _preambleLength = DetectPreambleLengthAndEncoding ( out var detectedEncoding ) ;
50+ ( _preambleLength , Encoding ? detectedEncoding ) = DetectPreambleLength ( _stream ) ;
5151
5252 var usedEncoding = DetermineEncoding ( encodingOptions , detectedEncoding ) ;
5353 _posIncPrecomputed = GetPosIncPrecomputed ( usedEncoding ) ;
@@ -165,11 +165,19 @@ protected void MovePosition (int offset)
165165
166166 #region Private Methods
167167
168+ public static Encoding DetermineEncoding ( EncodingOptions options , Encoding detectedEncoding )
169+ {
170+ return options ? . Encoding != null
171+ ? options . Encoding
172+ : detectedEncoding ?? options ? . DefaultEncoding ?? Encoding . Default ;
173+ }
174+
168175 /// <summary>
169- /// Determines the actual number of preamble bytes in the file.
176+ /// Determines the actual number of preamble bytes in the file and the Encoding .
170177 /// </summary>
171- /// <returns>Number of preamble bytes in the file</returns>
172- private int DetectPreambleLengthAndEncoding ( out Encoding detectedEncoding )
178+ /// <param name="stream"></param>
179+ /// <returns>Number of preamble bytes in the file and the Encoding if there is one</returns>
180+ public static ( int length , Encoding ? detectedEncoding ) DetectPreambleLength ( Stream stream )
173181 {
174182 /*
175183 UTF-8: EF BB BF
@@ -179,31 +187,15 @@ private int DetectPreambleLengthAndEncoding (out Encoding detectedEncoding)
179187 UTF-32-Little-Endian-Byteorder: FF FE 00 00
180188 */
181189
182- var ( length , encoding ) = DetectPreambleLength ( _stream ) ;
183- // not found or less than 2 byte read
184- detectedEncoding = encoding ;
185-
186- return length ;
187- }
188-
189- public static Encoding DetermineEncoding ( EncodingOptions options , Encoding detectedEncoding )
190- {
191- return options ? . Encoding != null
192- ? options . Encoding
193- : detectedEncoding ?? options ? . DefaultEncoding ?? Encoding . Default ;
194- }
195-
196- public static ( int length , Encoding ? detectedEncoding ) DetectPreambleLength ( Stream stream )
197- {
198190 if ( ! stream . CanSeek )
199191 {
200192 return ( 0 , null ) ;
201193 }
202194
203195 var originalPos = stream . Position ;
204- var buffer = new byte [ 4 ] ;
196+ Span < byte > buffer = stackalloc byte [ 4 ] ;
205197 _ = stream . Seek ( 0 , SeekOrigin . Begin ) ;
206- var readBytes = stream . Read ( buffer , 0 , buffer . Length ) ;
198+ var readBytes = stream . Read ( buffer ) ;
207199 _ = stream . Seek ( originalPos , SeekOrigin . Begin ) ;
208200
209201 if ( readBytes >= 2 )
0 commit comments