Reduce allocs and copies

batch-wip
Jack Christensen 2017-04-29 13:21:25 -05:00
parent 932caef600
commit a5f702c41d
2 changed files with 26 additions and 15 deletions

View File

@ -118,6 +118,20 @@ func (wb *WriteBuf) closeMsg() {
binary.BigEndian.PutUint32(wb.buf[wb.sizeIdx:wb.sizeIdx+4], uint32(len(wb.buf)-wb.sizeIdx))
}
func (wb *WriteBuf) reserveSize() int {
sizePosition := len(wb.buf)
wb.buf = append(wb.buf, 0, 0, 0, 0)
return sizePosition
}
func (wb *WriteBuf) setComputedSize(sizePosition int) {
binary.BigEndian.PutUint32(wb.buf[sizePosition:], uint32(len(wb.buf)-sizePosition-4))
}
func (wb *WriteBuf) setSize(sizePosition int, size int32) {
binary.BigEndian.PutUint32(wb.buf[sizePosition:], uint32(size))
}
func (wb *WriteBuf) WriteByte(b byte) {
wb.buf = append(wb.buf, b)
}

View File

@ -106,29 +106,27 @@ func encodePreparedStatementArgument(wbuf *WriteBuf, oid pgtype.Oid, arg interfa
switch arg := arg.(type) {
case pgtype.BinaryEncoder:
buf := &bytes.Buffer{}
null, err := arg.EncodeBinary(wbuf.conn.ConnInfo, buf)
sp := wbuf.reserveSize()
null, err := arg.EncodeBinary(wbuf.conn.ConnInfo, wbuf)
if err != nil {
return err
}
if null {
wbuf.WriteInt32(-1)
wbuf.setSize(sp, -1)
} else {
wbuf.WriteInt32(int32(buf.Len()))
wbuf.WriteBytes(buf.Bytes())
wbuf.setComputedSize(sp)
}
return nil
case pgtype.TextEncoder:
buf := &bytes.Buffer{}
null, err := arg.EncodeText(wbuf.conn.ConnInfo, buf)
sp := wbuf.reserveSize()
null, err := arg.EncodeText(wbuf.conn.ConnInfo, wbuf)
if err != nil {
return err
}
if null {
wbuf.WriteInt32(-1)
wbuf.setSize(sp, -1)
} else {
wbuf.WriteInt32(int32(buf.Len()))
wbuf.WriteBytes(buf.Bytes())
wbuf.setComputedSize(sp)
}
return nil
case driver.Valuer:
@ -161,16 +159,15 @@ func encodePreparedStatementArgument(wbuf *WriteBuf, oid pgtype.Oid, arg interfa
return err
}
buf := &bytes.Buffer{}
null, err := value.(pgtype.BinaryEncoder).EncodeBinary(wbuf.conn.ConnInfo, buf)
sp := wbuf.reserveSize()
null, err := value.(pgtype.BinaryEncoder).EncodeBinary(wbuf.conn.ConnInfo, wbuf)
if err != nil {
return err
}
if null {
wbuf.WriteInt32(-1)
wbuf.setSize(sp, -1)
} else {
wbuf.WriteInt32(int32(buf.Len()))
wbuf.WriteBytes(buf.Bytes())
wbuf.setComputedSize(sp)
}
return nil
}