Skip to content

Instantly share code, notes, and snippets.

@jimschubert
Last active March 27, 2025 09:49
Show Gist options
  • Select an option

  • Save jimschubert/b1437e210cdb9c411acde6654b4cdd01 to your computer and use it in GitHub Desktop.

Select an option

Save jimschubert/b1437e210cdb9c411acde6654b4cdd01 to your computer and use it in GitHub Desktop.
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
Copy Markdown

Thank you very much for this awesome example @jimschubert

@fabriciovergara
Copy link
Copy Markdown

Hidden gem

@jimschubert
Copy link
Copy Markdown
Author

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

@ronjunevaldoz
Copy link
Copy Markdown

nice work! very helpful for network physics

@blaksos
Copy link
Copy Markdown

blaksos commented Jan 29, 2025

Great example, thank you

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