index.go 811 Bytes
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 5 6
import (
  "fmt"
)

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
11 12 13 14 15 16
func NewString(s string) (*Multiaddr, error) {
  b, err := StringToBytes(s)
  if err != nil {
    return nil, err
  }
  return &Multiaddr{Bytes: b}, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
17
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
18 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

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
}