Crates.io | convert_traits |
lib.rs | convert_traits |
version | |
source | src |
created_at | 2024-10-21 14:00:52.815184 |
updated_at | 2024-10-29 03:35:57.534944 |
description | Define your own conversion traits to solve the problem of converting two external types without using new types. |
homepage | https://github.com/andeya/convert_traits |
repository | https://github.com/andeya/convert_traits |
max_upload_size | |
id | 1417539 |
Cargo.toml error: | TOML parse error at line 18, column 1 | 18 | autolib = false | ^^^^^^^ unknown field `autolib`, expected one of `name`, `version`, `edition`, `authors`, `description`, `readme`, `license`, `repository`, `homepage`, `documentation`, `build`, `resolver`, `links`, `default-run`, `default_dash_run`, `rust-version`, `rust_dash_version`, `rust_version`, `license-file`, `license_dash_file`, `license_file`, `licenseFile`, `license_capital_file`, `forced-target`, `forced_dash_target`, `autobins`, `autotests`, `autoexamples`, `autobenches`, `publish`, `metadata`, `keywords`, `categories`, `exclude`, `include` |
size | 0 |
Define your own conversion traits to solve the problem of converting two external types without using new types.
Generate a series of conversion traits with a specified prefix based on: [
::std::convert::AsRef
], [::std::convert::AsMut
], [::std::convert::From
], [::std::convert::Into
], [::std::convert::TryFrom
] and [::std::convert::TryInto
].
Run the following Cargo command in your project directory:
cargo add convert_traits
Or add the following line to your Cargo.toml:
convert_traits = "1"
#[cfg(test)]
#[allow(non_local_definitions)]
mod tests {
# extern crate convert_traits;
use convert_traits::my_convert;
#[derive(Debug, PartialEq)]
struct A(B);
#[derive(Debug, PartialEq)]
struct B;
my_convert!(a_Bc);
#[test]
fn test_as_ref() {
impl ABcAsRef<B> for A {
fn a_bc_as_ref(&self) -> &B {
&self.0
}
}
assert_eq!(&A(B).0, A(B).a_bc_as_ref())
}
#[test]
fn test_as_mut() {
impl ABcAsMut<B> for A {
fn a_bc_as_mut(&mut self) -> &mut B {
&mut self.0
}
}
assert_eq!(&mut B, A(B).a_bc_as_mut())
}
#[test]
fn test_from_into() {
impl ABcFrom<B> for A {
fn a_bc_from(value: B) -> Self {
Self(value)
}
}
assert_eq!(A(B), A::a_bc_from(B));
assert_eq!(A(B), B.a_bc_into());
assert_eq!(B, B.a_bc_into());
my_convert!(x, DISABLE_FROM_SELF);
// assert_eq!(B, B.x_into());
// ^^^^^^ the trait `XFrom<B>` is not implemented for `B`, which is required by `B: XInto<_>`
}
#[test]
fn test_try_from_into() {
impl ABcTryFrom<A> for B {
type Error = std::convert::Infallible;
fn a_bc_try_from(value: A) -> Result<Self, Self::Error> {
Ok(value.0)
}
}
assert_eq!(B, B::a_bc_try_from(A(B)).unwrap());
assert_eq!(B, A(B).a_bc_try_into().unwrap());
}
}