Skip to content

Commit c08972d

Browse files
baynevy
andcommitted
Fix empty string handling for TruncatingBufferedWriter (#2609)
Co-authored-by: Volkan Yazıcı <volkan@yazi.ci>
1 parent e29b7eb commit c08972d

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

log4j-layout-template-json-test/src/test/java/org/apache/logging/log4j/layout/template/json/util/TruncatingBufferedWriterTest.java

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,12 +38,20 @@ void test_okay_payloads() {
3838
writer.write(new char[] {Character.MIN_VALUE, Character.MAX_VALUE});
3939
writer.write("foo");
4040
writer.write("foobar", 3, 3);
41+
writer.write("empty", 3, 0);
4142
writer.write(new char[] {'f', 'o', 'o', 'b', 'a', 'r', 'b', 'u', 'z', 'z'}, 6, 4);
43+
writer.write(new char[] {'a', 'b', 'c'}, 0, 0);
44+
writer.write(new char[] {}, 0, 0);
45+
writer.write(new char[] {});
46+
writer.write("", 0, 0);
47+
writer.write("");
4248
writer.append('!');
4349
writer.append("yo");
4450
writer.append(null);
4551
writer.append("yo dog", 3, 6);
4652
writer.append(null, -1, -1);
53+
writer.append("", -1, -1);
54+
writer.append("");
4755

4856
// Verify accessors.
4957
final char[] expectedBuffer = new char[capacity];

log4j-layout-template-json/src/main/java/org/apache/logging/log4j/layout/template/json/util/TruncatingBufferedWriter.java

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,11 @@ public void write(final char[] source, final int offset, final int length) {
7777

7878
// Check arguments.
7979
Objects.requireNonNull(source, "source");
80+
81+
if (source.length == 0) {
82+
return;
83+
}
84+
8085
if (offset < 0 || offset >= source.length) {
8186
throw new IndexOutOfBoundsException("invalid offset: " + offset);
8287
}
@@ -126,6 +131,11 @@ public void write(final String string, final int offset, final int length) {
126131

127132
// Check arguments.
128133
Objects.requireNonNull(string, "string");
134+
135+
if (string.isEmpty()) {
136+
return;
137+
}
138+
129139
if (offset < 0 || offset >= string.length()) {
130140
throw new IndexOutOfBoundsException("invalid offset: " + offset);
131141
}
@@ -168,6 +178,11 @@ public Writer append(final CharSequence seq, final int start, final int end) {
168178
return this;
169179
}
170180

181+
// Short-circuit on empty sequence
182+
if (seq.length() == 0) {
183+
return this;
184+
}
185+
171186
// Check arguments.
172187
if (start < 0 || start >= seq.length()) {
173188
throw new IndexOutOfBoundsException("invalid start: " + start);

0 commit comments

Comments
 (0)