From 827cd14702e53ad354eb99dea5061d8ab4928bc4 Mon Sep 17 00:00:00 2001 From: Rustin Date: Tue, 19 Nov 2024 06:30:09 +0800 Subject: [PATCH] tracing: add index API for `Field` (#2820) ## Motivation Expose the index of the field in order to support cases such as sending field information by index instead of by the string name in Tokio Console. Details: https://github.com/tokio-rs/console/issues/462#issuecomment-1830842319 ## Solution Adds a new API which exposes the index of a field, which is how it is stored internally (together with a reference to the `FieldSet` containing the ordered field names. Signed-off-by: hi-rustin Co-authored-by: Hayden Stainsby --- tracing-core/src/field.rs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/tracing-core/src/field.rs b/tracing-core/src/field.rs index c46b00317..6b4c95090 100644 --- a/tracing-core/src/field.rs +++ b/tracing-core/src/field.rs @@ -681,6 +681,11 @@ impl Field { pub fn name(&self) -> &'static str { self.fields.names[self.i] } + + /// Returns the index of this field in its [`FieldSet`]. + pub fn index(&self) -> usize { + self.i + } } impl fmt::Display for Field { @@ -1053,6 +1058,17 @@ mod test { assert!(valueset.is_empty()); } + #[test] + fn index_of_field_in_fieldset_is_correct() { + let fields = TEST_META_1.fields(); + let foo = fields.field("foo").unwrap(); + assert_eq!(foo.index(), 0); + let bar = fields.field("bar").unwrap(); + assert_eq!(bar.index(), 1); + let baz = fields.field("baz").unwrap(); + assert_eq!(baz.index(), 2); + } + #[test] fn empty_value_set_is_empty() { let fields = TEST_META_1.fields();