Skip to content

Instantly share code, notes, and snippets.

@rsms
Last active August 29, 2015 14:12
Show Gist options
  • Save rsms/b60283b9ff03ec449a77 to your computer and use it in GitHub Desktop.
Save rsms/b60283b9ff03ec449a77 to your computer and use it in GitHub Desktop.
shift a slice rightwards w/o allocating memory
RShiftSlice(b = [abc.....], n = 3, padb = '0')
[ab0....c]
^ ^
[a00...bc]
^ ^
[000..abc]
^ ^
[0000.abc]
^
[00000abc]
^
RShiftSlice(b = [abcde...], n = 5, padb = '0')
[abcd0..e]
^ ^
[abc00.de]
^ ^
[ab000cde]
^ ^
[a000bcde]
^ ^
[000abcde]
^ ^
func main() {
b := []byte{65,66,67,68,69,0,0,0} // ABCDE...
RShiftSlice(b, 3, byte(48))
println(string(b)) // 000ABCDE
}
func RShiftSlice(b []byte, n uint, padb byte) {
if n != 0 {
bz := uint(len(b))
wi := bz-1
for ; wi >= n; wi-- {
b[wi] = b[wi-n]
b[wi-n] = padb
}
zn := bz-n-1
for ; wi > zn; wi-- {
b[wi] = padb
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment