Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Prototyping a Flags/Bitmasks implementation in Kotlin 1.1.1
META-INF/
*.class
class BitMask(val value: Long)
interface Flags {
val bit: Long
fun toBitMask(): BitMask = BitMask(bit)
}
infix fun Flags.and(other: Long): BitMask = BitMask(bit and other)
infix fun <T: Flags> Flags.or(other: T): BitMask = BitMask(bit or other.bit)
operator infix fun Flags.plus(other: Flags): BitMask = BitMask(bit or other.bit)
inline fun <reified T> enabledValues(mask: BitMask) : List<T> where T : Enum<T>, T : Flags {
return enumValues<T>().filter {
mask hasFlag it
}
}
infix fun BitMask.or(other: Flags): BitMask = BitMask(value or other.bit)
operator infix fun BitMask.plus(other: BitMask): BitMask = BitMask(value or other.value)
operator infix fun BitMask.plus(other: Flags): BitMask = BitMask(value or other.bit)
infix fun <T: Flags> BitMask.hasFlag(which: T): Boolean {
// an Undefined flag is a special case.
if(value == 0L || (value > 0L && which.bit == 0L)) return false
return value and which.bit == which.bit
}
infix fun <T: Flags> BitMask.unset(which: T): BitMask = BitMask(value xor which.bit)
fun main(args : Array<String>){
val mask: BitMask = ParameterFeature.Path +
ParameterFeature.Query +
ParameterFeature.Header;
val enabled = enabledValues<ParameterFeature>(mask)
println("flags enabled: $enabled")
println("flags disabled: ${enumValues<ParameterFeature>().filterNot { enabled.contains(it) } }")
println("mask hasFlag ParameterFeature.Query: ${mask hasFlag ParameterFeature.Query}")
println("mask hasFlag ParameterFeature.Body: ${mask hasFlag ParameterFeature.Body}")
}
enum class ParameterFeature(override val bit: Long) : Flags {
Undefined(0),
Path(1 shl 0),
Query(1 shl 1),
Header(1 shl 2),
Body(1 shl 3),
FormUnencoded(1 shl 4),
FormMultipart(1 shl 5);
}
#!/usr/bin/env bash
kotlinc {BitMask,Flags,globals,ParameterFeature,main}.kt && kotlin MainKt
@mochadwi
Copy link

mochadwi commented Feb 24, 2019

Thank you very much for this awesome example @jimschubert

@fabriciovergara
Copy link

fabriciovergara commented Aug 23, 2021

Hidden gem

@jimschubert
Copy link
Author

jimschubert commented Aug 24, 2021

@fabriciovergara thanks! I'm glad you've found it useful.

@ronjunevaldoz
Copy link

ronjunevaldoz commented Oct 13, 2022

nice work! very helpful for network physics

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment