github.com/nspcc-dev/neo-go@v0.105.2-0.20240517133400-6be757af3eba/pkg/smartcontract/binding/override.go (about)

     1  package binding
     2  
     3  import (
     4  	"strings"
     5  )
     6  
     7  // Override contains a package and a type to replace manifest method parameter type with.
     8  type Override struct {
     9  	// Package contains a fully-qualified package name.
    10  	Package string
    11  	// TypeName contains type name together with a package alias.
    12  	TypeName string
    13  }
    14  
    15  // NewOverrideFromString parses s and returns method parameter type override spec.
    16  func NewOverrideFromString(s string) Override {
    17  	var over Override
    18  
    19  	index := strings.LastIndexByte(s, '.')
    20  	if index == -1 {
    21  		over.TypeName = s
    22  		return over
    23  	}
    24  
    25  	// Arrays and maps can have fully-qualified types as elements.
    26  	last := strings.LastIndexAny(s, "]*")
    27  	isCompound := last != -1 && last < index
    28  	if isCompound {
    29  		over.Package = s[last+1 : index]
    30  	} else {
    31  		over.Package = s[:index]
    32  	}
    33  
    34  	switch over.Package {
    35  	case "iterator", "storage":
    36  		over.Package = "github.com/nspcc-dev/neo-go/pkg/interop/" + over.Package
    37  	case "ledger", "management":
    38  		over.Package = "github.com/nspcc-dev/neo-go/pkg/interop/native/" + over.Package
    39  	}
    40  
    41  	slashIndex := strings.LastIndexByte(s, '/')
    42  	if isCompound {
    43  		over.TypeName = s[:last+1] + s[slashIndex+1:]
    44  	} else {
    45  		over.TypeName = s[slashIndex+1:]
    46  	}
    47  	return over
    48  }
    49  
    50  // UnmarshalYAML implements the YAML Unmarshaler interface.
    51  func (o *Override) UnmarshalYAML(unmarshal func(any) error) error {
    52  	var s string
    53  
    54  	err := unmarshal(&s)
    55  	if err != nil {
    56  		return err
    57  	}
    58  
    59  	*o = NewOverrideFromString(s)
    60  	return err
    61  }
    62  
    63  // MarshalYAML implements the YAML marshaler interface.
    64  func (o Override) MarshalYAML() (any, error) {
    65  	if o.Package == "" {
    66  		return o.TypeName, nil
    67  	}
    68  
    69  	index := strings.LastIndexByte(o.TypeName, '.')
    70  	last := strings.LastIndexAny(o.TypeName, "]*")
    71  	if last == -1 {
    72  		return o.Package + o.TypeName[index:], nil
    73  	}
    74  	return o.TypeName[:last+1] + o.Package + o.TypeName[index:], nil
    75  }