Replace encoder API with ini builder
This commit is contained in:
parent
550ed5a8d9
commit
4bb3f9f999
55
ini.go
55
ini.go
|
@ -4,10 +4,14 @@ import (
|
|||
"bufio"
|
||||
"fmt"
|
||||
"io"
|
||||
"reflect"
|
||||
"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.
|
||||
type Entry struct {
|
||||
Section string
|
||||
|
@ -15,32 +19,6 @@ type Entry struct {
|
|||
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.
|
||||
func (parser *Parser) Err() error {
|
||||
return parser.err
|
||||
|
@ -52,7 +30,21 @@ func (parser *Parser) IsEnd() bool {
|
|||
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 {
|
||||
return &Parser{
|
||||
scanner: bufio.NewScanner(reader),
|
||||
|
@ -123,6 +115,13 @@ type Parser struct {
|
|||
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.
|
||||
func unquote(s string) string {
|
||||
var sLen = len(s)
|
||||
|
|
Loading…
Reference in New Issue