| 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 itf8 provides ITF-8 integer encoding. |
| 6 | // |
| 7 | // ITF-8 integer encoding is specified in the CRAM format specification |
| 8 | // section 2.3. |
| 9 | package itf8 |
| 10 | |
| 11 | import "math/bits" |
| 12 | |
| 13 | // Len returns the number of bytes required to encode u. |
| 14 | func Len(v int32) int { |
| 15 | u := uint32(v) |
| 16 | switch { |
| 17 | case u < 0x80: |
| 18 | return 1 |
| 19 | case u < 0x4000: |
| 20 | return 2 |
| 21 | case u < 0x200000: |
| 22 | return 3 |
| 23 | case u < 0x10000000: |
| 24 | return 4 |
| 25 | default: |
| 26 | return 5 |
| 27 | } |
| 28 | } |
| 29 | |
| 30 | // Decode decodes the ITF-8 encoding in b and returns the int32 value, its |
| 31 | // width in bytes and whether the decoding was successful. If the encoding |
| 32 | // is invalid, the expected length of b and false are returned. If b has zero |
| 33 | // length, zero, zero and false are returned. |
| 34 | func Decode(b []byte) (v int32, n int, ok bool) { |
| 35 | if len(b) == 0 { |
| 36 | return 0, 0, false |
| 37 | } |
| 38 | n = bits.LeadingZeros8(^(b[0] & 0xf0)) + 1 |
| 39 | if len(b) < n { |
| 40 | return 0, n, false |
| 41 | } |
| 42 | switch n { |
| 43 | case 1: |
| 44 | v = int32(b[0]) |
| 45 | case 2: |
| 46 | v = int32(b[1]) | int32(b[0]&0x3f)<<8 |
| 47 | case 3: |
| 48 | v = int32(b[2]) | int32(b[1])<<8 | int32(b[0]&0x1f)<<16 |
| 49 | case 4: |
| 50 | v = int32(b[3]) | int32(b[2])<<8 | int32(b[1])<<16 | int32(b[0]&0x0f)<<24 |
| 51 | case 5: |
| 52 | v = int32(b[4]&0x0f) | int32(b[3])<<4 | int32(b[2])<<12 | int32(b[1])<<20 | int32(b[0]&0x0f)<<28 |
| 53 | } |
| 54 | return v, n, true |
| 55 | } |
| 56 | |
| 57 | // Encode encodes v as an ITF-8 into b, which must be large enough, and |
| 58 | // and returns the number of bytes written. |
| 59 | func Encode(b []byte, v int32) int { |
| 60 | u := uint32(v) |
| 61 | switch { |
| 62 | case u < 0x80: |
| 63 | b[0] = byte(u) |
| 64 | return 1 |
| 65 | case u < 0x4000: |
| 66 | _ = b[1] |
| 67 | b[0] = byte(u>>8)&0x3f | 0x80 |
| 68 | b[1] = byte(u) |
| 69 | return 2 |
| 70 | case u < 0x200000: |
| 71 | _ = b[2] |
| 72 | b[0] = byte(u>>16)&0x1f | 0xc0 |
| 73 | b[1] = byte(u >> 8) |
| 74 | b[2] = byte(u) |
| 75 | return 3 |
| 76 | case u < 0x10000000: |
| 77 | _ = b[3] |
| 78 | b[0] = byte(u>>24)&0x0f | 0xe0 |
| 79 | b[1] = byte(u >> 16) |
| 80 | b[2] = byte(u >> 8) |
| 81 | b[3] = byte(u) |
| 82 | return 4 |
| 83 | default: |
| 84 | _ = b[4] |
| 85 | b[0] = byte(u>>28) | 0xf0 |
| 86 | b[1] = byte(u >> 20) |
| 87 | b[2] = byte(u >> 12) |
| 88 | b[3] = byte(u >> 2) |
| 89 | b[4] = byte(u) |
| 90 | return 5 |
| 91 | } |
| 92 | } |