1 // Copyright 2010 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
18 // ScanState represents the scanner state passed to custom scanners.
19 // Scanners may do rune-at-a-time scanning or ask the ScanState
20 // to discover the next space-delimited token.
21 type ScanState
interface {
22 // ReadRune reads the next rune (Unicode code point) from the input.
23 // If invoked during Scanln, Fscanln, or Sscanln, ReadRune() will
24 // return EOF after returning the first '\n' or when reading beyond
25 // the specified width.
26 ReadRune() (r rune
, size
int, err error
)
27 // UnreadRune causes the next call to ReadRune to return the same rune.
29 // SkipSpace skips space in the input. Newlines are treated appropriately
30 // for the operation being performed; see the package documentation
31 // for more information.
33 // Token skips space in the input if skipSpace is true, then returns the
34 // run of Unicode code points c satisfying f(c). If f is nil,
35 // !unicode.IsSpace(c) is used; that is, the token will hold non-space
36 // characters. Newlines are treated appropriately for the operation being
37 // performed; see the package documentation for more information.
38 // The returned slice points to shared data that may be overwritten
39 // by the next call to Token, a call to a Scan function using the ScanState
40 // as input, or when the calling Scan method returns.
41 Token(skipSpace
bool, f
func(rune
) bool) (token
[]byte, err error
)
42 // Width returns the value of the width option and whether it has been set.
43 // The unit is Unicode code points.
44 Width() (wid
int, ok
bool)
45 // Because ReadRune is implemented by the interface, Read should never be
46 // called by the scanning routines and a valid implementation of
47 // ScanState may choose always to return an error from Read.
48 Read(buf
[]byte) (n
int, err error
)
51 // Scanner is implemented by any value that has a Scan method, which scans
52 // the input for the representation of a value and stores the result in the
53 // receiver, which must be a pointer to be useful. The Scan method is called
54 // for any argument to Scan, Scanf, or Scanln that implements it.
55 type Scanner
interface {
56 Scan(state ScanState
, verb rune
) error
59 // Scan scans text read from standard input, storing successive
60 // space-separated values into successive arguments. Newlines count
61 // as space. It returns the number of items successfully scanned.
62 // If that is less than the number of arguments, err will report why.
63 func Scan(a
...any
) (n
int, err error
) {
64 return Fscan(os
.Stdin
, a
...)
67 // Scanln is similar to Scan, but stops scanning at a newline and
68 // after the final item there must be a newline or EOF.
69 func Scanln(a
...any
) (n
int, err error
) {
70 return Fscanln(os
.Stdin
, a
...)
73 // Scanf scans text read from standard input, storing successive
74 // space-separated values into successive arguments as determined by
75 // the format. It returns the number of items successfully scanned.
76 // If that is less than the number of arguments, err will report why.
77 // Newlines in the input must match newlines in the format.
78 // The one exception: the verb %c always scans the next rune in the
79 // input, even if it is a space (or tab etc.) or newline.
80 func Scanf(format
string, a
...any
) (n
int, err error
) {
81 return Fscanf(os
.Stdin
, format
, a
...)
84 type stringReader
string
86 func (r
*stringReader
) Read(b
[]byte) (n
int, err error
) {
95 // Sscan scans the argument string, storing successive space-separated
96 // values into successive arguments. Newlines count as space. It
97 // returns the number of items successfully scanned. If that is less
98 // than the number of arguments, err will report why.
99 func Sscan(str
string, a
...any
) (n
int, err error
) {
100 return Fscan((*stringReader
)(&str
), a
...)
103 // Sscanln is similar to Sscan, but stops scanning at a newline and
104 // after the final item there must be a newline or EOF.
105 func Sscanln(str
string, a
...any
) (n
int, err error
) {
106 return Fscanln((*stringReader
)(&str
), a
...)
109 // Sscanf scans the argument string, storing successive space-separated
110 // values into successive arguments as determined by the format. It
111 // returns the number of items successfully parsed.
112 // Newlines in the input must match newlines in the format.
113 func Sscanf(str
string, format
string, a
...any
) (n
int, err error
) {
114 return Fscanf((*stringReader
)(&str
), format
, a
...)
117 // Fscan scans text read from r, storing successive space-separated
118 // values into successive arguments. Newlines count as space. It
119 // returns the number of items successfully scanned. If that is less
120 // than the number of arguments, err will report why.
121 func Fscan(r io
.Reader
, a
...any
) (n
int, err error
) {
122 s
, old
:= newScanState(r
, true, false)
128 // Fscanln is similar to Fscan, but stops scanning at a newline and
129 // after the final item there must be a newline or EOF.
130 func Fscanln(r io
.Reader
, a
...any
) (n
int, err error
) {
131 s
, old
:= newScanState(r
, false, true)
137 // Fscanf scans text read from r, storing successive space-separated
138 // values into successive arguments as determined by the format. It
139 // returns the number of items successfully parsed.
140 // Newlines in the input must match newlines in the format.
141 func Fscanf(r io
.Reader
, format
string, a
...any
) (n
int, err error
) {
142 s
, old
:= newScanState(r
, false, false)
143 n
, err
= s
.doScanf(format
, a
)
148 // scanError represents an error generated by the scanning software.
149 // It's used as a unique signature to identify such errors when recovering.
150 type scanError
struct {
156 // ss is the internal implementation of ScanState.
158 rs io
.RuneScanner
// where to read input
159 buf buffer
// token accumulator
160 count
int // runes consumed so far.
161 atEOF
bool // already read EOF
165 // ssave holds the parts of ss that need to be
166 // saved and restored on recursive scans.
168 validSave
bool // is or was a part of an actual ss.
169 nlIsEnd
bool // whether newline terminates scan
170 nlIsSpace
bool // whether newline counts as white space
171 argLimit
int // max value of ss.count for this arg; argLimit <= limit
172 limit
int // max value of ss.count.
173 maxWid
int // width of this arg.
176 // The Read method is only in ScanState so that ScanState
177 // satisfies io.Reader. It will never be called when used as
178 // intended, so there is no need to make it actually work.
179 func (s
*ss
) Read(buf
[]byte) (n
int, err error
) {
180 return 0, errors
.New("ScanState's Read should not be called. Use ReadRune")
183 func (s
*ss
) ReadRune() (r rune
, size
int, err error
) {
184 if s
.atEOF || s
.count
>= s
.argLimit
{
189 r
, size
, err
= s
.rs
.ReadRune()
192 if s
.nlIsEnd
&& r
== '\n' {
195 } else if err
== io
.EOF
{
201 func (s
*ss
) Width() (wid
int, ok
bool) {
202 if s
.maxWid
== hugeWid
{
205 return s
.maxWid
, true
208 // The public method returns an error; this private one panics.
209 // If getRune reaches EOF, the return value is EOF (-1).
210 func (s
*ss
) getRune() (r rune
) {
211 r
, _
, err
:= s
.ReadRune()
221 // mustReadRune turns io.EOF into a panic(io.ErrUnexpectedEOF).
222 // It is called in cases such as string scanning where an EOF is a
224 func (s
*ss
) mustReadRune() (r rune
) {
227 s
.error(io
.ErrUnexpectedEOF
)
232 func (s
*ss
) UnreadRune() error
{
239 func (s
*ss
) error(err error
) {
240 panic(scanError
{err
})
243 func (s
*ss
) errorString(err
string) {
244 panic(scanError
{errors
.New(err
)})
247 func (s
*ss
) Token(skipSpace
bool, f
func(rune
) bool) (tok
[]byte, err error
) {
249 if e
:= recover(); e
!= nil {
250 if se
, ok
:= e
.(scanError
); ok
{
261 tok
= s
.token(skipSpace
, f
)
265 // space is a copy of the unicode.White_Space ranges,
266 // to avoid depending on package unicode.
267 var space
= [][2]uint16{
280 func isSpace(r rune
) bool {
285 for _
, rng
:= range space
{
296 // notSpace is the default scanning function used in Token.
297 func notSpace(r rune
) bool {
301 // readRune is a structure to enable reading UTF-8 encoded code points
302 // from an io.Reader. It is used if the Reader given to the scanner does
303 // not already implement io.RuneScanner.
304 type readRune
struct {
306 buf
[utf8
.UTFMax
]byte // used only inside ReadRune
307 pending
int // number of bytes in pendBuf; only >0 for bad UTF-8
308 pendBuf
[utf8
.UTFMax
]byte // bytes left over
309 peekRune rune
// if >=0 next rune; when <0 is ^(previous Rune)
312 // readByte returns the next byte from the input, which may be
313 // left over from a previous read if the UTF-8 was ill-formed.
314 func (r
*readRune
) readByte() (b
byte, err error
) {
317 copy(r
.pendBuf
[0:], r
.pendBuf
[1:])
321 n
, err
:= io
.ReadFull(r
.reader
, r
.pendBuf
[:1])
325 return r
.pendBuf
[0], err
328 // ReadRune returns the next UTF-8 encoded code point from the
329 // io.Reader inside r.
330 func (r
*readRune
) ReadRune() (rr rune
, size
int, err error
) {
333 r
.peekRune
= ^r
.peekRune
334 size
= utf8
.RuneLen(rr
)
337 r
.buf
[0], err
= r
.readByte()
341 if r
.buf
[0] < utf8
.RuneSelf
{ // fast check for common ASCII case
343 size
= 1 // Known to be 1.
344 // Flip the bits of the rune so it's available to UnreadRune.
349 for n
= 1; !utf8
.FullRune(r
.buf
[:n
]); n
++ {
350 r
.buf
[n
], err
= r
.readByte()
359 rr
, size
= utf8
.DecodeRune(r
.buf
[:n
])
360 if size
< n
{ // an error, save the bytes for the next read
361 copy(r
.pendBuf
[r
.pending
:], r
.buf
[size
:n
])
362 r
.pending
+= n
- size
364 // Flip the bits of the rune so it's available to UnreadRune.
369 func (r
*readRune
) UnreadRune() error
{
371 return errors
.New("fmt: scanning called UnreadRune with no rune available")
373 // Reverse bit flip of previously read rune to obtain valid >=0 state.
374 r
.peekRune
= ^r
.peekRune
378 var ssFree
= sync
.Pool
{
379 New
: func() any
{ return new(ss
) },
382 // newScanState allocates a new ss struct or grab a cached one.
383 func newScanState(r io
.Reader
, nlIsSpace
, nlIsEnd
bool) (s
*ss
, old ssave
) {
384 s
= ssFree
.Get().(*ss
)
385 if rs
, ok
:= r
.(io
.RuneScanner
); ok
{
388 s
.rs
= &readRune
{reader
: r
, peekRune
: -1}
390 s
.nlIsSpace
= nlIsSpace
401 // free saves used ss structs in ssFree; avoid an allocation per invocation.
402 func (s
*ss
) free(old ssave
) {
403 // If it was used recursively, just restore the old state.
408 // Don't hold on to ss structs with large buffers.
409 if cap(s
.buf
) > 1024 {
417 // SkipSpace provides Scan methods the ability to skip space and newline
418 // characters in keeping with the current scanning mode set by format strings
420 func (s
*ss
) SkipSpace() {
426 if r
== '\r' && s
.peek("\n") {
433 s
.errorString("unexpected newline")
443 // token returns the next space-delimited string from the input. It
444 // skips white space. For Scanln, it stops at newlines. For Scan,
445 // newlines are treated as spaces.
446 func (s
*ss
) token(skipSpace
bool, f
func(rune
) bool) []byte {
450 // read until white space or newline
465 var complexError
= errors
.New("syntax error scanning complex number")
466 var boolError
= errors
.New("syntax error scanning boolean")
468 func indexRune(s
string, r rune
) int {
469 for i
, c
:= range s
{
477 // consume reads the next rune in the input and reports whether it is in the ok string.
478 // If accept is true, it puts the character into the input token.
479 func (s
*ss
) consume(ok
string, accept
bool) bool {
484 if indexRune(ok
, r
) >= 0 {
490 if r
!= eof
&& accept
{
496 // peek reports whether the next character is in the ok string, without consuming it.
497 func (s
*ss
) peek(ok
string) bool {
502 return indexRune(ok
, r
) >= 0
505 func (s
*ss
) notEOF() {
506 // Guarantee there is data to be read.
507 if r
:= s
.getRune(); r
== eof
{
513 // accept checks the next rune in the input. If it's a byte (sic) in the string, it puts it in the
514 // buffer and returns true. Otherwise it return false.
515 func (s
*ss
) accept(ok
string) bool {
516 return s
.consume(ok
, true)
519 // okVerb verifies that the verb is present in the list, setting s.err appropriately if not.
520 func (s
*ss
) okVerb(verb rune
, okVerbs
, typ
string) bool {
521 for _
, v
:= range okVerbs
{
526 s
.errorString("bad verb '%" + string(verb
) + "' for " + typ
)
530 // scanBool returns the value of the boolean represented by the next token.
531 func (s
*ss
) scanBool(verb rune
) bool {
534 if !s
.okVerb(verb
, "tv", "boolean") {
537 // Syntax-checking a boolean is annoying. We're not fastidious about case.
544 if s
.accept("rR") && (!s
.accept("uU") ||
!s
.accept("eE")) {
549 if s
.accept("aA") && (!s
.accept("lL") ||
!s
.accept("sS") ||
!s
.accept("eE")) {
557 // Numerical elements
560 octalDigits
= "01234567"
561 decimalDigits
= "0123456789"
562 hexadecimalDigits
= "0123456789aAbBcCdDeEfF"
568 // getBase returns the numeric base represented by the verb and its digit string.
569 func (s
*ss
) getBase(verb rune
) (base
int, digits
string) {
570 s
.okVerb(verb
, "bdoUxXv", "integer") // sets s.err
572 digits
= decimalDigits
576 digits
= binaryDigits
582 digits
= hexadecimalDigits
587 // scanNumber returns the numerical string with specified digits starting here.
588 func (s
*ss
) scanNumber(digits
string, haveDigits
bool) string {
591 if !s
.accept(digits
) {
592 s
.errorString("expected integer")
595 for s
.accept(digits
) {
600 // scanRune returns the next rune value in the input.
601 func (s
*ss
) scanRune(bitSize
int) int64 {
605 x
:= (int64(r
) << (64 - n
)) >> (64 - n
)
607 s
.errorString("overflow on character value " + string(r
))
612 // scanBasePrefix reports whether the integer begins with a base prefix
613 // and returns the base, digit string, and whether a zero was found.
614 // It is called only if the verb is %v.
615 func (s
*ss
) scanBasePrefix() (base
int, digits
string, zeroFound
bool) {
617 return 0, decimalDigits
+ "_", false
620 // Special cases for 0, 0b, 0o, 0x.
623 s
.consume("bB", true)
624 return 0, binaryDigits
+ "_", true
626 s
.consume("oO", true)
627 return 0, octalDigits
+ "_", true
629 s
.consume("xX", true)
630 return 0, hexadecimalDigits
+ "_", true
632 return 0, octalDigits
+ "_", true
636 // scanInt returns the value of the integer represented by the next
637 // token, checking for overflow. Any error is stored in s.err.
638 func (s
*ss
) scanInt(verb rune
, bitSize
int) int64 {
640 return s
.scanRune(bitSize
)
644 base
, digits
:= s
.getBase(verb
)
647 if !s
.consume("U", false) ||
!s
.consume("+", false) {
648 s
.errorString("bad unicode format ")
651 s
.accept(sign
) // If there's a sign, it will be left in the token buffer.
653 base
, digits
, haveDigits
= s
.scanBasePrefix()
656 tok
:= s
.scanNumber(digits
, haveDigits
)
657 i
, err
:= strconv
.ParseInt(tok
, base
, 64)
662 x
:= (i
<< (64 - n
)) >> (64 - n
)
664 s
.errorString("integer overflow on token " + tok
)
669 // scanUint returns the value of the unsigned integer represented
670 // by the next token, checking for overflow. Any error is stored in s.err.
671 func (s
*ss
) scanUint(verb rune
, bitSize
int) uint64 {
673 return uint64(s
.scanRune(bitSize
))
677 base
, digits
:= s
.getBase(verb
)
680 if !s
.consume("U", false) ||
!s
.consume("+", false) {
681 s
.errorString("bad unicode format ")
683 } else if verb
== 'v' {
684 base
, digits
, haveDigits
= s
.scanBasePrefix()
686 tok
:= s
.scanNumber(digits
, haveDigits
)
687 i
, err
:= strconv
.ParseUint(tok
, base
, 64)
692 x
:= (i
<< (64 - n
)) >> (64 - n
)
694 s
.errorString("unsigned integer overflow on token " + tok
)
699 // floatToken returns the floating-point number starting here, no longer than swid
700 // if the width is specified. It's not rigorous about syntax because it doesn't check that
701 // we have at least some digits, but Atof will do that.
702 func (s
*ss
) floatToken() string {
705 if s
.accept("nN") && s
.accept("aA") && s
.accept("nN") {
711 if s
.accept("iI") && s
.accept("nN") && s
.accept("fF") {
714 digits
:= decimalDigits
+ "_"
716 if s
.accept("0") && s
.accept("xX") {
717 digits
= hexadecimalDigits
+ "_"
721 for s
.accept(digits
) {
724 if s
.accept(period
) {
726 for s
.accept(digits
) {
734 for s
.accept(decimalDigits
+ "_") {
740 // complexTokens returns the real and imaginary parts of the complex number starting here.
741 // The number might be parenthesized and has the format (N+Ni) where N is a floating-point
742 // number and there are no spaces within.
743 func (s
*ss
) complexTokens() (real
, imag
string) {
744 // TODO: accept N and Ni independently?
745 parens
:= s
.accept("(")
746 real
= s
.floatToken()
748 // Must now have a sign.
750 s
.error(complexError
)
752 // Sign is now in buffer
753 imagSign
:= string(s
.buf
)
754 imag
= s
.floatToken()
756 s
.error(complexError
)
758 if parens
&& !s
.accept(")") {
759 s
.error(complexError
)
761 return real
, imagSign
+ imag
764 func hasX(s
string) bool {
765 for i
:= 0; i
< len(s
); i
++ {
766 if s
[i
] == 'x' || s
[i
] == 'X' {
773 // convertFloat converts the string to a float64value.
774 func (s
*ss
) convertFloat(str
string, n
int) float64 {
775 // strconv.ParseFloat will handle "+0x1.fp+2",
776 // but we have to implement our non-standard
777 // decimal+binary exponent mix (1.2p4) ourselves.
778 if p
:= indexRune(str
, 'p'); p
>= 0 && !hasX(str
) {
779 // Atof doesn't handle power-of-2 exponents,
780 // but they're easy to evaluate.
781 f
, err
:= strconv
.ParseFloat(str
[:p
], n
)
783 // Put full string into error.
784 if e
, ok
:= err
.(*strconv
.NumError
); ok
{
789 m
, err
:= strconv
.Atoi(str
[p
+1:])
791 // Put full string into error.
792 if e
, ok
:= err
.(*strconv
.NumError
); ok
{
797 return math
.Ldexp(f
, m
)
799 f
, err
:= strconv
.ParseFloat(str
, n
)
806 // convertComplex converts the next token to a complex128 value.
807 // The atof argument is a type-specific reader for the underlying type.
808 // If we're reading complex64, atof will parse float32s and convert them
809 // to float64's to avoid reproducing this code for each complex type.
810 func (s
*ss
) scanComplex(verb rune
, n
int) complex128
{
811 if !s
.okVerb(verb
, floatVerbs
, "complex") {
816 sreal
, simag
:= s
.complexTokens()
817 real
:= s
.convertFloat(sreal
, n
/2)
818 imag
:= s
.convertFloat(simag
, n
/2)
819 return complex(real
, imag
)
822 // convertString returns the string represented by the next input characters.
823 // The format of the input is determined by the verb.
824 func (s
*ss
) convertString(verb rune
) (str
string) {
825 if !s
.okVerb(verb
, "svqxX", "string") {
832 str
= s
.quotedString()
836 str
= string(s
.token(true, notSpace
)) // %s and %v just return the next word
841 // quotedString returns the double- or back-quoted string represented by the next input characters.
842 func (s
*ss
) quotedString() string {
847 // Back-quoted: Anything goes until EOF or back quote.
849 r
:= s
.mustReadRune()
857 // Double-quoted: Include the quotes and let strconv.Unquote do the backslash escapes.
860 r
:= s
.mustReadRune()
863 // In a legal backslash escape, no matter how long, only the character
864 // immediately after the escape can itself be a backslash or quote.
865 // Thus we only need to protect the first character after the backslash.
866 s
.buf
.writeRune(s
.mustReadRune())
871 result
, err
:= strconv
.Unquote(string(s
.buf
))
877 s
.errorString("expected quoted string")
882 // hexDigit returns the value of the hexadecimal digit.
883 func hexDigit(d rune
) (int, bool) {
886 case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
887 return digit
- '0', true
888 case 'a', 'b', 'c', 'd', 'e', 'f':
889 return 10 + digit
- 'a', true
890 case 'A', 'B', 'C', 'D', 'E', 'F':
891 return 10 + digit
- 'A', true
896 // hexByte returns the next hex-encoded (two-character) byte from the input.
897 // It returns ok==false if the next bytes in the input do not encode a hex byte.
898 // If the first byte is hex and the second is not, processing stops.
899 func (s
*ss
) hexByte() (b
byte, ok
bool) {
904 value1
, ok
:= hexDigit(rune1
)
909 value2
, ok
:= hexDigit(s
.mustReadRune())
911 s
.errorString("illegal hex digit")
914 return byte(value1
<<4 | value2
), true
917 // hexString returns the space-delimited hexpair-encoded string.
918 func (s
*ss
) hexString() string {
928 s
.errorString("no hex data for %x string")
935 floatVerbs
= "beEfFgGv"
939 intBits
= 32 << (^uint(0) >> 63)
940 uintptrBits
= 32 << (^uintptr(0) >> 63)
943 // scanPercent scans a literal percent character.
944 func (s
*ss
) scanPercent() {
948 s
.errorString("missing literal %")
952 // scanOne scans a single value, deriving the scanner from the type of the argument.
953 func (s
*ss
) scanOne(verb rune
, arg any
) {
956 // If the parameter has its own Scan method, use that.
957 if v
, ok
:= arg
.(Scanner
); ok
{
958 err
= v
.Scan(s
, verb
)
961 err
= io
.ErrUnexpectedEOF
968 switch v
:= arg
.(type) {
970 *v
= s
.scanBool(verb
)
972 *v
= complex64(s
.scanComplex(verb
, 64))
974 *v
= s
.scanComplex(verb
, 128)
976 *v
= int(s
.scanInt(verb
, intBits
))
978 *v
= int8(s
.scanInt(verb
, 8))
980 *v
= int16(s
.scanInt(verb
, 16))
982 *v
= int32(s
.scanInt(verb
, 32))
984 *v
= s
.scanInt(verb
, 64)
986 *v
= uint(s
.scanUint(verb
, intBits
))
988 *v
= uint8(s
.scanUint(verb
, 8))
990 *v
= uint16(s
.scanUint(verb
, 16))
992 *v
= uint32(s
.scanUint(verb
, 32))
994 *v
= s
.scanUint(verb
, 64)
996 *v
= uintptr(s
.scanUint(verb
, uintptrBits
))
997 // Floats are tricky because you want to scan in the precision of the result, not
998 // scan in high precision and convert, in order to preserve the correct error condition.
1000 if s
.okVerb(verb
, floatVerbs
, "float32") {
1003 *v
= float32(s
.convertFloat(s
.floatToken(), 32))
1006 if s
.okVerb(verb
, floatVerbs
, "float64") {
1009 *v
= s
.convertFloat(s
.floatToken(), 64)
1012 *v
= s
.convertString(verb
)
1014 // We scan to string and convert so we get a copy of the data.
1015 // If we scanned to bytes, the slice would point at the buffer.
1016 *v
= []byte(s
.convertString(verb
))
1018 val
:= reflect
.ValueOf(v
)
1020 if ptr
.Kind() != reflect
.Pointer
{
1021 s
.errorString("type not a pointer: " + val
.Type().String())
1024 switch v
:= ptr
.Elem(); v
.Kind() {
1026 v
.SetBool(s
.scanBool(verb
))
1027 case reflect
.Int
, reflect
.Int8
, reflect
.Int16
, reflect
.Int32
, reflect
.Int64
:
1028 v
.SetInt(s
.scanInt(verb
, v
.Type().Bits()))
1029 case reflect
.Uint
, reflect
.Uint8
, reflect
.Uint16
, reflect
.Uint32
, reflect
.Uint64
, reflect
.Uintptr
:
1030 v
.SetUint(s
.scanUint(verb
, v
.Type().Bits()))
1031 case reflect
.String
:
1032 v
.SetString(s
.convertString(verb
))
1034 // For now, can only handle (renamed) []byte.
1036 if typ
.Elem().Kind() != reflect
.Uint8
{
1037 s
.errorString("can't scan type: " + val
.Type().String())
1039 str
:= s
.convertString(verb
)
1040 v
.Set(reflect
.MakeSlice(typ
, len(str
), len(str
)))
1041 for i
:= 0; i
< len(str
); i
++ {
1042 v
.Index(i
).SetUint(uint64(str
[i
]))
1044 case reflect
.Float32
, reflect
.Float64
:
1047 v
.SetFloat(s
.convertFloat(s
.floatToken(), v
.Type().Bits()))
1048 case reflect
.Complex64
, reflect
.Complex128
:
1049 v
.SetComplex(s
.scanComplex(verb
, v
.Type().Bits()))
1051 s
.errorString("can't scan type: " + val
.Type().String())
1056 // errorHandler turns local panics into error returns.
1057 func errorHandler(errp
*error
) {
1058 if e
:= recover(); e
!= nil {
1059 if se
, ok
:= e
.(scanError
); ok
{ // catch local error
1061 } else if eof
, ok
:= e
.(error
); ok
&& eof
== io
.EOF
{ // out of input
1069 // doScan does the real work for scanning without a format string.
1070 func (s
*ss
) doScan(a
[]any
) (numProcessed
int, err error
) {
1071 defer errorHandler(&err
)
1072 for _
, arg
:= range a
{
1076 // Check for newline (or EOF) if required (Scanln etc.).
1080 if r
== '\n' || r
== eof
{
1084 s
.errorString("expected newline")
1092 // advance determines whether the next characters in the input match
1093 // those of the format. It returns the number of bytes (sic) consumed
1094 // in the format. All runs of space characters in either input or
1095 // format behave as a single space. Newlines are special, though:
1096 // newlines in the format must match those in the input and vice versa.
1097 // This routine also handles the %% case. If the return value is zero,
1098 // either format starts with a % (with no following %) or the input
1099 // is empty. If it is negative, the input did not match the string.
1100 func (s
*ss
) advance(format
string) (i
int) {
1101 for i
< len(format
) {
1102 fmtc
, w
:= utf8
.DecodeRuneInString(format
[i
:])
1104 // Space processing.
1105 // In the rest of this comment "space" means spaces other than newline.
1106 // Newline in the format matches input of zero or more spaces and then newline or end-of-input.
1107 // Spaces in the format before the newline are collapsed into the newline.
1108 // Spaces in the format after the newline match zero or more spaces after the corresponding input newline.
1109 // Other spaces in the format match input of one or more spaces or end-of-input.
1112 trailingSpace
:= false
1113 for isSpace(fmtc
) && i
< len(format
) {
1116 trailingSpace
= false
1118 trailingSpace
= true
1121 fmtc
, w
= utf8
.DecodeRuneInString(format
[i
:])
1123 for j
:= 0; j
< newlines
; j
++ {
1124 inputc
:= s
.getRune()
1125 for isSpace(inputc
) && inputc
!= '\n' {
1126 inputc
= s
.getRune()
1128 if inputc
!= '\n' && inputc
!= eof
{
1129 s
.errorString("newline in format does not match input")
1133 inputc
:= s
.getRune()
1135 // If the trailing space stood alone (did not follow a newline),
1136 // it must find at least one space to consume.
1137 if !isSpace(inputc
) && inputc
!= eof
{
1138 s
.errorString("expected space in input to match format")
1141 s
.errorString("newline in input does not match format")
1144 for isSpace(inputc
) && inputc
!= '\n' {
1145 inputc
= s
.getRune()
1156 // % at end of string is an error.
1157 if i
+w
== len(format
) {
1158 s
.errorString("missing verb: % at end of format string")
1160 // %% acts like a real percent
1161 nextc
, _
:= utf8
.DecodeRuneInString(format
[i
+w
:]) // will not match % if string is empty
1165 i
+= w
// skip the first %
1169 inputc
:= s
.mustReadRune()
1179 // doScanf does the real work when scanning with a format string.
1180 // At the moment, it handles only pointers to basic types.
1181 func (s
*ss
) doScanf(format
string, a
[]any
) (numProcessed
int, err error
) {
1182 defer errorHandler(&err
)
1183 end
:= len(format
) - 1
1184 // We process one item per non-trivial format
1185 for i
:= 0; i
<= end
; {
1186 w
:= s
.advance(format
[i
:])
1191 // Either we failed to advance, we have a percent character, or we ran out of input.
1192 if format
[i
] != '%' {
1193 // Can't advance format. Why not?
1195 s
.errorString("input does not match format")
1197 // Otherwise at EOF; "too many operands" error handled below
1200 i
++ // % is one byte
1202 // do we have 20 (width)?
1204 s
.maxWid
, widPresent
, i
= parsenum(format
, i
, end
)
1209 c
, w
:= utf8
.DecodeRuneInString(format
[i
:])
1217 continue // Do not consume an argument.
1219 s
.argLimit
= s
.limit
1220 if f
:= s
.count
+ s
.maxWid
; f
< s
.argLimit
{
1224 if numProcessed
>= len(a
) { // out of operands
1225 s
.errorString("too few operands for format '%" + format
[i
-w
:] + "'")
1228 arg
:= a
[numProcessed
]
1232 s
.argLimit
= s
.limit
1234 if numProcessed
< len(a
) {
1235 s
.errorString("too many operands")