github.com/mdempsky/go@v0.0.0-20151201204031-5dd372bd1e70/src/bufio/scan.go (about) 1 // Copyright 2013 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. 4 5 package bufio 6 7 import ( 8 "bytes" 9 "errors" 10 "io" 11 "unicode/utf8" 12 ) 13 14 // Scanner provides a convenient interface for reading data such as 15 // a file of newline-delimited lines of text. Successive calls to 16 // the Scan method will step through the 'tokens' of a file, skipping 17 // the bytes between the tokens. The specification of a token is 18 // defined by a split function of type SplitFunc; the default split 19 // function breaks the input into lines with line termination stripped. Split 20 // functions are defined in this package for scanning a file into 21 // lines, bytes, UTF-8-encoded runes, and space-delimited words. The 22 // client may instead provide a custom split function. 23 // 24 // Scanning stops unrecoverably at EOF, the first I/O error, or a token too 25 // large to fit in the buffer. When a scan stops, the reader may have 26 // advanced arbitrarily far past the last token. Programs that need more 27 // control over error handling or large tokens, or must run sequential scans 28 // on a reader, should use bufio.Reader instead. 29 // 30 type Scanner struct { 31 r io.Reader // The reader provided by the client. 32 split SplitFunc // The function to split the tokens. 33 maxTokenSize int // Maximum size of a token; modified by tests. 34 token []byte // Last token returned by split. 35 buf []byte // Buffer used as argument to split. 36 start int // First non-processed byte in buf. 37 end int // End of data in buf. 38 err error // Sticky error. 39 empties int // Count of successive empty tokens. 40 scanCalled bool // Scan has been called; buffer is in use. 41 done bool // Scan has finished. 42 } 43 44 // SplitFunc is the signature of the split function used to tokenize the 45 // input. The arguments are an initial substring of the remaining unprocessed 46 // data and a flag, atEOF, that reports whether the Reader has no more data 47 // to give. The return values are the number of bytes to advance the input 48 // and the next token to return to the user, plus an error, if any. If the 49 // data does not yet hold a complete token, for instance if it has no newline 50 // while scanning lines, SplitFunc can return (0, nil, nil) to signal the 51 // Scanner to read more data into the slice and try again with a longer slice 52 // starting at the same point in the input. 53 // 54 // If the returned error is non-nil, scanning stops and the error 55 // is returned to the client. 56 // 57 // The function is never called with an empty data slice unless atEOF 58 // is true. If atEOF is true, however, data may be non-empty and, 59 // as always, holds unprocessed text. 60 type SplitFunc func(data []byte, atEOF bool) (advance int, token []byte, err error) 61 62 // Errors returned by Scanner. 63 var ( 64 ErrTooLong = errors.New("bufio.Scanner: token too long") 65 ErrNegativeAdvance = errors.New("bufio.Scanner: SplitFunc returns negative advance count") 66 ErrAdvanceTooFar = errors.New("bufio.Scanner: SplitFunc returns advance count beyond input") 67 ) 68 69 const ( 70 // MaxScanTokenSize is the maximum size used to buffer a token 71 // unless the user provides an explicit buffer with Scan.Buffer. 72 // The actual maximum token size may be smaller as the buffer 73 // may need to include, for instance, a newline. 74 MaxScanTokenSize = 64 * 1024 75 76 startBufSize = 4096 // Size of initial allocation for buffer. 77 ) 78 79 // NewScanner returns a new Scanner to read from r. 80 // The split function defaults to ScanLines. 81 func NewScanner(r io.Reader) *Scanner { 82 return &Scanner{ 83 r: r, 84 split: ScanLines, 85 maxTokenSize: MaxScanTokenSize, 86 } 87 } 88 89 // Err returns the first non-EOF error that was encountered by the Scanner. 90 func (s *Scanner) Err() error { 91 if s.err == io.EOF { 92 return nil 93 } 94 return s.err 95 } 96 97 // Bytes returns the most recent token generated by a call to Scan. 98 // The underlying array may point to data that will be overwritten 99 // by a subsequent call to Scan. It does no allocation. 100 func (s *Scanner) Bytes() []byte { 101 return s.token 102 } 103 104 // Text returns the most recent token generated by a call to Scan 105 // as a newly allocated string holding its bytes. 106 func (s *Scanner) Text() string { 107 return string(s.token) 108 } 109 110 // ErrFinalToken is a special sentinel error value. It is intended to be 111 // returned by a Split function to indicate that the token being delivered 112 // with the error is the last token and scanning should stop after this one. 113 // After ErrFinalToken is received by Scan, scanning stops with no error. 114 // The value is useful to stop processing early or when it is necessary to 115 // deliver a final empty token. One could achieve the same behavior 116 // with a custom error value but providing one here is tidier. 117 // See the emptyFinalToken example for a use of this value. 118 var ErrFinalToken = errors.New("final token") 119 120 // Scan advances the Scanner to the next token, which will then be 121 // available through the Bytes or Text method. It returns false when the 122 // scan stops, either by reaching the end of the input or an error. 123 // After Scan returns false, the Err method will return any error that 124 // occurred during scanning, except that if it was io.EOF, Err 125 // will return nil. 126 // Scan panics if the split function returns 100 empty tokens without 127 // advancing the input. This is a common error mode for scanners. 128 func (s *Scanner) Scan() bool { 129 if s.done { 130 return false 131 } 132 s.scanCalled = true 133 // Loop until we have a token. 134 for { 135 // See if we can get a token with what we already have. 136 // If we've run out of data but have an error, give the split function 137 // a chance to recover any remaining, possibly empty token. 138 if s.end > s.start || s.err != nil { 139 advance, token, err := s.split(s.buf[s.start:s.end], s.err != nil) 140 if err != nil { 141 if err == ErrFinalToken { 142 s.token = token 143 s.done = true 144 return true 145 } 146 s.setErr(err) 147 return false 148 } 149 if !s.advance(advance) { 150 return false 151 } 152 s.token = token 153 if token != nil { 154 if s.err == nil || advance > 0 { 155 s.empties = 0 156 } else { 157 // Returning tokens not advancing input at EOF. 158 s.empties++ 159 if s.empties > 100 { 160 panic("bufio.Scan: 100 empty tokens without progressing") 161 } 162 } 163 return true 164 } 165 } 166 // We cannot generate a token with what we are holding. 167 // If we've already hit EOF or an I/O error, we are done. 168 if s.err != nil { 169 // Shut it down. 170 s.start = 0 171 s.end = 0 172 return false 173 } 174 // Must read more data. 175 // First, shift data to beginning of buffer if there's lots of empty space 176 // or space is needed. 177 if s.start > 0 && (s.end == len(s.buf) || s.start > len(s.buf)/2) { 178 copy(s.buf, s.buf[s.start:s.end]) 179 s.end -= s.start 180 s.start = 0 181 } 182 // Is the buffer full? If so, resize. 183 if s.end == len(s.buf) { 184 // Guarantee no overflow in the multiplication below. 185 const maxInt = int(^uint(0) >> 1) 186 if len(s.buf) >= s.maxTokenSize || len(s.buf) > maxInt/2 { 187 s.setErr(ErrTooLong) 188 return false 189 } 190 newSize := len(s.buf) * 2 191 if newSize == 0 { 192 newSize = startBufSize 193 } 194 if newSize > s.maxTokenSize { 195 newSize = s.maxTokenSize 196 } 197 newBuf := make([]byte, newSize) 198 copy(newBuf, s.buf[s.start:s.end]) 199 s.buf = newBuf 200 s.end -= s.start 201 s.start = 0 202 continue 203 } 204 // Finally we can read some input. Make sure we don't get stuck with 205 // a misbehaving Reader. Officially we don't need to do this, but let's 206 // be extra careful: Scanner is for safe, simple jobs. 207 for loop := 0; ; { 208 n, err := s.r.Read(s.buf[s.end:len(s.buf)]) 209 s.end += n 210 if err != nil { 211 s.setErr(err) 212 break 213 } 214 if n > 0 { 215 s.empties = 0 216 break 217 } 218 loop++ 219 if loop > maxConsecutiveEmptyReads { 220 s.setErr(io.ErrNoProgress) 221 break 222 } 223 } 224 } 225 } 226 227 // advance consumes n bytes of the buffer. It reports whether the advance was legal. 228 func (s *Scanner) advance(n int) bool { 229 if n < 0 { 230 s.setErr(ErrNegativeAdvance) 231 return false 232 } 233 if n > s.end-s.start { 234 s.setErr(ErrAdvanceTooFar) 235 return false 236 } 237 s.start += n 238 return true 239 } 240 241 // setErr records the first error encountered. 242 func (s *Scanner) setErr(err error) { 243 if s.err == nil || s.err == io.EOF { 244 s.err = err 245 } 246 } 247 248 // Buffer sets the initial buffer to use when scanning and the maximum 249 // size of buffer that may be allocated during scanning. The maximum 250 // token size is the larger of max and cap(buf). If max <= cap(buf), 251 // Scan will use this buffer only and do no allocation. 252 // 253 // By default, Scan uses an internal buffer and sets the 254 // maximum token size to MaxScanTokenSize. 255 // 256 // Buffer panics if it is called after scanning has started. 257 func (s *Scanner) Buffer(buf []byte, max int) { 258 if s.scanCalled { 259 panic("Buffer called after Scan") 260 } 261 s.buf = buf[0:cap(buf)] 262 s.maxTokenSize = max 263 } 264 265 // Split sets the split function for the Scanner. 266 // The default split function is ScanLines. 267 // 268 // Split panics if it is called after scanning has started. 269 func (s *Scanner) Split(split SplitFunc) { 270 if s.scanCalled { 271 panic("Split called after Scan") 272 } 273 s.split = split 274 } 275 276 // Split functions 277 278 // ScanBytes is a split function for a Scanner that returns each byte as a token. 279 func ScanBytes(data []byte, atEOF bool) (advance int, token []byte, err error) { 280 if atEOF && len(data) == 0 { 281 return 0, nil, nil 282 } 283 return 1, data[0:1], nil 284 } 285 286 var errorRune = []byte(string(utf8.RuneError)) 287 288 // ScanRunes is a split function for a Scanner that returns each 289 // UTF-8-encoded rune as a token. The sequence of runes returned is 290 // equivalent to that from a range loop over the input as a string, which 291 // means that erroneous UTF-8 encodings translate to U+FFFD = "\xef\xbf\xbd". 292 // Because of the Scan interface, this makes it impossible for the client to 293 // distinguish correctly encoded replacement runes from encoding errors. 294 func ScanRunes(data []byte, atEOF bool) (advance int, token []byte, err error) { 295 if atEOF && len(data) == 0 { 296 return 0, nil, nil 297 } 298 299 // Fast path 1: ASCII. 300 if data[0] < utf8.RuneSelf { 301 return 1, data[0:1], nil 302 } 303 304 // Fast path 2: Correct UTF-8 decode without error. 305 _, width := utf8.DecodeRune(data) 306 if width > 1 { 307 // It's a valid encoding. Width cannot be one for a correctly encoded 308 // non-ASCII rune. 309 return width, data[0:width], nil 310 } 311 312 // We know it's an error: we have width==1 and implicitly r==utf8.RuneError. 313 // Is the error because there wasn't a full rune to be decoded? 314 // FullRune distinguishes correctly between erroneous and incomplete encodings. 315 if !atEOF && !utf8.FullRune(data) { 316 // Incomplete; get more bytes. 317 return 0, nil, nil 318 } 319 320 // We have a real UTF-8 encoding error. Return a properly encoded error rune 321 // but advance only one byte. This matches the behavior of a range loop over 322 // an incorrectly encoded string. 323 return 1, errorRune, nil 324 } 325 326 // dropCR drops a terminal \r from the data. 327 func dropCR(data []byte) []byte { 328 if len(data) > 0 && data[len(data)-1] == '\r' { 329 return data[0 : len(data)-1] 330 } 331 return data 332 } 333 334 // ScanLines is a split function for a Scanner that returns each line of 335 // text, stripped of any trailing end-of-line marker. The returned line may 336 // be empty. The end-of-line marker is one optional carriage return followed 337 // by one mandatory newline. In regular expression notation, it is `\r?\n`. 338 // The last non-empty line of input will be returned even if it has no 339 // newline. 340 func ScanLines(data []byte, atEOF bool) (advance int, token []byte, err error) { 341 if atEOF && len(data) == 0 { 342 return 0, nil, nil 343 } 344 if i := bytes.IndexByte(data, '\n'); i >= 0 { 345 // We have a full newline-terminated line. 346 return i + 1, dropCR(data[0:i]), nil 347 } 348 // If we're at EOF, we have a final, non-terminated line. Return it. 349 if atEOF { 350 return len(data), dropCR(data), nil 351 } 352 // Request more data. 353 return 0, nil, nil 354 } 355 356 // isSpace reports whether the character is a Unicode white space character. 357 // We avoid dependency on the unicode package, but check validity of the implementation 358 // in the tests. 359 func isSpace(r rune) bool { 360 if r <= '\u00FF' { 361 // Obvious ASCII ones: \t through \r plus space. Plus two Latin-1 oddballs. 362 switch r { 363 case ' ', '\t', '\n', '\v', '\f', '\r': 364 return true 365 case '\u0085', '\u00A0': 366 return true 367 } 368 return false 369 } 370 // High-valued ones. 371 if '\u2000' <= r && r <= '\u200a' { 372 return true 373 } 374 switch r { 375 case '\u1680', '\u2028', '\u2029', '\u202f', '\u205f', '\u3000': 376 return true 377 } 378 return false 379 } 380 381 // ScanWords is a split function for a Scanner that returns each 382 // space-separated word of text, with surrounding spaces deleted. It will 383 // never return an empty string. The definition of space is set by 384 // unicode.IsSpace. 385 func ScanWords(data []byte, atEOF bool) (advance int, token []byte, err error) { 386 // Skip leading spaces. 387 start := 0 388 for width := 0; start < len(data); start += width { 389 var r rune 390 r, width = utf8.DecodeRune(data[start:]) 391 if !isSpace(r) { 392 break 393 } 394 } 395 // Scan until space, marking end of word. 396 for width, i := 0, start; i < len(data); i += width { 397 var r rune 398 r, width = utf8.DecodeRune(data[i:]) 399 if isSpace(r) { 400 return i + width, data[start:i], nil 401 } 402 } 403 // If we're at EOF, we have a final, non-empty, non-terminated word. Return it. 404 if atEOF && len(data) > start { 405 return len(data), data[start:], nil 406 } 407 // Request more data. 408 return start, nil, nil 409 }