`num` crate help, lacks examples


#1

I’ve been trying to make a data type for colors, with red, green, blue, and alpha fields. Their type is a generic constrained to num::Float, allowing the user to decide if they want f32 or f64 precision. However, I’m having trouble when it comes to constructing one from an AARRGGBB-formatted integer. I’ve tried num::FromPrimitive, num::NumCast, and simple as, but none seem to work.

extern crate num;

use num::Float;

/// A color with red, green, blue, and alpha values
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Color<T: Float> {
  pub red: T,
  pub green: T,
  pub blue: T,
  pub alpha: T,
}

impl<T: Float> Color<T> {
  /// Construct a Color from a 32-bit unsigned integer in the format of ARGB.
  pub fn from_argb32<F: Float>(v: u32) -> Color<F> {
    Color {
      red: (((v & 0xff0000) >> 16) as F) / 255.0,
      green: (((v & 0xff00) >> 8) as F) / 255.0,
      blue: ((v & 0xff) as F) / 255.0,
      alpha: (((v & 0xff000000) >> 24) as F) / 255.0,
    }
  }
}

#2

You need to add a few more trait bounds, and then operate through operations defined on those traits. Here’s one way:

extern crate num;

use std::ops::Div;
use num::{Float, NumCast};

/// A color with red, green, blue, and alpha values
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Color<T: Float> {
  pub red: T,
  pub green: T,
  pub blue: T,
  pub alpha: T,
}

impl<T: Float> Color<T> {
  /// Construct a Color from a 32-bit unsigned integer in the format of ARGB.
  pub fn from_argb32<F: Float + NumCast + Div<F, Output=F>>(v: u32) -> Color<F> {
    Color {
      red: F::from((v & 0xff0000) >> 16).unwrap() / F::from(255.0).unwrap(),
      green: F::from((v & 0xff00) >> 8).unwrap() / F::from(255.0).unwrap(),
      blue: F::from(v & 0xff).unwrap() / F::from(255.0).unwrap(),
      alpha: F::from((v & 0xff000000) >> 24).unwrap() / F::from(255.0).unwrap(),
    }
  }
}

fn main() {}

Playground

Note I unwrap()'d the conversions only to avoid cluttering up the example.


#3

That’s pretty verbose. where clause, here I come! Thanks.