Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement Display for Val #10296

Merged
merged 4 commits into from
Oct 28, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions crates/bevy_ui/src/geometry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use bevy_reflect::ReflectDeserialize;
use bevy_reflect::ReflectSerialize;
use serde::Deserialize;
use serde::Serialize;
use std::fmt::Display;
use std::ops::Neg;
use std::ops::{Div, DivAssign, Mul, MulAssign};
use thiserror::Error;
Expand Down Expand Up @@ -155,6 +156,22 @@ impl DivAssign<f32> for Val {
}
}

impl Display for Val {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let (value, suffix) = match self {
Val::Auto => return write!(f, "auto"),
Val::Px(value) => (value, "px"),
Val::Percent(value) => (value, "%"),
Val::Vw(value) => (value, "vw"),
Val::Vh(value) => (value, "vh"),
Val::VMin(value) => (value, "vmin"),
Val::VMax(value) => (value, "vmax"),
};
value.fmt(f)?;
write!(f, "{suffix}")
Comment on lines +170 to +171
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would this be equivalent or does it result in a different output?

Suggested change
value.fmt(f)?;
write!(f, "{suffix}")
write!(f, "{value}{suffix}")

Copy link
Contributor Author

@ickshonpe ickshonpe Oct 28, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The first version allows you to specify formatting options.

So with value.fmt(f)?

println!("{:.2}", Val::Px(0.5689));

has output

0.57

whereas with write!(f, "{value}{suffix}") it will display

0.5689

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's good to know, thanks!

}
}

impl Neg for Val {
type Output = Val;

Expand Down