Source file src/bufio/example_test.go

     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_test
     6  
     7  import (
     8  	"bufio"
     9  	"fmt"
    10  	"os"
    11  	"strconv"
    12  	"strings"
    13  )
    14  
    15  func ExampleWriter() {
    16  	w := bufio.NewWriter(os.Stdout)
    17  	fmt.Fprint(w, "Hello, ")
    18  	fmt.Fprint(w, "world!")
    19  	w.Flush() // Don't forget to flush!
    20  	// Output: Hello, world!
    21  }
    22  
    23  func ExampleWriter_AvailableBuffer() {
    24  	w := bufio.NewWriter(os.Stdout)
    25  	for _, i := range []int64{1, 2, 3, 4} {
    26  		b := w.AvailableBuffer()
    27  		b = strconv.AppendInt(b, i, 10)
    28  		b = append(b, ' ')
    29  		w.Write(b)
    30  	}
    31  	w.Flush()
    32  	// Output: 1 2 3 4
    33  }
    34  
    35  // The simplest use of a Scanner, to read standard input as a set of lines.
    36  func ExampleScanner_lines() {
    37  	scanner := bufio.NewScanner(os.Stdin)
    38  	for scanner.Scan() {
    39  		fmt.Println(scanner.Text()) // Println will add back the final '\n'
    40  	}
    41  	if err := scanner.Err(); err != nil {
    42  		fmt.Fprintln(os.Stderr, "reading standard input:", err)
    43  	}
    44  }
    45  
    46  // Return the most recent call to Scan as a []byte.
    47  func ExampleScanner_Bytes() {
    48  	scanner := bufio.NewScanner(strings.NewReader("gopher"))
    49  	for scanner.Scan() {
    50  		fmt.Println(len(scanner.Bytes()) == 6)
    51  	}
    52  	if err := scanner.Err(); err != nil {
    53  		fmt.Fprintln(os.Stderr, "shouldn't see an error scanning a string")
    54  	}
    55  	// Output:
    56  	// true
    57  }
    58  
    59  // Use a Scanner to implement a simple word-count utility by scanning the
    60  // input as a sequence of space-delimited tokens.
    61  func ExampleScanner_words() {
    62  	// An artificial input source.
    63  	const input = "Now is the winter of our discontent,\nMade glorious summer by this sun of York.\n"
    64  	scanner := bufio.NewScanner(strings.NewReader(input))
    65  	// Set the split function for the scanning operation.
    66  	scanner.Split(bufio.ScanWords)
    67  	// Count the words.
    68  	count := 0
    69  	for scanner.Scan() {
    70  		count++
    71  	}
    72  	if err := scanner.Err(); err != nil {
    73  		fmt.Fprintln(os.Stderr, "reading input:", err)
    74  	}
    75  	fmt.Printf("%d\n", count)
    76  	// Output: 15
    77  }
    78  
    79  // Use a Scanner with a custom split function (built by wrapping ScanWords) to validate
    80  // 32-bit decimal input.
    81  func ExampleScanner_custom() {
    82  	// An artificial input source.
    83  	const input = "1234 5678 1234567901234567890"
    84  	scanner := bufio.NewScanner(strings.NewReader(input))
    85  	// Create a custom split function by wrapping the existing ScanWords function.
    86  	split := func(data []byte, atEOF bool) (advance int, token []byte, err error) {
    87  		advance, token, err = bufio.ScanWords(data, atEOF)
    88  		if err == nil && token != nil {
    89  			_, err = strconv.ParseInt(string(token), 10, 32)
    90  		}
    91  		return
    92  	}
    93  	// Set the split function for the scanning operation.
    94  	scanner.Split(split)
    95  	// Validate the input
    96  	for scanner.Scan() {
    97  		fmt.Printf("%s\n", scanner.Text())
    98  	}
    99  
   100  	if err := scanner.Err(); err != nil {
   101  		fmt.Printf("Invalid input: %s", err)
   102  	}
   103  	// Output:
   104  	// 1234
   105  	// 5678
   106  	// Invalid input: strconv.ParseInt: parsing "1234567901234567890": value out of range
   107  }
   108  
   109  // Use a Scanner with a custom split function to parse a comma-separated
   110  // list with an empty final value.
   111  func ExampleScanner_emptyFinalToken() {
   112  	// Comma-separated list; last entry is empty.
   113  	const input = "1,2,3,4,"
   114  	scanner := bufio.NewScanner(strings.NewReader(input))
   115  	// Define a split function that separates on commas.
   116  	onComma := func(data []byte, atEOF bool) (advance int, token []byte, err error) {
   117  		for i := 0; i < len(data); i++ {
   118  			if data[i] == ',' {
   119  				return i + 1, data[:i], nil
   120  			}
   121  		}
   122  		if !atEOF {
   123  			return 0, nil, nil
   124  		}
   125  		// There is one final token to be delivered, which may be the empty string.
   126  		// Returning bufio.ErrFinalToken here tells Scan there are no more tokens after this
   127  		// but does not trigger an error to be returned from Scan itself.
   128  		return 0, data, bufio.ErrFinalToken
   129  	}
   130  	scanner.Split(onComma)
   131  	// Scan.
   132  	for scanner.Scan() {
   133  		fmt.Printf("%q ", scanner.Text())
   134  	}
   135  	if err := scanner.Err(); err != nil {
   136  		fmt.Fprintln(os.Stderr, "reading input:", err)
   137  	}
   138  	// Output: "1" "2" "3" "4" ""
   139  }
   140  

View as plain text