github.com/bhojpur/cache@v0.0.4/pkg/file/core/split.go (about) 1 package core 2 3 // Copyright (c) 2018 Bhojpur Consulting Private Limited, India. All rights reserved. 4 5 // Permission is hereby granted, free of charge, to any person obtaining a copy 6 // of this software and associated documentation files (the "Software"), to deal 7 // in the Software without restriction, including without limitation the rights 8 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 // copies of the Software, and to permit persons to whom the Software is 10 // furnished to do so, subject to the following conditions: 11 12 // The above copyright notice and this permission notice shall be included in 13 // all copies or substantial portions of the Software. 14 15 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 // THE SOFTWARE. 22 23 import "errors" 24 25 // ErrCannotSplitBytes is returned when a byte slice cannot be split evenly 26 // with the given size array. 27 var ErrCannotSplitBytes = errors.New( 28 "byte array can not be split given size vector", 29 ) 30 31 // calculateSizeSum calculates the sum of all of the uint32s in a []uint32. 32 func calculateSizeSum(sizes []uint32) uint32 { 33 var sum uint32 // Init the sum 34 35 // Add all of the slice's elements 36 for _, size := range sizes { 37 sum += size 38 } 39 40 return sum // Return the sum 41 } 42 43 // SplitBytes splits a []byte n times. 44 func SplitBytes(bytes []byte, sizes []uint32) ([][]byte, error) { 45 // Check that the bytes can be split given the size vector 46 if uint32(len(bytes)) != calculateSizeSum(sizes) { 47 return nil, ErrCannotSplitBytes 48 } 49 50 var splitBytes [][]byte // Init the master slice 51 currentBytePos := 0 // Init the byte position 52 53 // For each size (shard) 54 for _, currentSize := range sizes { 55 var tempBytes []byte // Init shard[i]'s byte slice 56 57 // For each byte that needs to be added 58 for i := 0; i < int(currentSize); i++ { 59 tempBytes = append(tempBytes, bytes[currentBytePos]) // Add the byte 60 61 currentBytePos++ // Move the "byte cursor" 62 } 63 64 // Append the shard's bytes to the master slice 65 splitBytes = append(splitBytes, tempBytes) 66 } 67 68 return splitBytes, nil 69 }