Debian Codegraph @

bgzf/line_example_test.go

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 // Copyright ©2021 The bíogo 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 bgzf_test
6
7 import (
8 "bytes"
9 "fmt"
10 "io"
11 "log"
12 "os"
13
14 "github.com/biogo/hts/bgzf"
15 )
16
17 func ExampleReader_ReadByte() {
18 // Write Tom Sawyer into a bgzf buffer.
19 var buf bytes.Buffer
20 w := bgzf.NewWriter(&buf, 1)
21 f, err := os.Open("testdata/Mark.Twain-Tom.Sawyer.txt")
22 if err != nil {
23 log.Fatalf("failed to open file: %v", err)
24 }
25 defer f.Close()
26 _, err = io.Copy(w, f)
27 if err != nil {
28 log.Fatalf("failed to copy file: %v", err)
29 }
30 err = w.Close()
31 if err != nil {
32 log.Fatalf("failed to close bgzf writer: %v", err)
33 }
34
35 // The text to search for.
36 const line = `"It ain't any use, Huck, we're wrong again."`
37
38 // Read the data until the line is found and output the line
39 // number and bgzf.Chunk corresponding to the lines position
40 // in the compressed data.
41 r, err := bgzf.NewReader(&buf, 1)
42 if err != nil {
43 log.Fatal(err)
44 }
45 var n int
46 for {
47 n++
48 b, chunk, err := readLine(r)
49 if err != nil {
50 if err == io.EOF {
51 break
52 }
53 log.Fatal(err)
54 }
55 // Make sure we trim the trailing newline.
56 if bytes.Equal(bytes.TrimSpace(b), []byte(line)) {
57 fmt.Printf("line:%d chunk:%+v\n", n, chunk)
58 break
59 }
60 }
61
62 // Output:
63 //
64 // line:5986 chunk:{Begin:{File:112534 Block:11772} End:{File:112534 Block:11818}}
65 }
66
67 // readLine returns a line terminated by a '\n' and the bgzf.Chunk that contains
68 // the line, including the newline character. If the end of file is reached before
69 // a newline, the unterminated line and corresponding chunk are returned.
70 func readLine(r *bgzf.Reader) ([]byte, bgzf.Chunk, error) {
71 tx := r.Begin()
72 var (
73 data []byte
74 b byte
75 err error
76 )
77 for {
78 b, err = r.ReadByte()
79 if err != nil {
80 break
81 }
82 data = append(data, b)
83 if b == '\n' {
84 break
85 }
86 }
87 chunk := tx.End()
88 return data, chunk, err
89 }