Deprecate the bytes!() macro.

Replace its usage with byte string literals, except in `bytes!()` tests.
Also add a new snapshot, to be able to use the new b"foo" syntax.

The src/etc/2014-06-rewrite-bytes-macros.py script automatically
rewrites `bytes!()` invocations into byte string literals.
Pass it filenames as arguments to generate a diff that you can inspect,
or `--apply` followed by filenames to apply the changes in place.
Diffs can be piped into `tip` or `pygmentize -l diff` for coloring.
This commit is contained in:
Simon Sapin 2014-06-18 20:25:36 +02:00 committed by Alex Crichton
parent abf7e933df
commit 108b8b6dc7
42 changed files with 497 additions and 354 deletions

View File

@ -1269,7 +1269,7 @@ fn make_out_name(config: &Config, testfile: &Path, extension: &str) -> Path {
fn aux_output_dir_name(config: &Config, testfile: &Path) -> Path {
let mut f = output_base_name(config, testfile);
match f.filename().map(|s| Vec::from_slice(s).append(bytes!(".libaux"))) {
match f.filename().map(|s| Vec::from_slice(s).append(b".libaux")) {
Some(v) => f.set_filename(v),
None => ()
}
@ -1490,7 +1490,7 @@ fn append_suffix_to_stem(p: &Path, suffix: &str) -> Path {
(*p).clone()
} else {
let stem = p.filestem().unwrap();
p.with_filename(Vec::from_slice(stem).append(bytes!("-")).append(suffix.as_bytes()))
p.with_filename(Vec::from_slice(stem).append(b"-").append(suffix.as_bytes()))
}
}

View File

@ -76,7 +76,7 @@ character.
~~~
use std::str;
let x = bytes!(72u8,"ello ",0xF0,0x90,0x80,"World!");
let x = b"Hello \xF0\x90\x80World!";
let y = str::from_utf8_lossy(x);
~~~

View File

@ -378,6 +378,19 @@ the characters `U+0022` (double-quote) (except when followed by at least as
many `U+0023` (`#`) characters as were used to start the raw string literal) or
`U+005C` (`\`) do not have any special meaning.
Examples for byte string literals:
~~~~
b"foo"; br"foo"; // foo
b"\"foo\""; br#""foo""#; // "foo"
b"foo #\"# bar";
br##"foo #"# bar"##; // foo #"# bar
b"\x52"; b"R"; br"R"; // R
b"\\x52"; br"\x52"; // \x52
~~~~
#### Number literals
~~~~ {.ebnf .gram}

View File

@ -0,0 +1,138 @@
#!/bin/env python
#
# Copyright 2014 The Rust Project Developers. See the COPYRIGHT
# file at the top-level directory of this distribution and at
# http://rust-lang.org/COPYRIGHT.
#
# Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
# http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
# <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
# option. This file may not be copied, modified, or distributed
# except according to those terms.
import sys
import subprocess
import re
def main():
if len(sys.argv) <= 1:
print('Usage: %s [ --apply ] filename1.rs filename2.rs ...'
% sys.argv[0])
elif sys.argv[1] == '--apply':
for filename in sys.argv[2:]:
patch(filename)
else:
for filename in sys.argv[1:]:
diff(filename)
def patch(filename):
source = read(filename)
rewritten = rewrite_bytes_macros(source)
if rewritten is not None and rewritten != source:
write(filename, rewritten)
def diff(filename):
rewritten = rewrite_bytes_macros(read(filename))
if rewritten is not None:
p = subprocess.Popen(['diff', '-u', filename, '-'],
stdin=subprocess.PIPE)
p.stdin.write(rewritten)
p.stdin.close()
p.wait()
def read(filename):
with open(filename, 'rb') as f:
return f.read()
def write(filename, content):
with open(filename, 'wb') as f:
f.write(content)
def rewrite_bytes_macros(source):
rewritten, num_occurrences = BYTES_MACRO_RE.subn(rewrite_one_macro, source)
if num_occurrences > 0:
return rewritten
BYTES_MACRO_RE = re.compile(br'bytes!\( (?P<args> [^)]* ) \)', re.VERBOSE)
def rewrite_one_macro(match):
try:
bytes = parse_bytes(split_args(match.group('args')))
return b'b"' + b''.join(map(escape, bytes)) + b'"'
except SkipThisRewrite:
print('Skipped: %s' % match.group(0).decode('utf8', 'replace'))
return match.group(0)
class SkipThisRewrite(Exception):
pass
def split_args(args):
previous = b''
for arg in args.split(b','):
if previous:
arg = previous + b',' + arg
if arg.count(b'"') % 2 == 0:
yield arg
previous = b''
else:
previous = arg
if previous:
yield previous
def parse_bytes(args):
for arg in args:
arg = arg.strip()
if (arg.startswith(b'"') and arg.endswith(b'"')) or (
arg.startswith(b"'") and arg.endswith(b"'")):
# Escaped newline means something different in Rust and Python.
if b'\\\n' in arg:
raise SkipThisRewrite
for byte in eval(b'u' + arg).encode('utf8'):
yield ord(byte)
else:
if arg.endswith(b'u8'):
arg = arg[:-2]
# Assume that all Rust integer literals
# are valid Python integer literals
value = int(eval(arg))
assert value <= 0xFF
yield value
def escape(byte):
c = chr(byte)
escaped = {
b'\0': br'\0',
b'\t': br'\t',
b'\n': br'\n',
b'\r': br'\r',
b'\'': b'\\\'',
b'\\': br'\\',
}.get(c)
if escaped is not None:
return escaped
elif b' ' <= c <= b'~':
return chr(byte)
else:
return ('\\x%02X' % byte).encode('ascii')
if str is not bytes:
# Python 3.x
ord = lambda x: x
chr = lambda x: bytes([x])
if __name__ == '__main__':
main()

View File

@ -1957,30 +1957,30 @@ mod tests {
#[test]
fn test_starts_with() {
assert!(bytes!("foobar").starts_with(bytes!("foo")));
assert!(!bytes!("foobar").starts_with(bytes!("oob")));
assert!(!bytes!("foobar").starts_with(bytes!("bar")));
assert!(!bytes!("foo").starts_with(bytes!("foobar")));
assert!(!bytes!("bar").starts_with(bytes!("foobar")));
assert!(bytes!("foobar").starts_with(bytes!("foobar")));
assert!(b"foobar".starts_with(b"foo"));
assert!(!b"foobar".starts_with(b"oob"));
assert!(!b"foobar".starts_with(b"bar"));
assert!(!b"foo".starts_with(b"foobar"));
assert!(!b"bar".starts_with(b"foobar"));
assert!(b"foobar".starts_with(b"foobar"));
let empty: &[u8] = [];
assert!(empty.starts_with(empty));
assert!(!empty.starts_with(bytes!("foo")));
assert!(bytes!("foobar").starts_with(empty));
assert!(!empty.starts_with(b"foo"));
assert!(b"foobar".starts_with(empty));
}
#[test]
fn test_ends_with() {
assert!(bytes!("foobar").ends_with(bytes!("bar")));
assert!(!bytes!("foobar").ends_with(bytes!("oba")));
assert!(!bytes!("foobar").ends_with(bytes!("foo")));
assert!(!bytes!("foo").ends_with(bytes!("foobar")));
assert!(!bytes!("bar").ends_with(bytes!("foobar")));
assert!(bytes!("foobar").ends_with(bytes!("foobar")));
assert!(b"foobar".ends_with(b"bar"));
assert!(!b"foobar".ends_with(b"oba"));
assert!(!b"foobar".ends_with(b"foo"));
assert!(!b"foo".ends_with(b"foobar"));
assert!(!b"bar".ends_with(b"foobar"));
assert!(b"foobar".ends_with(b"foobar"));
let empty: &[u8] = [];
assert!(empty.ends_with(empty));
assert!(!empty.ends_with(bytes!("foo")));
assert!(bytes!("foobar").ends_with(empty));
assert!(!empty.ends_with(b"foo"));
assert!(b"foobar".ends_with(empty));
}
#[test]

View File

@ -382,7 +382,7 @@ static TAG_CONT_U8: u8 = 128u8;
/// # Example
///
/// ```rust
/// let input = bytes!("Hello ", 0xF0, 0x90, 0x80, "World");
/// let input = b"Hello \xF0\x90\x80World";
/// let output = std::str::from_utf8_lossy(input);
/// assert_eq!(output.as_slice(), "Hello \uFFFDWorld");
/// ```
@ -391,7 +391,7 @@ pub fn from_utf8_lossy<'a>(v: &'a [u8]) -> MaybeOwned<'a> {
return Slice(unsafe { mem::transmute(v) })
}
static REPLACEMENT: &'static [u8] = bytes!(0xEF, 0xBF, 0xBD); // U+FFFD in UTF-8
static REPLACEMENT: &'static [u8] = b"\xEF\xBF\xBD"; // U+FFFD in UTF-8
let mut i = 0;
let total = v.len();
fn unsafe_get(xs: &[u8], i: uint) -> u8 {
@ -994,7 +994,7 @@ mod tests {
fn test_into_bytes() {
let data = "asdf".to_string();
let buf = data.into_bytes();
assert_eq!(bytes!("asdf"), buf.as_slice());
assert_eq!(b"asdf", buf.as_slice());
}
#[test]
@ -2050,58 +2050,58 @@ mod tests {
#[test]
fn test_str_from_utf8() {
let xs = bytes!("hello");
let xs = b"hello";
assert_eq!(from_utf8(xs), Some("hello"));
let xs = bytes!("ศไทย中华Việt Nam");
let xs = "ศไทย中华Việt Nam".as_bytes();
assert_eq!(from_utf8(xs), Some("ศไทย中华Việt Nam"));
let xs = bytes!("hello", 0xff);
let xs = b"hello\xFF";
assert_eq!(from_utf8(xs), None);
}
#[test]
fn test_str_from_utf8_owned() {
let xs = Vec::from_slice(bytes!("hello"));
let xs = Vec::from_slice(b"hello");
assert_eq!(from_utf8_owned(xs), Ok("hello".to_string()));
let xs = Vec::from_slice(bytes!("ศไทย中华Việt Nam"));
let xs = Vec::from_slice("ศไทย中华Việt Nam".as_bytes());
assert_eq!(from_utf8_owned(xs), Ok("ศไทย中华Việt Nam".to_string()));
let xs = Vec::from_slice(bytes!("hello", 0xff));
let xs = Vec::from_slice(b"hello\xFF");
assert_eq!(from_utf8_owned(xs),
Err(Vec::from_slice(bytes!("hello", 0xff))));
Err(Vec::from_slice(b"hello\xFF")));
}
#[test]
fn test_str_from_utf8_lossy() {
let xs = bytes!("hello");
let xs = b"hello";
assert_eq!(from_utf8_lossy(xs), Slice("hello"));
let xs = bytes!("ศไทย中华Việt Nam");
let xs = "ศไทย中华Việt Nam".as_bytes();
assert_eq!(from_utf8_lossy(xs), Slice("ศไทย中华Việt Nam"));
let xs = bytes!("Hello", 0xC2, " There", 0xFF, " Goodbye");
let xs = b"Hello\xC2 There\xFF Goodbye";
assert_eq!(from_utf8_lossy(xs), Owned("Hello\uFFFD There\uFFFD Goodbye".to_string()));
let xs = bytes!("Hello", 0xC0, 0x80, " There", 0xE6, 0x83, " Goodbye");
let xs = b"Hello\xC0\x80 There\xE6\x83 Goodbye";
assert_eq!(from_utf8_lossy(xs), Owned("Hello\uFFFD\uFFFD There\uFFFD Goodbye".to_string()));
let xs = bytes!(0xF5, "foo", 0xF5, 0x80, "bar");
let xs = b"\xF5foo\xF5\x80bar";
assert_eq!(from_utf8_lossy(xs), Owned("\uFFFDfoo\uFFFD\uFFFDbar".to_string()));
let xs = bytes!(0xF1, "foo", 0xF1, 0x80, "bar", 0xF1, 0x80, 0x80, "baz");
let xs = b"\xF1foo\xF1\x80bar\xF1\x80\x80baz";
assert_eq!(from_utf8_lossy(xs), Owned("\uFFFDfoo\uFFFDbar\uFFFDbaz".to_string()));
let xs = bytes!(0xF4, "foo", 0xF4, 0x80, "bar", 0xF4, 0xBF, "baz");
let xs = b"\xF4foo\xF4\x80bar\xF4\xBFbaz";
assert_eq!(from_utf8_lossy(xs), Owned("\uFFFDfoo\uFFFDbar\uFFFD\uFFFDbaz".to_string()));
let xs = bytes!(0xF0, 0x80, 0x80, 0x80, "foo", 0xF0, 0x90, 0x80, 0x80, "bar");
let xs = b"\xF0\x80\x80\x80foo\xF0\x90\x80\x80bar";
assert_eq!(from_utf8_lossy(xs), Owned("\uFFFD\uFFFD\uFFFD\uFFFD\
foo\U00010000bar".to_string()));
// surrogates
let xs = bytes!(0xED, 0xA0, 0x80, "foo", 0xED, 0xBF, 0xBF, "bar");
let xs = b"\xED\xA0\x80foo\xED\xBF\xBFbar";
assert_eq!(from_utf8_lossy(xs), Owned("\uFFFD\uFFFD\uFFFDfoo\
\uFFFD\uFFFD\uFFFDbar".to_string()));
}
@ -2298,8 +2298,8 @@ mod bench {
#[bench]
fn is_utf8_100_ascii(b: &mut Bencher) {
let s = bytes!("Hello there, the quick brown fox jumped over the lazy dog! \
Lorem ipsum dolor sit amet, consectetur. ");
let s = b"Hello there, the quick brown fox jumped over the lazy dog! \
Lorem ipsum dolor sit amet, consectetur. ";
assert_eq!(100, s.len());
b.iter(|| {
@ -2309,7 +2309,7 @@ mod bench {
#[bench]
fn is_utf8_100_multibyte(b: &mut Bencher) {
let s = bytes!("𐌀𐌖𐌋𐌄𐌑𐌉ปรدولة الكويتทศไทย中华𐍅𐌿𐌻𐍆𐌹𐌻𐌰");
let s = "𐌀𐌖𐌋𐌄𐌑𐌉ปรدولة الكويتทศไทย中华𐍅𐌿𐌻𐍆𐌹𐌻𐌰".as_bytes();
assert_eq!(100, s.len());
b.iter(|| {
is_utf8(s)
@ -2318,8 +2318,8 @@ mod bench {
#[bench]
fn from_utf8_lossy_100_ascii(b: &mut Bencher) {
let s = bytes!("Hello there, the quick brown fox jumped over the lazy dog! \
Lorem ipsum dolor sit amet, consectetur. ");
let s = b"Hello there, the quick brown fox jumped over the lazy dog! \
Lorem ipsum dolor sit amet, consectetur. ";
assert_eq!(100, s.len());
b.iter(|| {
@ -2329,7 +2329,7 @@ mod bench {
#[bench]
fn from_utf8_lossy_100_multibyte(b: &mut Bencher) {
let s = bytes!("𐌀𐌖𐌋𐌄𐌑𐌉ปรدولة الكويتทศไทย中华𐍅𐌿𐌻𐍆𐌹𐌻𐌰");
let s = "𐌀𐌖𐌋𐌄𐌑𐌉ปรدولة الكويتทศไทย中华𐍅𐌿𐌻𐍆𐌹𐌻𐌰".as_bytes();
assert_eq!(100, s.len());
b.iter(|| {
let _ = from_utf8_lossy(s);
@ -2338,7 +2338,7 @@ mod bench {
#[bench]
fn from_utf8_lossy_invalid(b: &mut Bencher) {
let s = bytes!("Hello", 0xC0, 0x80, " There", 0xE6, 0x83, " Goodbye");
let s = b"Hello\xC0\x80 There\xE6\x83 Goodbye";
b.iter(|| {
let _ = from_utf8_lossy(s);
});

View File

@ -75,13 +75,13 @@ macro_rules! num_repr(($ty:ident, $suffix:expr) => (impl Repr for $ty {
fn write_repr(&self, writer: &mut io::Writer) -> io::IoResult<()> {
let s = self.to_str();
writer.write(s.as_bytes()).and_then(|()| {
writer.write(bytes!($suffix))
writer.write($suffix)
})
}
}))
num_repr!(f32, "f32")
num_repr!(f64, "f64")
num_repr!(f32, b"f32")
num_repr!(f64, b"f64")
// New implementation using reflect::MovePtr

View File

@ -360,7 +360,7 @@ pub fn readdir(p: &CString) -> IoResult<Vec<CString>> {
let root = Path::new(root);
dirs.move_iter().filter(|path| {
path.as_vec() != bytes!(".") && path.as_vec() != bytes!("..")
path.as_vec() != b"." && path.as_vec() != b".."
}).map(|path| root.join(path).to_c_str()).collect()
}
@ -529,7 +529,7 @@ mod tests {
let mut reader = FileDesc::new(reader, true);
let mut writer = FileDesc::new(writer, true);
writer.inner_write(bytes!("test")).ok().unwrap();
writer.inner_write(b"test").ok().unwrap();
let mut buf = [0u8, ..4];
match reader.inner_read(buf) {
Ok(4) => {
@ -552,7 +552,7 @@ mod tests {
assert!(!f.is_null());
let mut file = CFile::new(f);
file.write(bytes!("test")).ok().unwrap();
file.write(b"test").ok().unwrap();
let mut buf = [0u8, ..4];
let _ = file.seek(0, SeekSet).ok().unwrap();
match file.read(buf) {

View File

@ -351,7 +351,7 @@ pub fn readdir(p: &CString) -> IoResult<Vec<CString>> {
let root = Path::new(root);
dirs.move_iter().filter(|path| {
path.as_vec() != bytes!(".") && path.as_vec() != bytes!("..")
path.as_vec() != b"." && path.as_vec() != b".."
}).map(|path| root.join(path).to_c_str()).collect()
}

View File

@ -292,9 +292,9 @@ pub struct AsciiGenerator<'a, R> {
impl<'a, R: Rng> Iterator<char> for AsciiGenerator<'a, R> {
fn next(&mut self) -> Option<char> {
static GEN_ASCII_STR_CHARSET: &'static [u8] =
bytes!("ABCDEFGHIJKLMNOPQRSTUVWXYZ\
abcdefghijklmnopqrstuvwxyz\
0123456789");
b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
abcdefghijklmnopqrstuvwxyz\
0123456789";
Some(*self.rng.choose(GEN_ASCII_STR_CHARSET).unwrap() as char)
}
}

View File

@ -214,7 +214,7 @@ pub fn rust_path() -> Vec<Path> {
env_rust_path.push(cwd.clone());
}
loop {
if { let f = cwd.filename(); f.is_none() || f.unwrap() == bytes!("..") } {
if { let f = cwd.filename(); f.is_none() || f.unwrap() == b".." } {
break
}
cwd.set_filename(".rust");

View File

@ -1411,7 +1411,7 @@ fn compile_unit_metadata(cx: &CrateContext) {
match abs_path.path_relative_from(work_dir) {
Some(ref p) if p.is_relative() => {
// prepend "./" if necessary
let dotdot = bytes!("..");
let dotdot = b"..";
let prefix = &[dotdot[0], ::std::path::SEP_BYTE];
let mut path_bytes = Vec::from_slice(p.as_vec());

View File

@ -602,7 +602,7 @@ fn mkdir(path: &Path) -> io::IoResult<()> {
// FIXME (#9639): The closure should deal with &[u8] instead of &str
fn clean_srcpath(src: &[u8], f: |&str|) {
let p = Path::new(src);
if p.as_vec() != bytes!(".") {
if p.as_vec() != b"." {
for c in p.str_components().map(|x|x.unwrap()) {
if ".." == c {
f("up");
@ -714,7 +714,7 @@ impl<'a> SourceCollector<'a> {
});
cur.push(Vec::from_slice(p.filename().expect("source has no filename"))
.append(bytes!(".html")));
.append(b".html"));
let mut w = BufferedWriter::new(try!(File::create(&cur)));
let title = format!("{} -- source", cur.filename_display());

View File

@ -123,8 +123,8 @@ mod imp {
let saved_value = take();
let expected = vec![
Vec::from_slice(bytes!("happy")),
Vec::from_slice(bytes!("today?")),
Vec::from_slice(b"happy"),
Vec::from_slice(b"today?"),
];
put(expected.clone());

View File

@ -463,7 +463,7 @@ mod tests {
#[test]
fn test_str_multistring_parsing() {
unsafe {
let input = bytes!("zero", "\x00", "one", "\x00", "\x00");
let input = b"zero\0one\0\0";
let ptr = input.as_ptr();
let expected = ["zero", "one"];
let mut it = expected.iter();
@ -505,7 +505,7 @@ mod tests {
}
});
let _ = bytes!("hello").to_c_str().with_ref(|buf| {
let _ = b"hello".to_c_str().with_ref(|buf| {
unsafe {
assert_eq!(*buf.offset(0), 'h' as libc::c_char);
assert_eq!(*buf.offset(1), 'e' as libc::c_char);
@ -516,7 +516,7 @@ mod tests {
}
});
let _ = bytes!("foo", 0xff).to_c_str().with_ref(|buf| {
let _ = b"foo\xFF".to_c_str().with_ref(|buf| {
unsafe {
assert_eq!(*buf.offset(0), 'f' as libc::c_char);
assert_eq!(*buf.offset(1), 'o' as libc::c_char);
@ -595,22 +595,22 @@ mod tests {
#[test]
fn test_as_bytes() {
let c_str = "hello".to_c_str();
assert_eq!(c_str.as_bytes(), bytes!("hello", 0));
assert_eq!(c_str.as_bytes(), b"hello\0");
let c_str = "".to_c_str();
assert_eq!(c_str.as_bytes(), bytes!(0));
let c_str = bytes!("foo", 0xff).to_c_str();
assert_eq!(c_str.as_bytes(), bytes!("foo", 0xff, 0));
assert_eq!(c_str.as_bytes(), b"\0");
let c_str = b"foo\xFF".to_c_str();
assert_eq!(c_str.as_bytes(), b"foo\xFF\0");
}
#[test]
fn test_as_bytes_no_nul() {
let c_str = "hello".to_c_str();
assert_eq!(c_str.as_bytes_no_nul(), bytes!("hello"));
assert_eq!(c_str.as_bytes_no_nul(), b"hello");
let c_str = "".to_c_str();
let exp: &[u8] = [];
assert_eq!(c_str.as_bytes_no_nul(), exp);
let c_str = bytes!("foo", 0xff).to_c_str();
assert_eq!(c_str.as_bytes_no_nul(), bytes!("foo", 0xff));
let c_str = b"foo\xFF".to_c_str();
assert_eq!(c_str.as_bytes_no_nul(), b"foo\xFF");
}
#[test]
@ -633,7 +633,7 @@ mod tests {
assert_eq!(c_str.as_str(), Some("hello"));
let c_str = "".to_c_str();
assert_eq!(c_str.as_str(), Some(""));
let c_str = bytes!("foo", 0xff).to_c_str();
let c_str = b"foo\xFF".to_c_str();
assert_eq!(c_str.as_str(), None);
}

View File

@ -42,13 +42,13 @@ pub static URL_SAFE: Config =
pub static MIME: Config =
Config {char_set: Standard, pad: true, line_length: Some(76)};
static STANDARD_CHARS: &'static[u8] = bytes!("ABCDEFGHIJKLMNOPQRSTUVWXYZ",
"abcdefghijklmnopqrstuvwxyz",
"0123456789+/");
static STANDARD_CHARS: &'static[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
abcdefghijklmnopqrstuvwxyz\
0123456789+/";
static URLSAFE_CHARS: &'static[u8] = bytes!("ABCDEFGHIJKLMNOPQRSTUVWXYZ",
"abcdefghijklmnopqrstuvwxyz",
"0123456789-_");
static URLSAFE_CHARS: &'static[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
abcdefghijklmnopqrstuvwxyz\
0123456789-_";
/// A trait for converting a value to base64 encoding.
pub trait ToBase64 {
@ -193,7 +193,7 @@ impl<'a> FromBase64 for &'a str {
* use serialize::base64::{ToBase64, FromBase64, STANDARD};
*
* fn main () {
* let hello_str = bytes!("Hello, World").to_base64(STANDARD);
* let hello_str = b"Hello, World".to_base64(STANDARD);
* println!("base64 output: {}", hello_str);
* let res = hello_str.as_slice().from_base64();
* if res.is_ok() {

View File

@ -19,7 +19,7 @@ pub trait ToHex {
fn to_hex(&self) -> String;
}
static CHARS: &'static[u8] = bytes!("0123456789abcdef");
static CHARS: &'static[u8] = b"0123456789abcdef";
impl<'a> ToHex for &'a [u8] {
/**

View File

@ -535,7 +535,7 @@ mod test {
#[test]
fn test_read_line() {
let in_buf = MemReader::new(Vec::from_slice(bytes!("a\nb\nc")));
let in_buf = MemReader::new(Vec::from_slice(b"a\nb\nc"));
let mut reader = BufferedReader::with_capacity(2, in_buf);
assert_eq!(reader.read_line(), Ok("a\n".to_string()));
assert_eq!(reader.read_line(), Ok("b\n".to_string()));
@ -545,7 +545,7 @@ mod test {
#[test]
fn test_lines() {
let in_buf = MemReader::new(Vec::from_slice(bytes!("a\nb\nc")));
let in_buf = MemReader::new(Vec::from_slice(b"a\nb\nc"));
let mut reader = BufferedReader::with_capacity(2, in_buf);
let mut it = reader.lines();
assert_eq!(it.next(), Some(Ok("a\n".to_string())));

View File

@ -35,7 +35,7 @@ let path = Path::new("foo.txt");
// create the file, whether it exists or not
let mut file = File::create(&path);
file.write(bytes!("foobar"));
file.write(b"foobar");
# drop(file);
// open the file in read-only mode
@ -186,7 +186,7 @@ impl File {
/// use std::io::File;
///
/// let mut f = File::create(&Path::new("foo.txt"));
/// f.write(bytes!("This is a sample file"));
/// f.write(b"This is a sample file");
/// # drop(f);
/// # ::std::io::fs::unlink(&Path::new("foo.txt"));
/// ```
@ -1141,7 +1141,7 @@ mod test {
iotest!(fn file_test_fileinfo_check_exists_before_and_after_file_creation() {
let tmpdir = tmpdir();
let file = &tmpdir.join("fileinfo_check_exists_b_and_a.txt");
check!(File::create(file).write(bytes!("foo")));
check!(File::create(file).write(b"foo"));
assert!(file.exists());
check!(unlink(file));
assert!(!file.exists());
@ -1253,7 +1253,7 @@ mod test {
let canary = d2.join("do_not_delete");
check!(mkdir_recursive(&dtt, io::UserRWX));
check!(mkdir_recursive(&d2, io::UserRWX));
check!(File::create(&canary).write(bytes!("foo")));
check!(File::create(&canary).write(b"foo"));
check!(symlink(&d2, &dt.join("d2")));
check!(rmdir_recursive(&d1));
@ -1314,10 +1314,10 @@ mod test {
let input = tmpdir.join("in.txt");
let out = tmpdir.join("out.txt");
check!(File::create(&input).write(bytes!("hello")));
check!(File::create(&input).write(b"hello"));
check!(copy(&input, &out));
let contents = check!(File::open(&out).read_to_end());
assert_eq!(contents.as_slice(), bytes!("hello"));
assert_eq!(contents.as_slice(), b"hello");
assert_eq!(check!(input.stat()).perm, check!(out.stat()).perm);
})
@ -1342,7 +1342,7 @@ mod test {
check!(copy(&input, &output));
assert_eq!(check!(File::open(&output).read_to_end()),
(Vec::from_slice(bytes!("foo"))));
(Vec::from_slice(b"foo")));
})
iotest!(fn copy_file_src_dir() {
@ -1383,7 +1383,7 @@ mod test {
}
assert_eq!(check!(stat(&out)).size, check!(stat(&input)).size);
assert_eq!(check!(File::open(&out).read_to_end()),
(Vec::from_slice(bytes!("foobar"))));
(Vec::from_slice(b"foobar")));
})
#[cfg(not(windows))] // apparently windows doesn't like symlinks
@ -1418,7 +1418,7 @@ mod test {
assert_eq!(check!(stat(&out)).size, check!(stat(&input)).size);
assert_eq!(check!(stat(&out)).size, check!(input.stat()).size);
assert_eq!(check!(File::open(&out).read_to_end()),
(Vec::from_slice(bytes!("foobar"))));
(Vec::from_slice(b"foobar")));
// can't link to yourself
match link(&input, &input) {
@ -1456,7 +1456,7 @@ mod test {
let mut file = check!(File::open_mode(&path, io::Open, io::ReadWrite));
check!(file.fsync());
check!(file.datasync());
check!(file.write(bytes!("foo")));
check!(file.write(b"foo"));
check!(file.fsync());
check!(file.datasync());
drop(file);
@ -1467,29 +1467,29 @@ mod test {
let path = tmpdir.join("in.txt");
let mut file = check!(File::open_mode(&path, io::Open, io::ReadWrite));
check!(file.write(bytes!("foo")));
check!(file.write(b"foo"));
check!(file.fsync());
// Do some simple things with truncation
assert_eq!(check!(file.stat()).size, 3);
check!(file.truncate(10));
assert_eq!(check!(file.stat()).size, 10);
check!(file.write(bytes!("bar")));
check!(file.write(b"bar"));
check!(file.fsync());
assert_eq!(check!(file.stat()).size, 10);
assert_eq!(check!(File::open(&path).read_to_end()),
(Vec::from_slice(bytes!("foobar", 0, 0, 0, 0))));
(Vec::from_slice(b"foobar\0\0\0\0")));
// Truncate to a smaller length, don't seek, and then write something.
// Ensure that the intermediate zeroes are all filled in (we're seeked
// past the end of the file).
check!(file.truncate(2));
assert_eq!(check!(file.stat()).size, 2);
check!(file.write(bytes!("wut")));
check!(file.write(b"wut"));
check!(file.fsync());
assert_eq!(check!(file.stat()).size, 9);
assert_eq!(check!(File::open(&path).read_to_end()),
(Vec::from_slice(bytes!("fo", 0, 0, 0, 0, "wut"))));
(Vec::from_slice(b"fo\0\0\0\0wut")));
drop(file);
})

View File

@ -474,7 +474,7 @@ mod test {
#[test]
fn test_read_char() {
let b = bytes!("Việt");
let b = b"Vi\xE1\xBB\x87t";
let mut r = BufReader::new(b);
assert_eq!(r.read_char(), Ok('V'));
assert_eq!(r.read_char(), Ok('i'));
@ -485,7 +485,7 @@ mod test {
#[test]
fn test_read_bad_char() {
let b = bytes!(0x80);
let b = b"\x80";
let mut r = BufReader::new(b);
assert!(r.read_char().is_err());
}

View File

@ -50,7 +50,7 @@ Some examples of obvious things you might want to do
use std::io::File;
let mut file = File::create(&Path::new("message.txt"));
file.write(bytes!("hello, file!\n"));
file.write(b"hello, file!\n");
# drop(file);
# ::std::io::fs::unlink(&Path::new("message.txt"));
```
@ -90,7 +90,7 @@ Some examples of obvious things you might want to do
# // just stop it running (#11576)
# if false {
let mut socket = TcpStream::connect("127.0.0.1", 8080).unwrap();
socket.write(bytes!("GET / HTTP/1.0\n\n"));
socket.write(b"GET / HTTP/1.0\n\n");
let response = socket.read_to_end();
# }
```
@ -151,7 +151,7 @@ while still providing feedback about errors. The basic strategy:
to be 'unwrapped' before use.
These features combine in the API to allow for expressions like
`File::create(&Path::new("diary.txt")).write(bytes!("Met a girl.\n"))`
`File::create(&Path::new("diary.txt")).write(b"Met a girl.\n")`
without having to worry about whether "diary.txt" exists or whether
the write succeeds. As written, if either `new` or `write_line`
encounters an error then the result of the entire expression will
@ -163,7 +163,7 @@ If you wanted to handle the error though you might write:
# #![allow(unused_must_use)]
use std::io::File;
match File::create(&Path::new("diary.txt")).write(bytes!("Met a girl.\n")) {
match File::create(&Path::new("diary.txt")).write(b"Met a girl.\n") {
Ok(()) => (), // succeeded
Err(e) => println!("failed to write to my diary: {}", e),
}
@ -1839,55 +1839,55 @@ mod tests {
#[test]
fn test_read_at_least() {
let mut r = BadReader::new(MemReader::new(Vec::from_slice(bytes!("hello, world!"))),
let mut r = BadReader::new(MemReader::new(Vec::from_slice(b"hello, world!")),
Vec::from_slice([GoodBehavior(uint::MAX)]));
let mut buf = [0u8, ..5];
assert!(r.read_at_least(1, buf).unwrap() >= 1);
assert!(r.read_exact(5).unwrap().len() == 5); // read_exact uses read_at_least
assert!(r.read_at_least(0, buf).is_ok());
let mut r = BadReader::new(MemReader::new(Vec::from_slice(bytes!("hello, world!"))),
let mut r = BadReader::new(MemReader::new(Vec::from_slice(b"hello, world!")),
Vec::from_slice([BadBehavior(50), GoodBehavior(uint::MAX)]));
assert!(r.read_at_least(1, buf).unwrap() >= 1);
let mut r = BadReader::new(MemReader::new(Vec::from_slice(bytes!("hello, world!"))),
let mut r = BadReader::new(MemReader::new(Vec::from_slice(b"hello, world!")),
Vec::from_slice([BadBehavior(1), GoodBehavior(1),
BadBehavior(50), GoodBehavior(uint::MAX)]));
assert!(r.read_at_least(1, buf).unwrap() >= 1);
assert!(r.read_at_least(1, buf).unwrap() >= 1);
let mut r = BadReader::new(MemReader::new(Vec::from_slice(bytes!("hello, world!"))),
let mut r = BadReader::new(MemReader::new(Vec::from_slice(b"hello, world!")),
Vec::from_slice([BadBehavior(uint::MAX)]));
assert_eq!(r.read_at_least(1, buf).unwrap_err().kind, NoProgress);
let mut r = MemReader::new(Vec::from_slice(bytes!("hello, world!")));
let mut r = MemReader::new(Vec::from_slice(b"hello, world!"));
assert_eq!(r.read_at_least(5, buf).unwrap(), 5);
assert_eq!(r.read_at_least(6, buf).unwrap_err().kind, InvalidInput);
}
#[test]
fn test_push_at_least() {
let mut r = BadReader::new(MemReader::new(Vec::from_slice(bytes!("hello, world!"))),
let mut r = BadReader::new(MemReader::new(Vec::from_slice(b"hello, world!")),
Vec::from_slice([GoodBehavior(uint::MAX)]));
let mut buf = Vec::new();
assert!(r.push_at_least(1, 5, &mut buf).unwrap() >= 1);
assert!(r.push_at_least(0, 5, &mut buf).is_ok());
let mut r = BadReader::new(MemReader::new(Vec::from_slice(bytes!("hello, world!"))),
let mut r = BadReader::new(MemReader::new(Vec::from_slice(b"hello, world!")),
Vec::from_slice([BadBehavior(50), GoodBehavior(uint::MAX)]));
assert!(r.push_at_least(1, 5, &mut buf).unwrap() >= 1);
let mut r = BadReader::new(MemReader::new(Vec::from_slice(bytes!("hello, world!"))),
let mut r = BadReader::new(MemReader::new(Vec::from_slice(b"hello, world!")),
Vec::from_slice([BadBehavior(1), GoodBehavior(1),
BadBehavior(50), GoodBehavior(uint::MAX)]));
assert!(r.push_at_least(1, 5, &mut buf).unwrap() >= 1);
assert!(r.push_at_least(1, 5, &mut buf).unwrap() >= 1);
let mut r = BadReader::new(MemReader::new(Vec::from_slice(bytes!("hello, world!"))),
let mut r = BadReader::new(MemReader::new(Vec::from_slice(b"hello, world!")),
Vec::from_slice([BadBehavior(uint::MAX)]));
assert_eq!(r.push_at_least(1, 5, &mut buf).unwrap_err().kind, NoProgress);
let mut r = MemReader::new(Vec::from_slice(bytes!("hello, world!")));
let mut r = MemReader::new(Vec::from_slice(b"hello, world!"));
assert_eq!(r.push_at_least(5, 1, &mut buf).unwrap_err().kind, InvalidInput);
}
}

View File

@ -52,7 +52,7 @@ impl PipeStream {
///
/// fn main() {
/// let mut pipe = PipeStream::open(libc::STDERR_FILENO);
/// pipe.write(bytes!("Hello, stderr!"));
/// pipe.write(b"Hello, stderr!");
/// }
/// ```
pub fn open(fd: libc::c_int) -> IoResult<PipeStream> {

View File

@ -22,7 +22,7 @@ about the stream or terminal to which it is attached.
use std::io;
let mut out = io::stdout();
out.write(bytes!("Hello, world!"));
out.write(b"Hello, world!");
```
*/

View File

@ -463,7 +463,7 @@ pub mod builtin {
/// # Example
///
/// ```
/// let rust = bytes!("r", 'u', "st", 255);
/// let rust = b"rust\xFF";
/// assert_eq!(rust[1], 'u' as u8);
/// assert_eq!(rust[4], 255);
/// ```

View File

@ -219,7 +219,7 @@ pub trait GenericPath: Clone + GenericPathUnsafe {
let dot = '.' as u8;
match name.rposition_elem(&dot) {
None | Some(0) => name,
Some(1) if name == bytes!("..") => name,
Some(1) if name == b".." => name,
Some(pos) => name.slice_to(pos)
}
})
@ -242,7 +242,7 @@ pub trait GenericPath: Clone + GenericPathUnsafe {
let dot = '.' as u8;
match name.rposition_elem(&dot) {
None | Some(0) => None,
Some(1) if name == bytes!("..") => None,
Some(1) if name == b".." => None,
Some(pos) => Some(name.slice_from(pos+1))
}
}

View File

@ -142,7 +142,7 @@ impl GenericPathUnsafe for Path {
unsafe fn set_filename_unchecked<T: BytesContainer>(&mut self, filename: T) {
let filename = filename.container_as_bytes();
match self.sepidx {
None if bytes!("..") == self.repr.as_slice() => {
None if b".." == self.repr.as_slice() => {
let mut v = Vec::with_capacity(3 + filename.len());
v.push_all(dot_dot_static);
v.push(SEP_BYTE);
@ -153,7 +153,7 @@ impl GenericPathUnsafe for Path {
None => {
self.repr = Path::normalize(filename);
}
Some(idx) if self.repr.slice_from(idx+1) == bytes!("..") => {
Some(idx) if self.repr.slice_from(idx+1) == b".." => {
let mut v = Vec::with_capacity(self.repr.len() + 1 + filename.len());
v.push_all(self.repr.as_slice());
v.push(SEP_BYTE);
@ -202,20 +202,20 @@ impl GenericPath for Path {
fn dirname<'a>(&'a self) -> &'a [u8] {
match self.sepidx {
None if bytes!("..") == self.repr.as_slice() => self.repr.as_slice(),
None if b".." == self.repr.as_slice() => self.repr.as_slice(),
None => dot_static,
Some(0) => self.repr.slice_to(1),
Some(idx) if self.repr.slice_from(idx+1) == bytes!("..") => self.repr.as_slice(),
Some(idx) if self.repr.slice_from(idx+1) == b".." => self.repr.as_slice(),
Some(idx) => self.repr.slice_to(idx)
}
}
fn filename<'a>(&'a self) -> Option<&'a [u8]> {
match self.sepidx {
None if bytes!(".") == self.repr.as_slice() ||
bytes!("..") == self.repr.as_slice() => None,
None if b"." == self.repr.as_slice() ||
b".." == self.repr.as_slice() => None,
None => Some(self.repr.as_slice()),
Some(idx) if self.repr.slice_from(idx+1) == bytes!("..") => None,
Some(idx) if self.repr.slice_from(idx+1) == b".." => None,
Some(0) if self.repr.slice_from(1).is_empty() => None,
Some(idx) => Some(self.repr.slice_from(idx+1))
}
@ -223,13 +223,13 @@ impl GenericPath for Path {
fn pop(&mut self) -> bool {
match self.sepidx {
None if bytes!(".") == self.repr.as_slice() => false,
None if b"." == self.repr.as_slice() => false,
None => {
self.repr = vec!['.' as u8];
self.sepidx = None;
true
}
Some(0) if bytes!("/") == self.repr.as_slice() => false,
Some(0) if b"/" == self.repr.as_slice() => false,
Some(idx) => {
if idx == 0 {
self.repr.truncate(idx+1);
@ -261,19 +261,19 @@ impl GenericPath for Path {
} else {
let mut ita = self.components();
let mut itb = other.components();
if bytes!(".") == self.repr.as_slice() {
if b"." == self.repr.as_slice() {
return match itb.next() {
None => true,
Some(b) => b != bytes!("..")
Some(b) => b != b".."
};
}
loop {
match (ita.next(), itb.next()) {
(None, _) => break,
(Some(a), Some(b)) if a == b => { continue },
(Some(a), _) if a == bytes!("..") => {
(Some(a), _) if a == b".." => {
// if ita contains only .. components, it's an ancestor
return ita.all(|x| x == bytes!(".."));
return ita.all(|x| x == b"..");
}
_ => return false
}
@ -303,8 +303,8 @@ impl GenericPath for Path {
}
(None, _) => comps.push(dot_dot_static),
(Some(a), Some(b)) if comps.is_empty() && a == b => (),
(Some(a), Some(b)) if b == bytes!(".") => comps.push(a),
(Some(_), Some(b)) if b == bytes!("..") => return None,
(Some(a), Some(b)) if b == b"." => comps.push(a),
(Some(_), Some(b)) if b == b".." => return None,
(Some(a), Some(_)) => {
comps.push(dot_dot_static);
for _ in itb {
@ -425,8 +425,8 @@ fn normalize_helper<'a>(v: &'a [u8], is_abs: bool) -> Option<Vec<&'a [u8]>> {
let mut changed = false;
for comp in v.split(is_sep_byte) {
if comp.is_empty() { changed = true }
else if comp == bytes!(".") { changed = true }
else if comp == bytes!("..") {
else if comp == b"." { changed = true }
else if comp == b".." {
if is_abs && comps.is_empty() { changed = true }
else if comps.len() == n_up { comps.push(dot_dot_static); n_up += 1 }
else { comps.pop().unwrap(); changed = true }
@ -434,7 +434,7 @@ fn normalize_helper<'a>(v: &'a [u8], is_abs: bool) -> Option<Vec<&'a [u8]>> {
}
if changed {
if comps.is_empty() && !is_abs {
if v == bytes!(".") {
if v == b"." {
return None;
}
comps.push(dot_static);
@ -445,8 +445,8 @@ fn normalize_helper<'a>(v: &'a [u8], is_abs: bool) -> Option<Vec<&'a [u8]>> {
}
}
static dot_static: &'static [u8] = bytes!(".");
static dot_dot_static: &'static [u8] = bytes!("..");
static dot_static: &'static [u8] = b".";
static dot_dot_static: &'static [u8] = b"..";
#[cfg(test)]
mod tests {
@ -470,24 +470,15 @@ mod tests {
)
)
macro_rules! b(
($($arg:expr),+) => (
{
static the_bytes: &'static [u8] = bytes!($($arg),+);
the_bytes
}
)
)
#[test]
fn test_paths() {
let empty: &[u8] = [];
t!(v: Path::new(empty), b!("."));
t!(v: Path::new(b!("/")), b!("/"));
t!(v: Path::new(b!("a/b/c")), b!("a/b/c"));
t!(v: Path::new(b!("a/b/c", 0xff)), b!("a/b/c", 0xff));
t!(v: Path::new(b!(0xff, "/../foo", 0x80)), b!("foo", 0x80));
let p = Path::new(b!("a/b/c", 0xff));
t!(v: Path::new(empty), b".");
t!(v: Path::new(b"/"), b"/");
t!(v: Path::new(b"a/b/c"), b"a/b/c");
t!(v: Path::new(b"a/b/c\xFF"), b"a/b/c\xFF");
t!(v: Path::new(b"\xFF/../foo\x80"), b"foo\x80");
let p = Path::new(b"a/b/c\xFF");
assert!(p.as_str() == None);
t!(s: Path::new(""), ".");
@ -513,18 +504,18 @@ mod tests {
t!(s: Path::new("foo/../../.."), "../..");
t!(s: Path::new("foo/../../bar"), "../bar");
assert_eq!(Path::new(b!("foo/bar")).into_vec().as_slice(), b!("foo/bar"));
assert_eq!(Path::new(b!("/foo/../../bar")).into_vec().as_slice(),
b!("/bar"));
assert_eq!(Path::new(b"foo/bar").into_vec().as_slice(), b"foo/bar");
assert_eq!(Path::new(b"/foo/../../bar").into_vec().as_slice(),
b"/bar");
let p = Path::new(b!("foo/bar", 0x80));
let p = Path::new(b"foo/bar\x80");
assert!(p.as_str() == None);
}
#[test]
fn test_opt_paths() {
assert!(Path::new_opt(b!("foo/bar", 0)) == None);
t!(v: Path::new_opt(b!("foo/bar")).unwrap(), b!("foo/bar"));
assert!(Path::new_opt(b"foo/bar\0") == None);
t!(v: Path::new_opt(b"foo/bar").unwrap(), b"foo/bar");
assert!(Path::new_opt("foo/bar\0") == None);
t!(s: Path::new_opt("foo/bar").unwrap(), "foo/bar");
}
@ -533,17 +524,17 @@ mod tests {
fn test_null_byte() {
use task;
let result = task::try(proc() {
Path::new(b!("foo/bar", 0))
Path::new(b"foo/bar\0")
});
assert!(result.is_err());
let result = task::try(proc() {
Path::new("test").set_filename(b!("f", 0, "o"))
Path::new("test").set_filename(b"f\0o")
});
assert!(result.is_err());
let result = task::try(proc() {
Path::new("test").push(b!("f", 0, "o"));
Path::new("test").push(b"f\0o");
});
assert!(result.is_err());
}
@ -559,11 +550,11 @@ mod tests {
)
)
t!("foo", display, "foo");
t!(b!("foo", 0x80), display, "foo\uFFFD");
t!(b!("foo", 0xff, "bar"), display, "foo\uFFFDbar");
t!(b!("foo", 0xff, "/bar"), filename_display, "bar");
t!(b!("foo/", 0xff, "bar"), filename_display, "\uFFFDbar");
t!(b!("/"), filename_display, "");
t!(b"foo\x80", display, "foo\uFFFD");
t!(b"foo\xFFbar", display, "foo\uFFFDbar");
t!(b"foo\xFF/bar", filename_display, "bar");
t!(b"foo/\xFFbar", filename_display, "\uFFFDbar");
t!(b"/", filename_display, "");
macro_rules! t(
($path:expr, $exp:expr) => (
@ -583,11 +574,11 @@ mod tests {
)
t!("foo", "foo");
t!(b!("foo", 0x80), "foo\uFFFD");
t!(b!("foo", 0xff, "bar"), "foo\uFFFDbar");
t!(b!("foo", 0xff, "/bar"), "bar", filename);
t!(b!("foo/", 0xff, "bar"), "\uFFFDbar", filename);
t!(b!("/"), "", filename);
t!(b"foo\x80", "foo\uFFFD");
t!(b"foo\xFFbar", "foo\uFFFDbar");
t!(b"foo\xFF/bar", "bar", filename);
t!(b"foo/\xFFbar", "\uFFFDbar", filename);
t!(b"/", "", filename);
}
#[test]
@ -604,13 +595,13 @@ mod tests {
)
)
t!(b!("foo"), "foo", "foo");
t!(b!("foo/bar"), "foo/bar", "bar");
t!(b!("/"), "/", "");
t!(b!("foo", 0xff), "foo\uFFFD", "foo\uFFFD");
t!(b!("foo", 0xff, "/bar"), "foo\uFFFD/bar", "bar");
t!(b!("foo/", 0xff, "bar"), "foo/\uFFFDbar", "\uFFFDbar");
t!(b!(0xff, "foo/bar", 0xff), "\uFFFDfoo/bar\uFFFD", "bar\uFFFD");
t!(b"foo", "foo", "foo");
t!(b"foo/bar", "foo/bar", "bar");
t!(b"/", "/", "");
t!(b"foo\xFF", "foo\uFFFD", "foo\uFFFD");
t!(b"foo\xFF/bar", "foo\uFFFD/bar", "bar");
t!(b"foo/\xFFbar", "foo/\uFFFDbar", "\uFFFDbar");
t!(b"\xFFfoo/bar\xFF", "\uFFFDfoo/bar\uFFFD", "bar\uFFFD");
}
#[test]
@ -638,9 +629,9 @@ mod tests {
);
)
t!(v: b!("a/b/c"), filename, Some(b!("c")));
t!(v: b!("a/b/c", 0xff), filename, Some(b!("c", 0xff)));
t!(v: b!("a/b", 0xff, "/c"), filename, Some(b!("c")));
t!(v: b"a/b/c", filename, Some(b"c"));
t!(v: b"a/b/c\xFF", filename, Some(b"c\xFF"));
t!(v: b"a/b\xFF/c", filename, Some(b"c"));
t!(s: "a/b/c", filename, Some("c"), opt);
t!(s: "/a/b/c", filename, Some("c"), opt);
t!(s: "a", filename, Some("a"), opt);
@ -650,9 +641,9 @@ mod tests {
t!(s: "..", filename, None, opt);
t!(s: "../..", filename, None, opt);
t!(v: b!("a/b/c"), dirname, b!("a/b"));
t!(v: b!("a/b/c", 0xff), dirname, b!("a/b"));
t!(v: b!("a/b", 0xff, "/c"), dirname, b!("a/b", 0xff));
t!(v: b"a/b/c", dirname, b"a/b");
t!(v: b"a/b/c\xFF", dirname, b"a/b");
t!(v: b"a/b\xFF/c", dirname, b"a/b\xFF");
t!(s: "a/b/c", dirname, "a/b");
t!(s: "/a/b/c", dirname, "/a/b");
t!(s: "a", dirname, ".");
@ -662,9 +653,9 @@ mod tests {
t!(s: "..", dirname, "..");
t!(s: "../..", dirname, "../..");
t!(v: b!("hi/there.txt"), filestem, Some(b!("there")));
t!(v: b!("hi/there", 0x80, ".txt"), filestem, Some(b!("there", 0x80)));
t!(v: b!("hi/there.t", 0x80, "xt"), filestem, Some(b!("there")));
t!(v: b"hi/there.txt", filestem, Some(b"there"));
t!(v: b"hi/there\x80.txt", filestem, Some(b"there\x80"));
t!(v: b"hi/there.t\x80xt", filestem, Some(b"there"));
t!(s: "hi/there.txt", filestem, Some("there"), opt);
t!(s: "hi/there", filestem, Some("there"), opt);
t!(s: "there.txt", filestem, Some("there"), opt);
@ -678,11 +669,11 @@ mod tests {
t!(s: "..", filestem, None, opt);
t!(s: "../..", filestem, None, opt);
t!(v: b!("hi/there.txt"), extension, Some(b!("txt")));
t!(v: b!("hi/there", 0x80, ".txt"), extension, Some(b!("txt")));
t!(v: b!("hi/there.t", 0x80, "xt"), extension, Some(b!("t", 0x80, "xt")));
t!(v: b!("hi/there"), extension, None);
t!(v: b!("hi/there", 0x80), extension, None);
t!(v: b"hi/there.txt", extension, Some(b"txt"));
t!(v: b"hi/there\x80.txt", extension, Some(b"txt"));
t!(v: b"hi/there.t\x80xt", extension, Some(b"t\x80xt"));
t!(v: b"hi/there", extension, None);
t!(v: b"hi/there\x80", extension, None);
t!(s: "hi/there.txt", extension, Some("txt"), opt);
t!(s: "hi/there", extension, None, opt);
t!(s: "there.txt", extension, Some("txt"), opt);
@ -762,9 +753,9 @@ mod tests {
t!(s: "a/b/c", ["d", "/e"], "/e");
t!(s: "a/b/c", ["d", "/e", "f"], "/e/f");
t!(s: "a/b/c", ["d".to_string(), "e".to_string()], "a/b/c/d/e");
t!(v: b!("a/b/c"), [b!("d"), b!("e")], b!("a/b/c/d/e"));
t!(v: b!("a/b/c"), [b!("d"), b!("/e"), b!("f")], b!("/e/f"));
t!(v: b!("a/b/c"), [Vec::from_slice(b!("d")), Vec::from_slice(b!("e"))], b!("a/b/c/d/e"));
t!(v: b"a/b/c", [b"d", b"e"], b"a/b/c/d/e");
t!(v: b"a/b/c", [b"d", b"/e", b"f"], b"/e/f");
t!(v: b"a/b/c", [Vec::from_slice(b"d"), Vec::from_slice(b"e")], b"a/b/c/d/e");
}
#[test]
@ -778,25 +769,25 @@ mod tests {
assert!(result == $right);
}
);
(v: [$($path:expr),+], [$($left:expr),+], $right:expr) => (
(b: $path:expr, $left:expr, $right:expr) => (
{
let mut p = Path::new(b!($($path),+));
let mut p = Path::new($path);
let result = p.pop();
assert!(p.as_vec() == b!($($left),+));
assert!(p.as_vec() == $left);
assert!(result == $right);
}
)
)
t!(v: ["a/b/c"], ["a/b"], true);
t!(v: ["a"], ["."], true);
t!(v: ["."], ["."], false);
t!(v: ["/a"], ["/"], true);
t!(v: ["/"], ["/"], false);
t!(v: ["a/b/c", 0x80], ["a/b"], true);
t!(v: ["a/b", 0x80, "/c"], ["a/b", 0x80], true);
t!(v: [0xff], ["."], true);
t!(v: ["/", 0xff], ["/"], true);
t!(b: b"a/b/c", b"a/b", true);
t!(b: b"a", b".", true);
t!(b: b".", b".", false);
t!(b: b"/a", b"/", true);
t!(b: b"/", b"/", false);
t!(b: b"a/b/c\x80", b"a/b", true);
t!(b: b"a/b\x80/c", b"a/b\x80", true);
t!(b: b"\xFF", b".", true);
t!(b: b"/\xFF", b"/", true);
t!(s: "a/b/c", "a/b", true);
t!(s: "a", ".", true);
t!(s: ".", ".", false);
@ -806,15 +797,15 @@ mod tests {
#[test]
fn test_root_path() {
assert!(Path::new(b!("a/b/c")).root_path() == None);
assert!(Path::new(b!("/a/b/c")).root_path() == Some(Path::new("/")));
assert!(Path::new(b"a/b/c").root_path() == None);
assert!(Path::new(b"/a/b/c").root_path() == Some(Path::new("/")));
}
#[test]
fn test_join() {
t!(v: Path::new(b!("a/b/c")).join(b!("..")), b!("a/b"));
t!(v: Path::new(b!("/a/b/c")).join(b!("d")), b!("/a/b/c/d"));
t!(v: Path::new(b!("a/", 0x80, "/c")).join(b!(0xff)), b!("a/", 0x80, "/c/", 0xff));
t!(v: Path::new(b"a/b/c").join(b".."), b"a/b");
t!(v: Path::new(b"/a/b/c").join(b"d"), b"/a/b/c/d");
t!(v: Path::new(b"a/\x80/c").join(b"\xFF"), b"a/\x80/c/\xFF");
t!(s: Path::new("a/b/c").join(".."), "a/b");
t!(s: Path::new("/a/b/c").join("d"), "/a/b/c/d");
t!(s: Path::new("a/b").join("c/d"), "a/b/c/d");
@ -867,18 +858,18 @@ mod tests {
t!(s: "a/b/c", ["..", "d"], "a/b/d");
t!(s: "a/b/c", ["d", "/e", "f"], "/e/f");
t!(s: "a/b/c", ["d".to_string(), "e".to_string()], "a/b/c/d/e");
t!(v: b!("a/b/c"), [b!("d"), b!("e")], b!("a/b/c/d/e"));
t!(v: b!("a/b/c"), [Vec::from_slice(b!("d")), Vec::from_slice(b!("e"))], b!("a/b/c/d/e"));
t!(v: b"a/b/c", [b"d", b"e"], b"a/b/c/d/e");
t!(v: b"a/b/c", [Vec::from_slice(b"d"), Vec::from_slice(b"e")], b"a/b/c/d/e");
}
#[test]
fn test_with_helpers() {
let empty: &[u8] = [];
t!(v: Path::new(b!("a/b/c")).with_filename(b!("d")), b!("a/b/d"));
t!(v: Path::new(b!("a/b/c", 0xff)).with_filename(b!(0x80)), b!("a/b/", 0x80));
t!(v: Path::new(b!("/", 0xff, "/foo")).with_filename(b!(0xcd)),
b!("/", 0xff, "/", 0xcd));
t!(v: Path::new(b"a/b/c").with_filename(b"d"), b"a/b/d");
t!(v: Path::new(b"a/b/c\xFF").with_filename(b"\x80"), b"a/b/\x80");
t!(v: Path::new(b"/\xFF/foo").with_filename(b"\xCD"),
b"/\xFF/\xCD");
t!(s: Path::new("a/b/c").with_filename("d"), "a/b/d");
t!(s: Path::new(".").with_filename("foo"), "foo");
t!(s: Path::new("/a/b/c").with_filename("d"), "/a/b/d");
@ -899,13 +890,13 @@ mod tests {
t!(s: Path::new("..").with_filename(""), "..");
t!(s: Path::new("../..").with_filename(""), "../..");
t!(v: Path::new(b!("hi/there", 0x80, ".txt")).with_extension(b!("exe")),
b!("hi/there", 0x80, ".exe"));
t!(v: Path::new(b!("hi/there.txt", 0x80)).with_extension(b!(0xff)),
b!("hi/there.", 0xff));
t!(v: Path::new(b!("hi/there", 0x80)).with_extension(b!(0xff)),
b!("hi/there", 0x80, ".", 0xff));
t!(v: Path::new(b!("hi/there.", 0xff)).with_extension(empty), b!("hi/there"));
t!(v: Path::new(b"hi/there\x80.txt").with_extension(b"exe"),
b"hi/there\x80.exe");
t!(v: Path::new(b"hi/there.txt\x80").with_extension(b"\xFF"),
b"hi/there.\xFF");
t!(v: Path::new(b"hi/there\x80").with_extension(b"\xFF"),
b"hi/there\x80.\xFF");
t!(v: Path::new(b"hi/there.\xFF").with_extension(empty), b"hi/there");
t!(s: Path::new("hi/there.txt").with_extension("exe"), "hi/there.exe");
t!(s: Path::new("hi/there.txt").with_extension(""), "hi/there");
t!(s: Path::new("hi/there.txt").with_extension("."), "hi/there..");
@ -947,17 +938,17 @@ mod tests {
)
)
t!(v: b!("a/b/c"), set_filename, with_filename, b!("d"));
t!(v: b!("/"), set_filename, with_filename, b!("foo"));
t!(v: b!(0x80), set_filename, with_filename, b!(0xff));
t!(v: b"a/b/c", set_filename, with_filename, b"d");
t!(v: b"/", set_filename, with_filename, b"foo");
t!(v: b"\x80", set_filename, with_filename, b"\xFF");
t!(s: "a/b/c", set_filename, with_filename, "d");
t!(s: "/", set_filename, with_filename, "foo");
t!(s: ".", set_filename, with_filename, "foo");
t!(s: "a/b", set_filename, with_filename, "");
t!(s: "a", set_filename, with_filename, "");
t!(v: b!("hi/there.txt"), set_extension, with_extension, b!("exe"));
t!(v: b!("hi/there.t", 0x80, "xt"), set_extension, with_extension, b!("exe", 0xff));
t!(v: b"hi/there.txt", set_extension, with_extension, b"exe");
t!(v: b"hi/there.t\x80xt", set_extension, with_extension, b"exe\xFF");
t!(s: "hi/there.txt", set_extension, with_extension, "exe");
t!(s: "hi/there.", set_extension, with_extension, "txt");
t!(s: "hi/there", set_extension, with_extension, "txt");
@ -1001,10 +992,10 @@ mod tests {
)
)
t!(v: Path::new(b!("a/b/c")), Some(b!("c")), b!("a/b"), Some(b!("c")), None);
t!(v: Path::new(b!("a/b/", 0xff)), Some(b!(0xff)), b!("a/b"), Some(b!(0xff)), None);
t!(v: Path::new(b!("hi/there.", 0xff)), Some(b!("there.", 0xff)), b!("hi"),
Some(b!("there")), Some(b!(0xff)));
t!(v: Path::new(b"a/b/c"), Some(b"c"), b"a/b", Some(b"c"), None);
t!(v: Path::new(b"a/b/\xFF"), Some(b"\xFF"), b"a/b", Some(b"\xFF"), None);
t!(v: Path::new(b"hi/there.\xFF"), Some(b"there.\xFF"), b"hi",
Some(b"there"), Some(b"\xFF"));
t!(s: Path::new("a/b/c"), Some("c"), Some("a/b"), Some("c"), None);
t!(s: Path::new("."), None, Some("."), None, None);
t!(s: Path::new("/"), None, Some("/"), None, None);
@ -1018,16 +1009,16 @@ mod tests {
t!(s: Path::new("hi/.there"), Some(".there"), Some("hi"), Some(".there"), None);
t!(s: Path::new("hi/..there"), Some("..there"), Some("hi"),
Some("."), Some("there"));
t!(s: Path::new(b!("a/b/", 0xff)), None, Some("a/b"), None, None);
t!(s: Path::new(b!("a/b/", 0xff, ".txt")), None, Some("a/b"), None, Some("txt"));
t!(s: Path::new(b!("a/b/c.", 0x80)), None, Some("a/b"), Some("c"), None);
t!(s: Path::new(b!(0xff, "/b")), Some("b"), None, Some("b"), None);
t!(s: Path::new(b"a/b/\xFF"), None, Some("a/b"), None, None);
t!(s: Path::new(b"a/b/\xFF.txt"), None, Some("a/b"), None, Some("txt"));
t!(s: Path::new(b"a/b/c.\x80"), None, Some("a/b"), Some("c"), None);
t!(s: Path::new(b"\xFF/b"), Some("b"), None, Some("b"), None);
}
#[test]
fn test_dir_path() {
t!(v: Path::new(b!("hi/there", 0x80)).dir_path(), b!("hi"));
t!(v: Path::new(b!("hi", 0xff, "/there")).dir_path(), b!("hi", 0xff));
t!(v: Path::new(b"hi/there\x80").dir_path(), b"hi");
t!(v: Path::new(b"hi\xFF/there").dir_path(), b"hi\xFF");
t!(s: Path::new("hi/there").dir_path(), "hi");
t!(s: Path::new("hi").dir_path(), ".");
t!(s: Path::new("/hi").dir_path(), "/");
@ -1125,9 +1116,9 @@ mod tests {
t!(s: "/a/b/c", "d/e/f", false);
t!(s: "a/b/c", "a/b", false);
t!(s: "a/b/c", "b", false);
t!(v: b!("a/b/c"), b!("b/c"), true);
t!(v: b!("a/b/", 0xff), b!(0xff), true);
t!(v: b!("a/b/", 0xff), b!("b/", 0xff), true);
t!(v: b"a/b/c", b"b/c", true);
t!(v: b"a/b/\xFF", b"\xFF", true);
t!(v: b"a/b/\xFF", b"b/\xFF", true);
}
#[test]
@ -1192,11 +1183,11 @@ mod tests {
comps, exps);
}
);
(v: [$($arg:expr),+], [$([$($exp:expr),*]),*]) => (
(b: $arg:expr, [$($exp:expr),*]) => (
{
let path = Path::new(b!($($arg),+));
let path = Path::new($arg);
let comps = path.components().collect::<Vec<&[u8]>>();
let exp: &[&[u8]] = [$(b!($($exp),*)),*];
let exp: &[&[u8]] = [$($exp),*];
assert_eq!(comps.as_slice(), exp);
let comps = path.components().rev().collect::<Vec<&[u8]>>();
let exp = exp.iter().rev().map(|&x|x).collect::<Vec<&[u8]>>();
@ -1205,9 +1196,9 @@ mod tests {
)
)
t!(v: ["a/b/c"], [["a"], ["b"], ["c"]]);
t!(v: ["/", 0xff, "/a/", 0x80], [[0xff], ["a"], [0x80]]);
t!(v: ["../../foo", 0xcd, "bar"], [[".."], [".."], ["foo", 0xcd, "bar"]]);
t!(b: b"a/b/c", [b"a", b"b", b"c"]);
t!(b: b"/\xFF/a/\x80", [b"\xFF", b"a", b"\x80"]);
t!(b: b"../../foo\xCDbar", [b"..", b"..", b"foo\xCDbar"]);
t!(s: "a/b/c", ["a", "b", "c"]);
t!(s: "a/b/d", ["a", "b", "d"]);
t!(s: "a/b/cd", ["a", "b", "cd"]);
@ -1224,9 +1215,9 @@ mod tests {
#[test]
fn test_str_components() {
macro_rules! t(
(v: [$($arg:expr),+], $exp:expr) => (
(b: $arg:expr, $exp:expr) => (
{
let path = Path::new(b!($($arg),+));
let path = Path::new($arg);
let comps = path.str_components().collect::<Vec<Option<&str>>>();
let exp: &[Option<&str>] = $exp;
assert_eq!(comps.as_slice(), exp);
@ -1237,9 +1228,9 @@ mod tests {
)
)
t!(v: ["a/b/c"], [Some("a"), Some("b"), Some("c")]);
t!(v: ["/", 0xff, "/a/", 0x80], [None, Some("a"), None]);
t!(v: ["../../foo", 0xcd, "bar"], [Some(".."), Some(".."), None]);
t!(b: b"a/b/c", [Some("a"), Some("b"), Some("c")]);
t!(b: b"/\xFF/a/\x80", [None, Some("a"), None]);
t!(b: b"../../foo\xCDbar", [Some(".."), Some(".."), None]);
// str_components is a wrapper around components, so no need to do
// the full set of tests
}

View File

@ -1123,15 +1123,6 @@ mod tests {
)
)
macro_rules! b(
($($arg:expr),+) => (
{
static the_bytes: &'static [u8] = bytes!($($arg),+);
the_bytes
}
)
)
#[test]
fn test_parse_prefix() {
macro_rules! t(
@ -1196,9 +1187,9 @@ mod tests {
#[test]
fn test_paths() {
let empty: &[u8] = [];
t!(v: Path::new(empty), b!("."));
t!(v: Path::new(b!("\\")), b!("\\"));
t!(v: Path::new(b!("a\\b\\c")), b!("a\\b\\c"));
t!(v: Path::new(empty), b".");
t!(v: Path::new(b"\\"), b"\\");
t!(v: Path::new(b"a\\b\\c"), b"a\\b\\c");
t!(s: Path::new(""), ".");
t!(s: Path::new("\\"), "\\");
@ -1230,8 +1221,8 @@ mod tests {
t!(s: Path::new("foo\\..\\..\\.."), "..\\..");
t!(s: Path::new("foo\\..\\..\\bar"), "..\\bar");
assert_eq!(Path::new(b!("foo\\bar")).into_vec().as_slice(), b!("foo\\bar"));
assert_eq!(Path::new(b!("\\foo\\..\\..\\bar")).into_vec().as_slice(), b!("\\bar"));
assert_eq!(Path::new(b"foo\\bar").into_vec().as_slice(), b"foo\\bar");
assert_eq!(Path::new(b"\\foo\\..\\..\\bar").into_vec().as_slice(), b"\\bar");
t!(s: Path::new("\\\\a"), "\\a");
t!(s: Path::new("\\\\a\\"), "\\a");
@ -1284,9 +1275,9 @@ mod tests {
#[test]
fn test_opt_paths() {
assert!(Path::new_opt(b!("foo\\bar", 0)) == None);
assert!(Path::new_opt(b!("foo\\bar", 0x80)) == None);
t!(v: Path::new_opt(b!("foo\\bar")).unwrap(), b!("foo\\bar"));
assert!(Path::new_opt(b"foo\\bar\0") == None);
assert!(Path::new_opt(b"foo\\bar\x80") == None);
t!(v: Path::new_opt(b"foo\\bar").unwrap(), b"foo\\bar");
assert!(Path::new_opt("foo\\bar\0") == None);
t!(s: Path::new_opt("foo\\bar").unwrap(), "foo\\bar");
}
@ -1295,17 +1286,17 @@ mod tests {
fn test_null_byte() {
use task;
let result = task::try(proc() {
Path::new(b!("foo/bar", 0))
Path::new(b"foo/bar\0")
});
assert!(result.is_err());
let result = task::try(proc() {
Path::new("test").set_filename(b!("f", 0, "o"))
Path::new("test").set_filename(b"f\0o")
});
assert!(result.is_err());
let result = task::try(proc() {
Path::new("test").push(b!("f", 0, "o"));
Path::new("test").push(b"f\0o");
});
assert!(result.is_err());
}
@ -1313,20 +1304,20 @@ mod tests {
#[test]
#[should_fail]
fn test_not_utf8_fail() {
Path::new(b!("hello", 0x80, ".txt"));
Path::new(b"hello\x80.txt");
}
#[test]
fn test_display_str() {
let path = Path::new("foo");
assert_eq!(path.display().to_str(), "foo".to_string());
let path = Path::new(b!("\\"));
let path = Path::new(b"\\");
assert_eq!(path.filename_display().to_str(), "".to_string());
let path = Path::new("foo");
let mo = path.display().as_maybe_owned();
assert_eq!(mo.as_slice(), "foo");
let path = Path::new(b!("\\"));
let path = Path::new(b"\\");
let mo = path.filename_display().as_maybe_owned();
assert_eq!(mo.as_slice(), "");
}
@ -1377,7 +1368,7 @@ mod tests {
)
)
t!(v: b!("a\\b\\c"), filename, Some(b!("c")));
t!(v: b"a\\b\\c", filename, Some(b"c"));
t!(s: "a\\b\\c", filename_str, "c");
t!(s: "\\a\\b\\c", filename_str, "c");
t!(s: "a", filename_str, "a");
@ -1410,7 +1401,7 @@ mod tests {
t!(s: "\\\\.\\", filename_str, None, opt);
t!(s: "\\\\?\\a\\b\\", filename_str, "b");
t!(v: b!("a\\b\\c"), dirname, b!("a\\b"));
t!(v: b"a\\b\\c", dirname, b"a\\b");
t!(s: "a\\b\\c", dirname_str, "a\\b");
t!(s: "\\a\\b\\c", dirname_str, "\\a\\b");
t!(s: "a", dirname_str, ".");
@ -1441,7 +1432,7 @@ mod tests {
t!(s: "\\\\.\\foo", dirname_str, "\\\\.\\foo");
t!(s: "\\\\?\\a\\b\\", dirname_str, "\\\\?\\a");
t!(v: b!("hi\\there.txt"), filestem, Some(b!("there")));
t!(v: b"hi\\there.txt", filestem, Some(b"there"));
t!(s: "hi\\there.txt", filestem_str, "there");
t!(s: "hi\\there", filestem_str, "there");
t!(s: "there.txt", filestem_str, "there");
@ -1456,8 +1447,8 @@ mod tests {
t!(s: "..\\..", filestem_str, None, opt);
// filestem is based on filename, so we don't need the full set of prefix tests
t!(v: b!("hi\\there.txt"), extension, Some(b!("txt")));
t!(v: b!("hi\\there"), extension, None);
t!(v: b"hi\\there.txt", extension, Some(b"txt"));
t!(v: b"hi\\there", extension, None);
t!(s: "hi\\there.txt", extension_str, Some("txt"), opt);
t!(s: "hi\\there", extension_str, None, opt);
t!(s: "there.txt", extension_str, Some("txt"), opt);
@ -1583,10 +1574,10 @@ mod tests {
t!(s: "a\\b\\c", ["d", "\\e"], "\\e");
t!(s: "a\\b\\c", ["d", "\\e", "f"], "\\e\\f");
t!(s: "a\\b\\c", ["d".to_string(), "e".to_string()], "a\\b\\c\\d\\e");
t!(v: b!("a\\b\\c"), [b!("d"), b!("e")], b!("a\\b\\c\\d\\e"));
t!(v: b!("a\\b\\c"), [b!("d"), b!("\\e"), b!("f")], b!("\\e\\f"));
t!(v: b!("a\\b\\c"), [Vec::from_slice(b!("d")), Vec::from_slice(b!("e"))],
b!("a\\b\\c\\d\\e"));
t!(v: b"a\\b\\c", [b"d", b"e"], b"a\\b\\c\\d\\e");
t!(v: b"a\\b\\c", [b"d", b"\\e", b"f"], b"\\e\\f");
t!(v: b"a\\b\\c", [Vec::from_slice(b"d"), Vec::from_slice(b"e")],
b"a\\b\\c\\d\\e");
}
#[test]
@ -1604,11 +1595,11 @@ mod tests {
assert!(result == $right);
}
);
(v: [$($path:expr),+], [$($left:expr),+], $right:expr) => (
(b: $path:expr, $left:expr, $right:expr) => (
{
let mut p = Path::new(b!($($path),+));
let mut p = Path::new($path);
let result = p.pop();
assert_eq!(p.as_vec(), b!($($left),+));
assert_eq!(p.as_vec(), $left);
assert!(result == $right);
}
)
@ -1619,11 +1610,11 @@ mod tests {
t!(s: ".", ".", false);
t!(s: "\\a", "\\", true);
t!(s: "\\", "\\", false);
t!(v: ["a\\b\\c"], ["a\\b"], true);
t!(v: ["a"], ["."], true);
t!(v: ["."], ["."], false);
t!(v: ["\\a"], ["\\"], true);
t!(v: ["\\"], ["\\"], false);
t!(b: b"a\\b\\c", b"a\\b", true);
t!(b: b"a", b".", true);
t!(b: b".", b".", false);
t!(b: b"\\a", b"\\", true);
t!(b: b"\\", b"\\", false);
t!(s: "C:\\a\\b", "C:\\a", true);
t!(s: "C:\\a", "C:\\", true);
@ -1672,8 +1663,8 @@ mod tests {
t!(s: Path::new("a\\b").join("\\c\\d"), "\\c\\d");
t!(s: Path::new(".").join("a\\b"), "a\\b");
t!(s: Path::new("\\").join("a\\b"), "\\a\\b");
t!(v: Path::new(b!("a\\b\\c")).join(b!("..")), b!("a\\b"));
t!(v: Path::new(b!("\\a\\b\\c")).join(b!("d")), b!("\\a\\b\\c\\d"));
t!(v: Path::new(b"a\\b\\c").join(b".."), b"a\\b");
t!(v: Path::new(b"\\a\\b\\c").join(b"d"), b"\\a\\b\\c\\d");
// full join testing is covered under test_push_path, so no need for
// the full set of prefix tests
}
@ -1724,9 +1715,9 @@ mod tests {
t!(s: "a\\b\\c", ["..", "d"], "a\\b\\d");
t!(s: "a\\b\\c", ["d", "\\e", "f"], "\\e\\f");
t!(s: "a\\b\\c", ["d".to_string(), "e".to_string()], "a\\b\\c\\d\\e");
t!(v: b!("a\\b\\c"), [b!("d"), b!("e")], b!("a\\b\\c\\d\\e"));
t!(v: b!("a\\b\\c"), [Vec::from_slice(b!("d")), Vec::from_slice(b!("e"))],
b!("a\\b\\c\\d\\e"));
t!(v: b"a\\b\\c", [b"d", b"e"], b"a\\b\\c\\d\\e");
t!(v: b"a\\b\\c", [Vec::from_slice(b"d"), Vec::from_slice(b"e")],
b"a\\b\\c\\d\\e");
}
#[test]
@ -1839,15 +1830,15 @@ mod tests {
)
)
t!(v: b!("a\\b\\c"), set_filename, with_filename, b!("d"));
t!(v: b!("\\"), set_filename, with_filename, b!("foo"));
t!(v: b"a\\b\\c", set_filename, with_filename, b"d");
t!(v: b"\\", set_filename, with_filename, b"foo");
t!(s: "a\\b\\c", set_filename, with_filename, "d");
t!(s: "\\", set_filename, with_filename, "foo");
t!(s: ".", set_filename, with_filename, "foo");
t!(s: "a\\b", set_filename, with_filename, "");
t!(s: "a", set_filename, with_filename, "");
t!(v: b!("hi\\there.txt"), set_extension, with_extension, b!("exe"));
t!(v: b"hi\\there.txt", set_extension, with_extension, b"exe");
t!(s: "hi\\there.txt", set_extension, with_extension, "exe");
t!(s: "hi\\there.", set_extension, with_extension, "txt");
t!(s: "hi\\there", set_extension, with_extension, "txt");
@ -1894,7 +1885,7 @@ mod tests {
)
)
t!(v: Path::new(b!("a\\b\\c")), Some(b!("c")), b!("a\\b"), Some(b!("c")), None);
t!(v: Path::new(b"a\\b\\c"), Some(b"c"), b"a\\b", Some(b"c"), None);
t!(s: Path::new("a\\b\\c"), Some("c"), Some("a\\b"), Some("c"), None);
t!(s: Path::new("."), None, Some("."), None, None);
t!(s: Path::new("\\"), None, Some("\\"), None, None);
@ -2250,21 +2241,9 @@ mod tests {
assert_eq!(comps, exp);
}
);
(v: [$($arg:expr),+], $exp:expr) => (
{
let path = Path::new(b!($($arg),+));
let comps = path.str_components().map(|x|x.unwrap()).collect::<Vec<&str>>();
let exp: &[&str] = $exp;
assert_eq!(comps.as_slice(), exp);
let comps = path.str_components().rev().map(|x|x.unwrap())
.collect::<Vec<&str>>();
let exp = exp.iter().rev().map(|&x|x).collect::<Vec<&str>>();
assert_eq!(comps, exp);
}
)
)
t!(v: ["a\\b\\c"], ["a", "b", "c"]);
t!(s: b"a\\b\\c", ["a", "b", "c"]);
t!(s: "a\\b\\c", ["a", "b", "c"]);
t!(s: "a\\b\\d", ["a", "b", "d"]);
t!(s: "a\\b\\cd", ["a", "b", "cd"]);
@ -2320,8 +2299,8 @@ mod tests {
)
)
t!(s: "a\\b\\c", [b!("a"), b!("b"), b!("c")]);
t!(s: ".", [b!(".")]);
t!(s: "a\\b\\c", [b"a", b"b", b"c"]);
t!(s: ".", [b"."]);
// since this is really a wrapper around str_components, those tests suffice
}

View File

@ -19,6 +19,14 @@ use ext::build::AstBuilder;
pub fn expand_syntax_ext(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
-> Box<base::MacResult> {
cx.span_warn(sp, "`bytes!` is deprecated, use `b\"foo\"` literals instead");
cx.parse_sess.span_diagnostic.span_note(sp,
"see http://doc.rust-lang.org/rust.html#byte-and-byte-string-literals \
for documentation");
cx.parse_sess.span_diagnostic.span_note(sp,
"see https://github.com/rust-lang/rust/blob/master/src/etc/2014-06-rewrite-bytes-macros.py \
for a automated migration");
// Gather all argument expressions
let exprs = match get_exprs_from_tts(cx, sp, tts) {
None => return DummyResult::expr(sp),

View File

@ -106,7 +106,7 @@ pub fn expand(cap: &[u8], params: &[Param], vars: &mut Variables)
*dst = (*src).clone();
}
for c in cap.iter().map(|&x| x) {
for &c in cap.iter() {
let cur = c as char;
let mut old_state = state;
match state {
@ -575,25 +575,25 @@ mod test {
#[test]
fn test_basic_setabf() {
let s = bytes!("\\E[48;5;%p1%dm");
let s = b"\\E[48;5;%p1%dm";
assert_eq!(expand(s, [Number(1)], &mut Variables::new()).unwrap(),
bytes!("\\E[48;5;1m").iter().map(|x| *x).collect());
"\\E[48;5;1m".bytes().collect());
}
#[test]
fn test_multiple_int_constants() {
assert_eq!(expand(bytes!("%{1}%{2}%d%d"), [], &mut Variables::new()).unwrap(),
bytes!("21").iter().map(|x| *x).collect());
assert_eq!(expand(b"%{1}%{2}%d%d", [], &mut Variables::new()).unwrap(),
"21".bytes().collect());
}
#[test]
fn test_op_i() {
let mut vars = Variables::new();
assert_eq!(expand(bytes!("%p1%d%p2%d%p3%d%i%p1%d%p2%d%p3%d"),
assert_eq!(expand(b"%p1%d%p2%d%p3%d%i%p1%d%p2%d%p3%d",
[Number(1),Number(2),Number(3)], &mut vars),
Ok(bytes!("123233").iter().map(|x| *x).collect()));
assert_eq!(expand(bytes!("%p1%d%p2%d%i%p1%d%p2%d"), [], &mut vars),
Ok(bytes!("0011").iter().map(|x| *x).collect()));
Ok("123233".bytes().collect()));
assert_eq!(expand(b"%p1%d%p2%d%i%p1%d%p2%d", [], &mut vars),
Ok("0011".bytes().collect()));
}
#[test]
@ -610,7 +610,7 @@ mod test {
} else {
Number(97)
};
let res = expand(bytes!("%p1").iter().map(|x| *x).collect::<Vec<_>>()
let res = expand("%p1".bytes().collect::<Vec<_>>()
.append(cap.as_bytes()).as_slice(),
[p],
vars);
@ -622,13 +622,13 @@ mod test {
let res = expand(cap.as_bytes(), [], vars);
assert!(res.is_err(),
"Binop {} succeeded incorrectly with 0 stack entries", *cap);
let res = expand(bytes!("%{1}").iter().map(|x| *x).collect::<Vec<_>>()
let res = expand("%{1}".bytes().collect::<Vec<_>>()
.append(cap.as_bytes()).as_slice(),
[],
vars);
assert!(res.is_err(),
"Binop {} succeeded incorrectly with 1 stack entry", *cap);
let res = expand(bytes!("%{1}%{2}").iter().map(|x| *x).collect::<Vec<_>>()
let res = expand("%{1}%{2}".bytes().collect::<Vec<_>>()
.append(cap.as_bytes()).as_slice(),
[],
vars);
@ -639,7 +639,7 @@ mod test {
#[test]
fn test_push_bad_param() {
assert!(expand(bytes!("%pa"), [], &mut Variables::new()).is_err());
assert!(expand(b"%pa", [], &mut Variables::new()).is_err());
}
#[test]
@ -664,39 +664,37 @@ mod test {
#[test]
fn test_conditionals() {
let mut vars = Variables::new();
let s = bytes!("\\E[%?%p1%{8}%<%t3%p1%d%e%p1%{16}%<%t9%p1%{8}%-%d%e38;5;%p1%d%;m");
let s = b"\\E[%?%p1%{8}%<%t3%p1%d%e%p1%{16}%<%t9%p1%{8}%-%d%e38;5;%p1%d%;m";
let res = expand(s, [Number(1)], &mut vars);
assert!(res.is_ok(), res.unwrap_err());
assert_eq!(res.unwrap(),
bytes!("\\E[31m").iter().map(|x| *x).collect());
"\\E[31m".bytes().collect());
let res = expand(s, [Number(8)], &mut vars);
assert!(res.is_ok(), res.unwrap_err());
assert_eq!(res.unwrap(),
bytes!("\\E[90m").iter().map(|x| *x).collect());
"\\E[90m".bytes().collect());
let res = expand(s, [Number(42)], &mut vars);
assert!(res.is_ok(), res.unwrap_err());
assert_eq!(res.unwrap(),
bytes!("\\E[38;5;42m").iter().map(|x| *x).collect());
"\\E[38;5;42m".bytes().collect());
}
#[test]
fn test_format() {
let mut varstruct = Variables::new();
let vars = &mut varstruct;
assert_eq!(expand(bytes!("%p1%s%p2%2s%p3%2s%p4%.2s"),
assert_eq!(expand(b"%p1%s%p2%2s%p3%2s%p4%.2s",
[String("foo".to_string()),
String("foo".to_string()),
String("f".to_string()),
String("foo".to_string())], vars),
Ok(bytes!("foofoo ffo").iter().map(|x| *x).collect()));
assert_eq!(expand(bytes!("%p1%:-4.2s"), [String("foo".to_string())], vars),
Ok(bytes!("fo ").iter().map(|x| *x).collect()));
Ok("foofoo ffo".bytes().collect()));
assert_eq!(expand(b"%p1%:-4.2s", [String("foo".to_string())], vars),
Ok("fo ".bytes().collect()));
assert_eq!(expand(bytes!("%p1%d%p1%.3d%p1%5d%p1%:+d"), [Number(1)], vars),
Ok(bytes!("1001 1+1").iter().map(|x| *x).collect()));
assert_eq!(expand(bytes!("%p1%o%p1%#o%p2%6.4x%p2%#6.4X"), [Number(15), Number(27)], vars),
Ok(bytes!("17017 001b0X001B").iter()
.map(|x| *x)
.collect()));
assert_eq!(expand(b"%p1%d%p1%.3d%p1%5d%p1%:+d", [Number(1)], vars),
Ok("1001 1+1".bytes().collect()));
assert_eq!(expand(b"%p1%o%p1%#o%p2%6.4x%p2%#6.4X", [Number(15), Number(27)], vars),
Ok("17017 001b0X001B".bytes().collect()));
}
}

View File

@ -315,10 +315,10 @@ pub fn parse(file: &mut io::Reader, longnames: bool)
/// Create a dummy TermInfo struct for msys terminals
pub fn msys_terminfo() -> Box<TermInfo> {
let mut strings = HashMap::new();
strings.insert("sgr0".to_string(), Vec::from_slice(bytes!("\x1b[0m")));
strings.insert("bold".to_string(), Vec::from_slice(bytes!("\x1b[1m")));
strings.insert("setaf".to_string(), Vec::from_slice(bytes!("\x1b[3%p1%dm")));
strings.insert("setab".to_string(), Vec::from_slice(bytes!("\x1b[4%p1%dm")));
strings.insert("sgr0".to_string(), Vec::from_slice(b"\x1B[0m"));
strings.insert("bold".to_string(), Vec::from_slice(b"\x1B[1m"));
strings.insert("setaf".to_string(), Vec::from_slice(b"\x1B[3%p1%dm"));
strings.insert("setab".to_string(), Vec::from_slice(b"\x1B[4%p1%dm"));
box TermInfo {
names: vec!("cygwin".to_string()), // msys is a fork of an older cygwin version
bools: HashMap::new(),

View File

@ -1,3 +1,11 @@
S 2014-06-18 d6736a1
freebsd-x86_64 c1479bb3dc0ae3d8ba9193ff2caf92c805a95c51
linux-i386 bb1543b21235a51e81460b9419e112396ccf1d20
linux-x86_64 08df93f138bc6c9d083d28bb71384fcebf0380c1
macos-i386 d6c0039ad7cbd5959e69c980ecf822e5097bac2c
macos-x86_64 ee54924aa4103d35cf490da004d3cc4e48ca8fb0
winnt-i386 943c99971e82847abe272df58bb7656ac3b91430
S 2014-06-14 2c6caad
freebsd-x86_64 0152ba43f238014f0aede7c29f1c684c21077b0b
linux-i386 2eb1897c25abe0d5978ff03171ca943e92666046

View File

@ -22,7 +22,8 @@ enum CantDeriveThose {}
fn main() {
doesnt_exist!(); //~ ERROR
bytes!(invalid); //~ ERROR
bytes!(invalid); //~ ERROR non-literal in bytes!
//~^ WARN `bytes!` is deprecated
asm!(invalid); //~ ERROR

View File

@ -10,4 +10,5 @@
fn main() {
let vec = bytes!('λ'); //~ ERROR non-ascii char literal in bytes!
//~^ WARN `bytes!` is deprecated
}

View File

@ -10,4 +10,5 @@
fn main() {
let vec = bytes!(foo); //~ ERROR non-literal in bytes!
//~^ WARN `bytes!` is deprecated
}

View File

@ -10,4 +10,5 @@
fn main() {
let vec = bytes!(1024); //~ ERROR too large integer literal in bytes!
//~^ WARN `bytes!` is deprecated
}

View File

@ -10,4 +10,5 @@
fn main() {
let vec = bytes!(1024u8); //~ ERROR too large u8 literal in bytes!
//~^ WARN `bytes!` is deprecated
}

View File

@ -10,4 +10,5 @@
fn main() {
let vec = bytes!(-1024); //~ ERROR non-literal in bytes
//~^ WARN `bytes!` is deprecated
}

View File

@ -10,4 +10,5 @@
fn main() {
let vec = bytes!(-1024u8); //~ ERROR non-literal in bytes
//~^ WARN `bytes!` is deprecated
}

View File

@ -10,4 +10,5 @@
fn main() {
let vec = bytes!(45f64); //~ ERROR unsupported literal in bytes!
//~^ WARN `bytes!` is deprecated
}

View File

@ -12,5 +12,5 @@ use std::io;
pub fn main() {
let stdout = &mut io::stdout() as &mut io::Writer;
stdout.write(bytes!("Hello!"));
stdout.write(b"Hello!");
}

View File

@ -29,7 +29,7 @@ fn test_tempdir() {
let path = {
let p = TempDir::new_in(&Path::new("."), "foobar").unwrap();
let p = p.path();
assert!(p.as_vec().ends_with(bytes!("foobar")));
assert!(p.as_vec().ends_with(b"foobar"));
p.clone()
};
assert!(!path.exists());

View File

@ -26,7 +26,7 @@ impl Trait for Struct {
}
fn foo(mut a: Box<Writer>) {
a.write(bytes!("Hello\n"));
a.write(b"Hello\n");
}
pub fn main() {