Skip to content

Commit

Permalink
Reimplement some stuff as traits
Browse files Browse the repository at this point in the history
Signed-off-by: Elizabeth Myers <[email protected]>
  • Loading branch information
Elizafox committed Mar 15, 2024
1 parent 8fa9ef6 commit 28b34e1
Show file tree
Hide file tree
Showing 9 changed files with 40 additions and 35 deletions.
1 change: 0 additions & 1 deletion Cargo.lock

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

1 change: 0 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,6 @@ envy = "0.4.2"
heck = "0.5.0"
ipnetwork = "0.20.0"
itertools = "0.12.1"
lazy_static = "1.4.0"
num = "0.4.1"
once_cell = { version = "1.19.0", features = ["parking_lot"] }
password-auth = "1.0.0"
Expand Down
21 changes: 15 additions & 6 deletions src/util/bits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,22 @@
* work. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
*/

use std::mem::size_of;

use num::PrimInt;

pub fn count_trailing_zeroes<T: PrimInt>(mut n: T) -> u32 {
let mut count = 0;
while n != T::zero() {
count += 1;
n = n >> 1;
// NOTE: do not implement this type for size_of::<Size> > u32::MAX
// (size_of::<Self>() regrettably is not a compile-time expression, so we can't do a static assert)
pub trait IntBitUtil: Sized + PrimInt {
// Count the minimum number of bits required to represent this number
#[allow(clippy::cast_possible_truncation)]
fn bit_length(&self) -> u32 {
(size_of::<Self>() - (self.leading_zeros() as usize)) as u32
}
count
}

impl IntBitUtil for u8 {}
impl IntBitUtil for u16 {}
impl IntBitUtil for u32 {}
impl IntBitUtil for u64 {}
impl IntBitUtil for u128 {}
4 changes: 2 additions & 2 deletions src/util/format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use time::{
Duration,
};

use super::math::is_close;
use super::math::FloatMathUtil;

// This implementation is heavily modified from the time crate.
pub fn humanize_duration(duration: Duration) -> String {
Expand All @@ -40,7 +40,7 @@ pub fn humanize_duration(duration: Duration) -> String {
macro_rules! item {
($singular:literal, $plural:literal, $value:expr) => {
let value = $value;
if is_close(value.round(), 1.0) {
if value.round().is_close(1.0) {
return format!("{} {suffix}", $singular);
} else if value > 1.0 {
return format!("{value:.0} {} {suffix}", $plural);
Expand Down
30 changes: 17 additions & 13 deletions src/util/math.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,20 +14,24 @@

use num::Float;

// This algorithm is taken from Python's isclose() algorithm in C
pub fn is_close<T: Float>(a: T, b: T) -> bool {
let abs_tol = T::from(0.0).unwrap();
let rel_tol = T::from(1e-05).unwrap();
pub trait FloatMathUtil: Float {
// This algorithm is taken from Python's isclose() algorithm in C
fn is_close(self, n: Self) -> bool {
let abs_tol = Self::from(0.0).unwrap();
let rel_tol = Self::from(1e-05).unwrap();

if a == b {
return true;
}

if a.is_infinite() || b.is_infinite() {
return false;
}
if self == n {
return true;
}

let diff = (b - a).abs();
if self.is_infinite() || n.is_infinite() {
return false;
}

((diff <= (rel_tol * b).abs()) || (diff <= (rel_tol * a).abs())) || (diff <= abs_tol)
let diff = (n - self).abs();
((diff <= (rel_tol * n).abs()) || (diff <= (rel_tol * self).abs())) || (diff <= abs_tol)
}
}

impl FloatMathUtil for f32 {}
impl FloatMathUtil for f64 {}
6 changes: 3 additions & 3 deletions src/util/net.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use ipnetwork::{IpNetwork, IpNetworkError};
use tracing::debug;

use super::bits::count_trailing_zeroes;
use super::bits::IntBitUtil;

#[derive(Debug, thiserror::Error)]
pub enum NetworkPrefixError {
Expand Down Expand Up @@ -63,7 +63,7 @@ pub fn find_networks(start: IpAddr, end: IpAddr) -> Result<Vec<IpNetwork>, Netwo
#[allow(clippy::cast_possible_truncation)]
let nbits = start_int
.trailing_zeros()
.min(count_trailing_zeroes(end_int - start_int + 1) - 1)
.min((end_int - start_int + 1).bit_length() - 1)
as u8;
res.push(IpNetwork::new(
IpAddr::V4(Ipv4Addr::from(start_int)),
Expand All @@ -88,7 +88,7 @@ pub fn find_networks(start: IpAddr, end: IpAddr) -> Result<Vec<IpNetwork>, Netwo
#[allow(clippy::cast_possible_truncation)]
let nbits = start_int
.trailing_zeros()
.min(count_trailing_zeroes(end_int - start_int + 1) - 1)
.min((end_int - start_int + 1).bit_length() - 1)
as u8;
res.push(IpNetwork::new(
IpAddr::V6(Ipv6Addr::from(start_int)),
Expand Down
4 changes: 1 addition & 3 deletions src/web/admin/url_filter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,7 @@ use tracing::{debug, warn};
use entity::{url_filter, user};
use service::{Mutation, Query};

use crate::{
auth::AuthSession, csrf as csrf_crate, err::AppError, state::AppState, util::format,
};
use crate::{auth::AuthSession, csrf as csrf_crate, err::AppError, state::AppState, util::format};

#[derive(Template)]
#[template(path = "admin/url_filter.html")]
Expand Down
4 changes: 1 addition & 3 deletions src/web/admin/urls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,7 @@ use tracing::{debug, info};
use entity::url;
use service::{Mutation, Query};

use crate::{
auth::AuthSession, csrf as csrf_crate, err::AppError, state::AppState, util::format,
};
use crate::{auth::AuthSession, csrf as csrf_crate, err::AppError, state::AppState, util::format};

#[derive(Template)]
#[template(path = "admin/urls.html")]
Expand Down
4 changes: 1 addition & 3 deletions src/web/submission.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,7 @@ use validator::Validate;

use service::{Mutation, Query};

use crate::{
err::AppError, generate::Generator, state::AppState, validators::validate_url,
};
use crate::{err::AppError, generate::Generator, state::AppState, validators::validate_url};

#[derive(Template)]
#[template(path = "index.html")]
Expand Down

0 comments on commit 28b34e1

Please sign in to comment.