github.com/sagernet/sing-box@v1.9.0-rc.20/adapter/fakeip_metadata.go (about) 1 package adapter 2 3 import ( 4 "bytes" 5 "encoding" 6 "encoding/binary" 7 "io" 8 "net/netip" 9 10 "github.com/sagernet/sing/common" 11 ) 12 13 type FakeIPMetadata struct { 14 Inet4Range netip.Prefix 15 Inet6Range netip.Prefix 16 Inet4Current netip.Addr 17 Inet6Current netip.Addr 18 } 19 20 func (m *FakeIPMetadata) MarshalBinary() (data []byte, err error) { 21 var buffer bytes.Buffer 22 for _, marshaler := range []encoding.BinaryMarshaler{m.Inet4Range, m.Inet6Range, m.Inet4Current, m.Inet6Current} { 23 data, err = marshaler.MarshalBinary() 24 if err != nil { 25 return 26 } 27 common.Must(binary.Write(&buffer, binary.BigEndian, uint16(len(data)))) 28 buffer.Write(data) 29 } 30 data = buffer.Bytes() 31 return 32 } 33 34 func (m *FakeIPMetadata) UnmarshalBinary(data []byte) error { 35 reader := bytes.NewReader(data) 36 for _, unmarshaler := range []encoding.BinaryUnmarshaler{&m.Inet4Range, &m.Inet6Range, &m.Inet4Current, &m.Inet6Current} { 37 var length uint16 38 common.Must(binary.Read(reader, binary.BigEndian, &length)) 39 element := make([]byte, length) 40 _, err := io.ReadFull(reader, element) 41 if err != nil { 42 return err 43 } 44 err = unmarshaler.UnmarshalBinary(element) 45 if err != nil { 46 return err 47 } 48 } 49 return nil 50 }