【Golang源碼閱讀】strings/builder.go

// Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package strings

import (
	"unicode/utf8"
	"unsafe"
)

// Builder用於使用Write方法有效地構建字符串。它最大限度地減小了內存的複製。零值可以使用。不要複製非零的Builer。
type Builder struct {
	addr *Builder // of receiver, to detect copies by value
	buf  []byte
}

// noescape 在逃逸分析中隱藏了一個指針。 noescape 是恆等函數,但轉義分析並不認爲輸出取決於輸入。 noescape 是內聯的,目前編譯爲零指令。
func noescape(p unsafe.Pointer) unsafe.Pointer {
	x := uintptr(p)
	return unsafe.Pointer(x ^ 0)
}

func (b *Builder) copyCheck() {
	if b.addr == nil {
		// 這個 hack 解決了 Go 的逃逸分析失敗,致使 b 逃逸並被堆分配。
		b.addr = (*Builder)(noescape(unsafe.Pointer(b)))
	} else if b.addr != b {
		panic("strings: illegal use of non-zero Builder copied by value")
	}
}

// String 返回累積的字符串。
func (b *Builder) String() string {
	return *(*string)(unsafe.Pointer(&b.buf))
}

// Len 返回累積的字節數; b.Len() == len(b.String())。
func (b *Builder) Len() int { return len(b.buf) }

// Cap 返回構建器底層字節切片的容量。 它是爲正在構建的字符串分配的總空間,包括已寫入的任何字節。
func (b *Builder) Cap() int { return cap(b.buf) }

// Reset 將Builder重置爲空。
func (b *Builder) Reset() {
	b.addr = nil
	b.buf = nil
}

// grow 將緩衝區複製到一個新的更大的緩衝區,以便至少有 n 個字節的容量超出 len(b.buf)。
func (b *Builder) grow(n int) {
	buf := make([]byte, len(b.buf), 2*cap(b.buf)+n)
	copy(buf, b.buf)
	b.buf = buf
}

// 若有必要,Grow會增長b的容量,以保證另外n個字節的空間。 在Grow(n)以後,至少能夠將n個字節寫入 b 而無需其餘分配。 若是n爲負,則panic。
func (b *Builder) Grow(n int) {
	b.copyCheck()
	if n < 0 {
		panic("strings.Builder.Grow: negative count")
	}
	if cap(b.buf)-len(b.buf) < n {
		b.grow(n)
	}
}

// Write 將 p 的內容附加到 b 的緩衝區。 Write 老是返回 len(p), nil。
func (b *Builder) Write(p []byte) (int, error) {
	b.copyCheck()
	b.buf = append(b.buf, p...)
	return len(p), nil
}

// WriteByte 將字節 c 附加到 b 的緩衝區。 返回的錯誤始終爲nil。
func (b *Builder) WriteByte(c byte) error {
	b.copyCheck()
	b.buf = append(b.buf, c)
	return nil
}


// WriteRune 將 Unicode 代碼點 r 的 UTF-8 編碼附加到 b 的緩衝區。它返回 r 的長度和一個nil錯誤。
func (b *Builder) WriteRune(r rune) (int, error) {
	b.copyCheck()
	if r < utf8.RuneSelf {
		b.buf = append(b.buf, byte(r))
		return 1, nil
	}
	l := len(b.buf)
	if cap(b.buf)-l < utf8.UTFMax {
		b.grow(utf8.UTFMax)
	}
	n := utf8.EncodeRune(b.buf[l:l+utf8.UTFMax], r)
	b.buf = b.buf[:l+n]
	return n, nil
}

// WriteString 將 s 的內容附加到 b 的緩衝區。它返回 s 的長度和一個nil錯誤。
func (b *Builder) WriteString(s string) (int, error) {
	b.copyCheck()
	b.buf = append(b.buf, s...)
	return len(s), nil
}
相關文章
相關標籤/搜索