Skip to content

Commit 15044da

Browse files
committed
Use CStr::to_string_lossy in Base{Consumer,Producer}
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.
1 parent 0c5c131 commit 15044da

File tree

3 files changed

+9
-12
lines changed

3 files changed

+9
-12
lines changed

src/consumer/base_consumer.rs

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -149,12 +149,11 @@ where
149149
self.handle_offset_commit_event(event);
150150
}
151151
_ => {
152-
let buf = unsafe {
152+
let evname = unsafe {
153153
let evname = rdsys::rd_kafka_event_name(event.ptr());
154-
CStr::from_ptr(evname).to_bytes()
154+
CStr::from_ptr(evname).to_string_lossy()
155155
};
156-
let evname = String::from_utf8(buf.to_vec()).unwrap();
157-
warn!("Ignored event '{}' on consumer poll", evname);
156+
warn!("Ignored event '{evname}' on consumer poll");
158157
}
159158
}
160159
}
@@ -192,13 +191,12 @@ where
192191
.rebalance(self.client.native_client(), err, &mut tpl);
193192
}
194193
_ => {
195-
let buf = unsafe {
194+
let err = unsafe {
196195
let err_name =
197196
rdsys::rd_kafka_err2name(rdsys::rd_kafka_event_error(event.ptr()));
198-
CStr::from_ptr(err_name).to_bytes()
197+
CStr::from_ptr(err_name).to_string_lossy()
199198
};
200-
let err = String::from_utf8(buf.to_vec()).unwrap();
201-
warn!("invalid rebalance event: {:?}", err);
199+
warn!("invalid rebalance event: {err}");
202200
}
203201
}
204202
}

src/mocking.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,7 @@ where
137137
pub fn bootstrap_servers(&self) -> String {
138138
let bootstrap =
139139
unsafe { CStr::from_ptr(rdsys::rd_kafka_mock_cluster_bootstraps(self.mock_cluster)) };
140-
bootstrap.to_string_lossy().to_string()
140+
bootstrap.to_string_lossy().into_owned()
141141
}
142142

143143
/// Clear the cluster's error state for the given ApiKey.

src/producer/base_producer.rs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -368,11 +368,10 @@ where
368368
match evtype {
369369
rdsys::RD_KAFKA_EVENT_DR => self.handle_delivery_report_event(ev),
370370
_ => {
371-
let buf = unsafe {
371+
let evname = unsafe {
372372
let evname = rdsys::rd_kafka_event_name(ev.ptr());
373-
CStr::from_ptr(evname).to_bytes()
373+
CStr::from_ptr(evname).to_string_lossy()
374374
};
375-
let evname = String::from_utf8(buf.to_vec()).unwrap();
376375
warn!("Ignored event '{}' on base producer poll", evname);
377376
}
378377
}

0 commit comments

Comments
 (0)