1//! ## Per-Layer Filtering
2//!
3//! Per-layer filters permit individual `Layer`s to have their own filter
4//! configurations without interfering with other `Layer`s.
5//!
6//! This module is not public; the public APIs defined in this module are
7//! re-exported in the top-level `filter` module. Therefore, this documentation
8//! primarily concerns the internal implementation details. For the user-facing
9//! public API documentation, see the individual public types in this module, as
10//! well as the, see the `Layer` trait documentation's [per-layer filtering
11//! section]][1].
12//!
13//! ## How does per-layer filtering work?
14//!
15//! As described in the API documentation, the [`Filter`] trait defines a
16//! filtering strategy for a per-layer filter. We expect there will be a variety
17//! of implementations of [`Filter`], both in `tracing-subscriber` and in user
18//! code.
19//!
20//! To actually *use* a [`Filter`] implementation, it is combined with a
21//! [`Layer`] by the [`Filtered`] struct defined in this module. [`Filtered`]
22//! implements [`Layer`] by calling into the wrapped [`Layer`], or not, based on
23//! the filtering strategy. While there will be a variety of types that implement
24//! [`Filter`], all actual *uses* of per-layer filtering will occur through the
25//! [`Filtered`] struct. Therefore, most of the implementation details live
26//! there.
27//!
28//! [1]: crate::layer#per-layer-filtering
29//! [`Filter`]: crate::layer::Filter
30use crate::{
31 filter::LevelFilter,
32 layer::{self, Context, Layer},
33 registry,
34};
35use std::{
36 any::TypeId,
37 cell::{Cell, RefCell},
38 fmt,
39 marker::PhantomData,
40 ops::Deref,
41 sync::Arc,
42 thread_local,
43};
44use tracing_core::{
45 span,
46 subscriber::{Interest, Subscriber},
47 Dispatch, Event, Metadata,
48};
49pub mod combinator;
50
51/// A [`Layer`] that wraps an inner [`Layer`] and adds a [`Filter`] which
52/// controls what spans and events are enabled for that layer.
53///
54/// This is returned by the [`Layer::with_filter`] method. See the
55/// [documentation on per-layer filtering][plf] for details.
56///
57/// [`Filter`]: crate::layer::Filter
58/// [plf]: crate::layer#per-layer-filtering
59#[cfg_attr(docsrs, doc(cfg(feature = "registry")))]
60#[derive(Clone)]
61pub struct Filtered<L, F, S> {
62 filter: F,
63 layer: L,
64 id: MagicPlfDowncastMarker,
65 _s: PhantomData<fn(S)>,
66}
67
68/// Uniquely identifies an individual [`Filter`] instance in the context of
69/// a [`Subscriber`].
70///
71/// When adding a [`Filtered`] [`Layer`] to a [`Subscriber`], the [`Subscriber`]
72/// generates a `FilterId` for that [`Filtered`] layer. The [`Filtered`] layer
73/// will then use the generated ID to query whether a particular span was
74/// previously enabled by that layer's [`Filter`].
75///
76/// **Note**: Currently, the [`Registry`] type provided by this crate is the
77/// **only** [`Subscriber`] implementation capable of participating in per-layer
78/// filtering. Therefore, the `FilterId` type cannot currently be constructed by
79/// code outside of `tracing-subscriber`. In the future, new APIs will be added to `tracing-subscriber` to
80/// allow non-Registry [`Subscriber`]s to also participate in per-layer
81/// filtering. When those APIs are added, subscribers will be responsible
82/// for generating and assigning `FilterId`s.
83///
84/// [`Filter`]: crate::layer::Filter
85/// [`Subscriber`]: tracing_core::Subscriber
86/// [`Layer`]: crate::layer::Layer
87/// [`Registry`]: crate::registry::Registry
88#[cfg(feature = "registry")]
89#[cfg_attr(docsrs, doc(cfg(feature = "registry")))]
90#[derive(Copy, Clone)]
91pub struct FilterId(u64);
92
93/// A bitmap tracking which [`FilterId`]s have enabled a given span or
94/// event.
95///
96/// This is currently a private type that's used exclusively by the
97/// [`Registry`]. However, in the future, this may become a public API, in order
98/// to allow user subscribers to host [`Filter`]s.
99///
100/// [`Registry`]: crate::Registry
101/// [`Filter`]: crate::layer::Filter
102#[derive(Default, Copy, Clone, Eq, PartialEq)]
103pub(crate) struct FilterMap {
104 bits: u64,
105}
106
107/// The current state of `enabled` calls to per-layer filters on this
108/// thread.
109///
110/// When `Filtered::enabled` is called, the filter will set the bit
111/// corresponding to its ID if the filter will disable the event/span being
112/// filtered. When the event or span is recorded, the per-layer filter will
113/// check its bit to determine if it disabled that event or span, and skip
114/// forwarding the event or span to the inner layer if the bit is set. Once
115/// a span or event has been skipped by a per-layer filter, it unsets its
116/// bit, so that the `FilterMap` has been cleared for the next set of
117/// `enabled` calls.
118///
119/// FilterState is also read by the `Registry`, for two reasons:
120///
121/// 1. When filtering a span, the Registry must store the `FilterMap`
122/// generated by `Filtered::enabled` calls for that span as part of the
123/// span's per-span data. This allows `Filtered` layers to determine
124/// whether they had previously disabled a given span, and avoid showing it
125/// to the wrapped layer if it was disabled.
126///
127/// This allows `Filtered` layers to also filter out the spans they
128/// disable from span traversals (such as iterating over parents, etc).
129/// 2. If all the bits are set, then every per-layer filter has decided it
130/// doesn't want to enable that span or event. In that case, the
131/// `Registry`'s `enabled` method will return `false`, so that
132/// recording a span or event can be skipped entirely.
133#[derive(Debug)]
134pub(crate) struct FilterState {
135 enabled: Cell<FilterMap>,
136 // TODO(eliza): `Interest`s should _probably_ be `Copy`. The only reason
137 // they're not is our Obsessive Commitment to Forwards-Compatibility. If
138 // this changes in tracing-core`, we can make this a `Cell` rather than
139 // `RefCell`...
140 interest: RefCell<Option<Interest>>,
141
142 #[cfg(debug_assertions)]
143 counters: DebugCounters,
144}
145
146/// Extra counters added to `FilterState` used only to make debug assertions.
147#[cfg(debug_assertions)]
148#[derive(Debug, Default)]
149struct DebugCounters {
150 /// How many per-layer filters have participated in the current `enabled`
151 /// call?
152 in_filter_pass: Cell<usize>,
153
154 /// How many per-layer filters have participated in the current `register_callsite`
155 /// call?
156 in_interest_pass: Cell<usize>,
157}
158
159thread_local! {
160 pub(crate) static FILTERING: FilterState = FilterState::new();
161}
162
163/// Extension trait adding [combinators] for combining [`Filter`].
164///
165/// [combinators]: crate::filter::combinator
166/// [`Filter`]: crate::layer::Filter
167pub trait FilterExt<S>: layer::Filter<S> {
168 /// Combines this [`Filter`] with another [`Filter`] s so that spans and
169 /// events are enabled if and only if *both* filters return `true`.
170 ///
171 /// # Examples
172 ///
173 /// Enabling spans or events if they have both a particular target *and* are
174 /// above a certain level:
175 ///
176 /// ```
177 /// use tracing_subscriber::{
178 /// filter::{filter_fn, LevelFilter, FilterExt},
179 /// prelude::*,
180 /// };
181 ///
182 /// // Enables spans and events with targets starting with `interesting_target`:
183 /// let target_filter = filter_fn(|meta| {
184 /// meta.target().starts_with("interesting_target")
185 /// });
186 ///
187 /// // Enables spans and events with levels `INFO` and below:
188 /// let level_filter = LevelFilter::INFO;
189 ///
190 /// // Combine the two filters together, returning a filter that only enables
191 /// // spans and events that *both* filters will enable:
192 /// let filter = target_filter.and(level_filter);
193 ///
194 /// tracing_subscriber::registry()
195 /// .with(tracing_subscriber::fmt::layer().with_filter(filter))
196 /// .init();
197 ///
198 /// // This event will *not* be enabled:
199 /// tracing::info!("an event with an uninteresting target");
200 ///
201 /// // This event *will* be enabled:
202 /// tracing::info!(target: "interesting_target", "a very interesting event");
203 ///
204 /// // This event will *not* be enabled:
205 /// tracing::debug!(target: "interesting_target", "interesting debug event...");
206 /// ```
207 ///
208 /// [`Filter`]: crate::layer::Filter
209 fn and<B>(self, other: B) -> combinator::And<Self, B, S>
210 where
211 Self: Sized,
212 B: layer::Filter<S>,
213 {
214 combinator::And::new(self, other)
215 }
216
217 /// Combines two [`Filter`]s so that spans and events are enabled if *either* filter
218 /// returns `true`.
219 ///
220 /// # Examples
221 ///
222 /// Enabling spans and events at the `INFO` level and above, and all spans
223 /// and events with a particular target:
224 /// ```
225 /// use tracing_subscriber::{
226 /// filter::{filter_fn, LevelFilter, FilterExt},
227 /// prelude::*,
228 /// };
229 ///
230 /// // Enables spans and events with targets starting with `interesting_target`:
231 /// let target_filter = filter_fn(|meta| {
232 /// meta.target().starts_with("interesting_target")
233 /// });
234 ///
235 /// // Enables spans and events with levels `INFO` and below:
236 /// let level_filter = LevelFilter::INFO;
237 ///
238 /// // Combine the two filters together so that a span or event is enabled
239 /// // if it is at INFO or lower, or if it has a target starting with
240 /// // `interesting_target`.
241 /// let filter = level_filter.or(target_filter);
242 ///
243 /// tracing_subscriber::registry()
244 /// .with(tracing_subscriber::fmt::layer().with_filter(filter))
245 /// .init();
246 ///
247 /// // This event will *not* be enabled:
248 /// tracing::debug!("an uninteresting event");
249 ///
250 /// // This event *will* be enabled:
251 /// tracing::info!("an uninteresting INFO event");
252 ///
253 /// // This event *will* be enabled:
254 /// tracing::info!(target: "interesting_target", "a very interesting event");
255 ///
256 /// // This event *will* be enabled:
257 /// tracing::debug!(target: "interesting_target", "interesting debug event...");
258 /// ```
259 ///
260 /// Enabling a higher level for a particular target by using `or` in
261 /// conjunction with the [`and`] combinator:
262 ///
263 /// ```
264 /// use tracing_subscriber::{
265 /// filter::{filter_fn, LevelFilter, FilterExt},
266 /// prelude::*,
267 /// };
268 ///
269 /// // This filter will enable spans and events with targets beginning with
270 /// // `my_crate`:
271 /// let my_crate = filter_fn(|meta| {
272 /// meta.target().starts_with("my_crate")
273 /// });
274 ///
275 /// let filter = my_crate
276 /// // Combine the `my_crate` filter with a `LevelFilter` to produce a
277 /// // filter that will enable the `INFO` level and lower for spans and
278 /// // events with `my_crate` targets:
279 /// .and(LevelFilter::INFO)
280 /// // If a span or event *doesn't* have a target beginning with
281 /// // `my_crate`, enable it if it has the `WARN` level or lower:
282 /// .or(LevelFilter::WARN);
283 ///
284 /// tracing_subscriber::registry()
285 /// .with(tracing_subscriber::fmt::layer().with_filter(filter))
286 /// .init();
287 /// ```
288 ///
289 /// [`Filter`]: crate::layer::Filter
290 /// [`and`]: FilterExt::and
291 fn or<B>(self, other: B) -> combinator::Or<Self, B, S>
292 where
293 Self: Sized,
294 B: layer::Filter<S>,
295 {
296 combinator::Or::new(self, other)
297 }
298
299 /// Inverts `self`, returning a filter that enables spans and events only if
300 /// `self` would *not* enable them.
301 ///
302 /// This inverts the values returned by the [`enabled`] and [`callsite_enabled`]
303 /// methods on the wrapped filter; it does *not* invert [`event_enabled`], as
304 /// filters which do not implement filtering on event field values will return
305 /// the default `true` even for events that their [`enabled`] method disables.
306 ///
307 /// Consider a normal filter defined as:
308 ///
309 /// ```ignore (pseudo-code)
310 /// // for spans
311 /// match callsite_enabled() {
312 /// ALWAYS => on_span(),
313 /// SOMETIMES => if enabled() { on_span() },
314 /// NEVER => (),
315 /// }
316 /// // for events
317 /// match callsite_enabled() {
318 /// ALWAYS => on_event(),
319 /// SOMETIMES => if enabled() && event_enabled() { on_event() },
320 /// NEVER => (),
321 /// }
322 /// ```
323 ///
324 /// and an inverted filter defined as:
325 ///
326 /// ```ignore (pseudo-code)
327 /// // for spans
328 /// match callsite_enabled() {
329 /// ALWAYS => (),
330 /// SOMETIMES => if !enabled() { on_span() },
331 /// NEVER => on_span(),
332 /// }
333 /// // for events
334 /// match callsite_enabled() {
335 /// ALWAYS => (),
336 /// SOMETIMES => if !enabled() { on_event() },
337 /// NEVER => on_event(),
338 /// }
339 /// ```
340 ///
341 /// A proper inversion would do `!(enabled() && event_enabled())` (or
342 /// `!enabled() || !event_enabled()`), but because of the implicit `&&`
343 /// relation between `enabled` and `event_enabled`, it is difficult to
344 /// short circuit and not call the wrapped `event_enabled`.
345 ///
346 /// A combinator which remembers the result of `enabled` in order to call
347 /// `event_enabled` only when `enabled() == true` is possible, but requires
348 /// additional thread-local mutable state to support a very niche use case.
349 //
350 // Also, it'd mean the wrapped layer's `enabled()` always gets called and
351 // globally applied to events where it doesn't today, since we can't know
352 // what `event_enabled` will say until we have the event to call it with.
353 ///
354 /// [`Filter`]: crate::layer::Filter
355 /// [`enabled`]: crate::layer::Filter::enabled
356 /// [`event_enabled`]: crate::layer::Filter::event_enabled
357 /// [`callsite_enabled`]: crate::layer::Filter::callsite_enabled
358 fn not(self) -> combinator::Not<Self, S>
359 where
360 Self: Sized,
361 {
362 combinator::Not::new(self)
363 }
364
365 /// [Boxes] `self`, erasing its concrete type.
366 ///
367 /// This is equivalent to calling [`Box::new`], but in method form, so that
368 /// it can be used when chaining combinator methods.
369 ///
370 /// # Examples
371 ///
372 /// When different combinations of filters are used conditionally, they may
373 /// have different types. For example, the following code won't compile,
374 /// since the `if` and `else` clause produce filters of different types:
375 ///
376 /// ```compile_fail
377 /// use tracing_subscriber::{
378 /// filter::{filter_fn, LevelFilter, FilterExt},
379 /// prelude::*,
380 /// };
381 ///
382 /// let enable_bar_target: bool = // ...
383 /// # false;
384 ///
385 /// let filter = if enable_bar_target {
386 /// filter_fn(|meta| meta.target().starts_with("foo"))
387 /// // If `enable_bar_target` is true, add a `filter_fn` enabling
388 /// // spans and events with the target `bar`:
389 /// .or(filter_fn(|meta| meta.target().starts_with("bar")))
390 /// .and(LevelFilter::INFO)
391 /// } else {
392 /// filter_fn(|meta| meta.target().starts_with("foo"))
393 /// .and(LevelFilter::INFO)
394 /// };
395 ///
396 /// tracing_subscriber::registry()
397 /// .with(tracing_subscriber::fmt::layer().with_filter(filter))
398 /// .init();
399 /// ```
400 ///
401 /// By using `boxed`, the types of the two different branches can be erased,
402 /// so the assignment to the `filter` variable is valid (as both branches
403 /// have the type `Box<dyn Filter<S> + Send + Sync + 'static>`). The
404 /// following code *does* compile:
405 ///
406 /// ```
407 /// use tracing_subscriber::{
408 /// filter::{filter_fn, LevelFilter, FilterExt},
409 /// prelude::*,
410 /// };
411 ///
412 /// let enable_bar_target: bool = // ...
413 /// # false;
414 ///
415 /// let filter = if enable_bar_target {
416 /// filter_fn(|meta| meta.target().starts_with("foo"))
417 /// .or(filter_fn(|meta| meta.target().starts_with("bar")))
418 /// .and(LevelFilter::INFO)
419 /// // Boxing the filter erases its type, so both branches now
420 /// // have the same type.
421 /// .boxed()
422 /// } else {
423 /// filter_fn(|meta| meta.target().starts_with("foo"))
424 /// .and(LevelFilter::INFO)
425 /// .boxed()
426 /// };
427 ///
428 /// tracing_subscriber::registry()
429 /// .with(tracing_subscriber::fmt::layer().with_filter(filter))
430 /// .init();
431 /// ```
432 ///
433 /// [Boxes]: std::boxed
434 /// [`Box::new`]: std::boxed::Box::new
435 fn boxed(self) -> Box<dyn layer::Filter<S> + Send + Sync + 'static>
436 where
437 Self: Sized + Send + Sync + 'static,
438 {
439 Box::new(self)
440 }
441}
442
443// === impl Filter ===
444
445#[cfg(feature = "registry")]
446#[cfg_attr(docsrs, doc(cfg(feature = "registry")))]
447impl<S> layer::Filter<S> for LevelFilter {
448 fn enabled(&self, meta: &Metadata<'_>, _: &Context<'_, S>) -> bool {
449 meta.level() <= self
450 }
451
452 fn callsite_enabled(&self, meta: &'static Metadata<'static>) -> Interest {
453 if meta.level() <= self {
454 Interest::always()
455 } else {
456 Interest::never()
457 }
458 }
459
460 fn max_level_hint(&self) -> Option<LevelFilter> {
461 Some(*self)
462 }
463}
464
465macro_rules! filter_impl_body {
466 () => {
467 #[inline]
468 fn enabled(&self, meta: &Metadata<'_>, cx: &Context<'_, S>) -> bool {
469 self.deref().enabled(meta, cx)
470 }
471
472 #[inline]
473 fn callsite_enabled(&self, meta: &'static Metadata<'static>) -> Interest {
474 self.deref().callsite_enabled(meta)
475 }
476
477 #[inline]
478 fn max_level_hint(&self) -> Option<LevelFilter> {
479 self.deref().max_level_hint()
480 }
481
482 #[inline]
483 fn event_enabled(&self, event: &Event<'_>, cx: &Context<'_, S>) -> bool {
484 self.deref().event_enabled(event, cx)
485 }
486
487 #[inline]
488 fn on_new_span(&self, attrs: &span::Attributes<'_>, id: &span::Id, ctx: Context<'_, S>) {
489 self.deref().on_new_span(attrs, id, ctx)
490 }
491
492 #[inline]
493 fn on_record(&self, id: &span::Id, values: &span::Record<'_>, ctx: Context<'_, S>) {
494 self.deref().on_record(id, values, ctx)
495 }
496
497 #[inline]
498 fn on_enter(&self, id: &span::Id, ctx: Context<'_, S>) {
499 self.deref().on_enter(id, ctx)
500 }
501
502 #[inline]
503 fn on_exit(&self, id: &span::Id, ctx: Context<'_, S>) {
504 self.deref().on_exit(id, ctx)
505 }
506
507 #[inline]
508 fn on_close(&self, id: span::Id, ctx: Context<'_, S>) {
509 self.deref().on_close(id, ctx)
510 }
511 };
512}
513
514#[cfg(feature = "registry")]
515#[cfg_attr(docsrs, doc(cfg(feature = "registry")))]
516impl<S> layer::Filter<S> for Arc<dyn layer::Filter<S> + Send + Sync + 'static> {
517 filter_impl_body!();
518}
519
520#[cfg(feature = "registry")]
521#[cfg_attr(docsrs, doc(cfg(feature = "registry")))]
522impl<S> layer::Filter<S> for Box<dyn layer::Filter<S> + Send + Sync + 'static> {
523 filter_impl_body!();
524}
525
526// Implement Filter for Option<Filter> where None => allow
527#[cfg(feature = "registry")]
528#[cfg_attr(docsrs, doc(cfg(feature = "registry")))]
529impl<F, S> layer::Filter<S> for Option<F>
530where
531 F: layer::Filter<S>,
532{
533 #[inline]
534 fn enabled(&self, meta: &Metadata<'_>, ctx: &Context<'_, S>) -> bool {
535 self.as_ref()
536 .map(|inner| inner.enabled(meta, ctx))
537 .unwrap_or(true)
538 }
539
540 #[inline]
541 fn callsite_enabled(&self, meta: &'static Metadata<'static>) -> Interest {
542 self.as_ref()
543 .map(|inner| inner.callsite_enabled(meta))
544 .unwrap_or_else(Interest::always)
545 }
546
547 #[inline]
548 fn max_level_hint(&self) -> Option<LevelFilter> {
549 self.as_ref().and_then(|inner| inner.max_level_hint())
550 }
551
552 #[inline]
553 fn event_enabled(&self, event: &Event<'_>, ctx: &Context<'_, S>) -> bool {
554 self.as_ref()
555 .map(|inner| inner.event_enabled(event, ctx))
556 .unwrap_or(true)
557 }
558
559 #[inline]
560 fn on_new_span(&self, attrs: &span::Attributes<'_>, id: &span::Id, ctx: Context<'_, S>) {
561 if let Some(inner) = self {
562 inner.on_new_span(attrs, id, ctx)
563 }
564 }
565
566 #[inline]
567 fn on_record(&self, id: &span::Id, values: &span::Record<'_>, ctx: Context<'_, S>) {
568 if let Some(inner) = self {
569 inner.on_record(id, values, ctx)
570 }
571 }
572
573 #[inline]
574 fn on_enter(&self, id: &span::Id, ctx: Context<'_, S>) {
575 if let Some(inner) = self {
576 inner.on_enter(id, ctx)
577 }
578 }
579
580 #[inline]
581 fn on_exit(&self, id: &span::Id, ctx: Context<'_, S>) {
582 if let Some(inner) = self {
583 inner.on_exit(id, ctx)
584 }
585 }
586
587 #[inline]
588 fn on_close(&self, id: span::Id, ctx: Context<'_, S>) {
589 if let Some(inner) = self {
590 inner.on_close(id, ctx)
591 }
592 }
593}
594
595// === impl Filtered ===
596
597impl<L, F, S> Filtered<L, F, S> {
598 /// Wraps the provided [`Layer`] so that it is filtered by the given
599 /// [`Filter`].
600 ///
601 /// This is equivalent to calling the [`Layer::with_filter`] method.
602 ///
603 /// See the [documentation on per-layer filtering][plf] for details.
604 ///
605 /// [`Filter`]: crate::layer::Filter
606 /// [plf]: crate::layer#per-layer-filtering
607 pub fn new(layer: L, filter: F) -> Self {
608 Self {
609 layer,
610 filter,
611 id: MagicPlfDowncastMarker(FilterId::disabled()),
612 _s: PhantomData,
613 }
614 }
615
616 #[inline(always)]
617 fn id(&self) -> FilterId {
618 debug_assert!(
619 !self.id.0.is_disabled(),
620 "a `Filtered` layer was used, but it had no `FilterId`; \
621 was it registered with the subscriber?"
622 );
623 self.id.0
624 }
625
626 fn did_enable(&self, f: impl FnOnce()) {
627 FILTERING.with(|filtering| filtering.did_enable(self.id(), f))
628 }
629
630 /// Borrows the [`Filter`](crate::layer::Filter) used by this layer.
631 pub fn filter(&self) -> &F {
632 &self.filter
633 }
634
635 /// Mutably borrows the [`Filter`](crate::layer::Filter) used by this layer.
636 ///
637 /// When this layer can be mutably borrowed, this may be used to mutate the filter.
638 /// Generally, this will primarily be used with the
639 /// [`reload::Handle::modify`](crate::reload::Handle::modify) method.
640 ///
641 /// # Examples
642 ///
643 /// ```
644 /// # use tracing::info;
645 /// # use tracing_subscriber::{filter,fmt,reload,Registry,prelude::*};
646 /// # fn main() {
647 /// let filtered_layer = fmt::Layer::default().with_filter(filter::LevelFilter::WARN);
648 /// let (filtered_layer, reload_handle) = reload::Layer::new(filtered_layer);
649 /// #
650 /// # // specifying the Registry type is required
651 /// # let _: &reload::Handle<filter::Filtered<fmt::Layer<Registry>,
652 /// # filter::LevelFilter, Registry>,Registry>
653 /// # = &reload_handle;
654 /// #
655 /// info!("This will be ignored");
656 /// reload_handle.modify(|layer| *layer.filter_mut() = filter::LevelFilter::INFO);
657 /// info!("This will be logged");
658 /// # }
659 /// ```
660 pub fn filter_mut(&mut self) -> &mut F {
661 &mut self.filter
662 }
663
664 /// Borrows the inner [`Layer`] wrapped by this `Filtered` layer.
665 pub fn inner(&self) -> &L {
666 &self.layer
667 }
668
669 /// Mutably borrows the inner [`Layer`] wrapped by this `Filtered` layer.
670 ///
671 /// This method is primarily expected to be used with the
672 /// [`reload::Handle::modify`](crate::reload::Handle::modify) method.
673 ///
674 /// # Examples
675 ///
676 /// ```
677 /// # use tracing::info;
678 /// # use tracing_subscriber::{filter,fmt,reload,Registry,prelude::*};
679 /// # fn non_blocking<T: std::io::Write>(writer: T) -> (fn() -> std::io::Stdout) {
680 /// # std::io::stdout
681 /// # }
682 /// # fn main() {
683 /// let filtered_layer = fmt::layer().with_writer(non_blocking(std::io::stderr())).with_filter(filter::LevelFilter::INFO);
684 /// let (filtered_layer, reload_handle) = reload::Layer::new(filtered_layer);
685 /// #
686 /// # // specifying the Registry type is required
687 /// # let _: &reload::Handle<filter::Filtered<fmt::Layer<Registry, _, _, fn() -> std::io::Stdout>,
688 /// # filter::LevelFilter, Registry>, Registry>
689 /// # = &reload_handle;
690 /// #
691 /// info!("This will be logged to stderr");
692 /// reload_handle.modify(|layer| *layer.inner_mut().writer_mut() = non_blocking(std::io::stdout()));
693 /// info!("This will be logged to stdout");
694 /// # }
695 /// ```
696 ///
697 /// [`Layer`]: crate::layer::Layer
698 pub fn inner_mut(&mut self) -> &mut L {
699 &mut self.layer
700 }
701}
702
703impl<S, L, F> Layer<S> for Filtered<L, F, S>
704where
705 S: Subscriber + for<'span> registry::LookupSpan<'span> + 'static,
706 F: layer::Filter<S> + 'static,
707 L: Layer<S>,
708{
709 fn on_register_dispatch(&self, subscriber: &Dispatch) {
710 self.layer.on_register_dispatch(subscriber);
711 }
712
713 fn on_layer(&mut self, subscriber: &mut S) {
714 self.id = MagicPlfDowncastMarker(subscriber.register_filter());
715 self.layer.on_layer(subscriber);
716 }
717
718 // TODO(eliza): can we figure out a nice way to make the `Filtered` layer
719 // not call `is_enabled_for` in hooks that the inner layer doesn't actually
720 // have real implementations of? probably not...
721 //
722 // it would be cool if there was some wild rust reflection way of checking
723 // if a trait impl has the default impl of a trait method or not, but that's
724 // almsot certainly impossible...right?
725
726 fn register_callsite(&self, metadata: &'static Metadata<'static>) -> Interest {
727 let interest = self.filter.callsite_enabled(metadata);
728
729 // If the filter didn't disable the callsite, allow the inner layer to
730 // register it — since `register_callsite` is also used for purposes
731 // such as reserving/caching per-callsite data, we want the inner layer
732 // to be able to perform any other registration steps. However, we'll
733 // ignore its `Interest`.
734 if !interest.is_never() {
735 self.layer.register_callsite(metadata);
736 }
737
738 // Add our `Interest` to the current sum of per-layer filter `Interest`s
739 // for this callsite.
740 FILTERING.with(|filtering| filtering.add_interest(interest));
741
742 // don't short circuit! if the stack consists entirely of `Layer`s with
743 // per-layer filters, the `Registry` will return the actual `Interest`
744 // value that's the sum of all the `register_callsite` calls to those
745 // per-layer filters. if we returned an actual `never` interest here, a
746 // `Layered` layer would short-circuit and not allow any `Filtered`
747 // layers below us if _they_ are interested in the callsite.
748 Interest::always()
749 }
750
751 fn enabled(&self, metadata: &Metadata<'_>, cx: Context<'_, S>) -> bool {
752 let cx = cx.with_filter(self.id());
753 let enabled = self.filter.enabled(metadata, &cx);
754 FILTERING.with(|filtering| filtering.set(self.id(), enabled));
755
756 if enabled {
757 // If the filter enabled this metadata, ask the wrapped layer if
758 // _it_ wants it --- it might have a global filter.
759 self.layer.enabled(metadata, cx)
760 } else {
761 // Otherwise, return `true`. The _per-layer_ filter disabled this
762 // metadata, but returning `false` in `Layer::enabled` will
763 // short-circuit and globally disable the span or event. This is
764 // *not* what we want for per-layer filters, as other layers may
765 // still want this event. Returning `true` here means we'll continue
766 // asking the next layer in the stack.
767 //
768 // Once all per-layer filters have been evaluated, the `Registry`
769 // at the root of the stack will return `false` from its `enabled`
770 // method if *every* per-layer filter disabled this metadata.
771 // Otherwise, the individual per-layer filters will skip the next
772 // `new_span` or `on_event` call for their layer if *they* disabled
773 // the span or event, but it was not globally disabled.
774 true
775 }
776 }
777
778 fn on_new_span(&self, attrs: &span::Attributes<'_>, id: &span::Id, cx: Context<'_, S>) {
779 self.did_enable(|| {
780 let cx = cx.with_filter(self.id());
781 self.filter.on_new_span(attrs, id, cx.clone());
782 self.layer.on_new_span(attrs, id, cx);
783 })
784 }
785
786 #[doc(hidden)]
787 fn max_level_hint(&self) -> Option<LevelFilter> {
788 self.filter.max_level_hint()
789 }
790
791 fn on_record(&self, span: &span::Id, values: &span::Record<'_>, cx: Context<'_, S>) {
792 if let Some(cx) = cx.if_enabled_for(span, self.id()) {
793 self.filter.on_record(span, values, cx.clone());
794 self.layer.on_record(span, values, cx)
795 }
796 }
797
798 fn on_follows_from(&self, span: &span::Id, follows: &span::Id, cx: Context<'_, S>) {
799 // only call `on_follows_from` if both spans are enabled by us
800 if cx.is_enabled_for(span, self.id()) && cx.is_enabled_for(follows, self.id()) {
801 self.layer
802 .on_follows_from(span, follows, cx.with_filter(self.id()))
803 }
804 }
805
806 fn event_enabled(&self, event: &Event<'_>, cx: Context<'_, S>) -> bool {
807 let cx = cx.with_filter(self.id());
808 let enabled = FILTERING
809 .with(|filtering| filtering.and(self.id(), || self.filter.event_enabled(event, &cx)));
810
811 if enabled {
812 // If the filter enabled this event, ask the wrapped subscriber if
813 // _it_ wants it --- it might have a global filter.
814 self.layer.event_enabled(event, cx)
815 } else {
816 // Otherwise, return `true`. See the comment in `enabled` for why this
817 // is necessary.
818 true
819 }
820 }
821
822 fn on_event(&self, event: &Event<'_>, cx: Context<'_, S>) {
823 self.did_enable(|| {
824 self.layer.on_event(event, cx.with_filter(self.id()));
825 })
826 }
827
828 fn on_enter(&self, id: &span::Id, cx: Context<'_, S>) {
829 if let Some(cx) = cx.if_enabled_for(id, self.id()) {
830 self.filter.on_enter(id, cx.clone());
831 self.layer.on_enter(id, cx);
832 }
833 }
834
835 fn on_exit(&self, id: &span::Id, cx: Context<'_, S>) {
836 if let Some(cx) = cx.if_enabled_for(id, self.id()) {
837 self.filter.on_exit(id, cx.clone());
838 self.layer.on_exit(id, cx);
839 }
840 }
841
842 fn on_close(&self, id: span::Id, cx: Context<'_, S>) {
843 if let Some(cx) = cx.if_enabled_for(&id, self.id()) {
844 self.filter.on_close(id.clone(), cx.clone());
845 self.layer.on_close(id, cx);
846 }
847 }
848
849 // XXX(eliza): the existence of this method still makes me sad...
850 fn on_id_change(&self, old: &span::Id, new: &span::Id, cx: Context<'_, S>) {
851 if let Some(cx) = cx.if_enabled_for(old, self.id()) {
852 self.layer.on_id_change(old, new, cx)
853 }
854 }
855
856 #[doc(hidden)]
857 #[inline]
858 unsafe fn downcast_raw(&self, id: TypeId) -> Option<*const ()> {
859 match id {
860 id if id == TypeId::of::<Self>() => Some(self as *const _ as *const ()),
861 id if id == TypeId::of::<L>() => Some(&self.layer as *const _ as *const ()),
862 id if id == TypeId::of::<F>() => Some(&self.filter as *const _ as *const ()),
863 id if id == TypeId::of::<MagicPlfDowncastMarker>() => {
864 Some(&self.id as *const _ as *const ())
865 }
866 _ => self.layer.downcast_raw(id),
867 }
868 }
869}
870
871impl<F, L, S> fmt::Debug for Filtered<F, L, S>
872where
873 F: fmt::Debug,
874 L: fmt::Debug,
875{
876 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
877 f.debug_struct("Filtered")
878 .field("filter", &self.filter)
879 .field("layer", &self.layer)
880 .field("id", &self.id)
881 .finish()
882 }
883}
884
885// === impl FilterId ===
886
887impl FilterId {
888 const fn disabled() -> Self {
889 Self(std::u64::MAX)
890 }
891
892 /// Returns a `FilterId` that will consider _all_ spans enabled.
893 pub(crate) const fn none() -> Self {
894 Self(0)
895 }
896
897 pub(crate) fn new(id: u8) -> Self {
898 assert!(id < 64, "filter IDs may not be greater than 64");
899 Self(1 << id as usize)
900 }
901
902 /// Combines two `FilterId`s, returning a new `FilterId` that will match a
903 /// [`FilterMap`] where the span was disabled by _either_ this `FilterId`
904 /// *or* the combined `FilterId`.
905 ///
906 /// This method is called by [`Context`]s when adding the `FilterId` of a
907 /// [`Filtered`] layer to the context.
908 ///
909 /// This is necessary for cases where we have a tree of nested [`Filtered`]
910 /// layers, like this:
911 ///
912 /// ```text
913 /// Filtered {
914 /// filter1,
915 /// Layered {
916 /// layer1,
917 /// Filtered {
918 /// filter2,
919 /// layer2,
920 /// },
921 /// }
922 /// ```
923 ///
924 /// We want `layer2` to be affected by both `filter1` _and_ `filter2`.
925 /// Without combining `FilterId`s, this works fine when filtering
926 /// `on_event`/`new_span`, because the outer `Filtered` layer (`filter1`)
927 /// won't call the inner layer's `on_event` or `new_span` callbacks if it
928 /// disabled the event/span.
929 ///
930 /// However, it _doesn't_ work when filtering span lookups and traversals
931 /// (e.g. `scope`). This is because the [`Context`] passed to `layer2`
932 /// would set its filter ID to the filter ID of `filter2`, and would skip
933 /// spans that were disabled by `filter2`. However, what if a span was
934 /// disabled by `filter1`? We wouldn't see it in `new_span`, but we _would_
935 /// see it in lookups and traversals...which we don't want.
936 ///
937 /// When a [`Filtered`] layer adds its ID to a [`Context`], it _combines_ it
938 /// with any previous filter ID that the context had, rather than replacing
939 /// it. That way, `layer2`'s context will check if a span was disabled by
940 /// `filter1` _or_ `filter2`. The way we do this, instead of representing
941 /// `FilterId`s as a number number that we shift a 1 over by to get a mask,
942 /// we just store the actual mask,so we can combine them with a bitwise-OR.
943 ///
944 /// For example, if we consider the following case (pretending that the
945 /// masks are 8 bits instead of 64 just so i don't have to write out a bunch
946 /// of extra zeroes):
947 ///
948 /// - `filter1` has the filter id 1 (`0b0000_0001`)
949 /// - `filter2` has the filter id 2 (`0b0000_0010`)
950 ///
951 /// A span that gets disabled by filter 1 would have the [`FilterMap`] with
952 /// bits `0b0000_0001`.
953 ///
954 /// If the `FilterId` was internally represented as `(bits to shift + 1),
955 /// when `layer2`'s [`Context`] checked if it enabled the span, it would
956 /// make the mask `0b0000_0010` (`1 << 1`). That bit would not be set in the
957 /// [`FilterMap`], so it would see that it _didn't_ disable the span. Which
958 /// is *true*, it just doesn't reflect the tree-like shape of the actual
959 /// subscriber.
960 ///
961 /// By having the IDs be masks instead of shifts, though, when the
962 /// [`Filtered`] with `filter2` gets the [`Context`] with `filter1`'s filter ID,
963 /// instead of replacing it, it ors them together:
964 ///
965 /// ```ignore
966 /// 0b0000_0001 | 0b0000_0010 == 0b0000_0011;
967 /// ```
968 ///
969 /// We then test if the span was disabled by seeing if _any_ bits in the
970 /// mask are `1`:
971 ///
972 /// ```ignore
973 /// filtermap & mask != 0;
974 /// 0b0000_0001 & 0b0000_0011 != 0;
975 /// 0b0000_0001 != 0;
976 /// true;
977 /// ```
978 ///
979 /// [`Context`]: crate::layer::Context
980 pub(crate) fn and(self, FilterId(other): Self) -> Self {
981 // If this mask is disabled, just return the other --- otherwise, we
982 // would always see that every span is disabled.
983 if self.0 == Self::disabled().0 {
984 return Self(other);
985 }
986
987 Self(self.0 | other)
988 }
989
990 fn is_disabled(self) -> bool {
991 self.0 == Self::disabled().0
992 }
993}
994
995impl fmt::Debug for FilterId {
996 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
997 // don't print a giant set of the numbers 0..63 if the filter ID is disabled.
998 if self.0 == Self::disabled().0 {
999 return f
1000 .debug_tuple("FilterId")
1001 .field(&format_args!("DISABLED"))
1002 .finish();
1003 }
1004
1005 if f.alternate() {
1006 f.debug_struct("FilterId")
1007 .field("ids", &format_args!("{:?}", FmtBitset(self.0)))
1008 .field("bits", &format_args!("{:b}", self.0))
1009 .finish()
1010 } else {
1011 f.debug_tuple("FilterId").field(&FmtBitset(self.0)).finish()
1012 }
1013 }
1014}
1015
1016impl fmt::Binary for FilterId {
1017 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1018 f.debug_tuple("FilterId")
1019 .field(&format_args!("{:b}", self.0))
1020 .finish()
1021 }
1022}
1023
1024// === impl FilterExt ===
1025
1026impl<F, S> FilterExt<S> for F where F: layer::Filter<S> {}
1027
1028// === impl FilterMap ===
1029
1030impl FilterMap {
1031 pub(crate) fn set(self, FilterId(mask): FilterId, enabled: bool) -> Self {
1032 if mask == std::u64::MAX {
1033 return self;
1034 }
1035
1036 if enabled {
1037 Self {
1038 bits: self.bits & (!mask),
1039 }
1040 } else {
1041 Self {
1042 bits: self.bits | mask,
1043 }
1044 }
1045 }
1046
1047 #[inline]
1048 pub(crate) fn is_enabled(self, FilterId(mask): FilterId) -> bool {
1049 self.bits & mask == 0
1050 }
1051
1052 #[inline]
1053 pub(crate) fn any_enabled(self) -> bool {
1054 self.bits != std::u64::MAX
1055 }
1056}
1057
1058impl fmt::Debug for FilterMap {
1059 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1060 let alt = f.alternate();
1061 let mut s = f.debug_struct("FilterMap");
1062 s.field("disabled_by", &format_args!("{:?}", &FmtBitset(self.bits)));
1063
1064 if alt {
1065 s.field("bits", &format_args!("{:b}", self.bits));
1066 }
1067
1068 s.finish()
1069 }
1070}
1071
1072impl fmt::Binary for FilterMap {
1073 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1074 f.debug_struct("FilterMap")
1075 .field("bits", &format_args!("{:b}", self.bits))
1076 .finish()
1077 }
1078}
1079
1080// === impl FilterState ===
1081
1082impl FilterState {
1083 fn new() -> Self {
1084 Self {
1085 enabled: Cell::new(FilterMap::default()),
1086 interest: RefCell::new(None),
1087
1088 #[cfg(debug_assertions)]
1089 counters: DebugCounters::default(),
1090 }
1091 }
1092
1093 fn set(&self, filter: FilterId, enabled: bool) {
1094 #[cfg(debug_assertions)]
1095 {
1096 let in_current_pass = self.counters.in_filter_pass.get();
1097 if in_current_pass == 0 {
1098 debug_assert_eq!(self.enabled.get(), FilterMap::default());
1099 }
1100 self.counters.in_filter_pass.set(in_current_pass + 1);
1101 debug_assert_eq!(
1102 self.counters.in_interest_pass.get(),
1103 0,
1104 "if we are in or starting a filter pass, we must not be in an interest pass."
1105 )
1106 }
1107
1108 self.enabled.set(self.enabled.get().set(filter, enabled))
1109 }
1110
1111 fn add_interest(&self, interest: Interest) {
1112 let mut curr_interest = self.interest.borrow_mut();
1113
1114 #[cfg(debug_assertions)]
1115 {
1116 let in_current_pass = self.counters.in_interest_pass.get();
1117 if in_current_pass == 0 {
1118 debug_assert!(curr_interest.is_none());
1119 }
1120 self.counters.in_interest_pass.set(in_current_pass + 1);
1121 }
1122
1123 if let Some(curr_interest) = curr_interest.as_mut() {
1124 if (curr_interest.is_always() && !interest.is_always())
1125 || (curr_interest.is_never() && !interest.is_never())
1126 {
1127 *curr_interest = Interest::sometimes();
1128 }
1129 // If the two interests are the same, do nothing. If the current
1130 // interest is `sometimes`, stay sometimes.
1131 } else {
1132 *curr_interest = Some(interest);
1133 }
1134 }
1135
1136 pub(crate) fn event_enabled() -> bool {
1137 FILTERING
1138 .try_with(|this| {
1139 let enabled = this.enabled.get().any_enabled();
1140 #[cfg(debug_assertions)]
1141 {
1142 if this.counters.in_filter_pass.get() == 0 {
1143 debug_assert_eq!(this.enabled.get(), FilterMap::default());
1144 }
1145
1146 // Nothing enabled this event, we won't tick back down the
1147 // counter in `did_enable`. Reset it.
1148 if !enabled {
1149 this.counters.in_filter_pass.set(0);
1150 }
1151 }
1152 enabled
1153 })
1154 .unwrap_or(true)
1155 }
1156
1157 /// Executes a closure if the filter with the provided ID did not disable
1158 /// the current span/event.
1159 ///
1160 /// This is used to implement the `on_event` and `new_span` methods for
1161 /// `Filtered`.
1162 fn did_enable(&self, filter: FilterId, f: impl FnOnce()) {
1163 let map = self.enabled.get();
1164 if map.is_enabled(filter) {
1165 // If the filter didn't disable the current span/event, run the
1166 // callback.
1167 f();
1168 } else {
1169 // Otherwise, if this filter _did_ disable the span or event
1170 // currently being processed, clear its bit from this thread's
1171 // `FilterState`. The bit has already been "consumed" by skipping
1172 // this callback, and we need to ensure that the `FilterMap` for
1173 // this thread is reset when the *next* `enabled` call occurs.
1174 self.enabled.set(map.set(filter, true));
1175 }
1176 #[cfg(debug_assertions)]
1177 {
1178 let in_current_pass = self.counters.in_filter_pass.get();
1179 if in_current_pass <= 1 {
1180 debug_assert_eq!(self.enabled.get(), FilterMap::default());
1181 }
1182 self.counters
1183 .in_filter_pass
1184 .set(in_current_pass.saturating_sub(1));
1185 debug_assert_eq!(
1186 self.counters.in_interest_pass.get(),
1187 0,
1188 "if we are in a filter pass, we must not be in an interest pass."
1189 )
1190 }
1191 }
1192
1193 /// Run a second filtering pass, e.g. for Layer::event_enabled.
1194 fn and(&self, filter: FilterId, f: impl FnOnce() -> bool) -> bool {
1195 let map = self.enabled.get();
1196 let enabled = map.is_enabled(filter) && f();
1197 self.enabled.set(map.set(filter, enabled));
1198 enabled
1199 }
1200
1201 /// Clears the current in-progress filter state.
1202 ///
1203 /// This resets the [`FilterMap`] and current [`Interest`] as well as
1204 /// clearing the debug counters.
1205 pub(crate) fn clear_enabled() {
1206 // Drop the `Result` returned by `try_with` --- if we are in the middle
1207 // a panic and the thread-local has been torn down, that's fine, just
1208 // ignore it ratehr than panicking.
1209 let _ = FILTERING.try_with(|filtering| {
1210 filtering.enabled.set(FilterMap::default());
1211
1212 #[cfg(debug_assertions)]
1213 filtering.counters.in_filter_pass.set(0);
1214 });
1215 }
1216
1217 pub(crate) fn take_interest() -> Option<Interest> {
1218 FILTERING
1219 .try_with(|filtering| {
1220 #[cfg(debug_assertions)]
1221 {
1222 if filtering.counters.in_interest_pass.get() == 0 {
1223 debug_assert!(filtering.interest.try_borrow().ok()?.is_none());
1224 }
1225 filtering.counters.in_interest_pass.set(0);
1226 }
1227 filtering.interest.try_borrow_mut().ok()?.take()
1228 })
1229 .ok()?
1230 }
1231
1232 pub(crate) fn filter_map(&self) -> FilterMap {
1233 let map = self.enabled.get();
1234 #[cfg(debug_assertions)]
1235 {
1236 if self.counters.in_filter_pass.get() == 0 {
1237 debug_assert_eq!(map, FilterMap::default());
1238 }
1239 }
1240
1241 map
1242 }
1243}
1244/// This is a horrible and bad abuse of the downcasting system to expose
1245/// *internally* whether a layer has per-layer filtering, within
1246/// `tracing-subscriber`, without exposing a public API for it.
1247///
1248/// If a `Layer` has per-layer filtering, it will downcast to a
1249/// `MagicPlfDowncastMarker`. Since layers which contain other layers permit
1250/// downcasting to recurse to their children, this will do the Right Thing with
1251/// layers like Reload, Option, etc.
1252///
1253/// Why is this a wrapper around the `FilterId`, you may ask? Because
1254/// downcasting works by returning a pointer, and we don't want to risk
1255/// introducing UB by constructing pointers that _don't_ point to a valid
1256/// instance of the type they claim to be. In this case, we don't _intend_ for
1257/// this pointer to be dereferenced, so it would actually be fine to return one
1258/// that isn't a valid pointer...but we can't guarantee that the caller won't
1259/// (accidentally) dereference it, so it's better to be safe than sorry. We
1260/// could, alternatively, add an additional field to the type that's used only
1261/// for returning pointers to as as part of the evil downcasting hack, but I
1262/// thought it was nicer to just add a `repr(transparent)` wrapper to the
1263/// existing `FilterId` field, since it won't make the struct any bigger.
1264///
1265/// Don't worry, this isn't on the test. :)
1266#[derive(Clone, Copy)]
1267#[repr(transparent)]
1268struct MagicPlfDowncastMarker(FilterId);
1269impl fmt::Debug for MagicPlfDowncastMarker {
1270 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1271 // Just pretend that `MagicPlfDowncastMarker` doesn't exist for
1272 // `fmt::Debug` purposes...if no one *sees* it in their `Debug` output,
1273 // they don't have to know I thought this code would be a good idea.
1274 fmt::Debug::fmt(&self.0, f)
1275 }
1276}
1277
1278pub(crate) fn is_plf_downcast_marker(type_id: TypeId) -> bool {
1279 type_id == TypeId::of::<MagicPlfDowncastMarker>()
1280}
1281
1282/// Does a type implementing `Subscriber` contain any per-layer filters?
1283pub(crate) fn subscriber_has_plf<S>(subscriber: &S) -> bool
1284where
1285 S: Subscriber,
1286{
1287 (subscriber as &dyn Subscriber).is::<MagicPlfDowncastMarker>()
1288}
1289
1290/// Does a type implementing `Layer` contain any per-layer filters?
1291pub(crate) fn layer_has_plf<L, S>(layer: &L) -> bool
1292where
1293 L: Layer<S>,
1294 S: Subscriber,
1295{
1296 unsafe {
1297 // Safety: we're not actually *doing* anything with this pointer --- we
1298 // only care about the `Option`, which we're turning into a `bool`. So
1299 // even if the layer decides to be evil and give us some kind of invalid
1300 // pointer, we don't ever dereference it, so this is always safe.
1301 layer.downcast_raw(TypeId::of::<MagicPlfDowncastMarker>())
1302 }
1303 .is_some()
1304}
1305
1306struct FmtBitset(u64);
1307
1308impl fmt::Debug for FmtBitset {
1309 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1310 let mut set = f.debug_set();
1311 for bit in 0..64 {
1312 // if the `bit`-th bit is set, add it to the debug set
1313 if self.0 & (1 << bit) != 0 {
1314 set.entry(&bit);
1315 }
1316 }
1317 set.finish()
1318 }
1319}
1320