blob: ab262ad879167464a6dd6abf9ff7f290a2b15715 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
package scalevalapokalypsi.utils
import java.io.InputStream
import java.nio.charset.StandardCharsets
/** 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.getBytes(StandardCharsets.UTF_8)
/** 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, StandardCharsets.UTF_8))
|