Merge pull request #309 from bjz/conv

Add constrained conversion functions
This commit is contained in:
Brendan Zabarauskas 2016-03-27 16:38:59 +11:00
commit 3218046bfa
4 changed files with 90 additions and 0 deletions

View file

@ -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

View file

@ -35,3 +35,6 @@ rustc_serialize = "0.3"
[dependencies]
num = "0.1"
rand = "0.3"
[dev-dependencies]
glium = "0.13.5"

84
src/conv.rs Normal file
View file

@ -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<T, A: Into<[T; 2]>>(value: A) -> [T; 2] {
value.into()
}
/// Force a conversion into a 3-element array.
#[inline]
pub fn array3<T, A: Into<[T; 3]>>(value: A) -> [T; 3] {
value.into()
}
/// Force a conversion into a 4-element array.
#[inline]
pub fn array4<T, A: Into<[T; 4]>>(value: A) -> [T; 4] {
value.into()
}
/// Force a conversion into a 2x2-element array.
#[inline]
pub fn array2x2<T, A: Into<[[T; 2]; 2]>>(value: A) -> [[T; 2]; 2] {
value.into()
}
/// Force a conversion into a 3x3-element array.
#[inline]
pub fn array3x3<T, A: Into<[[T; 3]; 3]>>(value: A) -> [[T; 3]; 3] {
value.into()
}
/// Force a conversion into a 4x4-element array.
#[inline]
pub fn array4x4<T, A: Into<[[T; 4]; 4]>>(value: A) -> [[T; 4]; 4] {
value.into()
}

View file

@ -54,6 +54,7 @@ pub use rust_num::{One, Zero, one, zero};
// Modules
pub mod conv;
pub mod prelude;
mod macros;