feat(encode): write the TOML 1.1 output form
Assisted-by: DeepSeek V4.1 Flash
This commit is contained in:
+28
-15
@@ -28,29 +28,42 @@ type LocalDate struct{ time.Time }
|
||||
type LocalTime struct{ time.Time }
|
||||
|
||||
// String returns the TOML-canonical rendering of the local date-time, e.g.
|
||||
// "1979-05-27T07:32:00" or "...:00.000000123" when the time has a fractional
|
||||
// second. The fractional component is zero-padded to nanosecond precision.
|
||||
// "1979-05-27T07:32" or "1979-05-27T07:32:00.5" when the time carries a
|
||||
// fractional second. TOML 1.1 makes the seconds optional, so they appear only
|
||||
// when they are non-zero, and a fraction drops its trailing zeros.
|
||||
func (ldt LocalDateTime) String() string {
|
||||
base := ldt.Format("2006-01-02T15:04:05")
|
||||
if ns := ldt.Nanosecond(); ns > 0 {
|
||||
return base + "." + fmt.Sprintf("%09d", ns)
|
||||
}
|
||||
return base
|
||||
return ldt.Format("2006-01-02T") + clockString(ldt.Time)
|
||||
}
|
||||
|
||||
// String returns the TOML-canonical rendering of the local date, e.g.
|
||||
// "1979-05-27".
|
||||
func (ld LocalDate) String() string { return ld.Format("2006-01-02") }
|
||||
|
||||
// String returns the TOML-canonical rendering of the local time, e.g.
|
||||
// "07:32:00" or "...:00.000000123" when the time has a fractional second.
|
||||
// The fractional component is zero-padded to nanosecond precision.
|
||||
func (lt LocalTime) String() string {
|
||||
base := lt.Format("15:04:05")
|
||||
if ns := lt.Nanosecond(); ns > 0 {
|
||||
return base + "." + fmt.Sprintf("%09d", ns)
|
||||
// String returns the TOML-canonical rendering of the local time, e.g. "07:32"
|
||||
// or "07:32:00.5" when the time carries a fractional second.
|
||||
func (lt LocalTime) String() string { return clockString(lt.Time) }
|
||||
|
||||
// clockString renders a time of day the way TOML writes it: the seconds appear
|
||||
// only when the value carries them, and a fractional second drops its trailing
|
||||
// zeros, so half a second is "00.5" and not "00.500000000". Both are the same
|
||||
// value either way; the shorter form is the one TOML 1.1 allows.
|
||||
func clockString(t time.Time) string {
|
||||
out := t.Format("15:04")
|
||||
ns := t.Nanosecond()
|
||||
if t.Second() != 0 || ns != 0 {
|
||||
out += t.Format(":05")
|
||||
}
|
||||
return base
|
||||
if ns > 0 {
|
||||
out += "." + strings.TrimRight(fmt.Sprintf("%09d", ns), "0")
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// offsetString renders an offset date-time, the fourth TOML kind, in the same
|
||||
// shape: no zero seconds, no trailing zeros in the fraction, and the offset
|
||||
// written as "Z" when it is zero.
|
||||
func offsetString(t time.Time) string {
|
||||
return t.Format("2006-01-02T") + clockString(t) + t.Format("Z07:00")
|
||||
}
|
||||
|
||||
var (
|
||||
|
||||
Reference in New Issue
Block a user