diff --git a/ini.go b/ini.go index a94cd89..825c233 100644 --- a/ini.go +++ b/ini.go @@ -2,7 +2,9 @@ package ini import ( "bufio" + "fmt" "io" + "reflect" "strings" ) @@ -13,6 +15,32 @@ 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 @@ -95,48 +123,6 @@ type Parser struct { isEnd bool } -// Attempts to write `entries` to `writer`, returning any error that occured during writing. -func Write(writer io.StringWriter, entries []Entry) error { - // TODO: Not happy with this solution to writing files, needs more revision. - var section = "" - - for _, entry := range entries { - if entry.Section != section { - if _, writeError := writer.WriteString("\n["); writeError != nil { - return writeError - } - - if _, writeError := writer.WriteString(entry.Section); writeError != nil { - return writeError - } - - if _, writeError := writer.WriteString("]\n"); writeError != nil { - return writeError - } - - section = entry.Section - } - - if _, writeError := writer.WriteString(entry.Key); writeError != nil { - return writeError - } - - if _, writeError := writer.WriteString(" = "); writeError != nil { - return writeError - } - - if _, writeError := writer.WriteString(entry.Value); writeError != nil { - return writeError - } - - if _, writeError := writer.WriteString("\n"); writeError != nil { - return writeError - } - } - - return nil -} - // Returns a string with the the outer-most quotes surrounding `s` trimmed, should they exist. func unquote(s string) string { var sLen = len(s)