Skip to content

Commit

Permalink
fn BitDepth::pxstride: Make generic over stride type and `BitDept…
Browse files Browse the repository at this point in the history
…h` (#769)

This way we don't have to do `BD::pxstride(stride as usize) as isize`,
which is verbose and wrong for negative strides. There may still be some
places where strides are always positive, though, so it's kept generic.
This also lets us fix #636 gradually; this is the first major step in
fixing #636. We'll fully fix that later.

@fbossen, hopefully this'll help you in your PRs not have to write the
hundreds of extra `as usize) as isize` casts.
  • Loading branch information
kkysen authored Feb 28, 2024
2 parents 03c296f + d7a51ce commit 4a861d5
Showing 1 changed file with 12 additions and 10 deletions.
22 changes: 12 additions & 10 deletions include/common/bitdepth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,11 @@ use std::fmt::Display;
use std::fmt::Formatter;
use std::mem;
use std::ops::Add;
use std::ops::Div;
use std::ops::Mul;
use std::ops::Rem;
use std::ops::Shr;
use to_method::To as _;

pub trait FromPrimitive<T> {
fn from_prim(t: T) -> Self;
Expand Down Expand Up @@ -174,7 +177,15 @@ pub trait BitDepth: Clone + Copy {
clip(pixel, 0.into(), self.bitdepth_max())
}

fn pxstride(n: usize) -> usize;
/// `T` is generally meant to be `usize` or `isize`.
fn pxstride<T>(n: T) -> T
where
T: Copy + Eq + TryFrom<usize> + From<u8> + Div<Output = T> + Rem<Output = T>,
{
let scale = mem::size_of::<Self::Pixel>().try_to::<T>().ok().unwrap();
debug_assert!(n % scale == 0.into());
n / scale
}

fn bitdepth(&self) -> u8;

Expand Down Expand Up @@ -238,10 +249,6 @@ impl BitDepth for BitDepth8 {
DisplayPixel8(pixel)
}

fn pxstride(n: usize) -> usize {
n
}

fn bitdepth(&self) -> u8 {
Self::BITDEPTH
}
Expand Down Expand Up @@ -319,11 +326,6 @@ impl BitDepth for BitDepth16 {
DisplayPixel16(pixel)
}

fn pxstride(n: usize) -> usize {
debug_assert!(n & 1 == 0);
n >> 1
}

fn bitdepth(&self) -> u8 {
(Self::Pixel::BITS - self.bitdepth_max.leading_zeros()) as u8
}
Expand Down

0 comments on commit 4a861d5

Please sign in to comment.