Created
January 6, 2022 19:00
-
-
Save qxxt/87488118a053d8e434a7ce60a67afad9 to your computer and use it in GitHub Desktop.
Reading Large Bytes in Reverse Line Order [Golang]
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
// https://go.dev/play/p/qKDFxiJQAfF | |
package main | |
import ( | |
"fmt" | |
) | |
func main() { | |
someBytes := []byte(`Lorem ipsum dolor sit amet, | |
consectetur adipiscing elit. | |
Sed in mattis leo. Integer eu | |
tortor ut libero aliquet | |
dignissim. Etiam nisi metus, | |
consectetur eu luctus vel, | |
malesuada id arcu. | |
Integer egestas velit a velit | |
sollicitudin venenatis. | |
In volutpat nunc posuere | |
ex lobortis maximus. | |
Vivamus fringilla lacinia | |
nisi nec hendrerit. Duis | |
ipsum tortor, congue ut est | |
eu, volutpat pharetra orci. | |
`) | |
fmt.Println(string(ReverseByte(someBytes, 15))) | |
} | |
func ReverseByte(fileByte []byte, maxLine int) []byte { | |
// This is a byte "code" for NewLine or "\n" | |
nl := byte(10) | |
var reverseFileByte []byte | |
var lineLen, lineWritten int | |
byteIndex := len(fileByte) - 1 | |
for lineWritten < maxLine { | |
if fileByte[byteIndex] == nl { | |
currentLine := make([]byte, lineLen) | |
byteLineIndex := byteIndex | |
var currentLineIndex int | |
for currentLineIndex < lineLen { | |
currentLine[currentLineIndex] = fileByte[byteLineIndex] | |
byteLineIndex++ | |
currentLineIndex++ | |
} | |
reverseFileByte = append(reverseFileByte, currentLine...) | |
lineLen = 0 | |
lineWritten++ | |
} | |
lineLen++ | |
byteIndex-- | |
} | |
return reverseFileByte | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment