Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 9b7e41a

Browse files
committed
Amendments to #6.
- Switched to default `std` feature intead of `no_std`. - Updated test matrix. - Fixed tests to work without `std`.
1 parent 655658f commit 9b7e41a

10 files changed

Lines changed: 144 additions & 74 deletions

File tree

.travis.yml

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
language: rust
2-
script: cargo build --features "$CARGO_FEATURES" --verbose && cargo test --verbose
2+
script: >
3+
cargo build $CARGO_FLAGS --features "$CARGO_FEATURES"
4+
&& cargo test $CARGO_FLAGS --features "$CARGO_FEATURES"
35
rust:
46
- 1.2.0
57
- 1.3.0
@@ -9,16 +11,16 @@ rust:
911
- stable
1012
- beta
1113
- nightly
14+
env:
15+
- >
16+
CARGO_FLAGS="--verbose --no-default-features"
17+
CARGO_FEATURES=std
1218
matrix:
1319
allow_failures:
1420
- rust: nightly
15-
env:
16-
- CARGO_FEATURES=
17-
matrix:
1821
include:
1922
- rust: nightly
20-
env:
21-
- CARGO_FEATURES=no_std
23+
env: CARGO_FEATURES=
2224
branches:
2325
except:
2426
- /^issue-.*$/

Cargo.toml

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,11 @@ exclude = [
1616
]
1717

1818
[features]
19-
no_std = []
19+
default = ["std"]
20+
std = ["custom_derive/std"]
2021

2122
[dependencies]
22-
custom_derive = "0.1.2"
23+
custom_derive = { version = "0.1.5", default-features = false }
2324

2425
[dev-dependencies]
2526
quickcheck = "0.2.21, < 0.2.25"

scripts/test-matrix.py

Lines changed: 107 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,73 @@
1010
# or distributed except according to those terms.
1111

1212
import os.path
13+
import re
1314
import subprocess
1415
import sys
1516
import yaml
17+
from itertools import chain
18+
19+
LOG_DIR = os.path.join('local', 'tests')
1620

1721
TRACE = os.environ.get('TRACE_TEST_MATRIX', '') != ''
1822
USE_ANSI = True if sys.platform != 'win32' else os.environ.get('FORCE_ANSI', '') != '' or os.environ.get('ConEmuANSI', 'OFF') == 'ON'
1923

24+
def main():
25+
travis = yaml.load(open('.travis.yml'))
26+
script = translate_script(travis['script'])
27+
default_rust_vers = travis['rust']
28+
# env = {e[0].strip(): e[1].strip() for e in (
29+
# e.split('=', maxsplit=1) for e in travis['env'])}
30+
31+
matrix_includes = travis.get('matrix', {}).get('include', [])
32+
33+
vers = set(default_rust_vers)
34+
include_vers = []
35+
exclude_vers = set()
36+
37+
if not os.path.exists(LOG_DIR):
38+
os.makedirs(LOG_DIR)
39+
40+
for arg in sys.argv[1:]:
41+
if arg in vers and arg not in include_vers:
42+
include_vers.append(arg)
43+
elif arg.startswith('-') and arg[1:] in vers:
44+
exclude_vers.add(arg[1:])
45+
else:
46+
msg("Don't know how to deal with argument `%s`." % arg)
47+
sys.exit(1)
48+
49+
if include_vers == []:
50+
include_vers = default_rust_vers[:]
51+
52+
rust_vers = [v for v in include_vers if v not in exclude_vers]
53+
msg('Tests will be run for: %s' % ', '.join(rust_vers))
54+
55+
results = []
56+
for rust_ver in rust_vers:
57+
seq_id = 0
58+
for env_var_str in travis.get('env', [""]):
59+
env_vars = parse_env_vars(env_var_str)
60+
for row in chain([{}], matrix_includes):
61+
if row.get('rust', None) not in (None, rust_ver):
62+
continue
63+
64+
row_env_vars = parse_env_vars(row.get('env', ""))
65+
66+
cmd_env = {}
67+
cmd_env.update(env_vars)
68+
cmd_env.update(row_env_vars)
69+
70+
success = run_script(script, rust_ver, seq_id, cmd_env)
71+
results.append((rust_ver, seq_id, success))
72+
seq_id += 1
73+
74+
print("")
75+
76+
msg('Results:')
77+
for rust_ver, seq_id, success in results:
78+
msg('%s #%d: %s' % (rust_ver, seq_id, 'OK' if success else 'Failed!'))
79+
2080
def msg(*args):
2181
if USE_ANSI: sys.stdout.write('\x1b[1;34m')
2282
sys.stdout.write('> ')
@@ -37,6 +97,53 @@ def msg_trace(*args):
3797
sys.stderr.write('\n')
3898
sys.stderr.flush()
3999

