]> Cypherpunks repositories - gostls13.git/commitdiff
time: add Time.AppendFormat
authorCaleb Spare <cespare@gmail.com>
Thu, 18 Dec 2014 04:18:06 +0000 (17:18 +1300)
committerRob Pike <r@golang.org>
Fri, 10 Apr 2015 20:18:22 +0000 (20:18 +0000)
This is a version of Time.Format that doesn't require allocation.

This is an updated version of 0af302f50745b93e90a4507993a555d246acef45
submitted by @bradfitz which was later rolled back.

Fixes #5192
Updates #5195

Change-Id: I4e6255bee1cf3914a6cc8d9d2a881cfeb273c08e
Reviewed-on: https://go-review.googlesource.com/1760
Reviewed-by: Rob Pike <r@golang.org>
src/time/format.go

index e6d5ac6dfb334f3349e8eb52bd564e8f970c9cea..b15101e16051cfbdd37aa94eaa973e18405d1d89 100644 (file)
@@ -410,6 +410,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.AppendFormat(b, layout)
+       return string(b)
+}
+
+// AppendFormat is like Format but appends the textual
+// representation to b and returns the extended buffer.
+func (t Time) AppendFormat(b []byte, layout string) []byte {
        var (
                name, offset, abs = t.locabs()
 
@@ -419,16 +435,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)
@@ -568,7 +575,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