From b36209c9a4398f3fa56a8019038c474dfc0ed5e9 Mon Sep 17 00:00:00 2001 From: Alexander Pevzner Date: Sat, 22 Jun 2024 16:44:50 +0300 Subject: [PATCH] Formatter: one more fix of formatting of 1SetOf Collection --- formatter.go | 24 +++++++++++++++--------- formatter_test.go | 18 +++++++++--------- 2 files changed, 24 insertions(+), 18 deletions(-) diff --git a/formatter.go b/formatter.go index c4aac61..0735d5e 100644 --- a/formatter.go +++ b/formatter.go @@ -173,17 +173,19 @@ func (f *Formatter) fmtAttributeOrMember(attr Attribute, member bool) { } tag := TagZero - for i, val := range attr.Values { + for _, val := range attr.Values { if val.T != tag { fmt.Fprintf(buf, " %s:", val.T) tag = val.T } if collection, ok := val.V.(Collection); ok { - if i == 0 { - buf.WriteByte(' ') + if f.onNL() { + f.Printf("{") + } else { + buf.Write([]byte(" {\n")) } - buf.Write([]byte("{\n")) + f.indent++ for _, attr2 := range collection { @@ -200,12 +202,16 @@ func (f *Formatter) fmtAttributeOrMember(attr Attribute, member bool) { f.forceNL() } -// forceNL inserts newline character, text is not empty and the last -// character is not yet newline (i.e., if Formatter is not at the -// beginning of the new line). -func (f *Formatter) forceNL() { +// onNL returns true if formatter is at the beginning of new line +func (f *Formatter) onNL() bool { b := f.buf.Bytes() - if len(b) > 0 && b[len(b)-1] != '\n' { + return len(b) == 0 || b[len(b)-1] == '\n' +} + +// forceNL inserts newline character if formatter is not at the +// beginning of new line +func (f *Formatter) forceNL() { + if !f.onNL() { f.buf.WriteByte('\n') } } diff --git a/formatter_test.go b/formatter_test.go index def9574..87c9c56 100644 --- a/formatter_test.go +++ b/formatter_test.go @@ -95,16 +95,16 @@ func TestFmtAttribute(t *testing.T) { TagInteger, Integer(20990)), }, ), - + indent: 2, out: []string{ - `ATTR "media-size-supported" collection: {`, - ` MEMBER "x-dimension" integer: 20990`, - ` MEMBER "y-dimension" integer: 29704`, - `}`, - `{`, - ` MEMBER "x-dimension" integer: 14852`, - ` MEMBER "y-dimension" integer: 20990`, - `}`, + ` ATTR "media-size-supported" collection: {`, + ` MEMBER "x-dimension" integer: 20990`, + ` MEMBER "y-dimension" integer: 29704`, + ` }`, + ` {`, + ` MEMBER "x-dimension" integer: 14852`, + ` MEMBER "y-dimension" integer: 20990`, + ` }`, }, },