Replace encoder API with ini builder

This commit is contained in:
kayomn 2022-12-23 14:20:35 +00:00
parent 550ed5a8d9
commit 4bb3f9f999
1 changed files with 27 additions and 28 deletions

55
ini.go
View File

@ -4,10 +4,14 @@ import (
"bufio" "bufio"
"fmt" "fmt"
"io" "io"
"reflect"
"strings" "strings"
) )
// State machine for writing to streamable INI file sources.
type Builder struct {
writer *bufio.Writer
}
// Singular key-value pair under the given section within an INI file. // Singular key-value pair under the given section within an INI file.
type Entry struct { type Entry struct {
Section string Section string
@ -15,32 +19,6 @@ type Entry struct {
Value string Value string
} }
// Attempts to write `value` to `writer` in an INI-encoded format, returning any error that
// occured during writing.
func Encode(writer io.Writer, section string, value any) error {
if _, printError := fmt.Fprintf(writer, "[%s]\n", section); printError != nil {
return printError
}
var valueType = reflect.TypeOf(value)
if valueType.Kind() != reflect.Struct {
return fmt.Errorf("only structs may be encoded")
}
var valueInfo = reflect.ValueOf(value)
for i := 0; i < valueInfo.NumField(); i += 1 {
if _, printError := fmt.Fprintf(writer, "%s = %s\n",
valueType.Field(i).Name, valueInfo.Field(i).Interface()); printError != nil {
return printError
}
}
return nil
}
// Returns the last error that occured during parsing. // Returns the last error that occured during parsing.
func (parser *Parser) Err() error { func (parser *Parser) Err() error {
return parser.err return parser.err
@ -52,7 +30,21 @@ func (parser *Parser) IsEnd() bool {
return parser.isEnd return parser.isEnd
} }
// Creates and returns a new [Parser] by reference from `reader` // Appends a new key-value pair of `key` and `value` respectively in the `builder`.
func (builder *Builder) KeyValue(key string, value string) error {
var _, printError = fmt.Fprintf(builder.writer, "%s = %s\n", key, value)
return printError
}
// Creates and returns a new [Builder] by reference from `writer`.
func NewBuilder(writer io.Writer) *Builder {
return &Builder{
writer: bufio.NewWriter(writer),
}
}
// Creates and returns a new [Parser] by reference from `reader`.
func NewParser(reader io.Reader) *Parser { func NewParser(reader io.Reader) *Parser {
return &Parser{ return &Parser{
scanner: bufio.NewScanner(reader), scanner: bufio.NewScanner(reader),
@ -123,6 +115,13 @@ type Parser struct {
isEnd bool isEnd bool
} }
// Appends a new section titled `name` in the `builder`.
func (builder *Builder) Section(name string) error {
var _, printError = fmt.Fprintf(builder.writer, "[%s]\n", name)
return printError
}
// Returns a string with the the outer-most quotes surrounding `s` trimmed, should they exist. // Returns a string with the the outer-most quotes surrounding `s` trimmed, should they exist.
func unquote(s string) string { func unquote(s string) string {
var sLen = len(s) var sLen = len(s)