Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

avoid fmt.Sprintf and string alloc for time.Sql #2782

Merged
merged 3 commits into from
Dec 6, 2024
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 41 additions & 8 deletions sql/types/time.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
package types

import (
"fmt"
"math"
"reflect"
"strconv"
Expand Down Expand Up @@ -263,7 +262,7 @@ func (t TimespanType_) Promote() sql.Type {
}

// SQL implements Type interface.
func (t TimespanType_) SQL(ctx *sql.Context, dest []byte, v interface{}) (sqltypes.Value, error) {
func (t TimespanType_) SQL(_ *sql.Context, dest []byte, v interface{}) (sqltypes.Value, error) {
if v == nil {
return sqltypes.NULL, nil
}
Expand All @@ -272,7 +271,7 @@ func (t TimespanType_) SQL(ctx *sql.Context, dest []byte, v interface{}) (sqltyp
return sqltypes.Value{}, err
}

val := AppendAndSliceString(dest, ti.String())
val := AppendAndSliceBytes(dest, ti.Bytes())

return sqltypes.MakeTrusted(sqltypes.Time, val), nil
}
Expand Down Expand Up @@ -463,15 +462,49 @@ func (t Timespan) timespanToUnits() (isNegative bool, hours int16, minutes int8,

// String returns the Timespan formatted as a string (such as for display purposes).
func (t Timespan) String() string {
return string(t.Bytes())
}

func (t Timespan) Bytes() []byte {
isNegative, hours, minutes, seconds, microseconds := t.timespanToUnits()
sign := ""
ret := make([]byte, 1000)
i := 0
if isNegative {
sign = "-"
ret[0] = '-'
i++
}

i = printDigit(int64(hours), 2, ret, i)
ret[i] = ':'
i++
i = printDigit(int64(minutes), 2, ret, i)
ret[i] = ':'
i++
i = printDigit(int64(seconds), 2, ret, i)
if microseconds > 0 {
ret[i] = '.'
i++
i = printDigit(int64(microseconds), 6, ret, i)
}

return ret[:i]
}

func printDigit(v int64, extend int, buf []byte, i int) int {
cmp := int64(1)
for _ = range extend - 1 {
cmp *= 10
}
for cmp > 0 && v < cmp {
buf[i] = '0'
i++
cmp /= 10
}
if microseconds == 0 {
return fmt.Sprintf("%v%02d:%02d:%02d", sign, hours, minutes, seconds)
if v == 0 {
return i
}
return fmt.Sprintf("%v%02d:%02d:%02d.%06d", sign, hours, minutes, seconds, microseconds)
tmpBuf := strconv.AppendInt(buf[i:i], v, 10)
return i + len(tmpBuf)
}

// AsMicroseconds returns the Timespan in microseconds.
Expand Down
Loading