Skip to content

Commit 5f3abd7

Browse files
Reduce allocations when fetching headers.
1 parent d72c24a commit 5f3abd7

File tree

3 files changed

+18
-2
lines changed

3 files changed

+18
-2
lines changed

ext/hyper_ruby/src/gvl_helpers.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ use std::{ffi::c_void, mem::MaybeUninit, ptr::null_mut};
22
use rb_sys::rb_thread_call_without_gvl;
33

44
// Call a specified function, having released the GVL. Acquires the GVL before returning.
5+
// Credit to https://github.com/Shopify/lz4-flex-rb for this one.
56
pub(crate) fn nogvl<F, R>(mut func: F) -> R
67
where
78
F: FnMut() -> R,

ext/hyper_ruby/src/request.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,10 @@ impl Request {
1818
RString::new(&self.request.uri().path())
1919
}
2020

21-
pub fn header(&self, key: String) -> Value {
22-
match self.request.headers().get(key) {
21+
pub fn header(&self, key: RString) -> Value {
22+
// Avoid allocating a new header key string
23+
let key_str = unsafe { key.as_str().unwrap() };
24+
match self.request.headers().get(key_str) {
2325
Some(value) => match value.to_str() {
2426
Ok(value) => RString::new(value).as_value(),
2527
Err(_) => qnil().as_value(),

test/test_hyper_ruby.rb

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,14 @@ def test_simple_get
1717
end
1818
end
1919

20+
def test_header_fetch_get
21+
with_server(-> (request) { handler_return_header(request, 'User-Agent') }) do |client|
22+
response = client.get("/", headers: { 'User-Agent' => 'test' })
23+
assert_equal 200, response.status
24+
assert_equal "test", JSON.parse(response.body)["message"]
25+
end
26+
end
27+
2028
def test_simple_post
2129
with_server(-> (request) { handler_to_json(request) }) do |client|
2230
response = client.post("/", body: "Hello")
@@ -113,4 +121,9 @@ def handler_simple(request)
113121
def handler_to_json(request)
114122
HyperRuby::Response.new(200, { 'Content-Type' => 'application/json' }, { message: request.body }.to_json)
115123
end
124+
125+
126+
def handler_return_header(request, header_key)
127+
HyperRuby::Response.new(200, { 'Content-Type' => 'application/json' }, { message: request.header(header_key) }.to_json)
128+
end
116129
end

0 commit comments

Comments
 (0)