faster encapsulation + join

This commit is contained in:
Juan Batiz-Benet 2014-11-05 02:30:53 -08:00
parent 9d04132166
commit 62a88e015e
2 changed files with 21 additions and 12 deletions

View File

@ -84,10 +84,10 @@ func (m *multiaddr) Encapsulate(o Multiaddr) Multiaddr {
mb := m.bytes
ob := o.Bytes()
var b bytes.Buffer
b.Write(mb)
b.Write(ob)
return &multiaddr{bytes: b.Bytes()}
b := make([]byte, len(mb)+len(ob))
copy(b, mb)
copy(b[len(mb):], ob)
return &multiaddr{bytes: b}
}
// Decapsulate unwraps Multiaddr up until the given Multiaddr is found.

25
util.go
View File

@ -1,9 +1,6 @@
package multiaddr
import (
"bytes"
"fmt"
)
import "fmt"
// Split returns the sub-address portions of a multiaddr.
func Split(m Multiaddr) []Multiaddr {
@ -21,11 +18,23 @@ func Split(m Multiaddr) []Multiaddr {
// Join returns a combination of addresses.
func Join(ms ...Multiaddr) Multiaddr {
var b bytes.Buffer
for _, m := range ms {
b.Write(m.Bytes())
length := 0
bs := make([][]byte, len(ms))
for i, m := range ms {
bs[i] = m.Bytes()
length += len(bs[i])
}
return &multiaddr{bytes: b.Bytes()}
bidx := 0
b := make([]byte, length)
for _, mb := range bs {
for i := range mb {
b[bidx] = mb[i]
bidx++
}
}
return &multiaddr{bytes: b}
}
// Cast re-casts a byte slice as a multiaddr. will panic if it fails to parse.