Skip to content

Commit

Permalink
Merge pull request #161 from tisonkun/derive-visitor
Browse files Browse the repository at this point in the history
feat: integrate with derive-visitor
  • Loading branch information
mbrubeck authored Oct 16, 2024
2 parents 6c47902 + 0e7da65 commit dc0269e
Show file tree
Hide file tree
Showing 3 changed files with 110 additions and 0 deletions.
44 changes: 44 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ rust-version = "1.60"
arbitrary = { version = "1.0.0", optional = true }
borsh = { version = "1.2.0", optional = true, default-features = false }
bytemuck = { version = "1.12.2", optional = true, default-features = false }
derive-visitor = { version = "0.4.0", optional = true }
num-cmp = { version = "0.1.0", optional = true }
num-traits = { version = "0.2.1", default-features = false }
proptest = { version = "1.0.0", optional = true }
Expand Down
65 changes: 65 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,71 @@ fn canonicalize_signed_zero<T: FloatCore>(x: T) -> T {
#[repr(transparent)]
pub struct OrderedFloat<T>(pub T);

#[cfg(feature = "derive-visitor")]
mod impl_derive_visitor {
use crate::OrderedFloat;
use derive_visitor::{Drive, DriveMut, Event, Visitor, VisitorMut};

impl<T: 'static> Drive for OrderedFloat<T> {
fn drive<V: Visitor>(&self, visitor: &mut V) {
visitor.visit(self, Event::Enter);
visitor.visit(self, Event::Exit);
}
}

impl<T: 'static> DriveMut for OrderedFloat<T> {
fn drive_mut<V: VisitorMut>(&mut self, visitor: &mut V) {
visitor.visit(self, Event::Enter);
visitor.visit(self, Event::Exit);
}
}

#[test]
pub fn test_derive_visitor() {
#[derive(Debug, Clone, PartialEq, Eq, Drive, DriveMut)]
pub enum Literal {
Null,
Float(OrderedFloat<f64>),
}

#[derive(Visitor, VisitorMut)]
#[visitor(Literal(enter))]
struct FloatExpr(bool);

impl FloatExpr {
fn enter_literal(&mut self, lit: &Literal) {
if let Literal::Float(_) = lit {
self.0 = true;
}
}
}

assert!({
let mut visitor = FloatExpr(false);
Literal::Null.drive(&mut visitor);
!visitor.0
});

assert!({
let mut visitor = FloatExpr(false);
Literal::Null.drive_mut(&mut visitor);
!visitor.0
});

assert!({
let mut visitor = FloatExpr(false);
Literal::Float(OrderedFloat(0.0)).drive(&mut visitor);
visitor.0
});

assert!({
let mut visitor = FloatExpr(false);
Literal::Float(OrderedFloat(0.0)).drive_mut(&mut visitor);
visitor.0
});
}
}

#[cfg(feature = "num-cmp")]
mod impl_num_cmp {
use super::OrderedFloat;
Expand Down

0 comments on commit dc0269e

Please sign in to comment.