Bit Flags for Multiple Options

I was writing a CLI tool recently and had to make a configuration block mergeable, similar to opening files in C. I quickly thought of the single integer multiple-state mechanism of file access flags in C.


The file access mode can be O_CREAT, O_O_RDONLY, etc. but it can also be joined something like this:

int ACCESS_FLAG = O_CREAT | O_O_RDONLY;        

This is a super cool and easy way to enable application developers to make configurations joinable.

In my library I wanted to have a way to make the resource accessible via GET, POST, PUT, PATCH, and DELETE. Any of these HTTP methods should be made combinable. This is a trivial use-case of flags.

I implemented it like this.


GET? ? ? ?= 1 << 0? ? :-? ? ? 00001
POST? ? ? = 1 << 1? ? :-? ? ? 00010
PUT? ? ? ?= 1 << 2? ? :-? ? ? 00100
PATCH? ? ?= 1 << 3? ? :-? ? ? 01000
DELETE? ? = 1 << 4? ? :-? ? ? 10000        

Now, I can do this:

fn check_access(access, method)
??return access & method == method:        

How does this work?

The access variable is a combination of the flags. Each flag is a power of 2. This will set the bit at the position of the flag and not touch the other bits.

For example, if I want to allow GET and POST, I can do this:

??ACCESS = GET | POST
??where,
????GET | POST = 00001 | 00010 = 00011?        

Now, if I want to check if the access variable allows GET, I can do this:

check_access(ACCESS, GET)
i.e. 00011 & 00001 == 00001
i.e. 00001 == 00001
i.e. True)        

Thank you!

要查看或添加评论,请登录

Mahesh Regmi的更多文章

  • Optimistic Concurrency in Kubernetes

    Optimistic Concurrency in Kubernetes

    Concurrency is a tough problem to solve. There are a lot of ways to tackle concurrency problems, and yet we have to…

    1 条评论

社区洞察

其他会员也浏览了