Last active
August 29, 2015 14:12
-
-
Save rsms/b60283b9ff03ec449a77 to your computer and use it in GitHub Desktop.
shift a slice rightwards w/o allocating memory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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] | |
^ ^ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func main() { | |
b := []byte{65,66,67,68,69,0,0,0} // ABCDE... | |
RShiftSlice(b, 3, byte(48)) | |
println(string(b)) // 000ABCDE | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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