]> Cypherpunks repositories - gostls13.git/commitdiff
time: add Time.FormatAppend
authorBrad Fitzpatrick <bradfitz@golang.org>
Thu, 16 May 2013 00:23:40 +0000 (17:23 -0700)
committerBrad Fitzpatrick <bradfitz@golang.org>
Thu, 16 May 2013 00:23:40 +0000 (17:23 -0700)
This is a version of Time.Format that doesn't require allocation.

Fixes #5192
Update #5195

R=r
CC=gobot, golang-dev
https://golang.org/cl/8478044

src/pkg/time/format.go

index 7fe0402312f1ea0bd7ca83eecdecac13cbe7386c..e40911aa5358d04000b251d47095471f0a12dee3 100644 (file)
@@ -380,6 +380,22 @@ func (t Time) String() string {
 // about the formats and the definition of the reference time, see the
 // documentation for ANSIC and the other constants defined by this package.
 func (t Time) Format(layout string) string {
+       const bufSize = 64
+       var b []byte
+       max := len(layout) + 10
+       if max <= bufSize {
+               var buf [bufSize]byte
+               b = buf[:0]
+       } else {
+               b = make([]byte, 0, max)
+       }
+       b = t.FormatAppend(layout, b)
+       return string(b)
+}
+
+// FormatAppend works like Format but appends the textual
+// representation to b and returns the extended buffer.
+func (t Time) FormatAppend(layout string, b []byte) []byte {
        var (
                name, offset, abs = t.locabs()
 
@@ -389,16 +405,7 @@ func (t Time) Format(layout string) string {
                hour  int = -1
                min   int
                sec   int
-
-               b   []byte
-               buf [64]byte
        )
-       max := len(layout) + 10
-       if max <= len(buf) {
-               b = buf[:0]
-       } else {
-               b = make([]byte, 0, max)
-       }
        // Each iteration generates one std value.
        for layout != "" {
                prefix, std, suffix := nextStdChunk(layout)
@@ -546,7 +553,7 @@ func (t Time) Format(layout string) string {
                        b = formatNano(b, uint(t.Nanosecond()), std>>stdArgShift, std&stdMask == stdFracSecond9)
                }
        }
-       return string(b)
+       return b
 }
 
 var errBad = errors.New("bad value for field") // placeholder not passed to user