From b9236d654833adfd461219fa685bbb0912f593a8 Mon Sep 17 00:00:00 2001 From: Charlie Doern Date: Tue, 5 Jul 2022 21:38:56 -0400 Subject: [PATCH 1/2] add support for struct entities in `MakeVariant` currently, structs are not parsed properly since `format()` has no handling for the reflect type add a switch case to handle structs and encode some sane defaults if given an empty one resolves #328 Signed-off-by: Charlie Doern --- variant.go | 18 +++++++++++++++++- variant_test.go | 6 ++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/variant.go b/variant.go index ca3dbe1..cea77fb 100644 --- a/variant.go +++ b/variant.go @@ -73,7 +73,7 @@ func (v Variant) format() (string, bool) { } rv := reflect.ValueOf(v.value) switch rv.Kind() { - case reflect.Slice: + case reflect.Slice, reflect.Array: if rv.Len() == 0 { return "[]", false } @@ -119,6 +119,22 @@ func (v Variant) format() (string, bool) { } buf.WriteByte('}') return buf.String(), unamb + case reflect.Struct: + if rv.NumField() == 0 { + return "()", false + } + unamb := true + var buf bytes.Buffer + buf.WriteByte('(') + for i := 0; i < rv.NumField(); i++ { + s, b := MakeVariant(rv.Field(i).Interface()).format() + unamb = unamb && b + buf.WriteString(s) + buf.WriteString(", ") + } + buf.WriteByte(')') + return buf.String(), unamb + } return `"INVALID"`, true } diff --git a/variant_test.go b/variant_test.go index 23ac645..72153b6 100644 --- a/variant_test.go +++ b/variant_test.go @@ -5,10 +5,16 @@ import ( "testing" ) +type Testing struct { + First string + Second uint64 +} + var variantFormatTests = []struct { v interface{} s string }{ + {[]Testing{{First: "testing", Second: 123}}, "@a(st) [(\"testing\", 123,)]"}, {int32(1), `1`}, {"foo", `"foo"`}, {ObjectPath("/org/foo"), `@o "/org/foo"`}, From 85e276eef47ebe037317189aa2fe468e764735d5 Mon Sep 17 00:00:00 2001 From: Georg Reinke Date: Sat, 9 Nov 2024 14:24:42 +0100 Subject: [PATCH 2/2] variant: don't output unneeded space when formatting structs --- variant.go | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/variant.go b/variant.go index cea77fb..93a2ee8 100644 --- a/variant.go +++ b/variant.go @@ -130,7 +130,10 @@ func (v Variant) format() (string, bool) { s, b := MakeVariant(rv.Field(i).Interface()).format() unamb = unamb && b buf.WriteString(s) - buf.WriteString(", ") + buf.WriteString(",") + if i != rv.NumField()-1 { + buf.WriteString(" ") + } } buf.WriteByte(')') return buf.String(), unamb