diff options
author | Edoardo La Greca | 2025-07-30 17:58:58 +0200 |
---|---|---|
committer | Edoardo La Greca | 2025-07-30 17:58:58 +0200 |
commit | 66d673df736b2dee1945fef53612b78cab7358a5 (patch) | |
tree | 17ab02b53f0b8a2f69daf91d65daee0e24a3b71c /src | |
parent | 6b3eb12717a40590cd1dc8a7189c0a68e2e6bae6 (diff) |
add TagGenerator
Diffstat (limited to 'src')
-rw-r--r-- | src/main/kotlin/TagGenerator.kt | 62 |
1 files changed, 62 insertions, 0 deletions
diff --git a/src/main/kotlin/TagGenerator.kt b/src/main/kotlin/TagGenerator.kt new file mode 100644 index 0000000..d7662e6 --- /dev/null +++ b/src/main/kotlin/TagGenerator.kt @@ -0,0 +1,62 @@ +import kotlin.random.Random + +/** + * Generate tags for 9P messages. + */ +class TagGenerator(val method: TagGenerationMethod, val initial: UShort) { + + private var current: UShort = initial + private val rng: Random = Random(initial.toInt()) + private val randomReturned: Set<UShort> = emptySet() + + private val generationFunctions: Map<TagGenerationMethod, () -> UShort> = mapOf( + TagGenerationMethod.INCREMENTAL to this::generateIncremental, + TagGenerationMethod.RANDOM to this::generateRandom, + TagGenerationMethod.RANDOM_CHECKED to this::generateRandomChecked + ) + + /** + * How are tags generated? + */ + enum class TagGenerationMethod { + /** + * Return the initial value on the first generation. Increment the value on each generation. + */ + INCREMENTAL, + + /** + * Use the initial value as a seed and generate random values from it. + */ + RANDOM, + + /** + * Same as [RANDOM], but checks are added to avoid generating the same value twice. + */ + RANDOM_CHECKED, + } + + /** + * Generate a new tag. + */ + fun generate(): UShort { + return this.generationFunctions.getValue(method).invoke() + } + + private fun generateIncremental(): UShort { + val tmp = this.current + this.current++ + return tmp + } + + private fun generateRandom(): UShort { + return this.rng.nextBits(16).toUShort() + } + + private fun generateRandomChecked(): UShort { + var v: UShort + do { + v = generateRandom() + } while (v in randomReturned) + return v + } +}
\ No newline at end of file |