go_subnetter/netsplit/funcs_ianaprefix.go

66 lines
1.3 KiB
Go

package netsplit
import (
`encoding/xml`
`errors`
`fmt`
`io`
`net/netip`
`strings`
)
// UnmarshalXML conforms an IANAPrefix to (encoding/xml).Unmarshaler.
func (i *IANAPrefix) UnmarshalXML(d *xml.Decoder, start xml.StartElement) (err error) {
var tok xml.Token
var nextRefIdx int
var ref *IANARef
var pfxStr []string
var sb *strings.Builder = new(strings.Builder)
for {
if tok, err = d.Token(); err != nil {
if errors.Is(err, io.EOF) {
err = nil
break
}
return
}
switch t := tok.(type) {
case xml.CharData:
sb.Write(t)
case xml.StartElement:
switch t.Name.Local {
case "xref":
ref = new(IANARef)
if err = d.DecodeElement(ref, &t); err != nil {
return
}
if i.References == nil {
i.References = make([]*IANARef, 0)
}
i.References = append(i.References, ref)
// No reference for these; they should be only network addrs.
// fmt.Fprintf(sb, "[REF %d]", nextRefIdx)
nextRefIdx++
default:
fmt.Println(t.Name.Local)
continue
}
}
}
pfxStr = strings.Split(sb.String(), ",")
i.Prefixes = make([]*netip.Prefix, len(pfxStr))
for idx, p := range pfxStr {
i.Prefixes[idx] = new(netip.Prefix)
if *i.Prefixes[idx], err = netip.ParsePrefix(
strings.TrimSpace(p),
); err != nil {
return
}
}
return
}