github.com/hasnat/dolt/go@v0.0.0-20210628190320-9eb5d843fbb7/store/blobstore/range.go (about)

     1  // Copyright 2019 Dolthub, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package blobstore
    16  
    17  // BlobRange represents a segment of a blob of data.  Offset is the beginning of
    18  // the range and Length is the size.  If Length is 0 that means all data beyond
    19  // offset will be read. Lengths cannot be negative.  Negative offsets indicate
    20  // distance from the end of the end of the blob.
    21  type BlobRange struct {
    22  	offset int64
    23  	length int64
    24  }
    25  
    26  // NewBlobRange creates a BlobRange with a given offset and length
    27  func NewBlobRange(offset, length int64) BlobRange {
    28  	if length < 0 {
    29  		panic("BlobRanges cannot have 0 length")
    30  	}
    31  
    32  	return BlobRange{offset, length}
    33  }
    34  
    35  // IsAllRange is true if it represents the entire blob from index 0 to the end
    36  // and false if it is any subset of the data
    37  func (br BlobRange) isAllRange() bool {
    38  	return br.offset == 0 && br.length == 0
    39  }
    40  
    41  // PositiveRange returns a BlobRange which represents the same range but with
    42  // negative offsets replaced with actual values
    43  func (br BlobRange) positiveRange(size int64) BlobRange {
    44  	offset := br.offset
    45  	length := br.length
    46  
    47  	if offset < 0 {
    48  		offset = size + offset
    49  	}
    50  
    51  	if offset+length > size || length == 0 {
    52  		length = size - offset
    53  	}
    54  
    55  	return BlobRange{offset, length}
    56  }
    57  
    58  // AllRange is a BlobRange instance covering all values
    59  var AllRange = NewBlobRange(0, 0)