Debian Codegraph @

cram/cram.go

raw symbols SCIP
1 // Copyright ©2017 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 cram is a WIP CRAM reader implementation.
6 //
7 // Currently the package implements container, block and slice retrieval, and
8 // SAM header values can be retrieved from blocks.
9 //
10 // See https://samtools.github.io/hts-specs/CRAMv3.pdf for the CRAM
11 // specification.
12 package cram
13
14 import (
15 "bytes"
16 "compress/bzip2"
17 "compress/gzip"
18 "encoding/binary"
19 "errors"
20 "fmt"
21 "hash/crc32"
22 "io"
23 "os"
24 "reflect"
25
26 "github.com/ulikunitz/xz/lzma"
27
28 "github.com/biogo/hts/cram/encoding/itf8"
29 "github.com/biogo/hts/cram/encoding/ltf8"
30 "github.com/biogo/hts/sam"
31 )
32
33 // cramEOFmarker is the CRAM end of file marker.
34 //
35 // See CRAM spec section 9.
36 var cramEOFmarker = []byte{
37 0x0f, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, // |........|
38 0x0f, 0xe0, 0x45, 0x4f, 0x46, 0x00, 0x00, 0x00, // |..EOF...|
39 0x00, 0x01, 0x00, 0x05, 0xbd, 0xd9, 0x4f, 0x00, // |......O.|
40 0x01, 0x00, 0x06, 0x06, 0x01, 0x00, 0x01, 0x00, // |........|
41 0x01, 0x00, 0xee, 0x63, 0x01, 0x4b, /* */ // |...c.K|
42 }
43
44 // ErrNoEnd is returned when a stream cannot seek to a CRAM EOF block.
45 var ErrNoEnd = errors.New("cram: cannot determine offset from end")
46
47 // HasEOF checks for the presence of a CRAM magic EOF block.
48 // The magic block is defined in the CRAM specification. A magic block
49 // is written by a Writer on calling Close. The ReaderAt must provide
50 // some method for determining valid ReadAt offsets.
51 func HasEOF(r io.ReaderAt) (bool, error) {
52 type sizer interface {
53 Size() int64
54 }
55 type stater interface {
56 Stat() (os.FileInfo, error)
57 }
58 type lenSeeker interface {
59 io.Seeker
60 Len() int
61 }
62 var size int64
63 switch r := r.(type) {
64 case sizer:
65 size = r.Size()
66 case stater:
67 fi, err := r.Stat()
68 if err != nil {
69 return false, err
70 }
71 size = fi.Size()
72 case lenSeeker:
73 var err error
74 size, err = r.Seek(0, 1)
75 if err != nil {
76 return false, err
77 }
78 size += int64(r.Len())
79 default:
80 return false, ErrNoEnd
81 }
82
83 b := make([]byte, len(cramEOFmarker))
84 _, err := r.ReadAt(b, size-int64(len(cramEOFmarker)))
85 if err != nil {
86 return false, err
87 }
88 return bytes.Equal(b, cramEOFmarker), nil
89 }
90
91 // Reader is a CRAM format reader.
92 type Reader struct {
93 r io.Reader
94
95 d definition
96 c *Container
97
98 err error
99 }
100
101 // NewReader returns a new Reader.
102 func NewReader(r io.Reader) (*Reader, error) {
103 cr := Reader{r: r}
104 err := cr.d.readFrom(r)
105 if err != nil {
106 return nil, err
107 }
108 return &cr, nil
109 }
110
111 // Next advances the Reader to the next CRAM container. It returns false
112 // when the stream ends, either by reaching the end of the stream or
113 // encountering an error.
114 func (r *Reader) Next() bool {
115 if r.err != nil {
116 return false
117 }
118 if r.c != nil {
119 io.Copy(io.Discard, r.c.blockData)
120 }
121 var c Container
122 r.err = c.readFrom(r.r)
123 r.c = &c
124 return r.err == nil
125 }
126
127 // Container returns the current CRAM container. The returned Container
128 // is only valid after a previous call to Next has returned true.
129 func (r *Reader) Container() *Container {
130 return r.c
131 }
132
133 // Err returns the most recent error.
134 func (r *Reader) Err() error {
135 if r.err == io.EOF {
136 return nil
137 }
138 return r.err
139 }
140
141 // definition is a CRAM file definition.
142 //
143 // See CRAM spec section 6.
144 type definition struct {
145 Magic [4]byte `is:"CRAM"`
146 Version [2]byte
147 ID [20]byte
148 }
149
150 // readFrom populates a definition from the given io.Reader. If the magic
151 // number of the file is not "CRAM" readFrom returns an error.
152 func (d *definition) readFrom(r io.Reader) error {
153 err := binary.Read(r, binary.LittleEndian, d)
154 if err != nil {
155 return err
156 }
157 magic := reflect.TypeOf(*d).Field(0).Tag.Get("is")
158 if !bytes.Equal(d.Magic[:], []byte(magic)) {
159 return fmt.Errorf("cram: not a cram file: magic bytes %q", d.Magic)
160 }
161 return nil
162 }
163
164 // Container is a CRAM container.
165 //
166 // See CRAM spec section 7.
167 type Container struct {
168 blockLen int32
169 refID int32
170 start int32
171 span int32
172 nRec int32
173 recCount int64
174 bases int64
175 blocks int32
176 landmarks []int32
177 crc32 uint32
178 blockData io.Reader
179
180 block *Block
181 err error
182 }
183
184 // readFrom populates a Container from the given io.Reader checking that the
185 // CRC32 for the container header is correct.
186 func (c *Container) readFrom(r io.Reader) error {
187 crc := crc32.NewIEEE()
188 er := errorReader{r: io.TeeReader(r, crc)}
189 var buf [4]byte
190 io.ReadFull(&er, buf[:])
191 c.blockLen = int32(binary.LittleEndian.Uint32(buf[:]))
192 c.refID = er.itf8()
193 c.start = er.itf8()
194 c.span = er.itf8()
195 c.nRec = er.itf8()
196 c.recCount = er.ltf8()
197 c.bases = er.ltf8()
198 c.blocks = er.itf8()
199 c.landmarks = er.itf8slice()
200 sum := crc.Sum32()
201 _, err := io.ReadFull(&er, buf[:])
202 if err != nil {
203 return err
204 }
205 c.crc32 = binary.LittleEndian.Uint32(buf[:])
206 if c.crc32 != sum {
207 return fmt.Errorf("cram: container crc32 mismatch got:0x%08x want:0x%08x", sum, c.crc32)
208 }
209 if er.err != nil {
210 return er.err
211 }
212 // The spec says T[] is {itf8, element...}.
213 // This is not true for byte[] according to
214 // the EOF block.
215 c.blockData = &io.LimitedReader{R: r, N: int64(c.blockLen)}
216 return nil
217 }
218
219 // Next advances the Container to the next CRAM block. It returns false
220 // when the data ends, either by reaching the end of the container or
221 // encountering an error.
222 func (c *Container) Next() bool {
223 if c.err != nil {
224 return false
225 }
226 var b Block
227 c.err = b.readFrom(c.blockData)
228 if c.err == nil {
229 c.block = &b
230 return true
231 }
232 return false
233 }
234
235 // Block returns the current CRAM block. The returned Blcok is only
236 // valid after a previous call to Next has returned true.
237 func (c *Container) Block() *Block {
238 return c.block
239 }
240
241 // Err returns the most recent error.
242 func (c *Container) Err() error {
243 if c.err == io.EOF {
244 return nil
245 }
246 return c.err
247 }
248
249 // Block is a CRAM block structure.
250 //
251 // See CRAM spec section 8.
252 type Block struct {
253 method byte
254 typ byte
255 contentID int32
256 compressedSize int32
257 rawSize int32
258 blockData []byte
259 crc32 uint32
260 }
261
262 const (
263 rawMethod = iota
264 gzipMethod
265 bzip2Method
266 lzmaMethod
267 ransMethod
268 )
269
270 const (
271 fileHeader = iota
272 compressionHeader
273 mappedSliceHeader
274 _ // reserved
275 externalData
276 coreData
277 )
278
279 // readFrom fills a Block from the given io.Reader checking that the
280 // CRC32 for the block is correct.
281 func (b *Block) readFrom(r io.Reader) error {
282 crc := crc32.NewIEEE()
283 er := errorReader{r: io.TeeReader(r, crc)}
284 var buf [4]byte
285 io.ReadFull(&er, buf[:2])
286 b.method = buf[0]
287 b.typ = buf[1]
288 b.contentID = er.itf8()
289 b.compressedSize = er.itf8()
290 b.rawSize = er.itf8()
291 if b.method == rawMethod && b.compressedSize != b.rawSize {
292 return fmt.Errorf("cram: compressed (%d) != raw (%d) size for raw method", b.compressedSize, b.rawSize)
293 }
294 // The spec says T[] is {itf8, element...}.
295 // This is not true for byte[] according to
296 // the EOF block.
297 b.blockData = make([]byte, b.compressedSize)
298 _, err := io.ReadFull(&er, b.blockData)
299 if err != nil {
300 return err
301 }
302 sum := crc.Sum32()
303 _, err = io.ReadFull(&er, buf[:])
304 if err != nil {
305 return err
306 }
307 b.crc32 = binary.LittleEndian.Uint32(buf[:])
308 if b.crc32 != sum {
309 return fmt.Errorf("cram: block crc32 mismatch got:0x%08x want:0x%08x", sum, b.crc32)
310 }
311 return nil
312 }
313
314 // Value returns the value of the Block.
315 //
316 // Note that rANS decompression is not implemented.
317 func (b *Block) Value() (interface{}, error) {
318 switch b.typ {
319 case fileHeader:
320 var h sam.Header
321 blockData, err := b.expandBlockdata()
322 if err != nil {
323 return nil, err
324 }
325 end := binary.LittleEndian.Uint32(blockData[:4])
326 err = h.UnmarshalText(blockData[4 : 4+end])
327 if err != nil {
328 return nil, err
329 }
330 return &h, nil
331 case mappedSliceHeader:
332 var s Slice
333 s.readFrom(bytes.NewReader(b.blockData))
334 return &s, nil
335 default:
336 // Experimental.
337 switch b.method {
338 case gzipMethod, bzip2Method, lzmaMethod:
339 var err error
340 b.blockData, err = b.expandBlockdata()
341 if err != nil {
342 return nil, err
343 }
344 b.method |= 0x80
345 default:
346 // Do nothing.
347 }
348 return b, nil
349 }
350 }
351
352 // expandBlockdata decompresses the block's compressed data.
353 func (b *Block) expandBlockdata() ([]byte, error) {
354 switch b.method {
355 default:
356 panic(fmt.Sprintf("cram: unknown method: %v", b.method))
357 case rawMethod:
358 return b.blockData, nil
359 case gzipMethod:
360 gz, err := gzip.NewReader(bytes.NewReader(b.blockData))
361 if err != nil {
362 return nil, err
363 }
364 return io.ReadAll(gz)
365 case bzip2Method:
366 return io.ReadAll(bzip2.NewReader(bytes.NewReader(b.blockData)))
367 case lzmaMethod:
368 lz, err := lzma.NewReader(bytes.NewReader(b.blockData))
369 if err != nil {
370 return nil, err
371 }
372 return io.ReadAll(lz)
373 case ransMethod:
374 // Unimplemented.
375 // BUG(kortschak): The rANS method is not implemented.
376 // Data blocks compressed with rANS will be returned
377 // compressed and an "unimplemented" error will be
378 // returned.
379 return b.blockData, errors.New("unimplemented")
380 }
381 }
382
383 // Slice is a CRAM slice header block.
384 //
385 // See CRAM spec section 8.5.
386 type Slice struct {
387 refID int32
388 start int32
389 span int32
390 nRec int32
391 recCount int64
392 blocks int32
393 blockIDs []int32
394 embeddedRefID int32
395 md5sum [16]byte
396 tags []byte
397 }
398
399 // readFrom populates a Slice from the given io.Reader.
400 func (s *Slice) readFrom(r io.Reader) error {
401 er := errorReader{r: r}
402 s.refID = er.itf8()
403 s.start = er.itf8()
404 s.span = er.itf8()
405 s.nRec = er.itf8()
406 s.recCount = er.ltf8()
407 s.blocks = er.itf8()
408 s.blockIDs = er.itf8slice()
409 s.embeddedRefID = er.itf8()
410 _, err := io.ReadFull(&er, s.md5sum[:])
411 if err != nil {
412 return err
413 }
414 s.tags, err = io.ReadAll(&er)
415 return err
416 }
417
418 // errorReader is a sticky error io.Reader.
419 type errorReader struct {
420 r io.Reader
421 err error
422 }
423
424 // Read implements the io.Reader interface.
425 func (r *errorReader) Read(b []byte) (int, error) {
426 if r.err != nil {
427 return 0, r.err
428 }
429 var n int
430 n, r.err = r.r.Read(b)
431 return n, r.err
432 }
433
434 // itf8 returns the ITF-8 encoded number at the current reader position.
435 func (r *errorReader) itf8() int32 {
436 var buf [5]byte
437 _, r.err = io.ReadFull(r, buf[:1])
438 if r.err != nil {
439 return 0
440 }
441 i, n, ok := itf8.Decode(buf[:1])
442 if ok {
443 return i
444 }
445 _, r.err = io.ReadFull(r, buf[1:n])
446 if r.err != nil {
447 return 0
448 }
449 i, _, ok = itf8.Decode(buf[:n])
450 if !ok {
451 r.err = fmt.Errorf("cram: failed to decode itf-8 stream %#v", buf[:n])
452 }
453 return i
454 }
455
456 // itf8slice returns the n[ITF-8] encoded numbers at the current reader position
457 // where n is an ITF-8 encoded number.
458 func (r *errorReader) itf8slice() []int32 {
459 n := r.itf8()
460 if r.err != nil {
461 return nil
462 }
463 if n == 0 {
464 return nil
465 }
466 s := make([]int32, n)
467 for i := range s {
468 s[i] = r.itf8()
469 if r.err != nil {
470 return s[:i]
471 }
472 }
473 return s
474 }
475
476 // itf8 returns the LTF-8 encoded number at the current reader position.
477 func (r *errorReader) ltf8() int64 {
478 var buf [9]byte
479 _, r.err = io.ReadFull(r, buf[:1])
480 if r.err != nil {
481 return 0
482 }
483 i, n, ok := ltf8.Decode(buf[:1])
484 if ok {
485 return i
486 }
487 _, r.err = io.ReadFull(r, buf[1:n])
488 if r.err != nil {
489 return 0
490 }
491 i, _, ok = ltf8.Decode(buf[:n])
492 if !ok {
493 r.err = fmt.Errorf("cram: failed to decode ltf-8 stream %#v", buf[:n])
494 }
495 return i
496 }