Skip to content

Commit

Permalink
chore: Use empty headers when there is no value in builder.
Browse files Browse the repository at this point in the history
  • Loading branch information
nstdio committed Jan 7, 2023
1 parent 4863997 commit 88d2bb8
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 3 deletions.
2 changes: 1 addition & 1 deletion src/main/java/io/github/nstdio/http/ext/Headers.java
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ class Headers {
static final String HEADER_LAST_MODIFIED = "Last-Modified";
static final String HEADER_WARNING = "Warning";
static final BiPredicate<String, String> ALLOW_ALL = (s, s2) -> true;
private static final HttpHeaders EMPTY_HEADERS = HttpHeaders.of(Map.of(), ALLOW_ALL);
static final HttpHeaders EMPTY_HEADERS = HttpHeaders.of(Map.of(), ALLOW_ALL);
private static final DateTimeFormatter ASCTIME_DATE_TIME = new DateTimeFormatterBuilder()
.appendPattern("EEE MMM")
.appendLiteral(' ')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import java.util.function.BiPredicate;

import static io.github.nstdio.http.ext.Headers.ALLOW_ALL;
import static io.github.nstdio.http.ext.Headers.EMPTY_HEADERS;

class HttpHeadersBuilder {
private final TreeMap<String, List<String>> headersMap;
Expand All @@ -47,7 +48,7 @@ private void copyTo(HttpHeadersBuilder builder, Map<String, List<String>> source
private List<String> values(String name, int capacity) {
return headersMap.computeIfAbsent(name, k -> new ArrayList<>(capacity));
}

private List<String> values(String name) {
return values(name, 1);
}
Expand Down Expand Up @@ -118,7 +119,7 @@ HttpHeaders build() {
}

HttpHeaders build(BiPredicate<String, String> filter) {
return HttpHeaders.of(headersMap, filter);
return headersMap.isEmpty() ? EMPTY_HEADERS : HttpHeaders.of(headersMap, filter);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
package io.github.nstdio.http.ext

import io.github.nstdio.http.ext.Assertions.assertThat
import io.kotest.matchers.maps.shouldBeEmpty
import io.kotest.matchers.types.shouldBeSameInstanceAs
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test

Expand Down Expand Up @@ -126,4 +128,15 @@ internal class HttpHeadersBuilderTest {
assertThat(builder.build())
.isEmpty()
}

@Test
fun `Should not create new empty instances`() {
//when
val h1 = builder.build()
val h2 = builder.build()

//then
h1 shouldBeSameInstanceAs h2
h1.map().shouldBeEmpty()
}
}

0 comments on commit 88d2bb8

Please sign in to comment.