@@ -6,6 +6,7 @@ This file is a bit of a mess. It was an attempt at implementing a C# version of
66 for their arguments instead, along with not trying to reinvent the wheel and read actual C stdlib implementations.
77*/
88
9+ using System . Diagnostics . CodeAnalysis ;
910using System . Globalization ;
1011using System . Numerics ;
1112using System . Runtime . CompilerServices ;
@@ -181,102 +182,211 @@ public ref struct ScanF
181182{
182183 public CFormatReader Format ;
183184 ReadOnlySpan < char > input ;
184- int readArguments = 0 ;
185- public readonly int ReadArguments => readArguments - invalidArguments ;
186- public readonly bool ReadAny => readArguments > 0 ;
185+ int assigned ;
186+ bool failed ;
187+ bool inputFailure ;
188+
189+ public readonly int ReadArguments => assigned == 0 && inputFailure ? - 1 : assigned ;
190+ public readonly bool ReadAny => assigned > 0 ;
187191
188192 public ScanF ( ReadOnlySpan < char > input , ReadOnlySpan < char > format ) {
189193 Format = new ( format ) ;
190194 this . input = input . SliceNullTerminatedString ( ) ;
191195 }
192196 public readonly bool Overflowed => Format . Overflowed ( ) ;
193197
194- // NOTE: Only unsafe because C# can't tell we're never going to lose track of the stack allocated buffer target
195- // (which is needed to read out a literal)
196- private unsafe bool TryReadVariable ( Span < char > incoming , out char type , out int len ) {
197- type = '\0 ' ;
198- len = 0 ;
199- if ( Format . Overflowed ( ) || input . Length <= 0 )
198+ static bool IsSpace ( char c ) => c is ' ' or '\t ' or '\n ' or '\v ' or '\f ' or '\r ' ;
199+ static int DigitValue ( char c ) => c is >= '0' and <= '9' ? c - '0' : c is >= 'a' and <= 'f' ? c - 'a' + 10 : c is >= 'A' and <= 'F' ? c - 'A' + 10 : 99 ;
200+
201+ void SkipSpaces ( ) {
202+ while ( ! input . IsEmpty && IsSpace ( input [ 0 ] ) )
203+ input = input [ 1 .. ] ;
204+ }
205+
206+ bool Fail ( bool atEnd ) {
207+ inputFailure = atEnd ;
208+ failed = true ;
209+ return false ;
210+ }
211+
212+ bool NextConversion ( out CFormatSpec spec ) {
213+ spec = default ;
214+ if ( failed )
200215 return false ;
201216
202- // Read until a variable or overflow
203- Span < char > literalBufferTarget = stackalloc char [ 64 ] ;
204- while ( ! Format . Overflowed ( ) && input . Length > 0 ) {
205- #pragma warning disable CS9080 // Use of variable in this context may expose referenced variables outside of their declaration scope
206- int read = Format . ReadLiteral ( literalBufferTarget ) ;
207- #pragma warning restore CS9080 // Use of variable in this context may expose referenced variables outside of their declaration scope
208- if ( read > 0 ) {
209- input = input [ read .. ] ; // slice so we're aligned
210- continue ;
217+ Span < char > literal = stackalloc char [ 64 ] ;
218+ while ( true ) {
219+ for ( int read = Format . ReadLiteral ( literal ) ; read > 0 ; read = Format . ReadLiteral ( literal ) ) {
220+ for ( int i = 0 ; i < read ; i ++ ) {
221+ if ( IsSpace ( literal [ i ] ) ) {
222+ SkipSpaces ( ) ;
223+ continue ;
224+ }
225+
226+ if ( input . IsEmpty || input [ 0 ] != literal [ i ] )
227+ return Fail ( input . IsEmpty ) ;
228+ input = input [ 1 .. ] ;
229+ }
211230 }
212231
213- break ;
232+ if ( ! Format . ReadSpec ( out spec ) )
233+ return Fail ( false ) ;
234+ if ( spec . WidthArg < 0 )
235+ return true ;
236+
237+ if ( CFormatUtils . IsFloatConversion ( spec . Type ) ? ! ScanFloat ( in spec , out _ ) : ! ScanInteger ( in spec , out _ ) )
238+ return false ;
214239 }
240+ }
215241
216- if ( Format . ReadVariable ( out type , out int variableIdx ) ) {
217- readArguments = variableIdx + 1 ;
218- int writePtr = 0 ;
219- bool hasWarned = false ;
220- while ( input . Length > 0 ) {
221- char c = input [ 0 ] ;
222- if ( c == ' ' )
223- break ;
224- input = input [ 1 .. ] ;
225- if ( writePtr < incoming . Length ) // don't overflow but continue to read to not break further arguments
226- incoming [ writePtr ++ ] = c ;
227- else if ( ! hasWarned ) {
228- Warning ( $ "Overflowed scanf (max: { incoming . Length } ). Consider increasing max here! Truncated argument will be provided.\n ") ;
229- hasWarned = true ;
230- }
242+ ReadOnlySpan < char > Window ( in CFormatSpec spec ) {
243+ SkipSpaces ( ) ;
244+ return spec . Width > 0 && spec . Width < input . Length ? input [ .. spec . Width ] : input ;
245+ }
246+
247+ bool Consume ( bool valid , int length ) {
248+ if ( ! valid )
249+ return Fail ( length >= input . Length ) ;
250+
251+ input = input [ length .. ] ;
252+ return true ;
253+ }
254+
255+ bool ScanInteger ( in CFormatSpec spec , out long value ) {
256+ ReadOnlySpan < char > text = Window ( in spec ) ;
257+ int i = 0 ;
258+ bool negative = false ;
259+ if ( i < text . Length && text [ i ] is '+' or '-' )
260+ negative = text [ i ++ ] == '-' ;
261+
262+ int radix = spec . Type switch {
263+ 'x' or 'X' => 16 ,
264+ 'o' or 'O' => 8 ,
265+ 'i' => 0 ,
266+ _ => 10
267+ } ;
268+
269+ if ( radix is 0 or 16 && i + 1 < text . Length && text [ i ] == '0' && text [ i + 1 ] is 'x' or 'X' ) {
270+ radix = 16 ;
271+ i += 2 ;
272+ }
273+ else if ( radix == 0 )
274+ radix = i < text . Length && text [ i ] == '0' ? 8 : 10 ;
275+
276+ int start = i ;
277+ ulong number = 0 ;
278+ for ( ; i < text . Length && DigitValue ( text [ i ] ) < radix ; i ++ )
279+ number = unchecked ( number * ( ulong ) radix + ( ulong ) DigitValue ( text [ i ] ) ) ;
280+
281+ value = unchecked ( negative ? - ( long ) number : ( long ) number ) ;
282+ return Consume ( i > start , i ) ;
283+ }
284+
285+ bool ScanFloat ( in CFormatSpec spec , out float value ) {
286+ ReadOnlySpan < char > text = Window ( in spec ) ;
287+ int i = 0 ;
288+ bool negative = false ;
289+ if ( i < text . Length && text [ i ] is '+' or '-' )
290+ negative = text [ i ++ ] == '-' ;
291+
292+ bool valid ;
293+ value = 0 ;
294+ if ( text [ i .. ] . StartsWith ( "infinity" , StringComparison . OrdinalIgnoreCase ) || text [ i .. ] . StartsWith ( "inf" , StringComparison . OrdinalIgnoreCase ) ) {
295+ i += text [ i .. ] . StartsWith ( "infinity" , StringComparison . OrdinalIgnoreCase ) ? 8 : 3 ;
296+ value = float . PositiveInfinity ;
297+ valid = true ;
298+ }
299+ else if ( text [ i .. ] . StartsWith ( "nan" , StringComparison . OrdinalIgnoreCase ) ) {
300+ i += 3 ;
301+ value = float . NaN ;
302+ valid = true ;
303+ }
304+ else if ( i + 1 < text . Length && text [ i ] == '0' && text [ i + 1 ] is 'x' or 'X' ) {
305+ i += 2 ;
306+ double mantissa = 0 ;
307+ int digits = 0 ;
308+ int exponent = 0 ;
309+ for ( ; i < text . Length && DigitValue ( text [ i ] ) < 16 ; i ++ , digits ++ )
310+ mantissa = mantissa * 16 + DigitValue ( text [ i ] ) ;
311+ if ( i < text . Length && text [ i ] == '.' ) {
312+ for ( i ++ ; i < text . Length && DigitValue ( text [ i ] ) < 16 ; i ++ , digits ++ , exponent -= 4 )
313+ mantissa = mantissa * 16 + DigitValue ( text [ i ] ) ;
231314 }
232- len = writePtr ;
233- return true ;
315+
316+ valid = digits > 0 ;
317+ if ( valid && i < text . Length && text [ i ] is 'p' or 'P' ) {
318+ bool negativeExponent = ++ i < text . Length && text [ i ] == '-' ;
319+ if ( i < text . Length && text [ i ] is '+' or '-' )
320+ i ++ ;
321+ int exponentDigits = i ;
322+ int binaryExponent = 0 ;
323+ for ( ; i < text . Length && char . IsAsciiDigit ( text [ i ] ) ; i ++ )
324+ binaryExponent = Math . Min ( binaryExponent * 10 + ( text [ i ] - '0' ) , 100000 ) ;
325+ valid = i > exponentDigits ;
326+ exponent += negativeExponent ? - binaryExponent : binaryExponent ;
327+ }
328+
329+ value = ( float ) Math . ScaleB ( mantissa , exponent ) ;
234330 }
331+ else {
332+ int start = i ;
333+ int digits = 0 ;
334+ for ( ; i < text . Length && char . IsAsciiDigit ( text [ i ] ) ; i ++ )
335+ digits ++ ;
336+ if ( i < text . Length && text [ i ] == '.' ) {
337+ for ( i ++ ; i < text . Length && char . IsAsciiDigit ( text [ i ] ) ; i ++ )
338+ digits ++ ;
339+ }
235340
236- return false ;
341+ valid = digits > 0 ;
342+ if ( valid && i < text . Length && text [ i ] is 'e' or 'E' ) {
343+ if ( ++ i < text . Length && text [ i ] is '+' or '-' )
344+ i ++ ;
345+ int exponentDigits = i ;
346+ while ( i < text . Length && char . IsAsciiDigit ( text [ i ] ) )
347+ i ++ ;
348+ valid = i > exponentDigits ;
349+ }
350+
351+ if ( valid )
352+ value = float . Parse ( text [ start .. i ] , NumberStyles . Float , CultureInfo . InvariantCulture ) ;
353+ }
354+
355+ if ( negative )
356+ value = - value ;
357+ return Consume ( valid , i ) ;
237358 }
238- public const int DEFAULT_SCANF_MAX = 256 ;
239- public unsafe ScanF Read ( out int i , int max = DEFAULT_SCANF_MAX ) {
240- Span < char > incoming = stackalloc char [ max ] ;
241- i = default ;
242- int iAttempt ;
243359
244- #pragma warning disable CS9080 // Use of variable in this context may expose referenced variables outside of their declaration scope
245- if ( TryReadVariable ( incoming , out char type , out int len ) )
246- #pragma warning restore CS9080 // Use of variable in this context may expose referenced variables outside of their declaration scope
247- switch ( type ) {
248- case 'd' :
249- case ( char ) VariableType . SignedDecimalInteger :
250- i = int . TryParse ( incoming [ .. len ] , out iAttempt ) ? iAttempt : default ;
251- break ;
252- case ( char ) VariableType . UnsignedHexadecimalInteger :
253- i = int . TryParse ( incoming [ .. len ] , NumberStyles . HexNumber , CultureInfo . InvariantCulture , out iAttempt ) ? iAttempt : default ;
254- break ;
255- default : throw new NotImplementedException ( ) ;
360+ [ UnscopedRef ]
361+ public ref ScanF Read ( out int i ) {
362+ Unsafe . SkipInit ( out i ) ;
363+ if ( NextConversion ( out CFormatSpec spec ) ) {
364+ if ( ! CFormatUtils . IsIntegerConversion ( spec . Type ) )
365+ throw new NotImplementedException ( ) ;
366+
367+ if ( ScanInteger ( in spec , out long value ) ) {
368+ i = unchecked ( ( int ) value ) ;
369+ assigned ++ ;
256370 }
371+ }
257372
258- return this ;
373+ return ref this ;
259374 }
260- int invalidArguments = 0 ;
261- public unsafe ScanF Read ( out float i , int max = DEFAULT_SCANF_MAX ) {
262- Span < char > incoming = stackalloc char [ max ] ;
263- i = default ;
264- float iAttempt ;
265375
266- #pragma warning disable CS9080 // Use of variable in this context may expose referenced variables outside of their declaration scope
267- if ( TryReadVariable ( incoming , out char type , out int len ) )
268- #pragma warning restore CS9080 // Use of variable in this context may expose referenced variables outside of their declaration scope
269- switch ( type ) {
270- case ( char ) VariableType . DecimalFloatingPoint :
271- if ( float . TryParse ( incoming [ .. len ] , out iAttempt ) )
272- i = iAttempt ;
273- else
274- invalidArguments ++ ;
275- break ;
276- default : throw new NotImplementedException ( ) ;
376+ [ UnscopedRef ]
377+ public ref ScanF Read ( out float i ) {
378+ Unsafe . SkipInit ( out i ) ;
379+ if ( NextConversion ( out CFormatSpec spec ) ) {
380+ if ( ! CFormatUtils . IsFloatConversion ( spec . Type ) )
381+ throw new NotImplementedException ( ) ;
382+
383+ if ( ScanFloat ( in spec , out float value ) ) {
384+ i = value ;
385+ assigned ++ ;
277386 }
387+ }
278388
279- return this ;
389+ return ref this ;
280390 }
281391}
282392
0 commit comments