github.com/shogo82148/std@v1.22.1-0.20240327122250-4e474527810c/bufio/example_test.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_test 6 7 import ( 8 "github.com/shogo82148/std/bufio" 9 "github.com/shogo82148/std/bytes" 10 "github.com/shogo82148/std/fmt" 11 "github.com/shogo82148/std/os" 12 "github.com/shogo82148/std/strconv" 13 "github.com/shogo82148/std/strings" 14 ) 15 16 func ExampleWriter() { 17 w := bufio.NewWriter(os.Stdout) 18 fmt.Fprint(w, "Hello, ") 19 fmt.Fprint(w, "world!") 20 w.Flush() // フラッシュするのを忘れないで! 21 // Output: Hello, world! 22 } 23 24 func ExampleWriter_AvailableBuffer() { 25 w := bufio.NewWriter(os.Stdout) 26 for _, i := range []int64{1, 2, 3, 4} { 27 b := w.AvailableBuffer() 28 b = strconv.AppendInt(b, i, 10) 29 b = append(b, ' ') 30 w.Write(b) 31 } 32 w.Flush() 33 // Output: 1 2 3 4 34 } 35 36 // Scannerの最も単純な使用方法は、標準入力を行のセットとして読み取ることです。 37 func ExampleScanner_lines() { 38 scanner := bufio.NewScanner(os.Stdin) 39 for scanner.Scan() { 40 fmt.Println(scanner.Text()) // Printlnは最後の'\n'を追加します 41 } 42 if err := scanner.Err(); err != nil { 43 fmt.Fprintln(os.Stderr, "reading standard input:", err) 44 } 45 } 46 47 // 最新のScan呼び出しを[]byteとして返します。 48 func ExampleScanner_Bytes() { 49 scanner := bufio.NewScanner(strings.NewReader("gopher")) 50 for scanner.Scan() { 51 fmt.Println(len(scanner.Bytes()) == 6) 52 } 53 if err := scanner.Err(); err != nil { 54 fmt.Fprintln(os.Stderr, "shouldn't see an error scanning a string") 55 } 56 // Output: 57 // true 58 } 59 60 // スキャナを使用して、スペースで区切られたトークンのシーケンスとして入力をスキャンすることにより、 61 // 単純な単語カウントユーティリティを実装します。 62 func ExampleScanner_words() { 63 // 人工的な入力ソース。 64 const input = "Now is the winter of our discontent,\nMade glorious summer by this sun of York.\n" 65 scanner := bufio.NewScanner(strings.NewReader(input)) 66 // スキャン操作のための分割関数を設定します。 67 scanner.Split(bufio.ScanWords) 68 // 単語を数えます。 69 count := 0 70 for scanner.Scan() { 71 count++ 72 } 73 if err := scanner.Err(); err != nil { 74 fmt.Fprintln(os.Stderr, "reading input:", err) 75 } 76 fmt.Printf("%d\n", count) 77 // Output: 15 78 } 79 80 // ScanWordsをラップして構築されたカスタム分割関数を使用するScannerを使用して、 81 // 32ビットの10進数入力を検証します。 82 func ExampleScanner_custom() { 83 // 人工的な入力ソース。 84 const input = "1234 5678 1234567901234567890" 85 scanner := bufio.NewScanner(strings.NewReader(input)) 86 // 既存のScanWords関数をラップして、カスタム分割関数を作成します。 87 split := func(data []byte, atEOF bool) (advance int, token []byte, err error) { 88 advance, token, err = bufio.ScanWords(data, atEOF) 89 if err == nil && token != nil { 90 _, err = strconv.ParseInt(string(token), 10, 32) 91 } 92 return 93 } 94 // スキャン操作のための分割関数を設定します。 95 scanner.Split(split) 96 // 入力を検証します。 97 for scanner.Scan() { 98 fmt.Printf("%s\n", scanner.Text()) 99 } 100 101 if err := scanner.Err(); err != nil { 102 fmt.Printf("Invalid input: %s", err) 103 } 104 // Output: 105 // 1234 106 // 5678 107 // Invalid input: strconv.ParseInt: parsing "1234567901234567890": value out of range 108 } 109 110 // 空の最終値を持つカンマ区切りリストを解析するために、カスタム分割関数を使用するScannerを使用します。 111 func ExampleScanner_emptyFinalToken() { 112 // カンマ区切りのリスト。最後のエントリは空です。 113 const input = "1,2,3,4," 114 scanner := bufio.NewScanner(strings.NewReader(input)) 115 // コンマで区切る分割関数を定義します。 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 // 最後に配信されるトークンが1つあります。これが空の文字列である場合があります。 126 // ここでbufio.ErrFinalTokenを返すと、Scanにこれ以降のトークンがないことを伝えます。 127 // ただし、Scan自体からエラーが返されるわけではありません。 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 141 // Use a Scanner with a custom split function to parse a comma-separated 142 // list with an empty final value but stops at the token "STOP". 143 func ExampleScanner_earlyStop() { 144 onComma := func(data []byte, atEOF bool) (advance int, token []byte, err error) { 145 i := bytes.IndexByte(data, ',') 146 if i == -1 { 147 if !atEOF { 148 return 0, nil, nil 149 } 150 // If we have reached the end, return the last token. 151 return 0, data, bufio.ErrFinalToken 152 } 153 // If the token is "STOP", stop the scanning and ignore the rest. 154 if string(data[:i]) == "STOP" { 155 return i + 1, nil, bufio.ErrFinalToken 156 } 157 // Otherwise, return the token before the comma. 158 return i + 1, data[:i], nil 159 } 160 const input = "1,2,STOP,4," 161 scanner := bufio.NewScanner(strings.NewReader(input)) 162 scanner.Split(onComma) 163 for scanner.Scan() { 164 fmt.Printf("Got a token %q\n", scanner.Text()) 165 } 166 if err := scanner.Err(); err != nil { 167 fmt.Fprintln(os.Stderr, "reading input:", err) 168 } 169 // Output: 170 // Got a token "1" 171 // Got a token "2" 172 }