go-multiaddr/codec.go

97 lines
1.6 KiB
Go
Raw Normal View History

2014-07-04 06:42:24 +00:00
package multiaddr
2014-07-04 18:21:39 +00:00
import (
"encoding/binary"
"fmt"
"net"
"strconv"
"strings"
2014-07-04 06:42:24 +00:00
)
func StringToBytes(s string) ([]byte, error) {
2014-07-04 18:21:39 +00:00
b := []byte{}
sp := strings.Split(s, "/")
2014-07-04 06:42:24 +00:00
2014-07-04 18:21:39 +00:00
// consume first empty elem
sp = sp[1:]
2014-07-04 06:42:24 +00:00
2014-07-04 18:21:39 +00:00
for len(sp) > 0 {
p := ProtocolWithName(sp[0])
if p == nil {
return nil, fmt.Errorf("no protocol with name %s", sp[0])
}
b = append(b, byte(p.Code))
2014-07-04 06:42:24 +00:00
2014-07-04 18:21:39 +00:00
a := AddressStringToBytes(p, sp[1])
b = append(b, a...)
2014-07-04 06:42:24 +00:00
2014-07-04 18:21:39 +00:00
sp = sp[2:]
}
return b, nil
2014-07-04 06:42:24 +00:00
}
2014-07-04 06:52:58 +00:00
func BytesToString(b []byte) (ret string, err error) {
2014-07-04 18:21:39 +00:00
// panic handler, in case we try accessing bytes incorrectly.
defer func() {
if e := recover(); e != nil {
ret = ""
err = e.(error)
}
}()
s := ""
for len(b) > 0 {
p := ProtocolWithCode(int(b[0]))
if p == nil {
return "", fmt.Errorf("no protocol with code %d", b[0])
}
s = strings.Join([]string{s, "/", p.Name}, "")
b = b[1:]
a := AddressBytesToString(p, b[:(p.Size/8)])
if len(a) > 0 {
s = strings.Join([]string{s, "/", a}, "")
}
b = b[(p.Size / 8):]
}
return s, nil
2014-07-04 06:42:24 +00:00
}
2014-07-04 06:44:09 +00:00
func AddressStringToBytes(p *Protocol, s string) []byte {
2014-07-04 18:21:39 +00:00
switch p.Code {
// ipv4,6
case 4, 41:
return net.ParseIP(s).To4()
// tcp udp dccp sctp
case 6, 17, 33, 132:
b := make([]byte, 2)
i, err := strconv.Atoi(s)
if err == nil {
binary.BigEndian.PutUint16(b, uint16(i))
}
return b
}
return []byte{}
2014-07-04 06:44:09 +00:00
}
func AddressBytesToString(p *Protocol, b []byte) string {
2014-07-04 18:21:39 +00:00
switch p.Code {
2014-07-04 06:44:09 +00:00
2014-07-04 18:21:39 +00:00
// ipv4,6
case 4, 41:
return net.IP(b).String()
2014-07-04 06:44:09 +00:00
2014-07-04 18:21:39 +00:00
// tcp udp dccp sctp
case 6, 17, 33, 132:
i := binary.BigEndian.Uint16(b)
return strconv.Itoa(int(i))
}
2014-07-04 06:44:09 +00:00
2014-07-04 18:21:39 +00:00
return ""
2014-07-04 06:44:09 +00:00
}