Skip to content

Commit 88d2bb8

Browse files
committed
chore: Use empty headers when there is no value in builder.
1 parent 4863997 commit 88d2bb8

File tree

3 files changed

+17
-3
lines changed

3 files changed

+17
-3
lines changed

src/main/java/io/github/nstdio/http/ext/Headers.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ class Headers {
5151
static final String HEADER_LAST_MODIFIED = "Last-Modified";
5252
static final String HEADER_WARNING = "Warning";
5353
static final BiPredicate<String, String> ALLOW_ALL = (s, s2) -> true;
54-
private static final HttpHeaders EMPTY_HEADERS = HttpHeaders.of(Map.of(), ALLOW_ALL);
54+
static final HttpHeaders EMPTY_HEADERS = HttpHeaders.of(Map.of(), ALLOW_ALL);
5555
private static final DateTimeFormatter ASCTIME_DATE_TIME = new DateTimeFormatterBuilder()
5656
.appendPattern("EEE MMM")
5757
.appendLiteral(' ')

src/main/java/io/github/nstdio/http/ext/HttpHeadersBuilder.java

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
import java.util.function.BiPredicate;
2525

2626
import static io.github.nstdio.http.ext.Headers.ALLOW_ALL;
27+
import static io.github.nstdio.http.ext.Headers.EMPTY_HEADERS;
2728

2829
class HttpHeadersBuilder {
2930
private final TreeMap<String, List<String>> headersMap;
@@ -47,7 +48,7 @@ private void copyTo(HttpHeadersBuilder builder, Map<String, List<String>> source
4748
private List<String> values(String name, int capacity) {
4849
return headersMap.computeIfAbsent(name, k -> new ArrayList<>(capacity));
4950
}
50-
51+
5152
private List<String> values(String name) {
5253
return values(name, 1);
5354
}
@@ -118,7 +119,7 @@ HttpHeaders build() {
118119
}
119120

120121
HttpHeaders build(BiPredicate<String, String> filter) {
121-
return HttpHeaders.of(headersMap, filter);
122+
return headersMap.isEmpty() ? EMPTY_HEADERS : HttpHeaders.of(headersMap, filter);
122123
}
123124

124125
@Override

src/test/kotlin/io/github/nstdio/http/ext/HttpHeadersBuilderTest.kt

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@
1616
package io.github.nstdio.http.ext
1717

1818
import io.github.nstdio.http.ext.Assertions.assertThat
19+
import io.kotest.matchers.maps.shouldBeEmpty
20+
import io.kotest.matchers.types.shouldBeSameInstanceAs
1921
import org.junit.jupiter.api.BeforeEach
2022
import org.junit.jupiter.api.Test
2123

@@ -126,4 +128,15 @@ internal class HttpHeadersBuilderTest {
126128
assertThat(builder.build())
127129
.isEmpty()
128130
}
131+
132+
@Test
133+
fun `Should not create new empty instances`() {
134+
//when
135+
val h1 = builder.build()
136+
val h2 = builder.build()
137+
138+
//then
139+
h1 shouldBeSameInstanceAs h2
140+
h1.map().shouldBeEmpty()
141+
}
129142
}

0 commit comments

Comments
 (0)