ppforge/packetctl/packetctl.go

124 lines
2.6 KiB
Go

package packetctl
import (
"encoding/json"
"io/fs"
"os"
"gitea.mmo.to/ProtocolPacketForger/ppf/packet"
)
func NewPacketStructure() *packet.PacketStructure {
p := packet.PacketStructure{}
return &p
}
func UpdateMetaData(
pack *packet.PacketStructure,
) {
// still empty
}
func NewPacketLayer() *packet.PacketLayer {
p := packet.PacketLayer{}
return &p
}
func NewEmptyFieldValue() *packet.FieldValue {
f := packet.FieldValue{}
return &f
}
func NewFieldValue(
value string,
) *packet.FieldValue {
f := packet.FieldValue{
Value: value,
}
return &f
}
func AppendField(pack *packet.PacketLayer, field *packet.FieldValue) int {
i := len(pack.Values)
pack.Values = append(pack.Values, *field)
return i + 1
}
func AddField(pack *packet.PacketLayer, index int, field *packet.FieldValue) {
if len(pack.Values) == index {
AppendField(pack, field)
return
}
ret := make([]packet.FieldValue, 0)
ret = append(ret, pack.Values[:index]...)
ret = append(ret, *field)
ret = append(ret, pack.Values[index:]...)
pack.Values = ret
}
func AppendLayer(pack *packet.PacketStructure, layer *packet.PacketLayer) {
pack.Layers = append(pack.Layers, *layer)
}
func Addlayer(pack *packet.PacketStructure, index int, layer *packet.PacketLayer) {
if len(pack.Layers) == index {
AppendLayer(pack, layer)
return
}
ret := make([]packet.PacketLayer, 0)
ret = append(ret, pack.Layers[:index]...)
ret = append(ret, *layer)
ret = append(ret, pack.Layers[index:]...)
pack.Layers = ret
}
func UpdateField(pack *packet.PacketLayer, e int, field *packet.FieldValue) {
pack.Values[e] = *field
}
func UpdateLayer(pack *packet.PacketStructure, e int, layer *packet.PacketLayer) {
pack.Layers[e] = *layer
}
func RemoveField(pack *packet.PacketLayer, e int) {
l := len(pack.Values) - 1
ret := make([]packet.FieldValue, l)
ret = append(ret, pack.Values[:e]...)
ret = append(ret, pack.Values[e+1:]...)
pack.Values = ret
}
func RemoveLayer(pack *packet.PacketStructure, e int) {
l := len(pack.Layers) - 1
ret := make([]packet.PacketLayer, l)
ret = append(ret, pack.Layers[:e]...)
ret = append(ret, pack.Layers[e+1:]...)
pack.Layers = ret
}
func Load(pack *packet.PacketStructure, path string) error {
data, err := os.ReadFile(path)
if err != nil {
return err
}
err = json.Unmarshal(data, pack)
return err
}
func ToJson(pack *packet.PacketStructure) string {
data, err := json.MarshalIndent(*pack, "", " ")
if err != nil {
return ""
}
return string(data)
}
func Save(pack *packet.PacketStructure, path string) error {
data, err := json.MarshalIndent(*pack, "", " ")
if err != nil {
return err
}
err = os.WriteFile(path, data, fs.ModeAppend)
return err
}