diff options
author | Joel Kronqvist <joel.kronqvist@iki.fi> | 2024-11-17 13:45:44 +0200 |
---|---|---|
committer | Joel Kronqvist <joel.kronqvist@iki.fi> | 2024-11-17 13:45:44 +0200 |
commit | 4de67b497e0e229fe4a42f66f833640b6e50fd5a (patch) | |
tree | 34fb5b0e776f7cd3adcb4556f4d6a7c8ad66de39 /src/scalevalapokalypsi/utils | |
parent | 8595e892abc0e0554f589ed2eb88c351a347fbd4 (diff) | |
download | scalevalapokalypsi-4de67b497e0e229fe4a42f66f833640b6e50fd5a.tar.gz scalevalapokalypsi-4de67b497e0e229fe4a42f66f833640b6e50fd5a.zip |
Moved the project to an IDEA project & wrote part of README.txt
Diffstat (limited to 'src/scalevalapokalypsi/utils')
-rw-r--r-- | src/scalevalapokalypsi/utils/utils.scala | 28 |
1 files changed, 28 insertions, 0 deletions
diff --git a/src/scalevalapokalypsi/utils/utils.scala b/src/scalevalapokalypsi/utils/utils.scala new file mode 100644 index 0000000..b1bac4d --- /dev/null +++ b/src/scalevalapokalypsi/utils/utils.scala @@ -0,0 +1,28 @@ +package scalevalapokalypsi.utils + +import java.io.InputStream + +/** Converts this string to an array of bytes (probably for transmission). + * + * @param str the string to convert + * @return an array of bytes representing the string in UTF8. + */ +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)) |