♻️ Add tools.WriteValue

This commit is contained in:
Dan Jones 2024-03-03 13:56:48 -06:00
commit 286ac4557d
4 changed files with 97 additions and 31 deletions

View file

@ -2,12 +2,9 @@ package models
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"regexp"
"strconv"
"time"
"codeberg.org/danjones000/my-log/tools"
)
@ -25,33 +22,9 @@ func (m Meta) MarshalText() ([]byte, error) {
buff.WriteRune('@')
buff.WriteString(m.Key)
buff.WriteRune(' ')
switch v := m.Value.(type) {
default:
return nil, fmt.Errorf("Unknown type %T", v)
case nil:
return []byte{}, nil
case string:
buff.WriteString(v)
case int:
buff.WriteString(strconv.Itoa(v))
case int64:
buff.WriteString(strconv.FormatInt(v, 10))
case float64:
buff.WriteString(strconv.FormatFloat(v, 'f', -1, 64))
case json.Number:
buff.WriteString(v.String())
case json.RawMessage:
buff.Write(v)
case []byte:
buff.Write(v)
case byte:
buff.WriteByte(v)
case rune:
buff.WriteString(string(v))
case bool:
buff.WriteString(strconv.FormatBool(v))
case time.Time:
buff.WriteString(v.Format(time.RFC3339))
n, err := tools.WriteValue(buff, m.Value)
if n == 0 || err != nil {
return []byte{}, err
}
return buff.Bytes(), nil

View file

@ -40,7 +40,7 @@ func TestMeta(t *testing.T) {
{"byte", "byteme", byte(67), "@byteme C", nil, "C"},
{"json-obj", "obj", json.RawMessage(`{"foo":"bar","baz":"quux"}`), `@obj {"foo":"bar","baz":"quux"}`, nil, json.RawMessage(`{"foo":"bar","baz":"quux"}`)},
{"json-arr", "arr", json.RawMessage(`["foo",42,"bar", null,"quux", true]`), `@arr ["foo",42,"bar", null,"quux", true]`, nil, json.RawMessage(`["foo",42,"bar", null,"quux", true]`)},
{"chan", "nope", make(chan bool), "", errors.New("Unknown type chan bool"), ""},
{"chan", "nope", make(chan bool), "", errors.New("Unsupported type chan bool"), ""},
{"whitespace-key", "no space", "hi", "", errors.New("whitespace is not allowed in key: no space"), ""},
{"empty-mar", "nope", skipMarshalTest, "", nil, ErrorParsing},
{"no-key-mar", "nope", skipMarshalTest, "nope", nil, ErrorParsing},