diff options
| author | Shulhan <ms@kilabit.info> | 2023-04-09 19:47:42 +0700 |
|---|---|---|
| committer | Shulhan <ms@kilabit.info> | 2023-04-09 19:47:42 +0700 |
| commit | dff8d3f4295a343990974b8ea8eac52e4eccf4e4 (patch) | |
| tree | 14c824f2a61376c34c454093a3899df05a0106e4 | |
| parent | c376eccd25cbff56c72f2ec15674677bfa769d9e (diff) | |
| download | pakakeh.go-dff8d3f4295a343990974b8ea8eac52e4eccf4e4.tar.xz | |
lib/bytes: add method ReadLine to Parser
The ReadLine method read until it found new line ('\n') or end of content,
ignoring all delimiters.
The returned line will not contain '\n'.
| -rw-r--r-- | lib/bytes/parser.go | 16 | ||||
| -rw-r--r-- | lib/bytes/parser_example_test.go | 18 |
2 files changed, 34 insertions, 0 deletions
diff --git a/lib/bytes/parser.go b/lib/bytes/parser.go index 70230622..4a6f09d3 100644 --- a/lib/bytes/parser.go +++ b/lib/bytes/parser.go @@ -56,6 +56,22 @@ func (bp *Parser) Read() (token []byte, d byte) { return token, 0 } +// ReadLine read until it found new line ('\n') or end of content, ignoring +// all delimiters. +// The returned line will not contain '\n'. +func (bp *Parser) ReadLine() (line []byte, c byte) { + for bp.x < bp.size { + c = bp.content[bp.x] + if c == '\n' { + bp.x++ + return line, c + } + line = append(line, c) + bp.x++ + } + return line, 0 +} + // ReadN read exactly n characters ignoring the delimiters. // It will return the token and the character after n or 0 if end-of-content. func (bp *Parser) ReadN(n int) (token []byte, d byte) { diff --git a/lib/bytes/parser_example_test.go b/lib/bytes/parser_example_test.go index c62258fe..a30bda5a 100644 --- a/lib/bytes/parser_example_test.go +++ b/lib/bytes/parser_example_test.go @@ -37,6 +37,24 @@ func ExampleParser_Delimiters() { // =; } +func ExampleParser_ReadLine() { + var ( + content = []byte("a=b;\nc=d;") + delims = []byte{'=', ';'} + parser = libbytes.NewParser(content, delims) + ) + + token, c := parser.ReadLine() + fmt.Printf("token:%s c:%d\n", token, c) + + token, c = parser.ReadLine() + fmt.Printf("token:%s c:%d\n", token, c) + + // Output: + // token:a=b; c:10 + // token:c=d; c:0 +} + func ExampleParser_ReadN() { var ( content = []byte(`a=b;c=d;`) |
