Skip to content

Commit

Permalink
Merge pull request #57 from xackery/master
Browse files Browse the repository at this point in the history
Added SetJSONIndent to Encoder
  • Loading branch information
qmuntal committed Jul 11, 2022
2 parents 3645050 + 98b59d0 commit 3ea49a1
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
11 changes: 11 additions & 0 deletions encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ type Encoder struct {
AsBinary bool
Fsys CreateFS
w io.Writer
indent string
prefix string
}

// NewEncoder returns a new encoder that writes to w as a normal glTF file.
Expand All @@ -79,6 +81,12 @@ func NewEncoderFS(w io.Writer, fsys CreateFS) *Encoder {
}
}

// SetJSONIndent sets json encoded data to have provided prefix and indent settings
func (e *Encoder) SetJSONIndent(prefix string, indent string) {
e.prefix = prefix
e.indent = indent
}

// Encode writes the encoding of doc to the stream.
func (e *Encoder) Encode(doc *Document) error {
var err error
Expand Down Expand Up @@ -217,6 +225,9 @@ func (e *Encoder) marshalJSONDoc(doc *Document) ([]byte, error) {
tmp.CustomBuffers[i] = buf
}
}
if len(e.prefix) > 0 || len(e.indent) > 0 {
return json.MarshalIndent(tmp, e.prefix, e.indent)
}
return json.Marshal(tmp)
}

Expand Down
27 changes: 27 additions & 0 deletions encode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,19 @@ func saveMemory(doc *Document, asBinary bool) (*Decoder, error) {
return NewDecoderFS(buff, m), nil
}

func saveMemoryIndent(doc *Document, asBinary bool) (*Decoder, error) {
buff := new(bytes.Buffer)
m := mockChunkReadHandler{fstest.MapFS{}}
e := NewEncoderFS(buff, m)
e.AsBinary = asBinary
e.SetJSONIndent("", "\t")
if err := e.Encode(doc); err != nil {
return nil, err
}

return NewDecoderFS(buff, m), nil
}

func TestEncoder_Encode_AsBinary_WithoutBuffer(t *testing.T) {
doc := &Document{}
buff := new(bytes.Buffer)
Expand Down Expand Up @@ -243,6 +256,20 @@ func TestEncoder_Encode(t *testing.T) {
return
}
}

d, err = saveMemoryIndent(tt.args.doc, method == "binary")
if (err != nil) != tt.wantErr {
t.Errorf("Encoder.Encode() withIndent error = %v, wantErr %v", err, tt.wantErr)
return
}
if !tt.wantErr {
doc := new(Document)
d.Decode(doc)
if diff := deep.Equal(doc, tt.args.doc); diff != nil {
t.Errorf("Encoder.Encode() withIndent = %v", diff)
return
}
}
})
}
}
Expand Down

0 comments on commit 3ea49a1

Please sign in to comment.