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

packed object / bitfields #741

Open
timotheecour opened this issue May 21, 2021 · 5 comments
Open

packed object / bitfields #741

timotheecour opened this issue May 21, 2021 · 5 comments

Comments

@timotheecour
Copy link
Owner

timotheecour commented May 21, 2021

TODO: write proper RFC

proposal

add Packed, which generalizes builtin set by packing several set into 1 bit sequence, allowing one to represent objects compactly as a single bit sequence (eg equivalent to an int)

Example

import std/packed
type Bar = enum b0, b1, b2, b3
type A = Packed(switch: bool, val: 10..12, bar: Bar)
assert A.sizeof == nextPow2((2 * 3 * 4) div 8) = 4 # fits in an int32
let a = A.init(switch = true, bar = b2)
assert a.matches(switch = {true}, bar = {b0, b2})

links

@juancarlospaco
Copy link
Collaborator

Hows this different from a set of enum ?, or is it the metaprogramming part that has the magic ?. 🤔

@timotheecour
Copy link
Owner Author

timotheecour commented May 26, 2021

a packed object is intended to replace simple objects in cases like this:

type Bar = enum b0, b1, b2, b3

type A0 = object
  switch: bool
  val: range[10..12]
  bar: Bar

type A1 = Packed(switch: bool, val: 10..12, bar: Bar)

assert A0.sizeof == 24
assert A1.sizeof == 4

beside the large saving (and likely more efficient operations), you get syntax sugar like matches which generalizes set APIs (not just sugar; it allows more efficient operations, just like set does)

set[Bar] doesn't help with that and serves other purposes (note that a packed object could hold a set[Bar] too, as a field)

@juancarlospaco
Copy link
Collaborator

juancarlospaco commented May 26, 2021

So like an object implemented on top of a set ?, all attributes must be ordinal right ?, sounds interesting... 🤔

@timotheecour
Copy link
Owner Author

timotheecour commented May 26, 2021

all attributes must be ordinal right ?,

correct, you can't have these types as fields:
string, seq, ptr, ref, object, float

you can have these:
Ordinal

that's the restriction
(whether you can have a set[Bar] as field, I'm not sure yet; we can disallow it for now)

@juancarlospaco
Copy link
Collaborator

Write the RFC.

Offtopic: I wish stdlib had a fixed point.

@timotheecour timotheecour changed the title packed object packed object / bitfields May 31, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants