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 } 41 42 // SplitFunc is the signature of the split function used to tokenize the 43 // input. The arguments are an initial substring of the remaining unprocessed 44 // data and a flag, atEOF, that reports whether the Reader has no more data 45 // to give. The return values are the number of bytes to advance the input 46 // and the next token to return to the user, plus an error, if any. If the 47 // data does not yet hold a complete token, for instance if it has no newline 48 // while scanning lines, SplitFunc can return (0, nil, nil) to signal the 49 // Scanner to read more data into the slice and try again with a longer slice 50 // starting at the same point in the input. 51 // 52 // If the returned error is non-nil, scanning stops and the error 53 // is returned to the client. 54 // 55 // The function is never called with an empty data slice unless atEOF 56 // is true. If atEOF is true, however, data may be non-empty and, 57 // as always, holds unprocessed text. 58 type SplitFunc func(data []byte, atEOF bool) (advance int, token []byte, err error) 59 60 // Errors returned by Scanner. 61 var ( 62 ErrTooLong = errors.New("bufio.Scanner: token too long") 63 ErrNegativeAdvance = errors.New("bufio.Scanner: SplitFunc returns negative advance count") 64 ErrAdvanceTooFar = errors.New("bufio.Scanner: SplitFunc returns advance count beyond input") 65 ) 66 67 const ( 68 // MaxScanTokenSize is the maximum size used to buffer a token. 69 // The actual maximum token size may be smaller as the buffer 70 // may need to include, for instance, a newline. 71 MaxScanTokenSize = 64 * 1024 72 ) 73 74 // NewScanner returns a new Scanner to read from r. 75 // The split function defaults to ScanLines. 76 func NewScanner(r io.Reader) *Scanner { 77 return &Scanner{ 78 r: r, 79 split: ScanLines, 80 maxTokenSize: MaxScanTokenSize, 81 buf: make([]byte, 4096), // Plausible starting size; needn't be large. 82 } 83 } 84 85 // Err returns the first non-EOF error that was encountered by the Scanner. 86 func (s *Scanner) Err() error { 87 if s.err == io.EOF { 88 return nil 89 } 90 return s.err 91 } 92 93 // Bytes returns the most recent token generated by a call to Scan. 94 // The underlying array may point to data that will be overwritten 95 // by a subsequent call to Scan. It does no allocation. 96 func (s *Scanner) Bytes() []byte { 97 return s.token 98 } 99 100 // Text returns the most recent token generated by a call to Scan 101 // as a newly allocated string holding its bytes. 102 func (s *Scanner) Text() string { 103 return string(s.token) 104 } 105 106 // Scan advances the Scanner to the next token, which will then be 107 // available through the Bytes or Text method. It returns false when the 108 // scan stops, either by reaching the end of the input or an error. 109 // After Scan returns false, the Err method will return any error that 110 // occurred during scanning, except that if it was io.EOF, Err 111 // will return nil. 112 // Scan panics if the split function returns 100 empty tokens without 113 // advancing the input. This is a common error mode for scanners. 114 func (s *Scanner) Scan() bool { 115 // Loop until we have a token. 116 for { 117 // See if we can get a token with what we already have. 118 // If we've run out of data but have an error, give the split function 119 // a chance to recover any remaining, possibly empty token. 120 if s.end > s.start || s.err != nil { 121 advance, token, err := s.split(s.buf[s.start:s.end], s.err != nil) 122 if err != nil { 123 s.setErr(err) 124 return false 125 } 126 if !s.advance(advance) { 127 return false 128 } 129 s.token = token 130 if token != nil { 131 if s.err == nil || advance > 0 { 132 s.empties = 0 133 } else { 134 // Returning tokens not advancing input at EOF. 135 s.empties++ 136 if s.empties > 100 { 137 panic("bufio.Scan: 100 empty tokens without progressing") 138 } 139 } 140 return true 141 } 142 } 143 // We cannot generate a token with what we are holding. 144 // If we've already hit EOF or an I/O error, we are done. 145 if s.err != nil { 146 // Shut it down. 147 s.start = 0 148 s.end = 0 149 return false 150 } 151 // Must read more data. 152 // First, shift data to beginning of buffer if there's lots of empty space 153 // or space is needed. 154 if s.start > 0 && (s.end == len(s.buf) || s.start > len(s.buf)/2) { 155 copy(s.buf, s.buf[s.start:s.end]) 156 s.end -= s.start 157 s.start = 0 158 } 159 // Is the buffer full? If so, resize. 160 if s.end == len(s.buf) { 161 if len(s.buf) >= s.maxTokenSize { 162 s.setErr(ErrTooLong) 163 return false 164 } 165 newSize := len(s.buf) * 2 166 if newSize > s.maxTokenSize { 167 newSize = s.maxTokenSize 168 } 169 newBuf := make([]byte, newSize) 170 copy(newBuf, s.buf[s.start:s.end]) 171 s.buf = newBuf 172 s.end -= s.start 173 s.start = 0 174 continue 175 } 176 // Finally we can read some input. Make sure we don't get stuck with 177 // a misbehaving Reader. Officially we don't need to do this, but let's 178 // be extra careful: Scanner is for safe, simple jobs. 179 for loop := 0; ; { 180 n, err := s.r.Read(s.buf[s.end:len(s.buf)]) 181 s.end += n 182 if err != nil { 183 s.setErr(err) 184 break 185 } 186 if n > 0 { 187 s.empties = 0 188 break 189 } 190 loop++ 191 if loop > maxConsecutiveEmptyReads { 192 s.setErr(io.ErrNoProgress) 193 break 194 } 195 } 196 } 197 } 198 199 // advance consumes n bytes of the buffer. It reports whether the advance was legal. 200 func (s *Scanner) advance(n int) bool { 201 if n < 0 { 202 s.setErr(ErrNegativeAdvance) 203 return false 204 } 205 if n > s.end-s.start { 206 s.setErr(ErrAdvanceTooFar) 207 return false 208 } 209 s.start += n 210 return true 211 } 212 213 // setErr records the first error encountered. 214 func (s *Scanner) setErr(err error) { 215 if s.err == nil || s.err == io.EOF { 216 s.err = err 217 } 218 } 219 220 // Split sets the split function for the Scanner. If called, it must be 221 // called before Scan. The default split function is ScanLines. 222 func (s *Scanner) Split(split SplitFunc) { 223 s.split = split 224 } 225 226 // Split functions 227 228 // ScanBytes is a split function for a Scanner that returns each byte as a token. 229 func ScanBytes(data []byte, atEOF bool) (advance int, token []byte, err error) { 230 if atEOF && len(data) == 0 { 231 return 0, nil, nil 232 } 233 return 1, data[0:1], nil 234 } 235 236 var errorRune = []byte(string(utf8.RuneError)) 237 238 // ScanRunes is a split function for a Scanner that returns each 239 // UTF-8-encoded rune as a token. The sequence of runes returned is 240 // equivalent to that from a range loop over the input as a string, which 241 // means that erroneous UTF-8 encodings translate to U+FFFD = "\xef\xbf\xbd". 242 // Because of the Scan interface, this makes it impossible for the client to 243 // distinguish correctly encoded replacement runes from encoding errors. 244 func ScanRunes(data []byte, atEOF bool) (advance int, token []byte, err error) { 245 if atEOF && len(data) == 0 { 246 return 0, nil, nil 247 } 248 249 // Fast path 1: ASCII. 250 if data[0] < utf8.RuneSelf { 251 return 1, data[0:1], nil 252 } 253 254 // Fast path 2: Correct UTF-8 decode without error. 255 _, width := utf8.DecodeRune(data) 256 if width > 1 { 257 // It's a valid encoding. Width cannot be one for a correctly encoded 258 // non-ASCII rune. 259 return width, data[0:width], nil 260 } 261 262 // We know it's an error: we have width==1 and implicitly r==utf8.RuneError. 263 // Is the error because there wasn't a full rune to be decoded? 264 // FullRune distinguishes correctly between erroneous and incomplete encodings. 265 if !atEOF && !utf8.FullRune(data) { 266 // Incomplete; get more bytes. 267 return 0, nil, nil 268 } 269 270 // We have a real UTF-8 encoding error. Return a properly encoded error rune 271 // but advance only one byte. This matches the behavior of a range loop over 272 // an incorrectly encoded string. 273 return 1, errorRune, nil 274 } 275 276 // dropCR drops a terminal \r from the data. 277 func dropCR(data []byte) []byte { 278 if len(data) > 0 && data[len(data)-1] == '\r' { 279 return data[0 : len(data)-1] 280 } 281 return data 282 } 283 284 // ScanLines is a split function for a Scanner that returns each line of 285 // text, stripped of any trailing end-of-line marker. The returned line may 286 // be empty. The end-of-line marker is one optional carriage return followed 287 // by one mandatory newline. In regular expression notation, it is `\r?\n`. 288 // The last non-empty line of input will be returned even if it has no 289 // newline. 290 func ScanLines(data []byte, atEOF bool) (advance int, token []byte, err error) { 291 if atEOF && len(data) == 0 { 292 return 0, nil, nil 293 } 294 if i := bytes.IndexByte(data, '\n'); i >= 0 { 295 // We have a full newline-terminated line. 296 return i + 1, dropCR(data[0:i]), nil 297 } 298 // If we're at EOF, we have a final, non-terminated line. Return it. 299 if atEOF { 300 return len(data), dropCR(data), nil 301 } 302 // Request more data. 303 return 0, nil, nil 304 } 305 306 // isSpace reports whether the character is a Unicode white space character. 307 // We avoid dependency on the unicode package, but check validity of the implementation 308 // in the tests. 309 func isSpace(r rune) bool { 310 if r <= '\u00FF' { 311 // Obvious ASCII ones: \t through \r plus space. Plus two Latin-1 oddballs. 312 switch r { 313 case ' ', '\t', '\n', '\v', '\f', '\r': 314 return true 315 case '\u0085', '\u00A0': 316 return true 317 } 318 return false 319 } 320 // High-valued ones. 321 if '\u2000' <= r && r <= '\u200a' { 322 return true 323 } 324 switch r { 325 case '\u1680', '\u2028', '\u2029', '\u202f', '\u205f', '\u3000': 326 return true 327 } 328 return false 329 } 330 331 // ScanWords is a split function for a Scanner that returns each 332 // space-separated word of text, with surrounding spaces deleted. It will 333 // never return an empty string. The definition of space is set by 334 // unicode.IsSpace. 335 func ScanWords(data []byte, atEOF bool) (advance int, token []byte, err error) { 336 // Skip leading spaces. 337 start := 0 338 for width := 0; start < len(data); start += width { 339 var r rune 340 r, width = utf8.DecodeRune(data[start:]) 341 if !isSpace(r) { 342 break 343 } 344 } 345 // Scan until space, marking end of word. 346 for width, i := 0, start; i < len(data); i += width { 347 var r rune 348 r, width = utf8.DecodeRune(data[i:]) 349 if isSpace(r) { 350 return i + width, data[start:i], nil 351 } 352 } 353 // If we're at EOF, we have a final, non-empty, non-terminated word. Return it. 354 if atEOF && len(data) > start { 355 return len(data), data[start:], nil 356 } 357 // Request more data. 358 return start, nil, nil 359 } 360