Skip to content

Commit

Permalink
bug fix: always write 32 bit integers
Browse files Browse the repository at this point in the history
  • Loading branch information
iamcalledrob committed Nov 13, 2024
1 parent 9400918 commit fc3cc85
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 7 deletions.
2 changes: 1 addition & 1 deletion build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ plugins {
}

group = "com.github.iamcalledrob"
version = "1.0.2"
version = "1.0.3"

repositories {
mavenCentral()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,10 +78,10 @@ class SingleInstance(

private fun writeArgs(channel: SocketChannel, args: Array<String>) {
Channels.newOutputStream(channel).use { stream ->
stream.write(args.size)
stream.writeInt(args.size)
for (arg in args) {
val bytes = arg.toByteArray(Charsets.UTF_8)
stream.write(bytes.size)
stream.writeInt(bytes.size)
stream.write(bytes)
}
}
Expand All @@ -90,14 +90,14 @@ class SingleInstance(
private fun readArgs(channel: SocketChannel): Array<String> {
Channels.newInputStream(channel).use { stream ->
val rcvdArgs = mutableListOf<String>()
val count = stream.readNBytes(1).first().toInt()
val count = stream.readInt()

// Sanity check
check(count <= 1024) { "arg count out of range: $count" }
check(count in 0..1024) { "arg count out of range: $count" }

repeat(count) {
val len = stream.readNBytes(1).first().toInt()
check(len <= 1024) { "arg len out of range: $len" }
val len = stream.readInt()
check(len in 1..1024) { "arg len out of range: $len" }

val arg = stream.readNBytes(len).toString(Charsets.UTF_8)
rcvdArgs.add(arg)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package com.github.iamcalledrob.singleinstance

import java.io.InputStream
import java.io.OutputStream
import java.nio.ByteBuffer

// Utils for reading/writing Ints to a stream, because
// OutputStream.write(value: Int) *silently truncates* the value to 1 byte. Sigh.

internal fun OutputStream.writeInt(value: Int) {
val byteArray = ByteBuffer.allocate(Int.SIZE_BYTES).putInt(value).array()
write(byteArray)
}

internal fun InputStream.readInt(): Int {
val byteArray = readNBytes(Int.SIZE_BYTES)
return ByteBuffer.wrap(byteArray).getInt()
}

0 comments on commit fc3cc85

Please sign in to comment.