diff --git a/CHANGELOG.md b/CHANGELOG.md index 2b73712..3e90b17 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,8 @@ This project adheres to [Semantic Versioning](http://semver.org/). - Implements `fmt::Debug` for `Basis2`, `Basis3`, and `AffineMatrix3` - A `prelude` module for easy importing of common traits. +- Constrained conversion functions for assisting in situations where type + inference is difficult. ### Changed 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;