100+
def parse_env_vars(s):
101+
env_vars = {}
102+
for m in re.finditer(r"""([A-Za-z0-9_]+)=(?:"([^"]+)"|(\S*))""", s.strip()):
103+
k = m.group(1)
104+
v = m.group(2) or m.group(3)
105+
env_vars[k] = v
106+
return env_vars
107+
108+
def run_script(script, rust_ver, seq_id, env):
109+
target_dir = os.path.join('target', '%s-%d' % (rust_ver, seq_id))
110+
log_path = os.path.join(LOG_DIR, '%s-%d.log' % (rust_ver, seq_id))
111+
log_file = open(log_path, 'wt')
112+
msg('Running tests for %s #%d...' % (rust_ver, seq_id))
113+
success = True
114+
115+
def sub_env(m):
116+
name = m.group(1) or m.group(2)
117+
return cmd_env[name]
118+
119+
log_file.write('# %s #%d\n' % (rust_ver, seq_id))
120+
for k, v in env.items():
121+
log_file.write('# %s=%r\n' % (k, v))
122+
123+
cmd_env = os.environ.copy()
124+
cmd_env['CARGO_TARGET_DIR'] = target_dir
125+
cmd_env.update(env)
126+
127+
for cmd in script:
128+
cmd = re.sub(r"\$(?:([A-Za-z0-9_]+)|{([A-Za-z0-9_]+)})\b", sub_env, cmd)
129+
cmd_str = '> multirust run %s %s' % (rust_ver, cmd)
130+
log_file.write(cmd_str)
131+
log_file.write("\n")
132+
log_file.flush()
133+
success = sh(
134+
'multirust run %s %s' % (rust_ver, cmd),
135+
checked=False,
136+
stdout=log_file, stderr=log_file,
137+
env=cmd_env,
138+
)
139+
if not success:
140+
log_file.write('Command failed.\n')
141+
log_file.flush()
142+
break
143+
msg('... ', 'OK' if success else 'Failed!')
144+
log_file.close()
145+
return success
146+
40147
def sh(cmd, env=None, stdout=None, stderr=None, checked=True):
41148
msg_trace('sh(%r, env=%r)' % (cmd, env))
42149
try:
@@ -54,61 +161,5 @@ def translate_script(script):
54161
parts = script.split("&&")
55162
return [p.strip() for p in parts]
56163

57-
def main():
58-
travis = yaml.load(open('.travis.yml'))
59-
script = translate_script(travis['script'])
60-
default_rust_vers = travis['rust']
61-
62-
vers = set(default_rust_vers)
63-
include_vers = []
64-
exclude_vers = set()
65-
66-
for arg in sys.argv[1:]:
67-
if arg in vers and arg not in include_vers:
68-
include_vers.append(arg)
69-
elif arg.startswith('-') and arg[1:] in vers:
70-
exclude_vers.add(arg[1:])
71-
else:
72-
msg("Don't know how to deal with argument `%s`." % arg)
73-
sys.exit(1)
74-
75-
if include_vers == []:
76-
include_vers = default_rust_vers[:]
77-
78-
rust_vers = [v for v in include_vers if v not in exclude_vers]
79-
msg('Tests will be run for: %s' % ', '.join(rust_vers))
80-
81-
results = []
82-
for rust_ver in rust_vers:
83-
msg('Running tests for %s...' % rust_ver)
84-
target_dir = os.path.join('target', rust_ver)
85-
log_path = os.path.join('local', 'tests', '%s.log' % rust_ver)
86-
log_file = open(log_path, 'wt')
87-
success = True
88-
cmd_env = os.environ.copy()
89-
cmd_env['CARGO_TARGET_DIR'] = target_dir
90-
for cmd in script:
91-
cmd_str = '> multirust run %s %s' % (rust_ver, cmd)
92-
log_file.write(cmd_str)
93-
log_file.write("\n")
94-
success = sh(
95-
'multirust run %s %s' % (rust_ver, cmd),
96-
checked=False,
97-
stdout=log_file, stderr=log_file,
98-
env=cmd_env,
99-
)
100-
if not success:
101-
log_file.write('Command failed.\n')
102-
break
103-
msg('... ', 'OK' if success else 'Failed!')
104-
results.append((rust_ver, success))
105-
log_file.close()
106-
107-
print("")
108-
109-
msg('Results:')
110-
for rust_ver, success in results:
111-
msg('%s: %s' % (rust_ver, 'OK' if success else 'Failed!'))
112-
113164
if __name__ == '__main__':
114165
main()

src/impls.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -391,7 +391,7 @@ mod lang_ints {
391391
num_conv! { usize=> n-isize }
392392
}
393393

394-
#[cfg(not(feature = "no_std"))]
394+
#[cfg(feature = "std")]
395395
mod lang_floats {
396396
use {ApproxFrom, ApproxScheme};
397397
use ValueFrom;
@@ -434,7 +434,7 @@ mod lang_floats {
434434
}
435435
}
436436

