Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added PackedIntArray, PackedIntSlice to std #2422

Merged
merged 7 commits into from
May 5, 2019
Merged

Added PackedIntArray, PackedIntSlice to std #2422

merged 7 commits into from
May 5, 2019

Conversation

tgschultz
Copy link
Contributor

@tgschultz tgschultz commented May 4, 2019

PackedIntArray(comptime Int: type, comptime int_count: usize) type: Creates a bit-packed array of int_count integers of type Int. Bits are packed using native endianess and without storing any meta data. PackedIntArray(i3, 8) will occupy exactly 3 bytes of memory.

PackedIntSlice(comptime Int: type) type: Uses a slice as a bit-packed block of integers of type Int. Bits are packed using native endianess and without storing any meta data.

.len() gets the number of items the array/slice can hold.
.get(index: usize) and .set(index: usize, int: Int) are used for accessing the individual items.
.slice(start: usize, end: usize) creates a new PackedIntSlice(Int) instance covering the specified range of items (exclusive).
.sliceCast(NewInt: type) returns a new PackedIntSlice(NewInt) covering the same bytes but using a different bit-width integer (which must fit evenly within the old range of bits).

PackedIntArrays can be initialized from unpacked arrays or literals. PackedIntSlices initialize with a []u8 and a count of items. .bytesRequired(int_count: usize) can be used to calculate the number of bytes required in the slice for the given count.

Update: there are now also PackedIntArrayEndian, PackedIntSliceEndian, and .sliceCastEndian which allow specifying the endianess of the bit packing instead of using native.

@andrewrk
Copy link
Member

andrewrk commented May 5, 2019

These are likely to be moved to third party packages in the std lib audit (#1629), but for now, they're very welcome, because they provide a well-encapsulated, well-tested API that helps prevent regressions in the language, as well as an experiment in solving "packed arrays" in userland. 👍

@andrewrk andrewrk merged commit 7a41af2 into ziglang:master May 5, 2019
@tgschultz tgschultz deleted the stdlib-packed-int-array branch May 6, 2019 01:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants