github.com/moreal/bencodex-go@v0.0.0-20231021172012-18277a477d15/bencodex_json.go (about)

     1  package bencode
     2  
     3  import (
     4  	"encoding/hex"
     5  	"errors"
     6  	"fmt"
     7  	"github.com/moreal/bencodex-go/internal"
     8  )
     9  
    10  func convertBencodexKeyToJson(x interface{}) (string, error) {
    11  	switch v := x.(type) {
    12  	case string:
    13  		return fmt.Sprintf("\uFEFF%s", v), nil
    14  	case internal.BencodexBytesLike:
    15  		if v.IsString() {
    16  			return fmt.Sprintf("\uFEFF%s", v.MustAsString()), nil
    17  		}
    18  
    19  		return fmt.Sprintf("0x%s", hex.EncodeToString(v.MustAsBytes())), nil
    20  	}
    21  
    22  	return "", errors.New("convertBencodexKeyToJson: not supported type.")
    23  }
    24  
    25  func ConvertToBencodexJson(x interface{}) (interface{}, error) {
    26  	switch v := x.(type) {
    27  	case string:
    28  		return fmt.Sprintf("\uFEFF%s", v), nil
    29  	case internal.BencodexBytesLike:
    30  		if v.IsString() {
    31  			return fmt.Sprintf("\uFEFF%s", v.MustAsString()), nil
    32  		}
    33  
    34  		return fmt.Sprintf("0x%s", hex.EncodeToString(v.MustAsBytes())), nil
    35  	case int64:
    36  		return v, nil
    37  	case bool:
    38  		return v, nil
    39  	case nil:
    40  		return v, nil
    41  	case []interface{}:
    42  		result := make([]interface{}, len(v))
    43  		for i := 0; i < len(v); i++ {
    44  			newVal, err := ConvertToBencodexJson(v[i])
    45  			if err != nil {
    46  				return nil, err
    47  			}
    48  
    49  			result[i] = newVal
    50  		}
    51  
    52  		return result, nil
    53  	case map[internal.BencodexBytesLike]interface{}:
    54  		result := make(map[string]interface{})
    55  		for key, value := range v {
    56  			newKey, err := convertBencodexKeyToJson(key)
    57  			if err != nil {
    58  				return nil, err
    59  			}
    60  
    61  			newVal, err := ConvertToBencodexJson(value)
    62  			if err != nil {
    63  				return nil, err
    64  			}
    65  
    66  			result[newKey] = newVal
    67  		}
    68  
    69  		return result, nil
    70  	}
    71  
    72  	return nil, errors.New("ConvertToBencodexJson: not supported type.")
    73  }