Skip to content

Commit c79fea0

Browse files
committed
Adds setByteAt
1 parent 7aa1c2d commit c79fea0

File tree

3 files changed

+27
-0
lines changed

3 files changed

+27
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -440,6 +440,7 @@ MutableBytes b = Bytes.from(array).mutable();
440440
Mutable classes also enable further APIs for directly modify the internal array:
441441

442442
```java
443+
b.setByteAt(3, (byte) 0xF1)
443444
b.overwrite(anotherArray) //directly overwrite given array
444445
b.fill(0x03) // fills with e.g. 3
445446
b.wipe() //fills with zeros

src/main/java/at/favre/lib/bytes/MutableBytes.java

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
* <p>
3232
* Adds additional mutator, which may change the internal array in-place, like {@link #wipe()}
3333
*/
34+
@SuppressWarnings("WeakerAccess")
3435
public final class MutableBytes extends Bytes {
3536

3637
MutableBytes(byte[] byteArray, ByteOrder byteOrder) {
@@ -68,6 +69,18 @@ public MutableBytes overwrite(byte[] newArray, int offsetInternalArray) {
6869
return this;
6970
}
7071

72+
/**
73+
* Sets new byte to given index
74+
*
75+
* @param index the index to change
76+
* @param newByte the new byte to set
77+
* @return this instance
78+
*/
79+
public MutableBytes setByteAt(int index, byte newByte) {
80+
internalArray()[index] = newByte;
81+
return this;
82+
}
83+
7184
/**
7285
* Fills the internal byte array with all zeros
7386
*

src/test/java/at/favre/lib/bytes/MutableBytesABytesTest.java

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,19 @@ public void fill() throws Exception {
6868
assertArrayEquals(new byte[example_bytes_seven.length], b.array());
6969
}
7070

71+
@Test
72+
public void setByteAtTest() throws Exception {
73+
MutableBytes b = fromAndTest(example_bytes_sixteen).mutable();
74+
75+
for (int i = 0; i < b.length(); i++) {
76+
byte old = b.byteAt(i);
77+
b.setByteAt(i, (byte) 0);
78+
if (old != 0) {
79+
assertNotEquals(old, b.byteAt(i));
80+
}
81+
}
82+
}
83+
7184
@Test
7285
public void wipe() throws Exception {
7386
MutableBytes b = fromAndTest(example_bytes_seven).mutable();

0 commit comments

Comments
 (0)