Debian Codegraph @

bgzf/line_example_test.go

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