From 813b4aa5c2813717ef0ce6561aba436eece8c18a Mon Sep 17 00:00:00 2001 From: Brendan Zabarauskas Date: Sat, 26 Mar 2016 16:40:31 +1100 Subject: [PATCH] Add constrained conversion functions --- Cargo.toml | 3 ++ src/conv.rs | 84 +++++++++++++++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 1 + 3 files changed, 88 insertions(+) create mode 100644 src/conv.rs diff --git a/Cargo.toml b/Cargo.toml index cd7e321..957c53b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -35,3 +35,6 @@ rustc_serialize = "0.3" [dependencies] num = "0.1" rand = "0.3" + +[dev-dependencies] +glium = "0.13.5" diff --git a/src/conv.rs b/src/conv.rs new file mode 100644 index 0000000..833ebef --- /dev/null +++ b/src/conv.rs @@ -0,0 +1,84 @@ +//! Constrained conversion functions for assisting in situations where type +//! inference is difficult. +//! +//! For example, when declaring `glium` uniforms, we need to convert to fixed +//! length arrays. We can use the `Into` trait directly, but it is rather ugly! +//! +//! ```rust +//! #[macro_use] +//! extern crate glium; +//! extern crate cgmath; +//! +//! use cgmath::{Matrix4, Point2}; +//! use cgmath::prelude::*; +//! +//! # fn main() { +//! let point = Point2::new(1, 2); +//! let matrix = Matrix4::from_scale(2.0); +//! +//! let uniforms = uniform! { +//! point: Into::<[_; 2]>::into(point), +//! matrix: Into::<[[_; 4]; 4]>::into(matrix), +//! // Yuck!! (ノಥ益ಥ)ノ ┻━┻ +//! }; +//! # } +//! ``` +//! +//! Instead, we can use the conversion functions from the `conv` module: +//! +//! ```rust +//! #[macro_use] +//! extern crate glium; +//! extern crate cgmath; +//! +//! use cgmath::{Matrix4, Point2}; +//! use cgmath::prelude::*; +//! use cgmath::conv::*; +//! +//! # fn main() { +//! let point = Point2::new(1, 2); +//! let matrix = Matrix4::from_scale(2.0); +//! +//! let uniforms = uniform! { +//! point: array2(point), +//! matrix: array4x4(matrix), +//! // ┬─┬ノ( º _ ºノ) +//! }; +//! # } +//! ``` + +/// Force a conversion into a 2-element array. +#[inline] +pub fn array2>(value: A) -> [T; 2] { + value.into() +} + +/// Force a conversion into a 3-element array. +#[inline] +pub fn array3>(value: A) -> [T; 3] { + value.into() +} + +/// Force a conversion into a 4-element array. +#[inline] +pub fn array4>(value: A) -> [T; 4] { + value.into() +} + +/// Force a conversion into a 2x2-element array. +#[inline] +pub fn array2x2>(value: A) -> [[T; 2]; 2] { + value.into() +} + +/// Force a conversion into a 3x3-element array. +#[inline] +pub fn array3x3>(value: A) -> [[T; 3]; 3] { + value.into() +} + +/// Force a conversion into a 4x4-element array. +#[inline] +pub fn array4x4>(value: A) -> [[T; 4]; 4] { + value.into() +} diff --git a/src/lib.rs b/src/lib.rs index de3cb52..8c22cc4 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -54,6 +54,7 @@ pub use rust_num::{One, Zero, one, zero}; // Modules +pub mod conv; pub mod prelude; mod macros;