diff options
author | Joel Kronqvist <joel.kronqvist@iki.fi> | 2024-11-14 19:25:19 +0200 |
---|---|---|
committer | Joel Kronqvist <joel.kronqvist@iki.fi> | 2024-11-14 19:25:19 +0200 |
commit | a43812ed462630850edbf29bda182fbf1e5e1263 (patch) | |
tree | 20e84b60adee6fa31ceb970ffccffa5b6b583d86 /src/main/scala/utils.scala | |
parent | c87263e9e493fe6c130f5ad6a523871c08987f4c (diff) | |
download | scalevalapokalypsi-a43812ed462630850edbf29bda182fbf1e5e1263.tar.gz scalevalapokalypsi-a43812ed462630850edbf29bda182fbf1e5e1263.zip |
Immediate printing of actions & no prompt on blocking action & refactoring
Diffstat (limited to 'src/main/scala/utils.scala')
-rw-r--r-- | src/main/scala/utils.scala | 19 |
1 files changed, 19 insertions, 0 deletions
diff --git a/src/main/scala/utils.scala b/src/main/scala/utils.scala index f230be7..cfca568 100644 --- a/src/main/scala/utils.scala +++ b/src/main/scala/utils.scala @@ -1,5 +1,7 @@ package o1game.utils +import java.io.InputStream + /** Converts this string to an array of bytes (probably for transmission). * * @param str the string to convert @@ -7,3 +9,20 @@ package o1game.utils */ def stringToByteArray(str: String): Array[Byte] = str.toVector.map(_.toByte).toArray + +/** Reads n characters from the given InputStream blockingly. + * + * @param input the InputStream to read from + * @param n the number of bytes to read + * @return The read result, or None in case of failure + */ +def getNCharsFromSocket(input: InputStream, n: Int): Option[String] = + val buffer: Array[Byte] = Array.ofDim(n) + var i = 0 + var failed = false + while i < n && !failed do + val res = input.read(buffer, i, n - i) + if res < 0 then failed = true + i += res + // TODO: better error handling + if failed then None else Some(String(buffer)) |