这是拼接字节切片的另一种变体。该算法类似于 Anton Litvinov 的 stringSplice()。因为 append 函数与输入共享相同的切片,所以必须使用与输入相同长度的副本。这不是由上一个答案中的“beatgammit”完成的,它无法正常工作。
package main
import "fmt"
func sliceSplice(input []byte, start, deleteCount int, item []byte) ([]byte) {
fmt.Printf("input: %v start = %d deleteCount = %d item: %v\n", input, start, deleteCount, item)
cpy := make([]byte, len(input))
copy(cpy, input)
fmt.Println("cpy: ", cpy)
if start > len(cpy) {
return append(cpy, item...)
}
ret := append(cpy[:start], item...)
fmt.Println("ret: ", ret)
if start+deleteCount > len(cpy) {
return ret
}
fmt.Println("cpy: ", cpy, " modified by shared slice 'ret'")
fmt.Println("input[s+d] ", input[start+deleteCount:], " not modified")
return append(ret, input[start+deleteCount:]...)
}
func main() {
oldFull := []byte{0, 0, 1, 1, 1, 0, 0}
fmt.Println("oldFull: ", oldFull, "\n")
myFull := sliceSplice(oldFull, 3, 0, []byte{2, 2})
fmt.Println("myFull: ", myFull, "\n")
myFull = sliceSplice(oldFull, 3, 1, []byte{2, 2})
fmt.Println("myFull: ", myFull, "\n")
myFull = sliceSplice(oldFull, 3, 4, []byte{2, 2})
fmt.Println("myFull: ", myFull, "\n")
myFull = sliceSplice(oldFull, 3, 6, []byte{2, 2})
fmt.Println("myFull: ", myFull, "\n")
myFull = sliceSplice(oldFull, 7, 0, []byte{2, 2})
fmt.Println("myFull: ", myFull, "\n")
myFull = sliceSplice(oldFull, 9, 6, []byte{2, 2})
fmt.Println("myFull: ", myFull, "\n")
}
我还包括了一组测试用例