summaryrefslogtreecommitdiff
path: root/vendor/github.com/pquerna/ffjson/inception/writerstack.go
blob: 1521961c9451488a79db687462949ae25107be4e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package ffjsoninception

import "strings"

// ConditionalWrite is a stack containing a number of pending writes
type ConditionalWrite struct {
	Queued []string
}

// Write will add a string to be written
func (w *ConditionalWrite) Write(s string) {
	w.Queued = append(w.Queued, s)
}

// DeleteLast will delete the last added write
func (w *ConditionalWrite) DeleteLast() {
	if len(w.Queued) == 0 {
		return
	}
	w.Queued = w.Queued[:len(w.Queued)-1]
}

// Last will return the last added write
func (w *ConditionalWrite) Last() string {
	if len(w.Queued) == 0 {
		return ""
	}
	return w.Queued[len(w.Queued)-1]
}

// Flush will return all queued writes, and return
// "" (empty string) in nothing has been queued
// "buf.WriteByte('" + byte + "')" + '\n' if one bute has been queued.
// "buf.WriteString(`" + string + "`)" + "\n" if more than one byte has been queued.
func (w *ConditionalWrite) Flush() string {
	combined := strings.Join(w.Queued, "")
	if len(combined) == 0 {
		return ""
	}

	w.Queued = nil
	if len(combined) == 1 {
		return "buf.WriteByte('" + combined + "')" + "\n"
	}
	return "buf.WriteString(`" + combined + "`)" + "\n"
}

func (w *ConditionalWrite) FlushTo(out string) string {
	out += w.Flush()
	return out
}

// WriteFlush will add a string and return the Flush result for the queue
func (w *ConditionalWrite) WriteFlush(s string) string {
	w.Write(s)
	return w.Flush()
}

// GetQueued will return the current queued content without flushing.
func (w *ConditionalWrite) GetQueued() string {
	t := w.Queued
	s := w.Flush()
	w.Queued = t
	return s
}