mirror of
https://github.com/walles/moar.git
synced 2024-09-11 12:15:43 +03:00
Implement our string builder
This commit is contained in:
parent
18bd350dab
commit
78344d1761
@ -1,16 +1,32 @@
|
|||||||
package m
|
package m
|
||||||
|
|
||||||
|
import "unicode/utf8"
|
||||||
|
|
||||||
type reusableStringBuilder struct {
|
type reusableStringBuilder struct {
|
||||||
|
buf []byte
|
||||||
|
length int // Number of used bytes in buf
|
||||||
}
|
}
|
||||||
|
|
||||||
func (rsb reusableStringBuilder) Reset() {
|
func (rsb *reusableStringBuilder) Reset() {
|
||||||
panic("Unimplemented")
|
rsb.length = 0
|
||||||
}
|
}
|
||||||
|
|
||||||
func (rsb reusableStringBuilder) WriteRune(char rune) {
|
// Inspired by the source code of strings.Builder
|
||||||
panic("Unimplemented")
|
func (rsb *reusableStringBuilder) WriteRune(r rune) {
|
||||||
|
availableBytes := cap(rsb.buf) - rsb.length
|
||||||
|
if availableBytes < utf8.UTFMax {
|
||||||
|
newLength := 2*cap(rsb.buf) + utf8.UTFMax
|
||||||
|
newBuf := make([]byte, newLength)
|
||||||
|
for i := 0; i < rsb.length; i++ {
|
||||||
|
newBuf[i] = rsb.buf[i]
|
||||||
|
}
|
||||||
|
rsb.buf = newBuf
|
||||||
|
}
|
||||||
|
|
||||||
|
encodedBytesCount := utf8.EncodeRune(rsb.buf[rsb.length:rsb.length+utf8.UTFMax], r)
|
||||||
|
rsb.length += encodedBytesCount
|
||||||
}
|
}
|
||||||
|
|
||||||
func (rsb reusableStringBuilder) String() string {
|
func (rsb *reusableStringBuilder) String() string {
|
||||||
panic("Unimplemented")
|
return string(rsb.buf[0:rsb.length])
|
||||||
}
|
}
|
||||||
|
@ -15,6 +15,10 @@ func TestReusableStringBuilder_Basics(t *testing.T) {
|
|||||||
|
|
||||||
testMe.Reset()
|
testMe.Reset()
|
||||||
assert.Equal(t, "", testMe.String())
|
assert.Equal(t, "", testMe.String())
|
||||||
|
|
||||||
|
// Reset again to make sure it works when empty
|
||||||
|
testMe.Reset()
|
||||||
|
assert.Equal(t, "", testMe.String())
|
||||||
}
|
}
|
||||||
|
|
||||||
// Ensure the strings returned by our builder are real, rather than just being
|
// Ensure the strings returned by our builder are real, rather than just being
|
||||||
@ -32,3 +36,18 @@ func TestReusableStringBuilder_Copies(t *testing.T) {
|
|||||||
assert.Equal(t, s1, "a")
|
assert.Equal(t, s1, "a")
|
||||||
assert.Equal(t, s2, "b")
|
assert.Equal(t, s2, "b")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestReusableStringBuilder_AddMultiple(t *testing.T) {
|
||||||
|
testMe := reusableStringBuilder{}
|
||||||
|
|
||||||
|
// Should be more than utf8.UTFMax = 4 to force one expansion when we
|
||||||
|
// already have data
|
||||||
|
testMe.WriteRune('a')
|
||||||
|
testMe.WriteRune('b')
|
||||||
|
testMe.WriteRune('c')
|
||||||
|
testMe.WriteRune('d')
|
||||||
|
testMe.WriteRune('e')
|
||||||
|
testMe.WriteRune('f')
|
||||||
|
|
||||||
|
assert.Equal(t, testMe.String(), "abcdef")
|
||||||
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user