Skip to content

Commit 4c9b46c

Browse files
committed
instruction: Add no-alloc helper for instruction data
#### Problem Constructing instruction data requires using a serialization library such as bincode or borsh, but it's much simpler to create an instance of the instruction and just reinterpret those bytes (assuming the type is a properly packed struct). #### Summary of changes Add a helper for creating a type used for instruction data.
1 parent b658f47 commit 4c9b46c

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

src/instruction.zig

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,3 +52,32 @@ pub const Instruction = extern struct {
5252
return error.CrossProgramInvocationFailed;
5353
}
5454
};
55+
56+
/// Helper for no-alloc CPIs. By providing a discriminant and data type, the
57+
/// dynamic type can be constructed in-place and used for instruction data:
58+
///
59+
/// const Discriminant = enum(u32) {
60+
/// one,
61+
/// };
62+
/// const Data = packed struct {
63+
/// field: u64
64+
/// };
65+
/// const data = InstructionData(Discriminant, Data) {
66+
/// .discriminant = Discriminant.one,
67+
/// .data = .{ .field = 1 }
68+
/// };
69+
/// const instruction = Instruction.from(.{
70+
/// .program_id = ...,
71+
/// .accounts = &[_]Account.Param{...},
72+
/// .data = data.asBytes(),
73+
/// });
74+
pub fn InstructionData(comptime Discriminant: type, comptime Data: type) type {
75+
return packed struct {
76+
discriminant: Discriminant,
77+
data: Data,
78+
const Self = @This();
79+
fn asBytes(self: *const Self) []const u8 {
80+
return std.mem.asBytes(self)[0..(@sizeOf(Discriminant) + @sizeOf(Data))];
81+
}
82+
};
83+
}

0 commit comments

Comments
 (0)