Skip to content

Commit

Permalink
Use CStr::to_string_lossy in Base{Consumer,Producer}
Browse files Browse the repository at this point in the history
In some error cases, the `Base{Consumer,Producer}` were eagerly copying strings,
and `unwrap`ing utf8 validation, just to print an error message.

This will avoid the allocation in the common case, and be panic-safe in the presumably unreachable case of invalid utf-8.
  • Loading branch information
Swatinem committed Dec 19, 2023
1 parent 0c5c131 commit 15044da
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 12 deletions.
14 changes: 6 additions & 8 deletions src/consumer/base_consumer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,12 +149,11 @@ where
self.handle_offset_commit_event(event);
}
_ => {
let buf = unsafe {
let evname = unsafe {
let evname = rdsys::rd_kafka_event_name(event.ptr());
CStr::from_ptr(evname).to_bytes()
CStr::from_ptr(evname).to_string_lossy()
};
let evname = String::from_utf8(buf.to_vec()).unwrap();
warn!("Ignored event '{}' on consumer poll", evname);
warn!("Ignored event '{evname}' on consumer poll");
}
}
}
Expand Down Expand Up @@ -192,13 +191,12 @@ where
.rebalance(self.client.native_client(), err, &mut tpl);
}
_ => {
let buf = unsafe {
let err = unsafe {
let err_name =
rdsys::rd_kafka_err2name(rdsys::rd_kafka_event_error(event.ptr()));
CStr::from_ptr(err_name).to_bytes()
CStr::from_ptr(err_name).to_string_lossy()
};
let err = String::from_utf8(buf.to_vec()).unwrap();
warn!("invalid rebalance event: {:?}", err);
warn!("invalid rebalance event: {err}");
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/mocking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ where
pub fn bootstrap_servers(&self) -> String {
let bootstrap =
unsafe { CStr::from_ptr(rdsys::rd_kafka_mock_cluster_bootstraps(self.mock_cluster)) };
bootstrap.to_string_lossy().to_string()
bootstrap.to_string_lossy().into_owned()
}

/// Clear the cluster's error state for the given ApiKey.
Expand Down
5 changes: 2 additions & 3 deletions src/producer/base_producer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -368,11 +368,10 @@ where
match evtype {
rdsys::RD_KAFKA_EVENT_DR => self.handle_delivery_report_event(ev),
_ => {
let buf = unsafe {
let evname = unsafe {
let evname = rdsys::rd_kafka_event_name(ev.ptr());
CStr::from_ptr(evname).to_bytes()
CStr::from_ptr(evname).to_string_lossy()
};
let evname = String::from_utf8(buf.to_vec()).unwrap();
warn!("Ignored event '{}' on base producer poll", evname);
}
}
Expand Down

0 comments on commit 15044da

Please sign in to comment.