Skip to content

Commit 7514663

Browse files
committed
Add functions BinaryUtil.copyInto and .concat
1 parent 726a63b commit 7514663

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

yubico-util/src/main/java/com/yubico/internal/util/BinaryUtil.java

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,37 @@ public static byte[] copy(byte[] bytes) {
3636
return Arrays.copyOf(bytes, bytes.length);
3737
}
3838

39+
/**
40+
* Copy <code>src</code> into <code>dest</code> beginning at the offset <code>destFrom</code>,
41+
* then return the modified <code>dest</code>.
42+
*/
43+
public static byte[] copyInto(byte[] src, byte[] dest, int destFrom) {
44+
if (dest.length - destFrom < src.length) {
45+
throw new IllegalArgumentException("Source array will not fit in destination array");
46+
}
47+
if (destFrom < 0) {
48+
throw new IllegalArgumentException("Invalid destination range");
49+
}
50+
51+
for (int i = 0; i < src.length; ++i) {
52+
dest[destFrom + i] = src[i];
53+
}
54+
55+
return dest;
56+
}
57+
58+
/** Return a new array containing the concatenation of the argument <code>arrays</code>. */
59+
public static byte[] concat(byte[]... arrays) {
60+
final int len = Arrays.stream(arrays).map(a -> a.length).reduce(0, Integer::sum);
61+
byte[] result = new byte[len];
62+
int i = 0;
63+
for (byte[] src : arrays) {
64+
copyInto(src, result, i);
65+
i += src.length;
66+
}
67+
return result;
68+
}
69+
3970
/**
4071
* @param bytes Bytes to encode
4172
*/

0 commit comments

Comments
 (0)