Oid: use Go's conversion functions

Go already has all the necessary pieces for encoding and decoding hex
strings. Using them let's us avoid going into C land.

Benchmarks show this takes about half the time as using libgit2's
functions.
This commit is contained in:
Carlos Martín Nieto 2014-03-19 03:39:34 +01:00
parent c243c31f7d
commit 0bb73e43a8
1 changed files with 12 additions and 12 deletions

24
git.go
View File

@ -8,6 +8,7 @@ package git
import "C" import "C"
import ( import (
"bytes" "bytes"
"encoding/hex"
"errors" "errors"
"runtime" "runtime"
"strings" "strings"
@ -52,24 +53,23 @@ func (oid *Oid) toC() *C.git_oid {
} }
func NewOid(s string) (*Oid, error) { func NewOid(s string) (*Oid, error) {
o := new(Oid) if len(s) > C.GIT_OID_HEXSZ {
cs := C.CString(s) return nil, errors.New("string is too long for oid")
defer C.free(unsafe.Pointer(cs))
runtime.LockOSThread()
defer runtime.UnlockOSThread()
if ret := C.git_oid_fromstr(o.toC(), cs); ret < 0 {
return nil, MakeGitError(ret)
} }
o := new(Oid)
slice, error := hex.DecodeString(s)
if error != nil {
return nil, error
}
copy(o[:], slice[:20])
return o, nil return o, nil
} }
func (oid *Oid) String() string { func (oid *Oid) String() string {
buf := make([]byte, 40) return hex.EncodeToString(oid[:])
C.git_oid_fmt((*C.char)(unsafe.Pointer(&buf[0])), oid.toC())
return string(buf)
} }
func (oid *Oid) Cmp(oid2 *Oid) int { func (oid *Oid) Cmp(oid2 *Oid) int {