index.go 1.32 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 4
import (
  "fmt"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
5
  "strings"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
6 7
)

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
8 9 10 11
type Multiaddr struct {
  Bytes []byte
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
12
func NewMultiaddr(s string) (*Multiaddr, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
13 14 15 16 17
  b, err := StringToBytes(s)
  if err != nil {
    return nil, err
  }
  return &Multiaddr{Bytes: b}, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
18
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45

func (m *Multiaddr) String() (string, error) {
  return BytesToString(m.Bytes)
}

func (m *Multiaddr) Protocols() (ret []*Protocol, err error) {

  // panic handler, in case we try accessing bytes incorrectly.
  defer func() {
    if e := recover(); e != nil {
      ret = nil
      err = e.(error)
    }
  }()

  ps := []*Protocol{}
  b := m.Bytes[:]
  for ; len(b) > 0 ; {
    p := ProtocolWithCode(int(b[0]))
    if p == nil {
      return nil, fmt.Errorf("no protocol with code %d", b[0])
    }
    ps = append(ps, p)
    b = b[1 + (p.Size / 8):]
  }
  return ps, nil
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69

func (m *Multiaddr) Encapsulate(o *Multiaddr) *Multiaddr {
  b := make([]byte, len(m.Bytes) + len(o.Bytes))
  b = append(m.Bytes, o.Bytes...)
  return &Multiaddr{Bytes: b}
}

func (m *Multiaddr) Decapsulate(o *Multiaddr) (*Multiaddr, error) {
  s1, err := m.String()
  if err != nil {
    return nil, err
  }

  s2, err := o.String()
  if err != nil {
    return nil, err
  }

  i := strings.LastIndex(s1, s2)
  if i < 0 {
    return nil, fmt.Errorf("%s not contained in %s", s2, s1)
  }
  return NewMultiaddr(s1[:i])
}