github.com/tunabay/go-bitarray@v1.3.1/buffer_slice.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  // Slice extracts a subpart from the buffer and returns it as a new Buffer in
     8  // the same manner as Go's native slices. Note that like Go's native slices, the
     9  // sliced buffers share memory with the original buffer. Changes to the original
    10  // buffer affect slices and vice versa. Slice does not perform bit-shifting,
    11  // even when creating slices that are not aligned to byte boundaries. It just
    12  // records the offset and length for reference.
    13  //
    14  // The two arguments start and end specify the indexes of the bits to select. 0
    15  // points to the first bit and buf.Len()-1 points to the last bit. The start and
    16  // end select a half-open range which includes the start, but excludes the end.
    17  // If the index is outside the range of the buffer, Slice will panic.
    18  func (buf *Buffer) Slice(start, end int) *Buffer {
    19  	switch {
    20  	case start < 0, buf.Len() < start:
    21  		panicf("Slice: start %d out of range: 0..%d.", start, buf.Len())
    22  	case end < 0, buf.Len() < end:
    23  		panicf("Slice: end %d out of range: 0..%d.", end, buf.Len())
    24  	case end < start:
    25  		panicf("Slice: invalid range start=%d > end=%d.", start, end)
    26  	case start == end:
    27  		return &Buffer{}
    28  	}
    29  	off := buf.off + start
    30  	return &Buffer{
    31  		b:     buf.b[off>>3 : (buf.off+end+7)>>3],
    32  		nBits: end - start,
    33  		off:   off & 7,
    34  	}
    35  }
    36  
    37  // SliceToEnd is shorthand for Slice(start, buf.Len()) and returns the subpart
    38  // from the position specified start to the last bit.
    39  func (buf *Buffer) SliceToEnd(start int) *Buffer { return buf.Slice(start, buf.Len()) }