github.com/dolthub/dolt/go@v0.40.5-0.20240520175717-68db7794bea6/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 import ( 18 "fmt" 19 ) 20 21 // BlobRange represents a segment of a blob of data. Offset is the beginning of 22 // the range and Length is the size. If Length is 0 that means all data beyond 23 // offset will be read. Lengths cannot be negative. Negative offsets indicate 24 // distance from the end of the end of the blob. 25 type BlobRange struct { 26 offset int64 27 length int64 28 } 29 30 // NewBlobRange creates a BlobRange with a given offset and length 31 func NewBlobRange(offset, length int64) BlobRange { 32 if length < 0 { 33 panic("BlobRanges cannot have 0 length") 34 } 35 36 return BlobRange{offset, length} 37 } 38 39 // IsAllRange is true if it represents the entire blob from index 0 to the end 40 // and false if it is any subset of the data 41 func (br BlobRange) isAllRange() bool { 42 return br.offset == 0 && br.length == 0 43 } 44 45 // PositiveRange returns a BlobRange which represents the same range but with 46 // negative offsets replaced with actual values 47 func (br BlobRange) positiveRange(size int64) BlobRange { 48 offset := br.offset 49 length := br.length 50 51 if offset < 0 { 52 offset = size + offset 53 } 54 55 if offset+length > size || length == 0 { 56 length = size - offset 57 } 58 59 return BlobRange{offset, length} 60 } 61 62 func (br BlobRange) asHttpRangeHeader() string { 63 if br.isAllRange() { 64 return "" 65 } 66 if br.length == 0 || br.offset < 0 { 67 return fmt.Sprintf("bytes=%d", br.offset) 68 } 69 return fmt.Sprintf("bytes=%d-%d", br.offset, br.offset+br.length-1) 70 } 71 72 // AllRange is a BlobRange instance covering all values 73 var AllRange = NewBlobRange(0, 0)