diff options
author | Rob Pike <r@golang.org> | 2010-09-27 12:06:29 -0700 |
---|---|---|
committer | Rob Pike <r@golang.org> | 2010-09-27 12:06:29 -0700 |
commit | b4e358d7e1d06f0d3e3ba5582e046c98c57e715d (patch) | |
tree | 6182b8e18be23a2bc6dff322afe9120f31744c44 | |
parent | 2d5e732c545cb01bc59d4aa4f3ab27d298cf3f72 (diff) | |
download | go-b4e358d7e1d06f0d3e3ba5582e046c98c57e715d.tar.gz go-b4e358d7e1d06f0d3e3ba5582e046c98c57e715d.zip |
utf8.String: provide an Init method to avoid unnecessary allocation
when creating an array of Strings.
R=rsc
CC=golang-dev
https://golang.org/cl/2267046
-rw-r--r-- | src/pkg/utf8/string.go | 25 |
1 files changed, 17 insertions, 8 deletions
diff --git a/src/pkg/utf8/string.go b/src/pkg/utf8/string.go index 59107ac19d..83b56b9448 100644 --- a/src/pkg/utf8/string.go +++ b/src/pkg/utf8/string.go @@ -25,20 +25,29 @@ type String struct { // NewString returns a new UTF-8 string with the provided contents. func NewString(contents string) *String { + return new(String).Init(contents) +} + +// Init initializes an existing String to hold the provided contents. +// It returns a pointer to the initialized String. +func (s *String) Init(contents string) *String { + s.str = contents + s.bytePos = 0 + s.runePos = 0 for i := 0; i < len(contents); i++ { if contents[i] >= RuneSelf { // Not ASCII. - _, wid := DecodeRuneInString(contents) - return &String{ - str: contents, - numRunes: RuneCountInString(contents), - width: wid, - nonASCII: i, - } + s.numRunes = RuneCountInString(contents) + _, s.width = DecodeRuneInString(contents) + s.nonASCII = i + return s } } // ASCII is simple. Also, the empty string is ASCII. - return &String{str: contents, numRunes: len(contents), nonASCII: len(contents)} + s.numRunes = len(contents) + s.width = 0 + s.nonASCII = len(contents) + return s } // String returns the contents of the String. This method also means the |