util.go 1.3 KB
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1 2
package multiaddr

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
3
import "fmt"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
4 5 6 7 8 9 10 11 12 13

// Split returns the sub-address portions of a multiaddr.
func Split(m Multiaddr) []Multiaddr {
	split, err := bytesSplit(m.Bytes())
	if err != nil {
		panic(fmt.Errorf("invalid multiaddr %s", m.String()))
	}

	addrs := make([]Multiaddr, len(split))
	for i, addr := range split {
14
		addrs[i] = multiaddr{bytes: addr}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
15 16 17 18 19 20
	}
	return addrs
}

// Join returns a combination of addresses.
func Join(ms ...Multiaddr) Multiaddr {
Steven Allen's avatar
Steven Allen committed
21 22 23 24 25 26 27 28
	switch len(ms) {
	case 0:
		// empty multiaddr, unfortunately, we have callers that rely on
		// this contract.
		return multiaddr{}
	case 1:
		return ms[0]
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
29 30 31 32 33 34 35 36 37 38 39

	length := 0
	bs := make([][]byte, len(ms))
	for i, m := range ms {
		bs[i] = m.Bytes()
		length += len(bs[i])
	}

	bidx := 0
	b := make([]byte, length)
	for _, mb := range bs {
Steven Allen's avatar
Steven Allen committed
40
		bidx += copy(b[bidx:], mb)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
41
	}
42
	return multiaddr{bytes: b}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
43 44 45 46
}

// Cast re-casts a byte slice as a multiaddr. will panic if it fails to parse.
func Cast(b []byte) Multiaddr {
Steven Allen's avatar
Steven Allen committed
47
	m, err := NewMultiaddrBytes(b)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
48 49 50
	if err != nil {
		panic(fmt.Errorf("multiaddr failed to parse: %s", err))
	}
Steven Allen's avatar
Steven Allen committed
51
	return m
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
52 53 54 55 56 57 58 59 60 61
}

// StringCast like Cast, but parses a string. Will also panic if it fails to parse.
func StringCast(s string) Multiaddr {
	m, err := NewMultiaddr(s)
	if err != nil {
		panic(fmt.Errorf("multiaddr failed to parse: %s", err))
	}
	return m
}