github.com/tunabay/go-bitarray@v1.3.1/buffer_copy.go (about) 1 // Copyright (c) 2021 Hirotsuna Mizuno. All rights reserved. 2 // Use of this source code is governed by the MIT license that can be found in 3 // the LICENSE file. 4 5 package bitarray 6 7 // CopyBitsFromBytes reads nBits bits from b at the offset bOff, and write them 8 // into the buffer at the offset off. 9 func (buf *Buffer) CopyBitsFromBytes(off int, b []byte, bOff, nBits int) { 10 switch { 11 case off < 0: 12 panicf("CopyBitsFromBytes: negative off %d.", off) 13 case buf.nBits < off+nBits: 14 panicf("CopyBitsFromBytes: out of range: off=%d + nBits=%d > len=%d.", off, nBits, buf.nBits) 15 case nBits == 0: 16 return 17 } 18 copyBits(buf.b, b, buf.off+off, bOff, nBits) 19 } 20 21 // CopyBitsToBytes reads nBits bits of the buffer starting at the offset off, 22 // and write them into the byte slice b at the offset bOff. 23 func (buf *Buffer) CopyBitsToBytes(off int, b []byte, bOff, nBits int) { 24 switch { 25 case off < 0: 26 panicf("CopyBitsToBytes: negative off %d.", off) 27 case buf.nBits < off+nBits: 28 panicf("CopyBitsToBytes: out of range: off=%d + nBits=%d > len=%d.", off, nBits, buf.nBits) 29 case nBits == 0: 30 return 31 } 32 copyBits(b, buf.b, bOff, buf.off+off, nBits) 33 } 34 35 // CopyBits copies bits from src into dst. CopyBits returns the number of bits 36 // copied, which will be the minimum of src.Len() and dst.Len(). 37 func CopyBits(dst, src *Buffer) int { 38 nBits := dst.Len() 39 if sLen := src.Len(); sLen < nBits { 40 nBits = sLen 41 } 42 if nBits != 0 { 43 copyBits(dst.b, src.b, dst.off, src.off, nBits) 44 } 45 46 return nBits 47 } 48 49 // CopyBitsN is identical to CopyBits except that it copies up to nBits bits. 50 func CopyBitsN(dst, src *Buffer, nBits int) int { 51 if dLen := dst.Len(); dLen < nBits { 52 nBits = dLen 53 } 54 if sLen := src.Len(); sLen < nBits { 55 nBits = sLen 56 } 57 if nBits != 0 { 58 copyBits(dst.b, src.b, dst.off, src.off, nBits) 59 } 60 61 return nBits 62 } 63 64 // CopyBitsPartial is identical to CopyBitsN except that it reads and writes 65 // bits starting at specified offsets rather than the first bits. 66 func CopyBitsPartial(dst, src *Buffer, dstOff, srcOff, nBits int) int { 67 if dLen := dst.Len() - dstOff; dLen < nBits { 68 nBits = dLen 69 } 70 if sLen := src.Len() - srcOff; sLen < nBits { 71 nBits = sLen 72 } 73 if nBits != 0 { 74 copyBits(dst.b, src.b, dst.off+dstOff, src.off+srcOff, nBits) 75 } 76 77 return nBits 78 }