Created
November 2, 2014 04:04
-
-
Save hkparker/1129ea6a3be5270e9902 to your computer and use it in GitHub Desktop.
Memory safe strings
This file contains hidden or 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
package main | |
import ( | |
"os" | |
"io" | |
"log" | |
"fmt" | |
) | |
func is_ascii_byte(char byte) bool { | |
if char >= 32 && char <= 126 { | |
return true | |
} else { | |
return false | |
} | |
} | |
func bytes_to_chan(file *os.File, bytes chan byte) { | |
for { | |
data := make([]byte, 1) | |
_, err := file.Read(data) | |
if err == nil { | |
bytes <- data[0] | |
} else if err == io.EOF { | |
close(bytes) | |
break | |
} | |
} | |
} | |
func main() { | |
file, err := os.Open(os.Args[1]) | |
if err != nil { | |
log.Fatal(err) | |
} | |
defer file.Close() | |
bytes := make(chan byte) | |
go bytes_to_chan(file, bytes) | |
str := make([]byte, 0) | |
for data := range bytes { | |
if is_ascii_byte(data) { | |
str = append(str,data) | |
} else { | |
if len(str) != 0 { | |
fmt.Println(string(str)) | |
str = make([]byte, 0) | |
} | |
} | |
} | |
if len(str) != 0 { | |
fmt.Println(string(str)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment