37 lines
1021 B
Go
37 lines
1021 B
Go
// In this example, we show that any type can be extended into a parser,
|
|
// filling that type with data from the ParseHandler methods.
|
|
//
|
|
// Here, we create a custom type 'letterCollection', which is an alias
|
|
// for []string. We add a ParseHandler method directly to that type
|
|
// and let the parsing code fill the slice with strings during parsing.
|
|
|
|
package parsekit_test
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
"git.makaay.nl/mauricem/go-parsekit"
|
|
)
|
|
|
|
type chunks []string
|
|
|
|
func (l *chunks) AddChopped(s string, chunkSize int) *parsekit.Error {
|
|
parser := parsekit.NewParser(func(p *parsekit.ParseAPI) {
|
|
for p.On(parsekit.C.MinMax(1, chunkSize, parsekit.A.AnyRune)).Accept() {
|
|
*l = append(*l, p.BufLiteral())
|
|
p.BufClear()
|
|
}
|
|
})
|
|
return parser.Execute(s)
|
|
}
|
|
|
|
func Example_usingSliceAsParserState() {
|
|
chunks := &chunks{}
|
|
chunks.AddChopped("This string will", 4)
|
|
chunks.AddChopped("be cut to bits!!!!!!", 8)
|
|
|
|
fmt.Printf("Matches = %q", *chunks)
|
|
// Output:
|
|
// Matches = ["This" " str" "ing " "will" "be cut t" "o bits!!" "!!!!"]
|
|
}
|