Skip to content

Commit

Permalink
Add NoTypeIDEncoding
Browse files Browse the repository at this point in the history
  • Loading branch information
gagliardetto committed Sep 10, 2021
1 parent a5d63c3 commit 696468a
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions variant.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,8 +122,12 @@ const (
// written using the anchor SDK.
// The typeID is the sighash of the instruction.
AnchorTypeIDEncoding
// No type ID; ONLY ONE VARIANT PER PROGRAM.
NoTypeIDEncoding
)

var NoTypeIDDefaultID = TypeIDFromUint8(0)

// NewVariantDefinition creates a variant definition based on the *ordered* provided types.
//
// - For anchor instructions, it's the name that defines the binary variant value.
Expand Down Expand Up @@ -199,6 +203,22 @@ func NewVariantDefinition(typeIDEncoding TypeIDEncoding, types []VariantType) (o
out.typeIDToName[typeID] = typeDef.Name
out.typeNameToID[typeDef.Name] = typeID
}
case NoTypeIDEncoding:
if len(types) != 1 {
panic(fmt.Sprintf("NoTypeIDEncoding can only have one variant type definition, got %v", len(types)))
}
typeDef := types[0]

typeID := NoTypeIDDefaultID

// FIXME: Check how the reflect.Type is used and cache all its usage in the definition.
// Right now, on each Unmarshal, we re-compute some expensive stuff that can be
// re-used like the `typeGo.Elem()` which is always the same. It would be preferable
// to have those already pre-defined here so we can actually speed up the
// Unmarshal code.
out.typeIDToType[typeID] = reflect.TypeOf(typeDef.Type)
out.typeIDToName[typeID] = typeDef.Name
out.typeNameToID[typeDef.Name] = typeID

default:
panic(fmt.Errorf("unsupported TypeIDEncoding: %v", typeIDEncoding))
Expand Down Expand Up @@ -336,6 +356,8 @@ func (a *BaseVariant) UnmarshalBinaryVariant(decoder *Decoder, def *VariantDefin
if err != nil {
return fmt.Errorf("anchor: unable to read variant type id: %s", err)
}
case NoTypeIDEncoding:
typeID = NoTypeIDDefaultID
}

a.TypeID = typeID
Expand Down

0 comments on commit 696468a

Please sign in to comment.