Skip to content

Commit 87d40df

Browse files
authored
instruction: Add no-alloc helper for instruction data (#4)
* 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. * Bump patch version
1 parent b658f47 commit 87d40df

File tree

3 files changed

+31
-2
lines changed

3 files changed

+31
-2
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ You can run the convenience script in this repo to download the compiler to
3737
1. Add this package to your project:
3838

3939
```console
40-
zig fetch --save https://github.com/joncinque/solana-program-sdk-zig/archive/refs/tags/v0.14.0.tar.gz
40+
zig fetch --save https://github.com/joncinque/solana-program-sdk-zig/archive/refs/tags/v0.14.1.tar.gz
4141
```
4242

4343
2. (Optional) if you want to generate a keypair during building, you'll also

build.zig.zon

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
.{
22
.name = "solana-program-sdk",
3-
.version = "0.14.0",
3+
.version = "0.14.1",
44
.minimum_zig_version = "0.13.0",
55

66
// This field is optional.

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)