Skip to content

Commit 28a5e18

Browse files
authored
chore: reduce one Option match for elements in object pool (#159)
* chore: reduce one Option match for elements in object pool Signed-off-by: Andy Lok <[email protected]> * add LocalParentGuard back again Signed-off-by: Andy Lok <[email protected]> * improve doc * fix test Signed-off-by: Andy Lok <[email protected]> --------- Signed-off-by: Andy Lok <[email protected]>
1 parent 7713549 commit 28a5e18

File tree

10 files changed

+87
-48
lines changed

10 files changed

+87
-48
lines changed

minitrace/Cargo.toml

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@ keywords = ["tracing", "span", "datadog", "jaeger", "opentelemetry"]
1616
enable = []
1717

1818
[dependencies]
19-
defer = "0.1"
2019
futures = "0.3"
2120
minitrace-macro = { version = "0.5.0", path = "../minitrace-macro" }
2221
minstant = "0.1"

minitrace/src/collector/console_reporter.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
use super::global_collector::Reporter;
44
use super::SpanRecord;
55

6-
/// A console reporter that logs span records to the stderr.
6+
/// A console reporter that prints span records to the stderr.
77
pub struct ConsoleReporter;
88

99
impl Reporter for ConsoleReporter {

minitrace/src/collector/global_collector.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -438,7 +438,7 @@ fn amend_local_span(
438438
continue;
439439
}
440440

441-
let end_unix_time_ns = if span.end_instant == span.begin_instant {
441+
let end_time_unix_ns = if span.end_instant == span.begin_instant {
442442
local_spans.end_time.as_unix_nanos(anchor)
443443
} else {
444444
span.end_instant.as_unix_nanos(anchor)
@@ -448,7 +448,7 @@ fn amend_local_span(
448448
span_id: span.id,
449449
parent_id,
450450
begin_time_unix_ns,
451-
duration_ns: end_unix_time_ns.saturating_sub(begin_time_unix_ns),
451+
duration_ns: end_time_unix_ns.saturating_sub(begin_time_unix_ns),
452452
name: span.name,
453453
properties: span.properties.clone(),
454454
events: vec![],
@@ -476,13 +476,13 @@ fn amend_span(
476476
return;
477477
}
478478

479-
let end_unix_time_ns = raw_span.end_instant.as_unix_nanos(anchor);
479+
let end_time_unix_ns = raw_span.end_instant.as_unix_nanos(anchor);
480480
spans.push(SpanRecord {
481481
trace_id,
482482
span_id: raw_span.id,
483483
parent_id,
484484
begin_time_unix_ns,
485-
duration_ns: end_unix_time_ns.saturating_sub(begin_time_unix_ns),
485+
duration_ns: end_time_unix_ns.saturating_sub(begin_time_unix_ns),
486486
name: raw_span.name,
487487
properties: raw_span.properties.clone(),
488488
events: vec![],

minitrace/src/lib.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,13 +113,15 @@
113113
//!
114114
//! {
115115
//! let root_span = Span::root("root", SpanContext::random());
116+
//!
116117
//! {
117118
//! let child_span = Span::enter_with_parent("a child span", &root_span);
118119
//!
119120
//! // ...
120121
//!
121122
//! // child_span ends here.
122123
//! }
124+
//!
123125
//! // root_span ends here.
124126
//! }
125127
//!
@@ -145,6 +147,7 @@
145147
//!
146148
//! {
147149
//! let root = Span::root("root", SpanContext::random());
150+
//!
148151
//! {
149152
//! let _guard = root.set_local_parent();
150153
//!

minitrace/src/local/local_collector.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ use crate::local::local_span_stack::LOCAL_SPAN_STACK;
1212
use crate::util::CollectToken;
1313
use crate::util::RawSpans;
1414

15-
/// Collector to collect [`LocalSpan`].
15+
/// A collector to collect [`LocalSpan`].
1616
///
1717
/// `LocalCollector` allows to collect `LocalSpan` manually without a local parent. The collected `LocalSpan` can later be
1818
/// attached to a parent.

minitrace/src/local/local_span_line.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -193,11 +193,11 @@ span []
193193
span_line2.add_properties(&span, || [("k1".into(), "v1".into())]);
194194
span_line1.finish_span(span);
195195

196-
let raw_spans = span_line1.collect(1).unwrap().0.into_inner().1;
196+
let raw_spans = span_line1.collect(1).unwrap().0.into_inner();
197197
assert_eq!(raw_spans.len(), 1);
198198
assert_eq!(raw_spans[0].properties.len(), 0);
199199

200-
let raw_spans = span_line2.collect(2).unwrap().0.into_inner().1;
200+
let raw_spans = span_line2.collect(2).unwrap().0.into_inner();
201201
assert!(raw_spans.is_empty());
202202
}
203203

@@ -228,11 +228,11 @@ span []
228228
let (spans, collect_token) = span_line1.collect(1).unwrap();
229229
let collect_token = collect_token.unwrap();
230230
assert_eq!(collect_token.as_slice(), &[item]);
231-
assert_eq!(spans.into_inner().1.len(), 1);
231+
assert_eq!(spans.into_inner().len(), 1);
232232

233233
let (spans, collect_token) = span_line2.collect(2).unwrap();
234234
assert!(collect_token.is_none());
235-
assert!(spans.into_inner().1.is_empty());
235+
assert!(spans.into_inner().is_empty());
236236
}
237237

238238
#[test]

minitrace/src/local/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,3 +12,4 @@ pub(crate) mod span_queue;
1212
pub use self::local_collector::LocalCollector;
1313
pub use self::local_collector::LocalSpans;
1414
pub use self::local_span::LocalSpan;
15+
pub use crate::span::LocalParentGuard;

minitrace/src/span.rs

Lines changed: 54 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -226,10 +226,10 @@ impl Span {
226226
///
227227
/// [`LocalSpan`]: crate::local::LocalSpan
228228
/// [`LocalSpan::enter_with_local_parent()`]: crate::local::LocalSpan::enter_with_local_parent
229-
pub fn set_local_parent(&self) -> Option<impl Drop> {
229+
pub fn set_local_parent(&self) -> LocalParentGuard {
230230
#[cfg(not(feature = "enable"))]
231231
{
232-
None::<Span>
232+
LocalParentGuard::noop()
233233
}
234234

235235
#[cfg(feature = "enable")]
@@ -388,10 +388,11 @@ impl Span {
388388
pub(crate) fn attach_into_stack(
389389
&self,
390390
stack: &Rc<RefCell<LocalSpanStack>>,
391-
) -> Option<impl Drop> {
391+
) -> LocalParentGuard {
392392
self.inner
393393
.as_ref()
394394
.map(move |inner| inner.capture_local_spans(stack.clone()))
395+
.unwrap_or_else(LocalParentGuard::noop)
395396
}
396397
}
397398

@@ -409,19 +410,11 @@ impl SpanInner {
409410
}
410411

411412
#[inline]
412-
fn capture_local_spans(&self, stack: Rc<RefCell<LocalSpanStack>>) -> impl Drop {
413+
fn capture_local_spans(&self, stack: Rc<RefCell<LocalSpanStack>>) -> LocalParentGuard {
413414
let token = self.issue_collect_token().collect();
414415
let collector = LocalCollector::new(Some(token), stack);
415-
let collect = self.collect.clone();
416-
defer::defer(move || {
417-
let (spans, token) = collector.collect_spans_and_token();
418-
debug_assert!(token.is_some());
419-
let token = token.unwrap_or_else(|| [].iter().collect());
420416

421-
if !spans.spans.is_empty() {
422-
collect.submit_spans(SpanSet::LocalSpansInner(spans), token);
423-
}
424-
})
417+
LocalParentGuard::new(collector, self.collect.clone())
425418
}
426419

427420
#[inline]
@@ -473,6 +466,51 @@ impl Drop for Span {
473466
}
474467
}
475468

469+
/// A guard created by [`Span::set_local_parent()`].
470+
#[derive(Default)]
471+
pub struct LocalParentGuard {
472+
#[cfg(feature = "enable")]
473+
inner: Option<LocalParentGuardInner>,
474+
}
475+
476+
struct LocalParentGuardInner {
477+
collector: LocalCollector,
478+
collect: GlobalCollect,
479+
}
480+
481+
impl LocalParentGuard {
482+
pub(crate) fn noop() -> LocalParentGuard {
483+
LocalParentGuard {
484+
#[cfg(feature = "enable")]
485+
inner: None,
486+
}
487+
}
488+
489+
pub(crate) fn new(collector: LocalCollector, collect: GlobalCollect) -> LocalParentGuard {
490+
LocalParentGuard {
491+
#[cfg(feature = "enable")]
492+
inner: Some(LocalParentGuardInner { collector, collect }),
493+
}
494+
}
495+
}
496+
497+
impl Drop for LocalParentGuard {
498+
fn drop(&mut self) {
499+
#[cfg(feature = "enable")]
500+
if let Some(inner) = self.inner.take() {
501+
let (spans, token) = inner.collector.collect_spans_and_token();
502+
debug_assert!(token.is_some());
503+
if let Some(token) = token {
504+
if !spans.spans.is_empty() {
505+
inner
506+
.collect
507+
.submit_spans(SpanSet::LocalSpansInner(spans), token);
508+
}
509+
}
510+
}
511+
}
512+
}
513+
476514
#[cfg(test)]
477515
mod tests {
478516
use std::sync::atomic::AtomicUsize;
@@ -495,7 +533,7 @@ mod tests {
495533
fn noop_basic() {
496534
let span = Span::noop();
497535
let stack = Rc::new(RefCell::new(LocalSpanStack::with_capacity(16)));
498-
assert!(span.attach_into_stack(&stack).is_none());
536+
assert!(span.attach_into_stack(&stack).inner.is_none());
499537
assert!(stack.borrow_mut().enter_span("span1").is_none());
500538
}
501539

@@ -809,11 +847,11 @@ parent5 []
809847
{
810848
let parent_ctx = SpanContext::random();
811849
let root = Span::root("root", parent_ctx, collect.clone());
812-
let _g = root.attach_into_stack(&stack).unwrap();
850+
let _g = root.attach_into_stack(&stack);
813851
let child =
814852
Span::enter_with_stack("child", &mut stack.borrow_mut(), collect.clone());
815853
{
816-
let _g = child.attach_into_stack(&stack).unwrap();
854+
let _g = child.attach_into_stack(&stack);
817855
let _s = Span::enter_with_stack("grandchild", &mut stack.borrow_mut(), collect);
818856
}
819857
let _s = LocalSpan::enter_with_stack("local", stack);

minitrace/src/util/object_pool.rs

Lines changed: 18 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
// Copyright 2022 TiKV Project Authors. Licensed under Apache-2.0.
22

3+
use std::mem::ManuallyDrop;
34
use std::ops::Deref;
45
use std::ops::DerefMut;
56

@@ -21,16 +22,6 @@ impl<T> Pool<T> {
2122
}
2223
}
2324

24-
#[inline]
25-
#[allow(dead_code)]
26-
pub fn pull(&self) -> Reusable<T> {
27-
self.objects
28-
.lock()
29-
.pop()
30-
.map(|obj| Reusable::new(self, obj))
31-
.unwrap_or_else(|| Reusable::new(self, (self.init)()))
32-
}
33-
3425
#[inline]
3526
fn batch_pull<'a>(&'a self, n: usize, buffer: &mut Vec<Reusable<'a, T>>) {
3627
let mut objects = self.objects.lock();
@@ -78,26 +69,33 @@ impl<'a, T> Puller<'a, T> {
7869

7970
pub struct Reusable<'a, T> {
8071
pool: &'a Pool<T>,
81-
obj: Option<T>,
72+
obj: ManuallyDrop<T>,
8273
}
8374

8475
impl<'a, T> Reusable<'a, T> {
8576
#[inline]
86-
pub fn new(pool: &'a Pool<T>, t: T) -> Self {
87-
Self { pool, obj: Some(t) }
77+
pub fn new(pool: &'a Pool<T>, obj: T) -> Self {
78+
Self {
79+
pool,
80+
obj: ManuallyDrop::new(obj),
81+
}
8882
}
8983

9084
#[inline]
91-
pub fn into_inner(mut self) -> (&'a Pool<T>, T) {
92-
(self.pool, self.obj.take().unwrap())
85+
pub fn into_inner(mut self) -> T {
86+
unsafe {
87+
let obj = ManuallyDrop::take(&mut self.obj);
88+
std::mem::forget(self);
89+
obj
90+
}
9391
}
9492
}
9593

9694
impl<'a, T> std::fmt::Debug for Reusable<'a, T>
9795
where T: std::fmt::Debug
9896
{
9997
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
100-
self.obj.as_ref().unwrap().fmt(f)
98+
self.obj.fmt(f)
10199
}
102100
}
103101

@@ -116,22 +114,22 @@ impl<'a, T> Deref for Reusable<'a, T> {
116114

117115
#[inline]
118116
fn deref(&self) -> &Self::Target {
119-
self.obj.as_ref().unwrap()
117+
&self.obj
120118
}
121119
}
122120

123121
impl<'a, T> DerefMut for Reusable<'a, T> {
124122
#[inline]
125123
fn deref_mut(&mut self) -> &mut Self::Target {
126-
self.obj.as_mut().unwrap()
124+
&mut self.obj
127125
}
128126
}
129127

130128
impl<'a, T> Drop for Reusable<'a, T> {
131129
#[inline]
132130
fn drop(&mut self) {
133-
if let Some(obj) = self.obj.take() {
134-
self.pool.recycle(obj);
131+
unsafe {
132+
self.pool.recycle(ManuallyDrop::take(&mut self.obj));
135133
}
136134
}
137135
}

minitrace/src/util/tree.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ impl Tree {
5555
pub fn from_raw_spans(raw_spans: RawSpans) -> Vec<Tree> {
5656
let mut children = HashMap::new();
5757

58-
let spans = raw_spans.into_inner().1;
58+
let spans = raw_spans.into_inner();
5959
children.insert(SpanId::default(), ("", vec![], vec![]));
6060
for span in &spans {
6161
children.insert(span.id, (span.name, vec![], span.properties.clone()));

0 commit comments

Comments
 (0)