summaryrefslogtreecommitdiff
path: root/src/main/java/com/keuin/psmb4j/util/InputStreamUtils.java
diff options
context:
space:
mode:
authorKeuin <[email protected]>2022-02-04 22:54:22 +0800
committerKeuin <[email protected]>2022-02-04 22:54:22 +0800
commitdfa163e5a3cffa46f0241210f2c8be1f8e298d7a (patch)
tree72db589d79bcc3bbca45c3a34a6dac71b2f55526 /src/main/java/com/keuin/psmb4j/util/InputStreamUtils.java
parent12ddbba66e6f2585e59d05d1782c0e8ce9fe6146 (diff)
Add psmb support.
Diffstat (limited to 'src/main/java/com/keuin/psmb4j/util/InputStreamUtils.java')
-rw-r--r--src/main/java/com/keuin/psmb4j/util/InputStreamUtils.java56
1 files changed, 56 insertions, 0 deletions
diff --git a/src/main/java/com/keuin/psmb4j/util/InputStreamUtils.java b/src/main/java/com/keuin/psmb4j/util/InputStreamUtils.java
new file mode 100644
index 0000000..7b3fd9c
--- /dev/null
+++ b/src/main/java/com/keuin/psmb4j/util/InputStreamUtils.java
@@ -0,0 +1,56 @@
+package com.keuin.psmb4j.util;
+
+import com.keuin.psmb4j.util.error.SocketClosedException;
+import com.keuin.psmb4j.util.error.StringLengthExceededException;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+public class InputStreamUtils {
+ /**
+ * Read until '\0', the trailing '\0' is dropped.
+ */
+ public static String readCString(InputStream stream) throws IOException {
+ var sb = new StringBuilder();
+ int c;
+ while ((c = stream.read()) > 0) {
+ sb.append((char) c);
+ }
+ return sb.toString();
+ }
+
+ /**
+ * Read a C style string, with a length limit.
+ * If the string is longer than given limit,
+ * a {@link StringLengthExceededException} will be thrown.
+ */
+ public static String readCString(InputStream stream, long maxLength) throws IOException {
+ var sb = new StringBuilder();
+ int c;
+ long length = 0;
+ while ((c = stream.read()) > 0) {
+ sb.append((char) c);
+ if (++length > maxLength) {
+ throw new StringLengthExceededException(maxLength);
+ }
+ }
+ return sb.toString();
+ }
+
+ /**
+ * Read fixed length bytes from stream.
+ * If not enough, a {@link SocketClosedException} will be thrown.
+ */
+ public static byte[] readBytes(InputStream stream, int length) throws IOException {
+ var buffer = new byte[length];
+ int c;
+ for (int i = 0; i < length; i++) {
+ if ((c = stream.read()) >= 0) {
+ buffer[i] = (byte) c;
+ } else {
+ throw new SocketClosedException(length, i);
+ }
+ }
+ return buffer;
+ }
+}