aboutsummaryrefslogtreecommitdiff
path: root/passgen/diceware/src/main
diff options
context:
space:
mode:
Diffstat (limited to 'passgen/diceware/src/main')
-rw-r--r--passgen/diceware/src/main/kotlin/dev/msfjarvis/aps/passgen/diceware/Die.kt30
-rw-r--r--passgen/diceware/src/main/kotlin/dev/msfjarvis/aps/passgen/diceware/RandomIntGenerator.kt15
2 files changed, 45 insertions, 0 deletions
diff --git a/passgen/diceware/src/main/kotlin/dev/msfjarvis/aps/passgen/diceware/Die.kt b/passgen/diceware/src/main/kotlin/dev/msfjarvis/aps/passgen/diceware/Die.kt
new file mode 100644
index 00000000..d6e5aa23
--- /dev/null
+++ b/passgen/diceware/src/main/kotlin/dev/msfjarvis/aps/passgen/diceware/Die.kt
@@ -0,0 +1,30 @@
+/*
+ * Copyright © 2014-2021 The Android Password Store Authors. All Rights Reserved.
+ * SPDX-License-Identifier: GPL-3.0-only
+ */
+
+package dev.msfjarvis.aps.passgen.diceware
+
+import javax.inject.Inject
+
+/** Basic implementation of a die with configurable number of sides. */
+public class Die
+@Inject
+constructor(
+ private val sides: Int,
+ private val random: RandomIntGenerator,
+) {
+
+ /** Roll the die to return a single number. */
+ public fun roll(): Int {
+ return random.get(1..sides)
+ }
+
+ /**
+ * Roll the die multiple times, concatenating each result to obtain a number with [iterations]
+ * digits.
+ */
+ public fun rollMultiple(iterations: Int): Int {
+ return StringBuilder().apply { repeat(iterations) { append(roll()) } }.toString().toInt()
+ }
+}
diff --git a/passgen/diceware/src/main/kotlin/dev/msfjarvis/aps/passgen/diceware/RandomIntGenerator.kt b/passgen/diceware/src/main/kotlin/dev/msfjarvis/aps/passgen/diceware/RandomIntGenerator.kt
new file mode 100644
index 00000000..7f957419
--- /dev/null
+++ b/passgen/diceware/src/main/kotlin/dev/msfjarvis/aps/passgen/diceware/RandomIntGenerator.kt
@@ -0,0 +1,15 @@
+/*
+ * Copyright © 2014-2021 The Android Password Store Authors. All Rights Reserved.
+ * SPDX-License-Identifier: GPL-3.0-only
+ */
+
+package dev.msfjarvis.aps.passgen.diceware
+
+/**
+ * SAM interface that takes in an [IntRange] and returns a randomly chosen [Int] within its bounds.
+ * This is used as a replacement for [kotlin.random.Random] since there is no CSPRNG-backed
+ * implementation of it in the Kotlin stdlib.
+ */
+public fun interface RandomIntGenerator {
+ public fun get(range: IntRange): Int
+}