implement LuxState

This commit is contained in:
mykola2312 2025-01-11 02:28:46 +02:00
parent 73c1690c00
commit 164d23d28a
2 changed files with 79 additions and 2 deletions

View file

@ -1,6 +1,7 @@
package host package host
import ( import (
"fmt"
"lux/proto" "lux/proto"
"net" "net"
) )
@ -8,8 +9,8 @@ import (
type LuxOptionType uint type LuxOptionType uint
const ( const (
LuxOptionTypeWAN = 1 LuxOptionTypeWAN = 0
LuxOptionTypeWAN6 = 2 LuxOptionTypeWAN6 = 1
) )
type LuxOption interface { type LuxOption interface {
@ -62,3 +63,29 @@ func (opt *LuxOptionWAN6) Write(wd *proto.LuxBuffer) {
func (*LuxOptionWAN6) Type() LuxOptionType { func (*LuxOptionWAN6) Type() LuxOptionType {
return LuxOptionTypeWAN6 return LuxOptionTypeWAN6
} }
func ReadLuxOption(rd *proto.LuxBuffer) (LuxOption, error) {
var err error
optVal, err := rd.ReadUint16()
if err != nil {
return nil, err
}
switch LuxOptionType(optVal) {
case LuxOptionTypeWAN:
opt := &LuxOptionWAN{}
err = opt.Read(rd)
return opt, err
case LuxOptionTypeWAN6:
opt := &LuxOptionWAN6{}
err = opt.Read(rd)
return opt, err
default:
return nil, fmt.Errorf("unknown option %d", optVal)
}
}
func WriteLuxOption(wd *proto.LuxBuffer, opt LuxOption) {
wd.WriteUint16(uint16(opt.Type()))
opt.Write(wd)
}

50
host/lux_state.go Normal file
View file

@ -0,0 +1,50 @@
package host
import "lux/proto"
type LuxState struct {
Hostname string
Options map[LuxOptionType]LuxOption
}
func NewLuxState(hostname string) LuxState {
return LuxState{
Hostname: hostname,
Options: make(map[LuxOptionType]LuxOption),
}
}
func (state *LuxState) Read(rd *proto.LuxBuffer) error {
// hostname
hostname, err := rd.ReadString()
if err != nil {
return err
}
state.Hostname = hostname
// option count
count, err := rd.ReadUint16()
if err != nil {
return nil
}
for i := 0; i < int(count); i++ {
// read options
opt, err := ReadLuxOption(rd)
if err != nil {
return err
}
state.Options[opt.Type()] = opt
}
return nil
}
func (state *LuxState) Write(wd *proto.LuxBuffer) {
wd.WriteString(state.Hostname)
wd.WriteUint16(uint16(len(state.Options)))
for _, opt := range state.Options {
WriteLuxOption(wd, opt)
}
}