github.com/kelleygo/clashcore@v1.0.2/constant/tun.go (about)

     1  package constant
     2  
     3  import (
     4  	"encoding/json"
     5  	"errors"
     6  	"strings"
     7  )
     8  
     9  var StackTypeMapping = map[string]TUNStack{
    10  	strings.ToLower(TunGvisor.String()): TunGvisor,
    11  	strings.ToLower(TunSystem.String()): TunSystem,
    12  	strings.ToLower(TunMixed.String()):  TunMixed,
    13  }
    14  
    15  const (
    16  	TunGvisor TUNStack = iota
    17  	TunSystem
    18  	TunMixed
    19  )
    20  
    21  type TUNStack int
    22  
    23  // UnmarshalYAML unserialize TUNStack with yaml
    24  func (e *TUNStack) UnmarshalYAML(unmarshal func(any) error) error {
    25  	var tp string
    26  	if err := unmarshal(&tp); err != nil {
    27  		return err
    28  	}
    29  	mode, exist := StackTypeMapping[strings.ToLower(tp)]
    30  	if !exist {
    31  		return errors.New("invalid tun stack")
    32  	}
    33  	*e = mode
    34  	return nil
    35  }
    36  
    37  // MarshalYAML serialize TUNStack with yaml
    38  func (e TUNStack) MarshalYAML() (any, error) {
    39  	return e.String(), nil
    40  }
    41  
    42  // UnmarshalJSON unserialize TUNStack with json
    43  func (e *TUNStack) UnmarshalJSON(data []byte) error {
    44  	var tp string
    45  	json.Unmarshal(data, &tp)
    46  	mode, exist := StackTypeMapping[strings.ToLower(tp)]
    47  	if !exist {
    48  		return errors.New("invalid tun stack")
    49  	}
    50  	*e = mode
    51  	return nil
    52  }
    53  
    54  // MarshalJSON serialize TUNStack with json
    55  func (e TUNStack) MarshalJSON() ([]byte, error) {
    56  	return json.Marshal(e.String())
    57  }
    58  
    59  func (e TUNStack) String() string {
    60  	switch e {
    61  	case TunGvisor:
    62  		return "gVisor"
    63  	case TunSystem:
    64  		return "System"
    65  	case TunMixed:
    66  		return "Mixed"
    67  	default:
    68  		return "unknown"
    69  	}
    70  }