github.com/searKing/golang/go@v1.2.74/util/object/internal/preconditions/preconditions.go (about) 1 // Copyright 2020 The searKing Author. 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 preconditions 6 7 import "errors" 8 9 type ErrorOutOfBound error 10 11 var ( 12 errorOutOfBound = errors.New("out of bound") 13 ) 14 15 // CheckIndex checks if the {@code index} is within the bounds of the range from 16 // {@code 0} (inclusive) to {@code length} (exclusive). 17 func CheckIndex(index, length int) int { 18 if index < 0 || index >= length { 19 panic(ErrorOutOfBound(errors.New("CheckIndex"))) 20 } 21 return index 22 } 23 24 // CheckFromToIndex checks if the sub-range from {@code fromIndex} (inclusive) to 25 // {@code toIndex} (exclusive) is within the bounds of range from {@code 0} 26 // (inclusive) to {@code length} (exclusive). 27 func CheckFromToIndex(fromIndex, toIndex, length int) int { 28 if fromIndex < 0 || fromIndex > toIndex || toIndex > length { 29 panic(ErrorOutOfBound(errors.New("CheckFromToIndex"))) 30 } 31 return fromIndex 32 } 33 34 // Checks if the sub-range from {@code fromIndex} (inclusive) to 35 // {@code fromIndex + size} (exclusive) is within the bounds of range from 36 // {@code 0} (inclusive) to {@code length} (exclusive). 37 func CheckFromIndexSize(fromIndex, size, length int) int { 38 if length < 0 || fromIndex < 0 || size < 0 || size > length-fromIndex { 39 panic(ErrorOutOfBound(errors.New("CheckFromIndexSize"))) 40 } 41 return fromIndex 42 }