9 func stringToBytes(s string) ([]byte, error) {
11 // consume trailing slashes
12 s = strings.TrimRight(s, "/")
15 sp := strings.Split(s, "/")
18 return nil, fmt.Errorf("invalid multiaddr, must begin with /")
21 // consume first empty elem
26 p := ProtocolWithName(name)
28 return nil, fmt.Errorf("no protocol with name %s", sp[0])
30 _, _ = b.Write(CodeToVarint(p.Code))
33 if p.Size == 0 { // no length.
38 return nil, fmt.Errorf("protocol requires address, none given: %s", name)
42 // it's a path protocol (terminal).
43 // consume the rest of the address as the next component.
44 sp = []string{"/" + strings.Join(sp, "/")}
47 a, err := p.Transcoder.StringToBytes(sp[0])
49 return nil, fmt.Errorf("failed to parse %s: %s %s", p.Name, sp[0], err)
51 if p.Size < 0 { // varint size.
52 _, _ = b.Write(CodeToVarint(len(a)))
61 func validateBytes(b []byte) (err error) {
63 code, n, err := ReadVarintCode(b)
69 p := ProtocolWithCode(code)
71 return fmt.Errorf("no protocol with code %d", code)
78 n, size, err := sizeForAddr(p, b)
85 if len(b) < size || size < 0 {
86 return fmt.Errorf("invalid value for size %d", len(b))
89 err = p.Transcoder.ValidateBytes(b[:size])
100 func readComponent(b []byte) (int, Component, error) {
102 code, n, err := ReadVarintCode(b)
104 return 0, Component{}, err
108 p := ProtocolWithCode(code)
110 return 0, Component{}, fmt.Errorf("no protocol with code %d", code)
114 return offset, Component{
121 n, size, err := sizeForAddr(p, b[offset:])
123 return 0, Component{}, err
128 if len(b[offset:]) < size || size < 0 {
129 return 0, Component{}, fmt.Errorf("invalid value for size %d", len(b[offset:]))
132 return offset + size, Component{
133 bytes: b[:offset+size],
139 func bytesToString(b []byte) (ret string, err error) {
140 var buf strings.Builder
143 n, c, err := readComponent(b)
151 return buf.String(), nil
154 func sizeForAddr(p Protocol, b []byte) (skip, size int, err error) {
157 return 0, (p.Size / 8), nil
161 size, n, err := ReadVarintCode(b)
169 func bytesSplit(b []byte) ([][]byte, error) {
172 code, n, err := ReadVarintCode(b)
177 p := ProtocolWithCode(code)
179 return nil, fmt.Errorf("no protocol with code %d", b[0])
182 n2, size, err := sizeForAddr(p, b[n:])
187 length := n + n2 + size
188 ret = append(ret, b[:length])