437-
#[cfg(not(feature = "no_std"))]
437+
#[cfg(feature = "std")]
438438
mod lang_int_to_float {
439439
num_conv! { i8=> w f32, w f64 }
440440
num_conv! { i16=> w f32, w f64 }
@@ -452,7 +452,7 @@ mod lang_int_to_float {
452452
#[32] w f64, #[64] nf [, 9_007_199_254_740_992] f64 }
453453
}
454454

455-
#[cfg(not(feature = "no_std"))]
455+
#[cfg(feature = "std")]
456456
mod lang_float_to_int {
457457
/*
458458
We use explicit ranges on narrowing float-to-int conversions because it *turns out* that just because you can cast an integer to a float, this *does not* mean you can cast it back and get the original input. The non-explicit-range implementation of `fan` *depends* on this, so it was kinda *totally broken* for narrowing conversions.

src/lib.rs

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,7 @@ assert_eq!(400u16.approx_by::<Wrapping>(), Ok::<u8, _>(144u8));
159159
assert_eq!(400u16.approx_as::<u8>(), Err(PosOverflow(400)));
160160
assert_eq!(400u16.approx_as_by::<u8, Wrapping>(), Ok(144));
161161
162+
# #[cfg(feature = "std")] fn std_0() {
162163
// Integer -> float conversions *can* fail due to limited precision.
163164
// Once the continuous range of exactly representable integers is exceeded, the
164165
// provided implementations fail with overflow errors.
@@ -186,14 +187,24 @@ assert_eq!(256.0f32.approx(), Err::<u8, _>(FloatError::PosOverflow(256.0)));
186187
assert_eq!((-23.0f32).approx_as::<u8>().saturate(), Ok(0));
187188
assert_eq!(302.0f32.approx_as::<u8>().saturate(), Ok(255u8));
188189
assert!(std::f32::NAN.approx_as::<u8>().saturate().is_err());
190+
# }
191+
# #[cfg(not(feature = "std"))] fn std_0() {}
192+
# std_0();
189193
190194
// If you really don't care about the specific kind of error, you can just rely
191195
// on automatic conversion to `GeneralErrorKind`.
192196
fn too_many_errors() -> Result<(), GeneralErrorKind> {
193197
assert_eq!({let r: u8 = try!(0u8.value_into()); r}, 0u8);
194198
assert_eq!({let r: u8 = try!(0i8.value_into()); r}, 0u8);
195199
assert_eq!({let r: u8 = try!(0i16.value_into()); r}, 0u8);
200+
# #[cfg(feature = "std")] fn std_1() -> Result<(), GeneralErrorKind> {
196201
assert_eq!({let r: u8 = try!(0.0f32.approx()); r}, 0u8);
202+
# Ok(())
203+
# }
204+
# #[cfg(not(feature = "std"))] fn std_1() -> Result<(), GeneralErrorKind> {
205+
# Ok(())
206+
# }
207+
# try!(std_1());
197208
Ok(())
198209
}
199210
# let _ = too_many_errors();
@@ -204,8 +215,8 @@ fn too_many_errors() -> Result<(), GeneralErrorKind> {
204215

205216
#![deny(missing_docs)]
206217

207-
#![cfg_attr(feature = "no_std", no_std)]
208-
#[cfg(feature = "no_std")] extern crate core as std;
218+
#![cfg_attr(not(feature = "std"), no_std)]
219+
#[cfg(not(feature = "std"))] extern crate core as std;
209220

210221
#[macro_use] extern crate custom_derive;
211222

@@ -220,16 +231,16 @@ pub use errors::{
220231
UnwrapOk, UnwrapOrInf, UnwrapOrInvalid, UnwrapOrSaturate,
221232
};
222233

223-
#[cfg(feature = "no_std")]
234+
#[cfg(not(feature = "std"))]
224235
/**
225236
A conversion error. Corresponds to std::error:Error.
226237
*/
227-
pub trait Error {
238+
pub trait Error: core::fmt::Debug + core::fmt::Display + core::any::Any {
228239
/// A short description of the error
229240
fn description(&self) -> &str;
230241
}
231242

232-
#[cfg(not(feature = "no_std"))]
243+
#[cfg(feature = "std")]
233244
pub use std::error::Error;
234245

235246
/**

src/misc.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ pub trait InvalidSentinel {
3636
fn invalid_sentinel() -> Self;
3737
}
3838

39-
#[cfg(not(feature = "no_std"))]
39+
#[cfg(feature = "std")]
4040
item_for_each! {
4141
(f32), (f64) => {
4242
($ity:ident) => {
@@ -60,7 +60,7 @@ pub trait SignedInfinity {
6060
fn pos_infinity() -> Self;
6161
}
6262

63-
#[cfg(not(feature = "no_std"))]
63+
#[cfg(feature = "std")]
6464
item_for_each! {
6565
(f32), (f64) => {
6666
($ity:ident) => {

tests/conv_utils.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
use conv::prelude::*;
44

5+
#[cfg(feature = "std")]
56
#[test]
67
fn test_approx() {
78
use conv::DefaultApprox;
@@ -32,6 +33,7 @@ fn test_value() {
3233
assert_eq!((123u32).value_as::<u8>(), Ok(123));
3334
}
3435

36+
#[cfg(feature = "std")]
3537
#[test]
3638
fn test_whizzo() {
3739
use conv::errors::Unrepresentable;

tests/lang_floats.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
#![cfg(feature = "std")]
12
extern crate conv;
23

34
#[macro_use] mod util;

tests/lang_ints.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -333,6 +333,7 @@ fn test_usize() {
333333
}
334334
}
335335

336+
#[cfg(feature = "std")]
336337
#[test]
337338
fn test_i_to_f() {
338339
check!(i8, f32=> sident; qv: *; qa: *);

tests/unwraps.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
#![cfg(feature = "std")]
12
extern crate conv;
23

34
#[macro_use] mod util;

0 commit comments

Comments
 (0)