-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
move the unrelated "Joiner" out of "js_printer"
- Loading branch information
Showing
3 changed files
with
64 additions
and
61 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
package helpers | ||
|
||
// This provides an efficient way to join lots of big string and byte slices | ||
// together. It avoids the cost of repeatedly reallocating as the buffer grows | ||
// by measuring exactly how big the buffer should be and then allocating once. | ||
// This is a measurable speedup. | ||
type Joiner struct { | ||
lastByte byte | ||
strings []joinerString | ||
bytes []joinerBytes | ||
length uint32 | ||
} | ||
|
||
type joinerString struct { | ||
data string | ||
offset uint32 | ||
} | ||
|
||
type joinerBytes struct { | ||
data []byte | ||
offset uint32 | ||
} | ||
|
||
func (j *Joiner) AddString(data string) { | ||
if len(data) > 0 { | ||
j.lastByte = data[len(data)-1] | ||
} | ||
j.strings = append(j.strings, joinerString{data, j.length}) | ||
j.length += uint32(len(data)) | ||
} | ||
|
||
func (j *Joiner) AddBytes(data []byte) { | ||
if len(data) > 0 { | ||
j.lastByte = data[len(data)-1] | ||
} | ||
j.bytes = append(j.bytes, joinerBytes{data, j.length}) | ||
j.length += uint32(len(data)) | ||
} | ||
|
||
func (j *Joiner) LastByte() byte { | ||
return j.lastByte | ||
} | ||
|
||
func (j *Joiner) Length() uint32 { | ||
return j.length | ||
} | ||
|
||
func (j *Joiner) Done() []byte { | ||
buffer := make([]byte, j.length) | ||
for _, item := range j.strings { | ||
copy(buffer[item.offset:], item.data) | ||
} | ||
for _, item := range j.bytes { | ||
copy(buffer[item.offset:], item.data) | ||
} | ||
return buffer | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters