1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
//! A crate macro that allows you inspecting the fields of structs.
//!
//! See the docs on [`FieldsInspect`] for more.
//!
//! # no-std support
//!
//! This crate is no-std compatible.
#![no_std]
#![forbid(unsafe_op_in_unsafe_fn, rust_2018_idioms)]
#![warn(missing_docs)]
#![cfg_attr(docsrs, feature(doc_cfg))]
use core::any::Any;
use core::iter::FusedIterator;
use core::marker::PhantomData;
pub use fields_iter_macros::FieldsInspect;
// FIXME: We're forced to use a second trait because `*mut Self` cannot be the `self` pointer
// without `arbitrary_self_types`. When it is stabilized, remove this trait.
#[doc(hidden)]
pub trait FieldsInspectImpl {
fn struct_name() -> &'static str;
fn fields_count() -> u32;
fn field_name(n: u32) -> &'static str;
fn field(&self, n: u32) -> &dyn Any;
/// # Safety
///
/// You should call this only with `this` pointing to a valid `FieldsInspectImpl`-implementing
/// type (this is not a reference because this runs into issues with Stacked Borrows for
/// `FieldsIterMut`). You should use the resulting reference only for the lifetime of `this`,
/// and not create an overlapping reference (references from the same `n`) during this region.
unsafe fn field_mut(this: *mut (), n: u32) -> &'static mut dyn Any;
}
impl<'a, T: ?Sized + FieldsInspectImpl + 'a> FieldsInspectImpl for &'a mut T {
fn struct_name() -> &'static str {
T::struct_name()
}
fn fields_count() -> u32 {
T::fields_count()
}
fn field_name(n: u32) -> &'static str {
T::field_name(n)
}
fn field(&self, n: u32) -> &dyn Any {
T::field(*self, n)
}
unsafe fn field_mut(this: *mut (), n: u32) -> &'static mut dyn Any {
// SAFETY: Precondition.
unsafe { T::field_mut((*this.cast::<Self>()) as *mut T as *mut (), n) }
}
}
#[doc(hidden)]
pub struct FieldsIterMutVtable {
field_name: fn(u32) -> &'static str,
field_mut: unsafe fn(*mut (), n: u32) -> &'static mut dyn Any,
}
/// A trait that allows iterating over over struct's fields, getting their name and a mutable/shared
/// reference to them.
///
/// [You need to derive this trait](derive@FieldsInspect) (actually, it the derive creates an impl
/// for a hidden trait this trait has a blanket implementation to).
///
/// # Examples
///
/// Printing the values of all field whose name starts with "a" and are strings:
/// ```
/// use fields_iter::{FieldsInspect, FieldsIter};
///
/// fn print_starts_with_a(v: &dyn FieldsInspect) {
/// for (name, value) in FieldsIter::new(v) {
/// if !name.starts_with('a') { continue };
/// let Some(value) = value.downcast_ref::<String>() else { continue };
/// println!("{name}={value}");
/// }
/// }
/// ```
///
/// Adding one to the field `add_here`:
/// ```
/// use fields_iter::{FieldsInspect, FieldsIterMut};
///
/// # #[derive(FieldsInspect)]
/// # struct Type { add_here: i32 }
/// # let mut original = Type { add_here: 0 };
/// let v: &mut dyn FieldsInspect;
/// # let v: &mut dyn FieldsInspect = &mut original;
/// let field = FieldsIterMut::new(v)
/// .find(|&(name, _)| name == "add_here")
/// .expect("no `add_here` field")
/// .1
/// .downcast_mut::<i32>()
/// .expect("field `add_here` is not of type `i32`");
/// *field += 1;
/// # assert_eq!(original.add_here, 1);
/// ```
pub trait FieldsInspect {
/// The struct name.
///
/// This takes `&self` to make `FieldsIter` object safe.
fn struct_name(&self) -> &'static str;
/// The numbers of fields.
///
/// This allows you to iterate over the fields without allocating a `Box` and in `no_std` mode.
///
/// This takes `&self` to make `FieldsIter` object safe.
///
/// # Example
///
/// ```
/// # use fields_iter::FieldsInspect;
/// #[derive(FieldsInspect)]
/// struct HasFieldsInspect {
/// a: i32,
/// b: String,
/// }
///
/// let v = HasFieldsInspect { a: 0, b: String::new() };
/// assert_eq!(v.fields_count(), 2);
/// ```
///
/// This takes `&self` to make `FieldsIter` object safe.
fn fields_count(&self) -> u32;
/// The name of the nth field.
///
/// Named fields return their name; tuple fields return their index (e.g. "1", "2").
///
/// This allows you to iterate over the fields without allocating a `Box` and in `no_std` mode.
///
/// This takes `&self` to make `FieldsIter` object safe.
///
/// # Example
///
/// ```
/// # use fields_iter::FieldsInspect;
/// #[derive(FieldsInspect)]
/// struct HasFieldsInspect {
/// a: i32,
/// b: String,
/// }
///
/// let v = HasFieldsInspect { a: 0, b: String::new() };
/// assert_eq!(v.field_name(0), "a");
/// assert_eq!(v.field_name(1), "b");
/// ```
///
/// # Panics
///
/// This panics if given an out of bounds field index.
fn field_name(&self, n: u32) -> &'static str;
/// The value of the nth field.
///
/// This allows you to iterate over the fields without allocating a `Box` and in `no_std` mode.
///
/// # Example
///
/// ```
/// # use fields_iter::FieldsInspect;
/// #[derive(FieldsInspect)]
/// struct HasFieldsInspect {
/// a: i32,
/// b: String,
/// }
///
/// let v = HasFieldsInspect { a: 0, b: String::new() };
/// assert!(std::ptr::eq(v.field(0), &v.a));
/// assert!(std::ptr::eq(v.field(1), &v.b));
/// ```
///
/// # Panics
///
/// This panics if given an out of bounds field index.
fn field(&self, n: u32) -> &dyn Any;
/// The value of the nth field.
///
/// This allows you to iterate over the fields without allocating a `Box` and in `no_std` mode.
///
/// # Example
///
/// ```
/// # use fields_iter::FieldsInspect;
/// #[derive(FieldsInspect)]
/// struct HasFieldsInspect {
/// a: i32,
/// b: String,
/// }
///
/// let mut v = HasFieldsInspect { a: 0, b: String::new() };
/// *v.field_mut(0).downcast_mut::<i32>().unwrap() += 5;
/// assert_eq!(v.a, 5);
/// ```
///
/// # Panics
///
/// This panics if given an out of bounds field index.
fn field_mut(&mut self, n: u32) -> &mut dyn Any;
#[doc(hidden)]
fn __fields_mut_iter_vtable(&self) -> &'static FieldsIterMutVtable;
}
impl<T: ?Sized + FieldsInspectImpl> FieldsInspect for T {
fn struct_name(&self) -> &'static str {
<T as FieldsInspectImpl>::struct_name()
}
fn fields_count(&self) -> u32 {
<T as FieldsInspectImpl>::fields_count()
}
fn field_name(&self, n: u32) -> &'static str {
<T as FieldsInspectImpl>::field_name(n)
}
fn field(&self, n: u32) -> &dyn Any {
<T as FieldsInspectImpl>::field(self, n)
}
fn field_mut(&mut self, n: u32) -> &mut dyn Any {
// SAFETY: We derive the pointer from reference and return a reference with the same lifetime.
unsafe { <T as FieldsInspectImpl>::field_mut(self as *mut Self as *mut (), n) }
}
#[doc(hidden)]
fn __fields_mut_iter_vtable(&self) -> &'static FieldsIterMutVtable {
&FieldsIterMutVtable {
field_name: <Self as FieldsInspectImpl>::field_name,
field_mut: <Self as FieldsInspectImpl>::field_mut,
}
}
}
/// An iterator over the names and shared references to a type implementing `FieldsInspect`.
///
/// # Example
///
/// ```
/// # use std::any::Any;
/// # use fields_iter::{FieldsInspect, FieldsIter};
/// fn find_field<'a>(v: &'a dyn FieldsInspect, name: &str) -> Option<&'a dyn Any> {
/// FieldsIter::new(v).find_map(|(n, v)| (n == name).then_some(v))
/// }
///
/// #[derive(FieldsInspect)]
/// struct HasFieldsInspect {
/// a: i32,
/// b: String,
/// }
/// let v = HasFieldsInspect { a: 0, b: String::new() };
/// assert!(std::ptr::eq(&v.b, find_field(&v, "b").unwrap().downcast_ref::<String>().unwrap()));
/// ```
pub struct FieldsIter<'a, T: ?Sized = dyn FieldsInspect> {
fields_count: u32,
next_field_idx: u32,
value: &'a T,
}
impl<'a, T: ?Sized + FieldsInspect> FieldsIter<'a, T> {
/// Creates a new `FieldsIter`.
pub fn new(v: &'a T) -> Self {
Self { fields_count: v.fields_count(), next_field_idx: 0, value: v }
}
}
impl<'a, T: ?Sized + FieldsInspect> Iterator for FieldsIter<'a, T> {
type Item = (&'static str, &'a dyn Any);
fn next(&mut self) -> Option<Self::Item> {
if self.next_field_idx >= self.fields_count {
return None;
}
let name = self.value.field_name(self.next_field_idx);
let value = self.value.field(self.next_field_idx);
self.next_field_idx += 1;
Some((name, value))
}
fn size_hint(&self) -> (usize, Option<usize>) {
let result = self.len();
(result, Some(result))
}
}
impl<'a, T: ?Sized + FieldsInspect> ExactSizeIterator for FieldsIter<'a, T> {
fn len(&self) -> usize {
(self.fields_count - self.next_field_idx) as usize
}
}
impl<'a, T: ?Sized + FieldsInspect> FusedIterator for FieldsIter<'a, T> {}
impl<'a, T: ?Sized + FieldsInspect> DoubleEndedIterator for FieldsIter<'a, T> {
fn next_back(&mut self) -> Option<Self::Item> {
if self.fields_count == self.next_field_idx {
return None;
}
self.fields_count -= 1;
let name = self.value.field_name(self.fields_count);
let value = self.value.field(self.fields_count);
Some((name, value))
}
}
/// An iterator over the names and mutable references to a type implementing `FieldsInspect`.
///
/// # Example
///
/// ```
/// # use std::any::Any;
/// # use fields_iter::{FieldsInspect, FieldsIterMut};
/// fn find_field<'a>(v: &'a mut dyn FieldsInspect, name: &str) -> Option<&'a mut dyn Any> {
/// FieldsIterMut::new(v).find_map(|(n, v)| (n == name).then_some(v))
/// }
///
/// #[derive(FieldsInspect)]
/// struct HasFieldsInspect {
/// a: i32,
/// b: String,
/// }
/// let mut v = HasFieldsInspect { a: 0, b: String::new() };
/// *find_field(&mut v, "a").unwrap().downcast_mut::<i32>().unwrap() = 123;
/// assert_eq!(v.a, 123);
/// ```
pub struct FieldsIterMut<'a, T: ?Sized = dyn FieldsInspect> {
fields_count: u32,
next_field_idx: u32,
value: *mut (),
vtable: &'static FieldsIterMutVtable,
_marker: PhantomData<&'a mut T>,
}
impl<'a, T: ?Sized + FieldsInspect> FieldsIterMut<'a, T> {
/// Creates a new `FieldsIter`.
pub fn new(v: &'a mut T) -> Self {
Self {
fields_count: v.fields_count(),
next_field_idx: 0,
value: v as *mut T as *mut (),
vtable: v.__fields_mut_iter_vtable(),
_marker: PhantomData,
}
}
}
impl<'a, T: ?Sized + FieldsInspect> Iterator for FieldsIterMut<'a, T> {
type Item = (&'static str, &'a mut dyn Any);
fn next(&mut self) -> Option<Self::Item> {
if self.next_field_idx >= self.fields_count {
return None;
}
let name = (self.vtable.field_name)(self.next_field_idx);
// The pointer is created from reference by `new()`, we return a reference with the same
// lifetime, and we only borrow disjoint fields.
let value = unsafe { (self.vtable.field_mut)(self.value, self.next_field_idx) };
self.next_field_idx += 1;
Some((name, value))
}
fn size_hint(&self) -> (usize, Option<usize>) {
let result = self.len();
(result, Some(result))
}
}
impl<'a, T: ?Sized + FieldsInspect> ExactSizeIterator for FieldsIterMut<'a, T> {
fn len(&self) -> usize {
(self.fields_count - self.next_field_idx) as usize
}
}
impl<'a, T: ?Sized + FieldsInspect> FusedIterator for FieldsIterMut<'a, T> {}
impl<'a, T: ?Sized + FieldsInspect> DoubleEndedIterator for FieldsIterMut<'a, T> {
fn next_back(&mut self) -> Option<Self::Item> {
if self.fields_count == self.next_field_idx {
return None;
}
self.fields_count -= 1;
let name = (self.vtable.field_name)(self.fields_count);
// The pointer is created from reference by `new()`, we return a reference with the same
// lifetime, and we only borrow disjoint fields.
let value = unsafe { (self.vtable.field_mut)(self.value, self.fields_count) };
Some((name, value))
}
}
#[cold]
#[doc(hidden)]
#[track_caller]
pub fn field_out_of_bounds(struct_name: &str, field: u32) -> ! {
panic!("field index {field} is out of bounds for struct `{struct_name}`")
}
#[doc(hidden)]
pub use core::ptr::addr_of_mut;