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

Add enum utilities and add enum with holes support #115

Merged
merged 6 commits into from
Jun 9, 2022
Merged

Conversation

lchenut
Copy link
Contributor

@lchenut lchenut commented May 24, 2022

Add one macro and one procedure:

  • macro enumRangeOrd(e: type[enum]): untyped
    Creates an array with all the ordinal value of an enum (sorted by default from what I saw)
type
  Test = enum
    A1 = 1, B1 = 2, C1 = 3
  TestWithHoles = enum
    A2 = 1, B2 = 3, C2 = 5
assert(enumRangeOrd(Test) == [ 1, 2, 3 ])
assert(enumRangeOrd(TestWithHoles) == [ 1, 3, 5 ])
  • proc contains(e: type[enum], v: SomeInteger): bool
    With the macro described above, it checks if an integer is in the enum, in order to use someInt in / notin RandomEnum

In addition to that, I use those two macro/proc to implement the hole management in the macro hasHoles and the proc checkEnumAssign

@lchenut lchenut requested a review from zah May 24, 2022 13:24
stew/objects.nim Outdated Show resolved Hide resolved
Copy link
Contributor

@Menduist Menduist left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This PR doesn't work when used with other types than int

Eg, 5.byte in SomeEnum

Also, since hasHoles is used in contains, put hasHoles first (it's causing issues in some cases currently)

stew/objects.nim Outdated
if v > int.high.uint64:
return false
when e.hasHoles():
v.int64 in enumRangeOrd(e).mapIt(it.int64)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Using mapIt here would be a bit inefficient as it would allocate a sequence just to perform the check. It would be better to directly produce an int64 array in enumRangeOrd.

@zah zah merged commit c2f0cbf into master Jun 9, 2022
@zah zah deleted the enumUtilities branch June 9, 2022 23:29
@Menduist Menduist mentioned this pull request May 22, 2023
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.

3 participants