Unstable is the conservative choice.
cc #22950.
};
// The value our Makefile configures valgrind to return on failure
- static VALGRIND_ERR: int = 100;
+ const VALGRIND_ERR: int = 100;
if proc_res.status.matches_exit_status(VALGRIND_ERR) {
fatal_proc_rec("run-fail test isn't valgrind-clean!", &proc_res);
}
fn check_correct_failure_status(proc_res: &ProcRes) {
// The value the rust runtime returns on failure
- static RUST_ERR: int = 101;
+ const RUST_ERR: int = 101;
if !proc_res.status.matches_exit_status(RUST_ERR) {
fatal_proc_rec(
&format!("failure produced the wrong error: {:?}",
use std::env;
/// Conversion table from triple OS name to Rust SYSNAME
-static OS_TABLE: &'static [(&'static str, &'static str)] = &[
+const OS_TABLE: &'static [(&'static str, &'static str)] = &[
("mingw32", "windows"),
("win32", "windows"),
("windows", "windows"),
numbers[0] is 2
```
-Each time, we can get a slithtly different output because the threads
-are not quaranteed to run in any set order. If you get the same order
-every time it is because each of these threads are very small and
-complete too fast for their indeterminate behavior to surface.
+Each time, we can get a slightly different output because the threads are not
+guaranteed to run in any set order. If you get the same order every time it is
+because each of these threads are very small and complete too fast for their
+indeterminate behavior to surface.
The important part here is that the Rust compiler was able to use ownership to
give us assurance _at compile time_ that we weren't doing something incorrect
* `staged_api` - Allows usage of stability markers and `#![staged_api]` in a crate
+* `static_assert` - The `#[static_assert]` functionality is experimental and
+ unstable. The attribute can be attached to a `static` of
+ type `bool` and the compiler will error if the `bool` is
+ `false` at compile time. This version of this functionality
+ is unintuitive and suboptimal.
+
* `start` - Allows use of the `#[start]` attribute, which changes the entry point
into a Rust program. This capabiilty, especially the signature for the
annotated function, is subject to change.
tell `random()` what to generate. In a similar fashion, both of these work:
```{rust,ignore}
-let input_num = "5".parse::<u32>(); // input_num: Option<u32>
-let input_num: Result<u32, _> = "5".parse(); // input_num: Result<u32, <u32 as FromStr>::Err>
+let input_num_option = "5".parse::<u32>().ok(); // input_num: Option<u32>
+let input_num_result: Result<u32, _> = "5".parse(); // input_num: Result<u32, <u32 as FromStr>::Err>
```
-Here we're converting the `Result` returned by `parse` to an `Option` by using
+Above, we're converting the `Result` returned by `parse` to an `Option` by using
the `ok` method as well. Anyway, with us now converting our input to a number,
our code looks like this:
```bash
$ cargo build
Compiling guessing_game v0.0.1 (file:///home/you/projects/guessing_game)
-src/main.rs:22:15: 22:24 error: mismatched types: expected `u32` but found `core::option::Option<u32>` (expected u32 but found enum core::option::Option)
-src/main.rs:22 match cmp(input_num, secret_number) {
+src/main.rs:21:15: 21:24 error: mismatched types: expected `u32`, found `core::result::Result<u32, core::num::ParseIntError>` (expected u32, found enum `core::result::Result`) [E0308]
+src/main.rs:21 match cmp(input_num, secret_number) {
^~~~~~~~~
error: aborting due to previous error
```
-Oh yeah! Our `input_num` has the type `Option<u32>`, rather than `u32`. We
-need to unwrap the Option. If you remember from before, `match` is a great way
+Oh yeah! Our `input_num` has the type `Result<u32, <some error>>`, rather than `u32`. We
+need to unwrap the Result. If you remember from before, `match` is a great way
to do that. Try this code:
```{rust,no_run}
let input_num: Result<u32, _> = input.parse();
let num = match input_num {
- Ok(num) => num,
+ Ok(n) => n,
Err(_) => {
println!("Please input a number!");
return;
}
```
-We use a `match` to either give us the `u32` inside of the `Option`, or else
+We use a `match` to either give us the `u32` inside of the `Result`, or else
print an error message and return. Let's give this a shot:
```bash
fn bsearch_range_table(c: char, r: &'static [(char,char)]) -> bool {
use core::cmp::Ordering::{Equal, Less, Greater};
use core::slice::SliceExt;
- r.binary_search(|&(lo,hi)| {
+ r.binary_search_by(|&(lo,hi)| {
if lo <= c && c <= hi { Equal }
else if hi < c { Less }
else { Greater }
- }).found().is_some()
+ }).is_ok()
}\n
""")
pub_string = ""
if is_pub:
pub_string = "pub "
- f.write(" %sstatic %s: %s = &[\n" % (pub_string, name, t_type))
+ f.write(" %sconst %s: %s = &[\n" % (pub_string, name, t_type))
data = ""
first = True
for dat in t_data:
def emit_regex_module(f, cats, w_data):
f.write("pub mod regex {\n")
regex_class = "&'static [(char, char)]"
- class_table = "&'static [(&'static str, &'static %s)]" % regex_class
+ class_table = "&'static [(&'static str, %s)]" % regex_class
emit_table(f, "UNICODE_CLASSES", cats, class_table,
- pfun=lambda x: "(\"%s\",&super::%s::%s_table)" % (x[0], x[1], x[0]))
+ pfun=lambda x: "(\"%s\",super::%s::%s_table)" % (x[0], x[1], x[0]))
- f.write(" pub static PERLD: &'static %s = &super::general_category::Nd_table;\n\n"
+ f.write(" pub const PERLD: %s = super::general_category::Nd_table;\n\n"
% regex_class)
- f.write(" pub static PERLS: &'static %s = &super::property::White_Space_table;\n\n"
+ f.write(" pub const PERLS: %s = super::property::White_Space_table;\n\n"
% regex_class)
emit_table(f, "PERLW", w_data, regex_class)
use core::slice::SliceExt;
use core::option::Option;
use core::option::Option::{Some, None};
- use core::slice;
+ use core::result::Result::{Ok, Err};
pub fn to_lower(c: char) -> char {
match bsearch_case_table(c, LuLl_table) {
}
fn bsearch_case_table(c: char, table: &'static [(char, char)]) -> Option<usize> {
- match table.binary_search(|&(key, _)| {
+ match table.binary_search_by(|&(key, _)| {
if c == key { Equal }
else if key < c { Less }
else { Greater }
}) {
- slice::BinarySearchResult::Found(i) => Some(i),
- slice::BinarySearchResult::NotFound(_) => None,
+ Ok(i) => Some(i),
+ Err(_) => None,
}
}
def emit_grapheme_module(f, grapheme_table, grapheme_cats):
f.write("""pub mod grapheme {
- use core::kinds::Copy;
use core::slice::SliceExt;
pub use self::GraphemeCat::*;
- use core::slice;
+ use core::result::Result::{Ok, Err};
#[allow(non_camel_case_types)]
#[derive(Clone, Copy)]
fn bsearch_range_value_table(c: char, r: &'static [(char, char, GraphemeCat)]) -> GraphemeCat {
use core::cmp::Ordering::{Equal, Less, Greater};
- match r.binary_search(|&(lo, hi, _)| {
+ match r.binary_search_by(|&(lo, hi, _)| {
if lo <= c && c <= hi { Equal }
else if hi < c { Less }
else { Greater }
}) {
- slice::BinarySearchResult::Found(idx) => {
+ Ok(idx) => {
let (_, _, cat) = r[idx];
cat
}
- slice::BinarySearchResult::NotFound(_) => GC_Any
+ Err(_) => GC_Any
}
}
f.write(" use core::option::Option;\n")
f.write(" use core::option::Option::{Some, None};\n")
f.write(" use core::slice::SliceExt;\n")
- f.write(" use core::slice;\n")
+ f.write(" use core::result::Result::{Ok, Err};\n")
f.write("""
fn bsearch_range_value_table(c: char, is_cjk: bool, r: &'static [(char, char, u8, u8)]) -> u8 {
use core::cmp::Ordering::{Equal, Less, Greater};
- match r.binary_search(|&(lo, hi, _, _)| {
+ match r.binary_search_by(|&(lo, hi, _, _)| {
if lo <= c && c <= hi { Equal }
else if hi < c { Less }
else { Greater }
}) {
- slice::BinarySearchResult::Found(idx) => {
+ Ok(idx) => {
let (_, _, r_ncjk, r_cjk) = r[idx];
if is_cjk { r_cjk } else { r_ncjk }
}
- slice::BinarySearchResult::NotFound(_) => 1
+ Err(_) => 1
}
}
""")
fn bsearch_range_value_table(c: char, r: &'static [(char, char, u8)]) -> u8 {
use core::cmp::Ordering::{Equal, Less, Greater};
use core::slice::SliceExt;
- use core::slice;
- match r.binary_search(|&(lo, hi, _)| {
+ use core::result::Result::{Ok, Err};
+ match r.binary_search_by(|&(lo, hi, _)| {
if lo <= c && c <= hi { Equal }
else if hi < c { Less }
else { Greater }
}) {
- slice::BinarySearchResult::Found(idx) => {
+ Ok(idx) => {
let (_, _, result) = r[idx];
result
}
- slice::BinarySearchResult::NotFound(_) => 0
+ Err(_) => 0
}
}\n
""")
unicode_version = re.search(pattern, readme.read()).groups()
rf.write("""
/// The version of [Unicode](http://www.unicode.org/)
-/// that the `UnicodeChar` and `UnicodeStrPrelude` traits are based on.
+/// that the unicode parts of `CharExt` and `UnicodeStrPrelude` traits are based on.
pub const UNICODE_VERSION: (u64, u64, u64) = (%s, %s, %s);
""" % unicode_version)
(canon_decomp, compat_decomp, gencats, combines,
impl<T> Arc<T> {
#[inline]
fn inner(&self) -> &ArcInner<T> {
- // This unsafety is ok because while this arc is alive we're guaranteed that the inner
- // pointer is valid. Furthermore, we know that the `ArcInner` structure itself is `Sync`
- // because the inner data is `Sync` as well, so we're ok loaning out an immutable pointer
- // to these contents.
+ // This unsafety is ok because while this arc is alive we're guaranteed
+ // that the inner pointer is valid. Furthermore, we know that the
+ // `ArcInner` structure itself is `Sync` because the inner data is
+ // `Sync` as well, so we're ok loaning out an immutable pointer to these
+ // contents.
unsafe { &**self._ptr }
}
}
/// ```
#[inline]
fn clone(&self) -> Arc<T> {
- // Using a relaxed ordering is alright here, as knowledge of the original reference
- // prevents other threads from erroneously deleting the object.
+ // Using a relaxed ordering is alright here, as knowledge of the
+ // original reference prevents other threads from erroneously deleting
+ // the object.
//
- // As explained in the [Boost documentation][1], Increasing the reference counter can
- // always be done with memory_order_relaxed: New references to an object can only be formed
- // from an existing reference, and passing an existing reference from one thread to another
- // must already provide any required synchronization.
+ // As explained in the [Boost documentation][1], Increasing the
+ // reference counter can always be done with memory_order_relaxed: New
+ // references to an object can only be formed from an existing
+ // reference, and passing an existing reference from one thread to
+ // another must already provide any required synchronization.
//
// [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
self.inner().strong.fetch_add(1, Relaxed);
//
// Note that we can technically avoid this branch with the expression
// `(nbits + u32::BITS - 1) / 32::BITS`, but if nbits is almost usize::MAX this will overflow.
- if bits % u32::BITS == 0 {
- bits / u32::BITS
+ if bits % u32::BITS as usize == 0 {
+ bits / u32::BITS as usize
} else {
- bits / u32::BITS + 1
+ bits / u32::BITS as usize + 1
}
}
/// Computes the bitmask for the final word of the vector
fn mask_for_bits(bits: usize) -> u32 {
// Note especially that a perfect multiple of u32::BITS should mask all 1s.
- !0u32 >> (u32::BITS - bits % u32::BITS) % u32::BITS
+ !0u32 >> (u32::BITS as usize - bits % u32::BITS as usize) % u32::BITS as usize
}
impl BitVec {
/// An operation might screw up the unused bits in the last block of the
/// `BitVec`. As per (3), it's assumed to be all 0s. This method fixes it up.
fn fix_last_block(&mut self) {
- let extra_bits = self.len() % u32::BITS;
+ let extra_bits = self.len() % u32::BITS as usize;
if extra_bits > 0 {
let mask = (1 << extra_bits) - 1;
let storage_len = self.storage.len();
/// false, false, true, false]));
/// ```
pub fn from_bytes(bytes: &[u8]) -> BitVec {
- let len = bytes.len().checked_mul(u8::BITS).expect("capacity overflow");
+ let len = bytes.len().checked_mul(u8::BITS as usize).expect("capacity overflow");
let mut bit_vec = BitVec::with_capacity(len);
let complete_words = bytes.len() / 4;
let extra_bytes = bytes.len() % 4;
if i >= self.nbits {
return None;
}
- let w = i / u32::BITS;
- let b = i % u32::BITS;
+ let w = i / u32::BITS as usize;
+ let b = i % u32::BITS as usize;
self.storage.get(w).map(|&block|
(block & (1 << b)) != 0
)
reason = "panic semantics are likely to change in the future")]
pub fn set(&mut self, i: usize, x: bool) {
assert!(i < self.nbits);
- let w = i / u32::BITS;
- let b = i % u32::BITS;
+ let w = i / u32::BITS as usize;
+ let b = i % u32::BITS as usize;
let flag = 1 << b;
let val = if x { self.storage[w] | flag }
else { self.storage[w] & !flag };
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn capacity(&self) -> usize {
- self.storage.capacity().checked_mul(u32::BITS).unwrap_or(usize::MAX)
+ self.storage.capacity().checked_mul(u32::BITS as usize).unwrap_or(usize::MAX)
}
/// Grows the `BitVec` in-place, adding `n` copies of `value` to the `BitVec`.
// Correct the old tail word, setting or clearing formerly unused bits
let old_last_word = blocks_for_bits(self.nbits) - 1;
- if self.nbits % u32::BITS > 0 {
+ if self.nbits % u32::BITS as usize > 0 {
let mask = mask_for_bits(self.nbits);
if value {
self.storage[old_last_word] |= !mask;
// (3)
self.set(i, false);
self.nbits = i;
- if self.nbits % u32::BITS == 0 {
+ if self.nbits % u32::BITS as usize == 0 {
// (2)
self.storage.pop();
}
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn push(&mut self, elem: bool) {
- if self.nbits % u32::BITS == 0 {
+ if self.nbits % u32::BITS as usize == 0 {
self.storage.push(0);
}
let insert_pos = self.nbits;
// Truncate
let trunc_len = cmp::max(old_len - n, 1);
bit_vec.storage.truncate(trunc_len);
- bit_vec.nbits = trunc_len * u32::BITS;
+ bit_vec.nbits = trunc_len * u32::BITS as usize;
}
/// Iterator over each u32 stored in the `BitSet`.
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn len(&self) -> usize {
- self.bit_vec.blocks().fold(0, |acc, n| acc + n.count_ones())
+ self.bit_vec.blocks().fold(0, |acc, n| acc + n.count_ones() as usize)
}
/// Returns whether there are no bits set in this set
fn next(&mut self) -> Option<usize> {
while self.next_idx < self.set.bit_vec.len() ||
self.next_idx < self.other.bit_vec.len() {
- let bit_idx = self.next_idx % u32::BITS;
+ let bit_idx = self.next_idx % u32::BITS as usize;
if bit_idx == 0 {
let s_bit_vec = &self.set.bit_vec;
let o_bit_vec = &self.other.bit_vec;
// Merging the two words is a bit of an awkward dance since
// one BitVec might be longer than the other
- let word_idx = self.next_idx / u32::BITS;
+ let word_idx = self.next_idx / u32::BITS as usize;
let w1 = if word_idx < s_bit_vec.storage.len() {
s_bit_vec.storage[word_idx]
} else { 0 };
#[test]
fn test_bit_vec_push_pop() {
- let mut s = BitVec::from_elem(5 * u32::BITS - 2, false);
- assert_eq!(s.len(), 5 * u32::BITS - 2);
- assert_eq!(s[5 * u32::BITS - 3], false);
+ let mut s = BitVec::from_elem(5 * u32::BITS as usize - 2, false);
+ assert_eq!(s.len(), 5 * u32::BITS as usize - 2);
+ assert_eq!(s[5 * u32::BITS as usize - 3], false);
s.push(true);
s.push(true);
- assert_eq!(s[5 * u32::BITS - 2], true);
- assert_eq!(s[5 * u32::BITS - 1], true);
+ assert_eq!(s[5 * u32::BITS as usize - 2], true);
+ assert_eq!(s[5 * u32::BITS as usize - 1], true);
// Here the internal vector will need to be extended
s.push(false);
- assert_eq!(s[5 * u32::BITS], false);
+ assert_eq!(s[5 * u32::BITS as usize], false);
s.push(false);
- assert_eq!(s[5 * u32::BITS + 1], false);
- assert_eq!(s.len(), 5 * u32::BITS + 2);
+ assert_eq!(s[5 * u32::BITS as usize + 1], false);
+ assert_eq!(s.len(), 5 * u32::BITS as usize + 2);
// Pop it all off
assert_eq!(s.pop(), Some(false));
assert_eq!(s.pop(), Some(false));
assert_eq!(s.pop(), Some(true));
assert_eq!(s.pop(), Some(true));
- assert_eq!(s.len(), 5 * u32::BITS - 2);
+ assert_eq!(s.len(), 5 * u32::BITS as usize - 2);
}
#[test]
fn test_bit_vec_truncate() {
- let mut s = BitVec::from_elem(5 * u32::BITS, true);
+ let mut s = BitVec::from_elem(5 * u32::BITS as usize, true);
- assert_eq!(s, BitVec::from_elem(5 * u32::BITS, true));
- assert_eq!(s.len(), 5 * u32::BITS);
- s.truncate(4 * u32::BITS);
- assert_eq!(s, BitVec::from_elem(4 * u32::BITS, true));
- assert_eq!(s.len(), 4 * u32::BITS);
+ assert_eq!(s, BitVec::from_elem(5 * u32::BITS as usize, true));
+ assert_eq!(s.len(), 5 * u32::BITS as usize);
+ s.truncate(4 * u32::BITS as usize);
+ assert_eq!(s, BitVec::from_elem(4 * u32::BITS as usize, true));
+ assert_eq!(s.len(), 4 * u32::BITS as usize);
// Truncating to a size > s.len() should be a noop
- s.truncate(5 * u32::BITS);
- assert_eq!(s, BitVec::from_elem(4 * u32::BITS, true));
- assert_eq!(s.len(), 4 * u32::BITS);
- s.truncate(3 * u32::BITS - 10);
- assert_eq!(s, BitVec::from_elem(3 * u32::BITS - 10, true));
- assert_eq!(s.len(), 3 * u32::BITS - 10);
+ s.truncate(5 * u32::BITS as usize);
+ assert_eq!(s, BitVec::from_elem(4 * u32::BITS as usize, true));
+ assert_eq!(s.len(), 4 * u32::BITS as usize);
+ s.truncate(3 * u32::BITS as usize - 10);
+ assert_eq!(s, BitVec::from_elem(3 * u32::BITS as usize - 10, true));
+ assert_eq!(s.len(), 3 * u32::BITS as usize - 10);
s.truncate(0);
assert_eq!(s, BitVec::from_elem(0, true));
assert_eq!(s.len(), 0);
#[test]
fn test_bit_vec_reserve() {
- let mut s = BitVec::from_elem(5 * u32::BITS, true);
+ let mut s = BitVec::from_elem(5 * u32::BITS as usize, true);
// Check capacity
- assert!(s.capacity() >= 5 * u32::BITS);
- s.reserve(2 * u32::BITS);
- assert!(s.capacity() >= 7 * u32::BITS);
- s.reserve(7 * u32::BITS);
- assert!(s.capacity() >= 12 * u32::BITS);
- s.reserve_exact(7 * u32::BITS);
- assert!(s.capacity() >= 12 * u32::BITS);
- s.reserve(7 * u32::BITS + 1);
- assert!(s.capacity() >= 12 * u32::BITS + 1);
+ assert!(s.capacity() >= 5 * u32::BITS as usize);
+ s.reserve(2 * u32::BITS as usize);
+ assert!(s.capacity() >= 7 * u32::BITS as usize);
+ s.reserve(7 * u32::BITS as usize);
+ assert!(s.capacity() >= 12 * u32::BITS as usize);
+ s.reserve_exact(7 * u32::BITS as usize);
+ assert!(s.capacity() >= 12 * u32::BITS as usize);
+ s.reserve(7 * u32::BITS as usize + 1);
+ assert!(s.capacity() >= 12 * u32::BITS as usize + 1);
// Check that length hasn't changed
- assert_eq!(s.len(), 5 * u32::BITS);
+ assert_eq!(s.len(), 5 * u32::BITS as usize);
s.push(true);
s.push(false);
s.push(true);
- assert_eq!(s[5 * u32::BITS - 1], true);
- assert_eq!(s[5 * u32::BITS - 0], true);
- assert_eq!(s[5 * u32::BITS + 1], false);
- assert_eq!(s[5 * u32::BITS + 2], true);
+ assert_eq!(s[5 * u32::BITS as usize - 1], true);
+ assert_eq!(s[5 * u32::BITS as usize - 0], true);
+ assert_eq!(s[5 * u32::BITS as usize + 1], false);
+ assert_eq!(s[5 * u32::BITS as usize + 2], true);
}
#[test]
use super::BitVec;
- static BENCH_BITS : usize = 1 << 14;
+ const BENCH_BITS : usize = 1 << 14;
fn rng() -> rand::IsaacRng {
let seed: &[_] = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
let mut bit_vec = 0 as usize;
b.iter(|| {
for _ in 0..100 {
- bit_vec |= 1 << ((r.next_u32() as usize) % u32::BITS);
+ bit_vec |= 1 << ((r.next_u32() as usize) % u32::BITS as usize);
}
black_box(&bit_vec);
});
#[bench]
fn bench_bit_set_small(b: &mut Bencher) {
let mut r = rng();
- let mut bit_vec = BitVec::from_elem(u32::BITS, false);
+ let mut bit_vec = BitVec::from_elem(u32::BITS as usize, false);
b.iter(|| {
for _ in 0..100 {
- bit_vec.set((r.next_u32() as usize) % u32::BITS, true);
+ bit_vec.set((r.next_u32() as usize) % u32::BITS as usize, true);
}
black_box(&bit_vec);
});
#[bench]
fn bench_bit_vec_small_iter(b: &mut Bencher) {
- let bit_vec = BitVec::from_elem(u32::BITS, false);
+ let bit_vec = BitVec::from_elem(u32::BITS as usize, false);
b.iter(|| {
let mut sum = 0;
for _ in 0..10 {
use super::{BitVec, BitSet};
- static BENCH_BITS : usize = 1 << 14;
+ const BENCH_BITS : usize = 1 << 14;
fn rng() -> rand::IsaacRng {
let seed: &[_] = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
let mut bit_vec = BitSet::new();
b.iter(|| {
for _ in 0..100 {
- bit_vec.insert((r.next_u32() as usize) % u32::BITS);
+ bit_vec.insert((r.next_u32() as usize) % u32::BITS as usize);
}
black_box(&bit_vec);
});
fn bit<E:CLike>(e: &E) -> usize {
use core::usize;
let value = e.to_usize();
- assert!(value < usize::BITS,
+ assert!(value < usize::BITS as usize,
"EnumSet only supports up to {} variants.", usize::BITS - 1);
1 << value
}
#[unstable(feature = "collections",
reason = "matches collection reform specification, waiting for dust to settle")]
pub fn len(&self) -> usize {
- self.bits.count_ones()
+ self.bits.count_ones() as usize
}
/// Returns true if the `EnumSet` is empty.
}
fn size_hint(&self) -> (usize, Option<usize>) {
- let exact = self.bits.count_ones();
+ let exact = self.bits.count_ones() as usize;
(exact, Some(exact))
}
}
//! * `o` - precedes the argument with a "0o"
//! * '0' - This is used to indicate for integer formats that the padding should
//! both be done with a `0` character as well as be sign-aware. A format
-//! like `{:08d}` would yield `00000001` for the integer `1`, while the
+//! like `{:08}` would yield `00000001` for the integer `1`, while the
//! same format would yield `-0000001` for the integer `-1`. Notice that
//! the negative version has one fewer zero than the positive version.
//!
fn merge_sort<T, F>(v: &mut [T], mut compare: F) where F: FnMut(&T, &T) -> Ordering {
// warning: this wildly uses unsafe.
- static BASE_INSERTION: usize = 32;
- static LARGE_INSERTION: usize = 16;
+ const BASE_INSERTION: usize = 32;
+ const LARGE_INSERTION: usize = 16;
// FIXME #12092: smaller insertion runs seems to make sorting
// vectors of large elements a little faster on some platforms,
/// ```
#[unstable(feature = "collections")]
#[deprecated(since = "1.0.0", reason = "use `split()` with a `&str`")]
+ #[allow(deprecated) /* for SplitStr */]
fn split_str<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitStr<'a, P> {
core_str::StrExt::split_str(&self[..], pat)
}
}
}
- static TAG_CONT_U8: u8 = 128u8;
- static REPLACEMENT: &'static [u8] = b"\xEF\xBF\xBD"; // U+FFFD in UTF-8
+ const TAG_CONT_U8: u8 = 128u8;
+ const REPLACEMENT: &'static [u8] = b"\xEF\xBF\xBD"; // U+FFFD in UTF-8
let total = v.len();
fn unsafe_get(xs: &[u8], i: usize) -> u8 {
unsafe { *xs.get_unchecked(i) }
__impl_slice_eq1! { Vec<A>, Vec<B> }
__impl_slice_eq2! { Vec<A>, &'b [B] }
__impl_slice_eq2! { Vec<A>, &'b mut [B] }
-__impl_slice_eq2! { CowVec<'a, A>, &'b [B], Clone }
-__impl_slice_eq2! { CowVec<'a, A>, &'b mut [B], Clone }
-__impl_slice_eq2! { CowVec<'a, A>, Vec<B>, Clone }
+__impl_slice_eq2! { Cow<'a, [A]>, &'b [B], Clone }
+__impl_slice_eq2! { Cow<'a, [A]>, &'b mut [B], Clone }
+__impl_slice_eq2! { Cow<'a, [A]>, Vec<B>, Clone }
macro_rules! array_impls {
($($N: expr)+) => {
__impl_slice_eq2! { Vec<A>, [B; $N] }
__impl_slice_eq2! { Vec<A>, &'b [B; $N] }
// __impl_slice_eq2! { Vec<A>, &'b mut [B; $N] }
- // __impl_slice_eq2! { CowVec<'a, A>, [B; $N], Clone }
- // __impl_slice_eq2! { CowVec<'a, A>, &'b [B; $N], Clone }
- // __impl_slice_eq2! { CowVec<'a, A>, &'b mut [B; $N], Clone }
+ // __impl_slice_eq2! { Cow<'a, [A]>, [B; $N], Clone }
+ // __impl_slice_eq2! { Cow<'a, [A]>, &'b [B; $N], Clone }
+ // __impl_slice_eq2! { Cow<'a, [A]>, &'b mut [B; $N], Clone }
)+
}
}
#[unstable(feature = "collections")]
pub use VecDeque as RingBuf;
-static INITIAL_CAPACITY: usize = 7; // 2^3 - 1
-static MINIMUM_CAPACITY: usize = 1; // 2 - 1
+const INITIAL_CAPACITY: usize = 7; // 2^3 - 1
+const MINIMUM_CAPACITY: usize = 1; // 2 - 1
/// `VecDeque` is a growable ring buffer, which can be used as a
/// double-ended queue efficiently.
v: UnsafeCell<int>,
}
+#[allow(deprecated)]
unsafe impl Sync for AtomicInt {}
#[unstable(feature = "core")]
v: UnsafeCell<uint>,
}
+#[allow(deprecated)]
unsafe impl Sync for AtomicUint {}
#[unstable(feature = "core")]
SignNeg
}
-static DIGIT_E_RADIX: u32 = ('e' as u32) - ('a' as u32) + 11;
+const DIGIT_E_RADIX: u32 = ('e' as u32) - ('a' as u32) + 11;
/// Converts a number to its string representation as a byte vector.
/// This is meant to be a common base implementation for all numeric string
deccum = deccum / radix_gen;
deccum = deccum.trunc();
- let c = char::from_digit(current_digit.to_int().unwrap() as u32, radix);
+ let c = char::from_digit(current_digit.to_isize().unwrap() as u32, radix);
buf[end] = c.unwrap() as u8;
end += 1;
// See note in first loop.
let current_digit = deccum.trunc().abs();
- let c = char::from_digit(current_digit.to_int().unwrap() as u32,
+ let c = char::from_digit(current_digit.to_isize().unwrap() as u32,
radix);
buf[end] = c.unwrap() as u8;
end += 1;
/// A hexadecimal (base 16) radix, formatted with upper-case characters
#[derive(Clone, PartialEq)]
-pub struct UpperHex;
+struct UpperHex;
macro_rules! radix {
($T:ident, $base:expr, $prefix:expr, $($x:pat => $conv:expr),+) => {
}
macro_rules! radix_fmt {
- ($T:ty as $U:ty, $fmt:ident, $S:expr) => {
+ ($T:ty as $U:ty, $fmt:ident) => {
#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Debug for RadixFmt<$T, Radix> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
}
}
-macro_rules! show {
- ($T:ident with $S:expr) => {
+macro_rules! debug {
+ ($T:ident) => {
#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Debug for $T {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
}
macro_rules! integer {
($Int:ident, $Uint:ident) => {
- integer! { $Int, $Uint, stringify!($Int), stringify!($Uint) }
- };
- ($Int:ident, $Uint:ident, $SI:expr, $SU:expr) => {
int_base! { Display for $Int as $Int -> Decimal }
int_base! { Binary for $Int as $Uint -> Binary }
int_base! { Octal for $Int as $Uint -> Octal }
int_base! { LowerHex for $Int as $Uint -> LowerHex }
int_base! { UpperHex for $Int as $Uint -> UpperHex }
- radix_fmt! { $Int as $Int, fmt_int, $SI }
- show! { $Int with $SI }
+ radix_fmt! { $Int as $Int, fmt_int }
+ debug! { $Int }
int_base! { Display for $Uint as $Uint -> Decimal }
int_base! { Binary for $Uint as $Uint -> Binary }
int_base! { Octal for $Uint as $Uint -> Octal }
int_base! { LowerHex for $Uint as $Uint -> LowerHex }
int_base! { UpperHex for $Uint as $Uint -> UpperHex }
- radix_fmt! { $Uint as $Uint, fmt_int, $SU }
- show! { $Uint with $SU }
+ radix_fmt! { $Uint as $Uint, fmt_int }
+ debug! { $Uint }
}
}
-integer! { isize, usize, "i", "u" }
+integer! { isize, usize }
integer! { i8, u8 }
integer! { i16, u16 }
integer! { i32, u32 }
}
fn hash_slice<H: Hasher>(data: &[$ty], state: &mut H) {
- let newlen = data.len() * ::$ty::BYTES;
+ let newlen = data.len() * ::$ty::BYTES as usize;
let ptr = data.as_ptr() as *const u8;
state.write(unsafe { slice::from_raw_parts(ptr, newlen) })
}
Some(a) => {
let sz = self.stop.to_i64().map(|b| b.checked_sub(a));
match sz {
- Some(Some(bound)) => bound.to_uint(),
+ Some(Some(bound)) => bound.to_usize(),
_ => None,
}
},
Some(a) => {
let sz = self.stop.to_u64().map(|b| b.checked_sub(a));
match sz {
- Some(Some(bound)) => bound.to_uint(),
+ Some(Some(bound)) => bound.to_usize(),
_ => None
}
},
if self.start >= self.end {
(0, Some(0))
} else {
- let length = (self.end - self.start).to_uint();
+ let length = (self.end - self.start).to_usize();
(length.unwrap_or(0), length)
}
}
//! distribution.
//!
//! * `rust_begin_unwind` - This function takes three arguments, a
-//! `fmt::Arguments`, a `&str`, and a `uint`. These three arguments dictate
+//! `fmt::Arguments`, a `&str`, and a `usize`. These three arguments dictate
//! the panic message, the file at which panic was invoked, and the line.
//! It is up to consumers of this core library to define this panic
//! function; it is only required to never return.
#[macro_use]
mod uint_macros;
-#[path = "num/int.rs"] pub mod int;
#[path = "num/isize.rs"] pub mod isize;
#[path = "num/i8.rs"] pub mod i8;
#[path = "num/i16.rs"] pub mod i16;
#[path = "num/i32.rs"] pub mod i32;
#[path = "num/i64.rs"] pub mod i64;
-#[path = "num/uint.rs"] pub mod uint;
#[path = "num/usize.rs"] pub mod usize;
#[path = "num/u8.rs"] pub mod u8;
#[path = "num/u16.rs"] pub mod u16;
use option::Option;
#[unstable(feature = "core", reason = "pending integer conventions")]
-pub const RADIX: uint = 2;
+pub const RADIX: u32 = 2;
#[unstable(feature = "core", reason = "pending integer conventions")]
-pub const MANTISSA_DIGITS: uint = 24;
+pub const MANTISSA_DIGITS: u32 = 24;
#[unstable(feature = "core", reason = "pending integer conventions")]
-pub const DIGITS: uint = 6;
+pub const DIGITS: u32 = 6;
#[stable(feature = "rust1", since = "1.0.0")]
pub const EPSILON: f32 = 1.19209290e-07_f32;
pub const MAX: f32 = 3.40282347e+38_f32;
#[unstable(feature = "core", reason = "pending integer conventions")]
-pub const MIN_EXP: int = -125;
+pub const MIN_EXP: i32 = -125;
#[unstable(feature = "core", reason = "pending integer conventions")]
-pub const MAX_EXP: int = 128;
+pub const MAX_EXP: i32 = 128;
#[unstable(feature = "core", reason = "pending integer conventions")]
-pub const MIN_10_EXP: int = -37;
+pub const MIN_10_EXP: i32 = -37;
#[unstable(feature = "core", reason = "pending integer conventions")]
-pub const MAX_10_EXP: int = 38;
+pub const MAX_10_EXP: i32 = 38;
#[stable(feature = "rust1", since = "1.0.0")]
pub const NAN: f32 = 0.0_f32/0.0_f32;
#[inline]
#[unstable(feature = "core")]
#[deprecated(since = "1.0.0")]
- fn mantissa_digits(_: Option<f32>) -> uint { MANTISSA_DIGITS }
+ fn mantissa_digits(_: Option<f32>) -> uint { MANTISSA_DIGITS as uint }
#[inline]
#[unstable(feature = "core")]
#[deprecated(since = "1.0.0")]
- fn digits(_: Option<f32>) -> uint { DIGITS }
+ fn digits(_: Option<f32>) -> uint { DIGITS as uint }
#[inline]
#[unstable(feature = "core")]
#[inline]
#[unstable(feature = "core")]
#[deprecated(since = "1.0.0")]
- fn min_exp(_: Option<f32>) -> int { MIN_EXP }
+ fn min_exp(_: Option<f32>) -> int { MIN_EXP as int }
#[inline]
#[unstable(feature = "core")]
#[deprecated(since = "1.0.0")]
- fn max_exp(_: Option<f32>) -> int { MAX_EXP }
+ fn max_exp(_: Option<f32>) -> int { MAX_EXP as int }
#[inline]
#[unstable(feature = "core")]
#[deprecated(since = "1.0.0")]
- fn min_10_exp(_: Option<f32>) -> int { MIN_10_EXP }
+ fn min_10_exp(_: Option<f32>) -> int { MIN_10_EXP as int }
#[inline]
#[unstable(feature = "core")]
#[deprecated(since = "1.0.0")]
- fn max_10_exp(_: Option<f32>) -> int { MAX_10_EXP }
+ fn max_10_exp(_: Option<f32>) -> int { MAX_10_EXP as int }
#[inline]
#[unstable(feature = "core")]
// members of `Bounded` and `Float`.
#[unstable(feature = "core", reason = "pending integer conventions")]
-pub const RADIX: uint = 2;
+pub const RADIX: u32 = 2;
-pub const MANTISSA_DIGITS: uint = 53;
+pub const MANTISSA_DIGITS: u32 = 53;
#[unstable(feature = "core", reason = "pending integer conventions")]
-pub const DIGITS: uint = 15;
+pub const DIGITS: u32 = 15;
#[stable(feature = "rust1", since = "1.0.0")]
pub const EPSILON: f64 = 2.2204460492503131e-16_f64;
pub const MAX: f64 = 1.7976931348623157e+308_f64;
#[unstable(feature = "core", reason = "pending integer conventions")]
-pub const MIN_EXP: int = -1021;
+pub const MIN_EXP: i32 = -1021;
#[unstable(feature = "core", reason = "pending integer conventions")]
-pub const MAX_EXP: int = 1024;
+pub const MAX_EXP: i32 = 1024;
#[unstable(feature = "core", reason = "pending integer conventions")]
-pub const MIN_10_EXP: int = -307;
+pub const MIN_10_EXP: i32 = -307;
#[unstable(feature = "core", reason = "pending integer conventions")]
-pub const MAX_10_EXP: int = 308;
+pub const MAX_10_EXP: i32 = 308;
#[stable(feature = "rust1", since = "1.0.0")]
pub const NAN: f64 = 0.0_f64/0.0_f64;
#[inline]
#[unstable(feature = "core")]
#[deprecated(since = "1.0.0")]
- fn mantissa_digits(_: Option<f64>) -> uint { MANTISSA_DIGITS }
+ fn mantissa_digits(_: Option<f64>) -> uint { MANTISSA_DIGITS as uint }
#[inline]
#[unstable(feature = "core")]
#[deprecated(since = "1.0.0")]
- fn digits(_: Option<f64>) -> uint { DIGITS }
+ fn digits(_: Option<f64>) -> uint { DIGITS as uint }
#[inline]
#[unstable(feature = "core")]
#[inline]
#[unstable(feature = "core")]
#[deprecated(since = "1.0.0")]
- fn min_exp(_: Option<f64>) -> int { MIN_EXP }
+ fn min_exp(_: Option<f64>) -> int { MIN_EXP as int }
#[inline]
#[unstable(feature = "core")]
#[deprecated(since = "1.0.0")]
- fn max_exp(_: Option<f64>) -> int { MAX_EXP }
+ fn max_exp(_: Option<f64>) -> int { MAX_EXP as int }
#[inline]
#[unstable(feature = "core")]
#[deprecated(since = "1.0.0")]
- fn min_10_exp(_: Option<f64>) -> int { MIN_10_EXP }
+ fn min_10_exp(_: Option<f64>) -> int { MIN_10_EXP as int }
#[inline]
#[unstable(feature = "core")]
#[deprecated(since = "1.0.0")]
- fn max_10_exp(_: Option<f64>) -> int { MAX_10_EXP }
+ fn max_10_exp(_: Option<f64>) -> int { MAX_10_EXP as int }
#[inline]
#[unstable(feature = "core")]
+++ /dev/null
-// Copyright 2012-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.
-
-//! Deprecated: replaced by `isize`.
-//!
-//! The rollout of the new type will gradually take place over the
-//! alpha cycle along with the development of clearer conventions
-//! around integer types.
-
-#![unstable(feature = "core")]
-#![deprecated(since = "1.0.0", reason = "replaced by isize")]
-
-#[cfg(target_pointer_width = "32")] int_module! { int, 32 }
-#[cfg(target_pointer_width = "64")] int_module! { int, 64 }
// FIXME(#11621): Should be deprecated once CTFE is implemented in favour of
// calling the `mem::size_of` function.
#[unstable(feature = "core")]
-pub const BITS : uint = $bits;
+pub const BITS : u32 = $bits;
// FIXME(#11621): Should be deprecated once CTFE is implemented in favour of
// calling the `mem::size_of` function.
#[unstable(feature = "core")]
-pub const BYTES : uint = ($bits / 8);
+pub const BYTES : u32 = ($bits / 8);
// FIXME(#11621): Should be deprecated once CTFE is implemented in favour of
// calling the `Bounded::min_value` function.
/// ```
#[unstable(feature = "core",
reason = "pending integer conventions")]
- fn count_ones(self) -> uint;
+ fn count_ones(self) -> u32;
/// Returns the number of zeros in the binary representation of `self`.
///
#[unstable(feature = "core",
reason = "pending integer conventions")]
#[inline]
- fn count_zeros(self) -> uint {
+ fn count_zeros(self) -> u32 {
(!self).count_ones()
}
/// ```
#[unstable(feature = "core",
reason = "pending integer conventions")]
- fn leading_zeros(self) -> uint;
+ fn leading_zeros(self) -> u32;
/// Returns the number of trailing zeros in the binary representation
/// of `self`.
/// ```
#[unstable(feature = "core",
reason = "pending integer conventions")]
- fn trailing_zeros(self) -> uint;
+ fn trailing_zeros(self) -> u32;
/// Shifts the bits to the left by a specified amount amount, `n`, wrapping
/// the truncated bits to the end of the resulting integer.
/// ```
#[unstable(feature = "core",
reason = "pending integer conventions")]
- fn rotate_left(self, n: uint) -> Self;
+ fn rotate_left(self, n: u32) -> Self;
/// Shifts the bits to the right by a specified amount amount, `n`, wrapping
/// the truncated bits to the beginning of the resulting integer.
/// ```
#[unstable(feature = "core",
reason = "pending integer conventions")]
- fn rotate_right(self, n: uint) -> Self;
+ fn rotate_right(self, n: u32) -> Self;
/// Reverses the byte order of the integer.
///
fn max_value() -> $T { -1 }
#[inline]
- fn count_ones(self) -> uint { unsafe { $ctpop(self as $ActualT) as uint } }
+ fn count_ones(self) -> u32 { unsafe { $ctpop(self as $ActualT) as u32 } }
#[inline]
- fn leading_zeros(self) -> uint { unsafe { $ctlz(self as $ActualT) as uint } }
+ fn leading_zeros(self) -> u32 { unsafe { $ctlz(self as $ActualT) as u32 } }
#[inline]
- fn trailing_zeros(self) -> uint { unsafe { $cttz(self as $ActualT) as uint } }
+ fn trailing_zeros(self) -> u32 { unsafe { $cttz(self as $ActualT) as u32 } }
#[inline]
- fn rotate_left(self, n: uint) -> $T {
+ fn rotate_left(self, n: u32) -> $T {
// Protect against undefined behaviour for over-long bit shifts
let n = n % $BITS;
(self << n) | (self >> (($BITS - n) % $BITS))
}
#[inline]
- fn rotate_right(self, n: uint) -> $T {
+ fn rotate_right(self, n: u32) -> $T {
// Protect against undefined behaviour for over-long bit shifts
let n = n % $BITS;
(self >> n) | (self << (($BITS - n) % $BITS))
fn max_value() -> $T { let min: $T = Int::min_value(); !min }
#[inline]
- fn count_ones(self) -> uint { (self as $UnsignedT).count_ones() }
+ fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
#[inline]
- fn leading_zeros(self) -> uint { (self as $UnsignedT).leading_zeros() }
+ fn leading_zeros(self) -> u32 { (self as $UnsignedT).leading_zeros() }
#[inline]
- fn trailing_zeros(self) -> uint { (self as $UnsignedT).trailing_zeros() }
+ fn trailing_zeros(self) -> u32 { (self as $UnsignedT).trailing_zeros() }
#[inline]
- fn rotate_left(self, n: uint) -> $T { (self as $UnsignedT).rotate_left(n) as $T }
+ fn rotate_left(self, n: u32) -> $T { (self as $UnsignedT).rotate_left(n) as $T }
#[inline]
- fn rotate_right(self, n: uint) -> $T { (self as $UnsignedT).rotate_right(n) as $T }
+ fn rotate_right(self, n: u32) -> $T { (self as $UnsignedT).rotate_right(n) as $T }
#[inline]
fn swap_bytes(self) -> $T { (self as $UnsignedT).swap_bytes() as $T }
fn next_power_of_two(self) -> Self {
let bits = size_of::<Self>() * 8;
let one: Self = Int::one();
- one << ((bits - (self - one).leading_zeros()) % bits)
+ one << ((bits - (self - one).leading_zeros() as usize) % bits)
}
/// Returns the smallest power of two greater than or equal to `n`. If the
pub trait ToPrimitive {
/// Converts the value of `self` to an `int`.
#[inline]
+ #[unstable(feature = "core")]
+ #[deprecated(since = "1.0.0", reason = "use to_isize")]
fn to_int(&self) -> Option<int> {
- self.to_i64().and_then(|x| x.to_int())
+ self.to_i64().and_then(|x| x.to_isize())
+ }
+
+ /// Converts the value of `self` to an `isize`.
+ #[inline]
+ fn to_isize(&self) -> Option<isize> {
+ self.to_i64().and_then(|x| x.to_isize())
}
/// Converts the value of `self` to an `i8`.
/// Converts the value of `self` to an `uint`.
#[inline]
+ #[unstable(feature = "core")]
+ #[deprecated(since = "1.0.0", reason = "use to_usize")]
fn to_uint(&self) -> Option<uint> {
- self.to_u64().and_then(|x| x.to_uint())
+ self.to_u64().and_then(|x| x.to_usize())
+ }
+
+ /// Converts the value of `self` to a `usize`.
+ #[inline]
+ fn to_usize(&self) -> Option<usize> {
+ self.to_u64().and_then(|x| x.to_usize())
}
/// Converts the value of `self` to an `u8`.
#[inline]
fn to_int(&self) -> Option<int> { impl_to_primitive_int_to_int!($T, int, *self) }
#[inline]
+ fn to_isize(&self) -> Option<isize> { impl_to_primitive_int_to_int!($T, isize, *self) }
+ #[inline]
fn to_i8(&self) -> Option<i8> { impl_to_primitive_int_to_int!($T, i8, *self) }
#[inline]
fn to_i16(&self) -> Option<i16> { impl_to_primitive_int_to_int!($T, i16, *self) }
#[inline]
fn to_uint(&self) -> Option<uint> { impl_to_primitive_int_to_uint!($T, uint, *self) }
#[inline]
+ fn to_usize(&self) -> Option<usize> { impl_to_primitive_int_to_uint!($T, usize, *self) }
+ #[inline]
fn to_u8(&self) -> Option<u8> { impl_to_primitive_int_to_uint!($T, u8, *self) }
#[inline]
fn to_u16(&self) -> Option<u16> { impl_to_primitive_int_to_uint!($T, u16, *self) }
)
}
-impl_to_primitive_int! { int }
+impl_to_primitive_int! { isize }
impl_to_primitive_int! { i8 }
impl_to_primitive_int! { i16 }
impl_to_primitive_int! { i32 }
#[inline]
fn to_int(&self) -> Option<int> { impl_to_primitive_uint_to_int!(int, *self) }
#[inline]
+ fn to_isize(&self) -> Option<int> { impl_to_primitive_uint_to_int!(isize, *self) }
+ #[inline]
fn to_i8(&self) -> Option<i8> { impl_to_primitive_uint_to_int!(i8, *self) }
#[inline]
fn to_i16(&self) -> Option<i16> { impl_to_primitive_uint_to_int!(i16, *self) }
#[inline]
fn to_uint(&self) -> Option<uint> { impl_to_primitive_uint_to_uint!($T, uint, *self) }
#[inline]
+ fn to_usize(&self) -> Option<uint> { impl_to_primitive_uint_to_uint!($T, usize, *self) }
+ #[inline]
fn to_u8(&self) -> Option<u8> { impl_to_primitive_uint_to_uint!($T, u8, *self) }
#[inline]
fn to_u16(&self) -> Option<u16> { impl_to_primitive_uint_to_uint!($T, u16, *self) }
)
}
-impl_to_primitive_uint! { uint }
+impl_to_primitive_uint! { usize }
impl_to_primitive_uint! { u8 }
impl_to_primitive_uint! { u16 }
impl_to_primitive_uint! { u32 }
#[inline]
fn to_int(&self) -> Option<int> { Some(*self as int) }
#[inline]
+ fn to_isize(&self) -> Option<int> { Some(*self as isize) }
+ #[inline]
fn to_i8(&self) -> Option<i8> { Some(*self as i8) }
#[inline]
fn to_i16(&self) -> Option<i16> { Some(*self as i16) }
#[inline]
fn to_uint(&self) -> Option<uint> { Some(*self as uint) }
#[inline]
+ fn to_usize(&self) -> Option<uint> { Some(*self as usize) }
+ #[inline]
fn to_u8(&self) -> Option<u8> { Some(*self as u8) }
#[inline]
fn to_u16(&self) -> Option<u16> { Some(*self as u16) }
/// Convert an `int` to return an optional value of this type. If the
/// value cannot be represented by this value, the `None` is returned.
#[inline]
+ #[unstable(feature = "core")]
+ #[deprecated(since = "1.0.0", reason = "use from_isize")]
fn from_int(n: int) -> Option<Self> {
FromPrimitive::from_i64(n as i64)
}
+ /// Convert an `isize` to return an optional value of this type. If the
+ /// value cannot be represented by this value, the `None` is returned.
+ #[inline]
+ fn from_isize(n: isize) -> Option<Self> {
+ FromPrimitive::from_i64(n as i64)
+ }
+
/// Convert an `i8` to return an optional value of this type. If the
/// type cannot be represented by this value, the `None` is returned.
#[inline]
/// Convert an `uint` to return an optional value of this type. If the
/// type cannot be represented by this value, the `None` is returned.
#[inline]
+ #[unstable(feature = "core")]
+ #[deprecated(since = "1.0.0", reason = "use from_usize")]
fn from_uint(n: uint) -> Option<Self> {
FromPrimitive::from_u64(n as u64)
}
+ /// Convert a `usize` to return an optional value of this type. If the
+ /// type cannot be represented by this value, the `None` is returned.
+ #[inline]
+ fn from_usize(n: usize) -> Option<Self> {
+ FromPrimitive::from_u64(n as u64)
+ }
+
/// Convert an `u8` to return an optional value of this type. If the
/// type cannot be represented by this value, the `None` is returned.
#[inline]
/// A utility function that just calls `FromPrimitive::from_int`.
#[unstable(feature = "core", reason = "likely to be removed")]
+#[deprecated(since = "1.0.0", reason = "use from_isize")]
pub fn from_int<A: FromPrimitive>(n: int) -> Option<A> {
- FromPrimitive::from_int(n)
+ FromPrimitive::from_isize(n)
+}
+
+/// A utility function that just calls `FromPrimitive::from_isize`.
+#[unstable(feature = "core", reason = "likely to be removed")]
+pub fn from_isize<A: FromPrimitive>(n: isize) -> Option<A> {
+ FromPrimitive::from_isize(n)
}
/// A utility function that just calls `FromPrimitive::from_i8`.
/// A utility function that just calls `FromPrimitive::from_uint`.
#[unstable(feature = "core", reason = "likely to be removed")]
+#[deprecated(since = "1.0.0", reason = "use from_uint")]
pub fn from_uint<A: FromPrimitive>(n: uint) -> Option<A> {
- FromPrimitive::from_uint(n)
+ FromPrimitive::from_usize(n)
+}
+
+/// A utility function that just calls `FromPrimitive::from_usize`.
+#[unstable(feature = "core", reason = "likely to be removed")]
+pub fn from_usize<A: FromPrimitive>(n: usize) -> Option<A> {
+ FromPrimitive::from_usize(n)
}
/// A utility function that just calls `FromPrimitive::from_u8`.
}
}
}
-from_str_radix_int_impl! { int }
+from_str_radix_int_impl! { isize }
from_str_radix_int_impl! { i8 }
from_str_radix_int_impl! { i16 }
from_str_radix_int_impl! { i32 }
from_str_radix_int_impl! { i64 }
-from_str_radix_int_impl! { uint }
+from_str_radix_int_impl! { usize }
from_str_radix_int_impl! { u8 }
from_str_radix_int_impl! { u16 }
from_str_radix_int_impl! { u32 }
+++ /dev/null
-// Copyright 2012-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.
-
-//! Deprecated: replaced by `usize`.
-//!
-//! The rollout of the new type will gradually take place over the
-//! alpha cycle along with the development of clearer conventions
-//! around integer types.
-
-#![unstable(feature = "core")]
-#![deprecated(since = "1.0.0", reason = "replaced by usize")]
-
-uint_module! { uint, int, ::int::BITS }
macro_rules! uint_module { ($T:ty, $T_SIGNED:ty, $bits:expr) => (
#[unstable(feature = "core")]
-pub const BITS : uint = $bits;
+pub const BITS : u32 = $bits;
#[unstable(feature = "core")]
-pub const BYTES : uint = ($bits / 8);
+pub const BYTES : u32 = ($bits / 8);
#[stable(feature = "rust1", since = "1.0.0")]
pub const MIN: $T = 0 as $T;
#[deprecated(reason = "unboxed new closures do not have a universal representation; \
`&Fn` (etc) trait objects should use `TraitObject` instead",
since= "1.0.0")]
+#[allow(deprecated) /* for deriving Copy impl */]
pub struct Closure {
pub code: *mut (),
pub env: *mut (),
forward_iterator! { RSplitNMut: T, &'a mut [T] }
/// An iterator over overlapping subslices of length `size`.
-#[derive(Clone)]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Windows<'a, T:'a> {
v: &'a [T],
size: usize
}
+// FIXME(#19839) Remove in favor of `#[derive(Clone)]`
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<'a, T> Clone for Windows<'a, T> {
+ fn clone(&self) -> Windows<'a, T> {
+ Windows {
+ v: self.v,
+ size: self.size,
+ }
+ }
+}
+
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T> Iterator for Windows<'a, T> {
type Item = &'a [T];
///
/// When the slice len is not evenly divided by the chunk size, the last slice
/// of the iteration will be the remainder.
-#[derive(Clone)]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Chunks<'a, T:'a> {
v: &'a [T],
size: usize
}
+// FIXME(#19839) Remove in favor of `#[derive(Clone)]`
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<'a, T> Clone for Chunks<'a, T> {
+ fn clone(&self) -> Chunks<'a, T> {
+ Chunks {
+ v: self.v,
+ size: self.size,
+ }
+ }
+}
+
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T> Iterator for Chunks<'a, T> {
type Item = &'a [T];
/// Parse a `bool` from a string.
///
- /// Yields an `Option<bool>`, because `s` may or may not actually be
- /// parseable.
+ /// Yields a `Result<bool, ParseBoolError>`, because `s` may or may not
+ /// actually be parseable.
///
/// # Examples
///
/// ```rust
+ /// use std::str::FromStr;
+ ///
+ /// assert_eq!(FromStr::from_str("true"), Ok(true));
+ /// assert_eq!(FromStr::from_str("false"), Ok(false));
+ /// assert!(<bool as FromStr>::from_str("not even a boolean").is_err());
+ /// ```
+ ///
+ /// Note, in many cases, the StrExt::parse() which is based on
+ /// this FromStr::from_str() is more proper.
+ ///
+ /// ```rust
/// assert_eq!("true".parse(), Ok(true));
/// assert_eq!("false".parse(), Ok(false));
/// assert!("not even a boolean".parse::<bool>().is_err());
#[unstable(feature = "core")]
#[deprecated(since = "1.0.0", reason = "use `Split` with a `&str`")]
pub struct SplitStr<'a, P: Pattern<'a>>(Split<'a, P>);
+#[allow(deprecated)]
impl<'a, P: Pattern<'a>> Iterator for SplitStr<'a, P> {
type Item = &'a str;
fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P>;
fn rsplitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> RSplitN<'a, P>;
fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P>;
+ #[allow(deprecated) /* for SplitStr */]
fn split_str<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitStr<'a, P>;
fn lines<'a>(&'a self) -> Lines<'a>;
fn lines_any<'a>(&'a self) -> LinesAny<'a>;
use core::iter::order::*;
use core::iter::MinMaxResult::*;
use core::num::SignedInt;
-use core::uint;
+use core::usize;
use core::cmp;
use test::Bencher;
fn test_cycle() {
let cycle_len = 3;
let it = count(0, 1).take(cycle_len).cycle();
- assert_eq!(it.size_hint(), (uint::MAX, None));
+ assert_eq!(it.size_hint(), (usize::MAX, None));
for (i, x) in it.take(100).enumerate() {
assert_eq!(i % cycle_len, x);
}
let v2 = &[10, 11, 12];
let vi = v.iter();
- assert_eq!(c.size_hint(), (uint::MAX, None));
+ assert_eq!(c.size_hint(), (usize::MAX, None));
assert_eq!(vi.clone().size_hint(), (10, Some(10)));
assert_eq!(c.clone().take(5).size_hint(), (5, Some(5)));
assert_eq!(c.clone().skip(5).size_hint().1, None);
assert_eq!(c.clone().take_while(|_| false).size_hint(), (0, None));
assert_eq!(c.clone().skip_while(|_| false).size_hint(), (0, None));
- assert_eq!(c.clone().enumerate().size_hint(), (uint::MAX, None));
- assert_eq!(c.clone().chain(vi.clone().cloned()).size_hint(), (uint::MAX, None));
+ assert_eq!(c.clone().enumerate().size_hint(), (usize::MAX, None));
+ assert_eq!(c.clone().chain(vi.clone().cloned()).size_hint(), (usize::MAX, None));
assert_eq!(c.clone().zip(vi.clone()).size_hint(), (10, Some(10)));
assert_eq!(c.clone().scan(0, |_,_| Some(0)).size_hint(), (0, None));
assert_eq!(c.clone().filter(|_| false).size_hint(), (0, None));
- assert_eq!(c.clone().map(|_| 0).size_hint(), (uint::MAX, None));
+ assert_eq!(c.clone().map(|_| 0).size_hint(), (usize::MAX, None));
assert_eq!(c.filter_map(|_| Some(0)).size_hint(), (0, None));
assert_eq!(vi.clone().take(5).size_hint(), (5, Some(5)));
assert_eq!((0..100).size_hint(), (100, Some(100)));
// this test is only meaningful when sizeof uint < sizeof u64
- assert_eq!((uint::MAX - 1..uint::MAX).size_hint(), (1, Some(1)));
+ assert_eq!((usize::MAX - 1..usize::MAX).size_hint(), (1, Some(1)));
assert_eq!((-10..-1).size_hint(), (9, Some(9)));
assert_eq!((-1..-10).size_hint(), (0, Some(0)));
}
+++ /dev/null
-// 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.
-
-int_module!(int, int);
#[cfg(test)]
mod tests {
use core::$T_i::*;
- use core::int;
+ use core::isize;
use core::num::{FromStrRadix, Int, SignedInt};
use core::ops::{Shl, Shr, Not, BitXor, BitAnd, BitOr};
use num;
assert!(-(0b11 as $T) - (1 as $T) == (0b11 as $T).not());
}
- static A: $T = 0b0101100;
- static B: $T = 0b0100001;
- static C: $T = 0b1111001;
+ const A: $T = 0b0101100;
+ const B: $T = 0b0100001;
+ const C: $T = 0b1111001;
- static _0: $T = 0;
- static _1: $T = !0;
+ const _0: $T = 0;
+ const _1: $T = !0;
#[test]
fn test_count_ones() {
fn test_signed_checked_div() {
assert!(10.checked_div(2) == Some(5));
assert!(5.checked_div(0) == None);
- assert!(int::MIN.checked_div(-1) == None);
+ assert!(isize::MIN.checked_div(-1) == None);
}
#[test]
mod i16;
mod i32;
mod i64;
-mod int;
#[macro_use]
mod uint_macros;
mod u16;
mod u32;
mod u64;
-mod uint;
/// Helper function for testing numeric operations
pub fn test_num<T>(ten: T, two: T) where
+++ /dev/null
-// 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.
-
-uint_module!(uint, uint);
assert!(MAX - (0b1011 as $T) == (0b1011 as $T).not());
}
- static A: $T = 0b0101100;
- static B: $T = 0b0100001;
- static C: $T = 0b1111001;
+ const A: $T = 0b0101100;
+ const B: $T = 0b0100001;
+ const C: $T = 0b1111001;
- static _0: $T = 0;
- static _1: $T = !0;
+ const _0: $T = 0;
+ const _1: $T = !0;
#[test]
fn test_count_ones() {
-> *mut c_void;
}
-static LZ_NORM : c_int = 0x80; // LZ with 128 probes, "normal"
-static TINFL_FLAG_PARSE_ZLIB_HEADER : c_int = 0x1; // parse zlib header and adler32 checksum
-static TDEFL_WRITE_ZLIB_HEADER : c_int = 0x01000; // write zlib header and adler32 checksum
+const LZ_NORM: c_int = 0x80; // LZ with 128 probes, "normal"
+const TINFL_FLAG_PARSE_ZLIB_HEADER: c_int = 0x1; // parse zlib header and adler32 checksum
+const TDEFL_WRITE_ZLIB_HEADER: c_int = 0x01000; // write zlib header and adler32 checksum
fn deflate_bytes_internal(bytes: &[u8], flags: c_int) -> Option<Bytes> {
unsafe {
"little lamb".to_string(),
"Little lamb".to_string()
]);
- t("\nMary had a little lamb\nLittle lamb\n", ::std::uint::MAX,
+ t("\nMary had a little lamb\nLittle lamb\n", ::std::usize::MAX,
&["Mary had a little lamb\nLittle lamb".to_string()]);
}
//! Each node label is derived directly from the int representing the node,
//! while the edge labels are all empty strings.
//!
-//! This example also illustrates how to use `CowVec` to return
+//! This example also illustrates how to use `Cow<[T]>` to return
//! an owned vector or a borrowed slice as appropriate: we construct the
//! node vector from scratch, but borrow the edge list (rather than
//! constructing a copy of all the edges from scratch).
/// that is bound by the self lifetime `'a`.
///
/// The `nodes` and `edges` method each return instantiations of
-/// `CowVec` to leave implementers the freedom to create
+/// `Cow<[T]>` to leave implementers the freedom to create
/// entirely new vectors or to pass back slices into internally owned
/// vectors.
pub trait GraphWalk<'a, N, E> {
pub mod posix88 {
pub type off_t = i64;
pub type dev_t = u32;
- pub type ino_t = u32;
pub type pid_t = i32;
pub type uid_t = u32;
pub type gid_t = u32;
mut pdf: P,
mut zero_case: Z)
-> f64 where P: FnMut(f64) -> f64, Z: FnMut(&mut R, f64) -> f64 {
- static SCALE: f64 = (1u64 << 53) as f64;
+ const SCALE: f64 = (1u64 << 53) as f64;
loop {
// reimplement the f64 generation as an optimisation suggested
// by the Doornik paper: we have a lot of precision-space
let mut a = self.a;
let mut b = self.b + self.c;
- static MIDPOINT: uint = (RAND_SIZE / 2) as uint;
+ const MIDPOINT: uint = (RAND_SIZE / 2) as uint;
macro_rules! ind {
($x:expr) => ( self.mem[(($x >> 2) as uint & ((RAND_SIZE - 1) as uint))] )
use distributions::range::SampleRange;
#[cfg(test)]
-static RAND_BENCH_N: u64 = 100;
+const RAND_BENCH_N: u64 = 100;
pub mod distributions;
pub mod isaac;
type Item = char;
fn next(&mut self) -> Option<char> {
- static GEN_ASCII_STR_CHARSET: &'static [u8] =
+ const GEN_ASCII_STR_CHARSET: &'static [u8] =
b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
abcdefghijklmnopqrstuvwxyz\
0123456789";
use core::prelude::*;
use core::char;
-use core::int;
-use core::uint;
+use core::isize;
+use core::usize;
use {Rand,Rng};
-impl Rand for int {
+impl Rand for isize {
#[inline]
- fn rand<R: Rng>(rng: &mut R) -> int {
- if int::BITS == 32 {
- rng.gen::<i32>() as int
+ fn rand<R: Rng>(rng: &mut R) -> isize {
+ if isize::BITS == 32 {
+ rng.gen::<i32>() as isize
} else {
- rng.gen::<i64>() as int
+ rng.gen::<i64>() as isize
}
}
}
}
}
-impl Rand for uint {
+impl Rand for usize {
#[inline]
- fn rand<R: Rng>(rng: &mut R) -> uint {
- if uint::BITS == 32 {
- rng.gen::<u32>() as uint
+ fn rand<R: Rng>(rng: &mut R) -> usize {
+ if usize::BITS == 32 {
+ rng.gen::<u32>() as usize
} else {
- rng.gen::<u64>() as uint
+ rng.gen::<u64>() as usize
}
}
}
#[inline]
fn rand<R: Rng>(rng: &mut R) -> char {
// a char is 21 bits
- static CHAR_MASK: u32 = 0x001f_ffff;
+ const CHAR_MASK: u32 = 0x001f_ffff;
loop {
// Rejection sampling. About 0.2% of numbers with at most
// 21-bits are invalid codepoints (surrogates), so this
/// How many bytes of entropy the underling RNG is allowed to generate
/// before it is reseeded.
-static DEFAULT_GENERATION_THRESHOLD: uint = 32 * 1024;
+const DEFAULT_GENERATION_THRESHOLD: uint = 32 * 1024;
/// A wrapper around any RNG which reseeds the underlying RNG after it
/// has generated a certain number of random bytes.
assert_eq!(string1, string2);
}
- static FILL_BYTES_V_LEN: uint = 13579;
+ const FILL_BYTES_V_LEN: uint = 13579;
#[test]
fn test_rng_fill_bytes() {
let mut v = repeat(0u8).take(FILL_BYTES_V_LEN).collect::<Vec<_>>();
use std::slice;
use std::iter::repeat;
-static BUF_CAPACITY: uint = 128;
+const BUF_CAPACITY: uint = 128;
fn combine(seek: SeekStyle, cur: uint, end: uint, offset: i64) -> IoResult<u64> {
// compute offset as signed and clamp to prevent overflow
-// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
+// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-//! Really Bad Markup Language (rbml) is a temporary measure until we migrate
-//! the rust object metadata to a better serialization format. It is not
-//! intended to be used by users.
+//! Really Bad Markup Language (rbml) is an internal serialization format of rustc.
+//! This is not intended to be used by users.
//!
-//! It is loosely based on the Extensible Binary Markup Language (ebml):
-//! http://www.matroska.org/technical/specs/rfc/index.html
+//! Originally based on the Extensible Binary Markup Language
+//! (ebml; http://www.matroska.org/technical/specs/rfc/index.html),
+//! it is now a separate format tuned for the rust object metadata.
+//!
+//! # Encoding
+//!
+//! RBML document consists of the tag, length and data.
+//! The encoded data can contain multiple RBML documents concatenated.
+//!
+//! **Tags** are a hint for the following data.
+//! Tags are a number from 0x000 to 0xfff, where 0xf0 through 0xff is reserved.
+//! Tags less than 0xf0 are encoded in one literal byte.
+//! Tags greater than 0xff are encoded in two big-endian bytes,
+//! where the tag number is ORed with 0xf000. (E.g. tag 0x123 = `f1 23`)
+//!
+//! **Lengths** encode the length of the following data.
+//! It is a variable-length unsigned int, and one of the following forms:
+//!
+//! - `80` through `fe` for lengths up to 0x7e;
+//! - `40 ff` through `7f ff` for lengths up to 0x3fff;
+//! - `20 40 00` through `3f ff ff` for lengths up to 0x1fffff;
+//! - `10 20 00 00` through `1f ff ff ff` for lengths up to 0xfffffff.
+//!
+//! The "overlong" form is allowed so that the length can be encoded
+//! without the prior knowledge of the encoded data.
+//! For example, the length 0 can be represented either by `80`, `40 00`,
+//! `20 00 00` or `10 00 00 00`.
+//! The encoder tries to minimize the length if possible.
+//! Also, some predefined tags listed below are so commonly used that
+//! their lengths are omitted ("implicit length").
+//!
+//! **Data** can be either binary bytes or zero or more nested RBML documents.
+//! Nested documents cannot overflow, and should be entirely contained
+//! within a parent document.
+//!
+//! # Predefined Tags
+//!
+//! Most RBML tags are defined by the application.
+//! (For the rust object metadata, see also `rustc::metadata::common`.)
+//! RBML itself does define a set of predefined tags however,
+//! intended for the auto-serialization implementation.
+//!
+//! Predefined tags with an implicit length:
+//!
+//! - `U8` (`00`): 1-byte unsigned integer.
+//! - `U16` (`01`): 2-byte big endian unsigned integer.
+//! - `U32` (`02`): 4-byte big endian unsigned integer.
+//! - `U64` (`03`): 8-byte big endian unsigned integer.
+//! Any of `U*` tags can be used to encode primitive unsigned integer types,
+//! as long as it is no greater than the actual size.
+//! For example, `u8` can only be represented via the `U8` tag.
+//!
+//! - `I8` (`04`): 1-byte signed integer.
+//! - `I16` (`05`): 2-byte big endian signed integer.
+//! - `I32` (`06`): 4-byte big endian signed integer.
+//! - `I64` (`07`): 8-byte big endian signed integer.
+//! Similar to `U*` tags. Always uses two's complement encoding.
+//!
+//! - `Bool` (`08`): 1-byte boolean value, `00` for false and `01` for true.
+//!
+//! - `Char` (`09`): 4-byte big endian Unicode scalar value.
+//! Surrogate pairs or out-of-bound values are invalid.
+//!
+//! - `F32` (`0a`): 4-byte big endian unsigned integer representing
+//! IEEE 754 binary32 floating-point format.
+//! - `F64` (`0b`): 8-byte big endian unsigned integer representing
+//! IEEE 754 binary64 floating-point format.
+//!
+//! - `Sub8` (`0c`): 1-byte unsigned integer for supplementary information.
+//! - `Sub32` (`0d`): 4-byte unsigned integer for supplementary information.
+//! Those two tags normally occur as the first subdocument of certain tags,
+//! namely `Enum`, `Vec` and `Map`, to provide a variant or size information.
+//! They can be used interchangably.
+//!
+//! Predefined tags with an explicit length:
+//!
+//! - `Str` (`10`): A UTF-8-encoded string.
+//!
+//! - `Enum` (`11`): An enum.
+//! The first subdocument should be `Sub*` tags with a variant ID.
+//! Subsequent subdocuments, if any, encode variant arguments.
+//!
+//! - `Vec` (`12`): A vector (sequence).
+//! - `VecElt` (`13`): A vector element.
+//! The first subdocument should be `Sub*` tags with the number of elements.
+//! Subsequent subdocuments should be `VecElt` tag per each element.
+//!
+//! - `Map` (`14`): A map (associated array).
+//! - `MapKey` (`15`): A key part of the map entry.
+//! - `MapVal` (`16`): A value part of the map entry.
+//! The first subdocument should be `Sub*` tags with the number of entries.
+//! Subsequent subdocuments should be an alternating sequence of
+//! `MapKey` and `MapVal` tags per each entry.
+//!
+//! - `Opaque` (`17`): An opaque, custom-format tag.
+//! Used to wrap ordinary custom tags or data in the auto-serialized context.
+//! Rustc typically uses this to encode type informations.
+//!
+//! First 0x20 tags are reserved by RBML; custom tags start at 0x20.
#![crate_name = "rbml"]
#![unstable(feature = "rustc_private")]
reader::get_doc(*self, tag)
}
+ pub fn is_empty(&self) -> bool {
+ self.start == self.end
+ }
+
pub fn as_str_slice<'a>(&'a self) -> &'a str {
str::from_utf8(&self.data[self.start..self.end]).unwrap()
}
#[derive(Copy, Debug)]
pub enum EbmlEncoderTag {
- EsUint, // 0
- EsU64, // 1
- EsU32, // 2
- EsU16, // 3
- EsU8, // 4
- EsInt, // 5
- EsI64, // 6
- EsI32, // 7
- EsI16, // 8
- EsI8, // 9
- EsBool, // 10
- EsChar, // 11
- EsStr, // 12
- EsF64, // 13
- EsF32, // 14
- EsFloat, // 15
- EsEnum, // 16
- EsEnumVid, // 17
- EsEnumBody, // 18
- EsVec, // 19
- EsVecLen, // 20
- EsVecElt, // 21
- EsMap, // 22
- EsMapLen, // 23
- EsMapKey, // 24
- EsMapVal, // 25
-
- EsOpaque,
-
- EsLabel, // Used only when debugging
+ // tags 00..1f are reserved for auto-serialization.
+ // first NUM_IMPLICIT_TAGS tags are implicitly sized and lengths are not encoded.
+
+ EsU8 = 0x00, // + 1 byte
+ EsU16 = 0x01, // + 2 bytes
+ EsU32 = 0x02, // + 4 bytes
+ EsU64 = 0x03, // + 8 bytes
+ EsI8 = 0x04, // + 1 byte
+ EsI16 = 0x05, // + 2 bytes
+ EsI32 = 0x06, // + 4 bytes
+ EsI64 = 0x07, // + 8 bytes
+ EsBool = 0x08, // + 1 byte
+ EsChar = 0x09, // + 4 bytes
+ EsF32 = 0x0a, // + 4 bytes
+ EsF64 = 0x0b, // + 8 bytes
+ EsSub8 = 0x0c, // + 1 byte
+ EsSub32 = 0x0d, // + 4 bytes
+ // 0x0e and 0x0f are reserved
+
+ EsStr = 0x10,
+ EsEnum = 0x11, // encodes the variant id as the first EsSub*
+ EsVec = 0x12, // encodes the # of elements as the first EsSub*
+ EsVecElt = 0x13,
+ EsMap = 0x14, // encodes the # of pairs as the first EsSub*
+ EsMapKey = 0x15,
+ EsMapVal = 0x16,
+ EsOpaque = 0x17,
}
+const NUM_TAGS: uint = 0x1000;
+const NUM_IMPLICIT_TAGS: uint = 0x0e;
+
+static TAG_IMPLICIT_LEN: [i8; NUM_IMPLICIT_TAGS] = [
+ 1, 2, 4, 8, // EsU*
+ 1, 2, 4, 8, // ESI*
+ 1, // EsBool
+ 4, // EsChar
+ 4, 8, // EsF*
+ 1, 4, // EsSub*
+];
+
#[derive(Debug)]
pub enum Error {
IntTooBig(uint),
+ InvalidTag(uint),
Expected(String),
IoError(std::old_io::IoError),
ApplicationError(String)
use serialize;
- use super::{ ApplicationError, EsVec, EsMap, EsEnum, EsVecLen, EsVecElt,
- EsMapLen, EsMapKey, EsEnumVid, EsU64, EsU32, EsU16, EsU8, EsInt, EsI64,
+ use super::{ ApplicationError, EsVec, EsMap, EsEnum, EsSub8, EsSub32,
+ EsVecElt, EsMapKey, EsU64, EsU32, EsU16, EsU8, EsI64,
EsI32, EsI16, EsI8, EsBool, EsF64, EsF32, EsChar, EsStr, EsMapVal,
- EsEnumBody, EsUint, EsOpaque, EsLabel, EbmlEncoderTag, Doc, TaggedDoc,
- Error, IntTooBig, Expected };
+ EsOpaque, EbmlEncoderTag, Doc, TaggedDoc,
+ Error, IntTooBig, InvalidTag, Expected, NUM_IMPLICIT_TAGS, TAG_IMPLICIT_LEN };
pub type DecodeResult<T> = Result<T, Error>;
// rbml reading
pub next: uint
}
+ pub fn tag_at(data: &[u8], start: uint) -> DecodeResult<Res> {
+ let v = data[start] as uint;
+ if v < 0xf0 {
+ Ok(Res { val: v, next: start + 1 })
+ } else if v > 0xf0 {
+ Ok(Res { val: ((v & 0xf) << 8) | data[start + 1] as uint, next: start + 2 })
+ } else {
+ // every tag starting with byte 0xf0 is an overlong form, which is prohibited.
+ Err(InvalidTag(v))
+ }
+ }
+
#[inline(never)]
fn vuint_at_slow(data: &[u8], start: uint) -> DecodeResult<Res> {
let a = data[start];
}
}
+ pub fn tag_len_at(data: &[u8], tag: Res) -> DecodeResult<Res> {
+ if tag.val < NUM_IMPLICIT_TAGS && TAG_IMPLICIT_LEN[tag.val] >= 0 {
+ Ok(Res { val: TAG_IMPLICIT_LEN[tag.val] as uint, next: tag.next })
+ } else {
+ vuint_at(data, tag.next)
+ }
+ }
+
pub fn doc_at<'a>(data: &'a [u8], start: uint) -> DecodeResult<TaggedDoc<'a>> {
- let elt_tag = try!(vuint_at(data, start));
- let elt_size = try!(vuint_at(data, elt_tag.next));
+ let elt_tag = try!(tag_at(data, start));
+ let elt_size = try!(tag_len_at(data, elt_tag));
let end = elt_size.next + elt_size.val;
Ok(TaggedDoc {
tag: elt_tag.val,
pub fn maybe_get_doc<'a>(d: Doc<'a>, tg: uint) -> Option<Doc<'a>> {
let mut pos = d.start;
while pos < d.end {
- let elt_tag = try_or!(vuint_at(d.data, pos), None);
- let elt_size = try_or!(vuint_at(d.data, elt_tag.next), None);
+ let elt_tag = try_or!(tag_at(d.data, pos), None);
+ let elt_size = try_or!(tag_len_at(d.data, elt_tag), None);
pos = elt_size.next + elt_size.val;
if elt_tag.val == tg {
return Some(Doc { data: d.data, start: elt_size.next,
{
let mut pos = d.start;
while pos < d.end {
- let elt_tag = try_or!(vuint_at(d.data, pos), false);
- let elt_size = try_or!(vuint_at(d.data, elt_tag.next), false);
+ let elt_tag = try_or!(tag_at(d.data, pos), false);
+ let elt_size = try_or!(tag_len_at(d.data, elt_tag), false);
pos = elt_size.next + elt_size.val;
let doc = Doc { data: d.data, start: elt_size.next, end: pos };
if !it(elt_tag.val, doc) {
{
let mut pos = d.start;
while pos < d.end {
- let elt_tag = try_or!(vuint_at(d.data, pos), false);
- let elt_size = try_or!(vuint_at(d.data, elt_tag.next), false);
+ let elt_tag = try_or!(tag_at(d.data, pos), false);
+ let elt_size = try_or!(tag_len_at(d.data, elt_tag), false);
pos = elt_size.next + elt_size.val;
if elt_tag.val == tg {
let doc = Doc { data: d.data, start: elt_size.next,
}
}
- fn _check_label(&mut self, lbl: &str) -> DecodeResult<()> {
- if self.pos < self.parent.end {
- let TaggedDoc { tag: r_tag, doc: r_doc } =
- try!(doc_at(self.parent.data, self.pos));
-
- if r_tag == (EsLabel as uint) {
- self.pos = r_doc.end;
- let str = r_doc.as_str_slice();
- if lbl != str {
- return Err(Expected(format!("Expected label {:?} but \
- found {:?}", lbl, str)));
- }
- }
- }
- Ok(())
- }
-
fn next_doc(&mut self, exp_tag: EbmlEncoderTag) -> DecodeResult<Doc<'doc>> {
debug!(". next_doc(exp_tag={:?})", exp_tag);
if self.pos >= self.parent.end {
Ok(r)
}
- fn _next_uint(&mut self, exp_tag: EbmlEncoderTag) -> DecodeResult<uint> {
- let r = doc_as_u32(try!(self.next_doc(exp_tag)));
- debug!("_next_uint exp_tag={:?} result={:?}", exp_tag, r);
- Ok(r as uint)
+ fn _next_sub(&mut self) -> DecodeResult<uint> {
+ // empty vector/map optimization
+ if self.parent.is_empty() {
+ return Ok(0);
+ }
+
+ let TaggedDoc { tag: r_tag, doc: r_doc } =
+ try!(doc_at(self.parent.data, self.pos));
+ let r = if r_tag == (EsSub8 as uint) {
+ doc_as_u8(r_doc) as uint
+ } else if r_tag == (EsSub32 as uint) {
+ doc_as_u32(r_doc) as uint
+ } else {
+ return Err(Expected(format!("expected EBML doc with tag {:?} or {:?} but \
+ found tag {:?}", EsSub8, EsSub32, r_tag)));
+ };
+ if r_doc.end > self.parent.end {
+ return Err(Expected(format!("invalid EBML, child extends to \
+ {:#x}, parent to {:#x}",
+ r_doc.end, self.parent.end)));
+ }
+ self.pos = r_doc.end;
+ debug!("_next_sub result={:?}", r);
+ Ok(r)
+ }
+
+ // variable-length unsigned integer with different tags.
+ // `first_tag` should be a tag for u8 or i8.
+ // `last_tag` should be the largest allowed integer tag with the matching signedness.
+ // all tags between them should be valid, in the order of u8, u16, u32 and u64.
+ fn _next_int(&mut self,
+ first_tag: EbmlEncoderTag,
+ last_tag: EbmlEncoderTag) -> DecodeResult<u64> {
+ if self.pos >= self.parent.end {
+ return Err(Expected(format!("no more documents in \
+ current node!")));
+ }
+
+ let TaggedDoc { tag: r_tag, doc: r_doc } =
+ try!(doc_at(self.parent.data, self.pos));
+ let r = if first_tag as uint <= r_tag && r_tag <= last_tag as uint {
+ match r_tag - first_tag as uint {
+ 0 => doc_as_u8(r_doc) as u64,
+ 1 => doc_as_u16(r_doc) as u64,
+ 2 => doc_as_u32(r_doc) as u64,
+ 3 => doc_as_u64(r_doc) as u64,
+ _ => unreachable!(),
+ }
+ } else {
+ return Err(Expected(format!("expected EBML doc with tag {:?} through {:?} but \
+ found tag {:?}", first_tag, last_tag, r_tag)));
+ };
+ if r_doc.end > self.parent.end {
+ return Err(Expected(format!("invalid EBML, child extends to \
+ {:#x}, parent to {:#x}",
+ r_doc.end, self.parent.end)));
+ }
+ self.pos = r_doc.end;
+ debug!("_next_int({:?}, {:?}) result={:?}", first_tag, last_tag, r);
+ Ok(r)
}
pub fn read_opaque<R, F>(&mut self, op: F) -> DecodeResult<R> where
type Error = Error;
fn read_nil(&mut self) -> DecodeResult<()> { Ok(()) }
- fn read_u64(&mut self) -> DecodeResult<u64> { Ok(doc_as_u64(try!(self.next_doc(EsU64)))) }
- fn read_u32(&mut self) -> DecodeResult<u32> { Ok(doc_as_u32(try!(self.next_doc(EsU32)))) }
- fn read_u16(&mut self) -> DecodeResult<u16> { Ok(doc_as_u16(try!(self.next_doc(EsU16)))) }
- fn read_u8 (&mut self) -> DecodeResult<u8 > { Ok(doc_as_u8 (try!(self.next_doc(EsU8 )))) }
+ fn read_u64(&mut self) -> DecodeResult<u64> { self._next_int(EsU8, EsU64) }
+ fn read_u32(&mut self) -> DecodeResult<u32> { Ok(try!(self._next_int(EsU8, EsU32)) as u32) }
+ fn read_u16(&mut self) -> DecodeResult<u16> { Ok(try!(self._next_int(EsU8, EsU16)) as u16) }
+ fn read_u8(&mut self) -> DecodeResult<u8> { Ok(doc_as_u8(try!(self.next_doc(EsU8)))) }
fn read_uint(&mut self) -> DecodeResult<uint> {
- let v = doc_as_u64(try!(self.next_doc(EsUint)));
+ let v = try!(self._next_int(EsU8, EsU64));
if v > (::std::usize::MAX as u64) {
Err(IntTooBig(v as uint))
} else {
}
}
- fn read_i64(&mut self) -> DecodeResult<i64> {
- Ok(doc_as_u64(try!(self.next_doc(EsI64))) as i64)
- }
- fn read_i32(&mut self) -> DecodeResult<i32> {
- Ok(doc_as_u32(try!(self.next_doc(EsI32))) as i32)
- }
- fn read_i16(&mut self) -> DecodeResult<i16> {
- Ok(doc_as_u16(try!(self.next_doc(EsI16))) as i16)
- }
- fn read_i8 (&mut self) -> DecodeResult<i8> {
- Ok(doc_as_u8(try!(self.next_doc(EsI8 ))) as i8)
- }
+ fn read_i64(&mut self) -> DecodeResult<i64> { Ok(try!(self._next_int(EsI8, EsI64)) as i64) }
+ fn read_i32(&mut self) -> DecodeResult<i32> { Ok(try!(self._next_int(EsI8, EsI32)) as i32) }
+ fn read_i16(&mut self) -> DecodeResult<i16> { Ok(try!(self._next_int(EsI8, EsI16)) as i16) }
+ fn read_i8(&mut self) -> DecodeResult<i8> { Ok(doc_as_u8(try!(self.next_doc(EsI8))) as i8) }
fn read_int(&mut self) -> DecodeResult<int> {
- let v = doc_as_u64(try!(self.next_doc(EsInt))) as i64;
+ let v = try!(self._next_int(EsI8, EsI64)) as i64;
if v > (isize::MAX as i64) || v < (isize::MIN as i64) {
debug!("FIXME \\#6122: Removing this makes this function miscompile");
Err(IntTooBig(v as uint))
F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>,
{
debug!("read_enum({})", name);
- try!(self._check_label(name));
let doc = try!(self.next_doc(EsEnum));
where F: FnMut(&mut Decoder<'doc>, uint) -> DecodeResult<T>,
{
debug!("read_enum_variant()");
- let idx = try!(self._next_uint(EsEnumVid));
+ let idx = try!(self._next_sub());
debug!(" idx={}", idx);
- let doc = try!(self.next_doc(EsEnumBody));
-
- let (old_parent, old_pos) = (self.parent, self.pos);
- self.parent = doc;
- self.pos = self.parent.start;
-
- let result = try!(f(self, idx));
-
- self.parent = old_parent;
- self.pos = old_pos;
- Ok(result)
+ f(self, idx)
}
fn read_enum_variant_arg<T, F>(&mut self, idx: uint, f: F) -> DecodeResult<T> where
where F: FnMut(&mut Decoder<'doc>, uint) -> DecodeResult<T>,
{
debug!("read_enum_struct_variant()");
- let idx = try!(self._next_uint(EsEnumVid));
+ let idx = try!(self._next_sub());
debug!(" idx={}", idx);
- let doc = try!(self.next_doc(EsEnumBody));
-
- let (old_parent, old_pos) = (self.parent, self.pos);
- self.parent = doc;
- self.pos = self.parent.start;
-
- let result = try!(f(self, idx));
-
- self.parent = old_parent;
- self.pos = old_pos;
- Ok(result)
+ f(self, idx)
}
fn read_enum_struct_variant_field<T, F>(&mut self,
F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>,
{
debug!("read_struct_field(name={}, idx={})", name, idx);
- try!(self._check_label(name));
f(self)
}
{
debug!("read_seq()");
self.push_doc(EsVec, move |d| {
- let len = try!(d._next_uint(EsVecLen));
+ let len = try!(d._next_sub());
debug!(" len={}", len);
f(d, len)
})
{
debug!("read_map()");
self.push_doc(EsMap, move |d| {
- let len = try!(d._next_uint(EsMapLen));
+ let len = try!(d._next_sub());
debug!(" len={}", len);
f(d, len)
})
use std::num::Int;
use std::old_io::{Writer, Seek};
use std::old_io;
+ use std::slice::bytes;
+ use std::num::ToPrimitive;
- use super::{ EsVec, EsMap, EsEnum, EsVecLen, EsVecElt, EsMapLen, EsMapKey,
- EsEnumVid, EsU64, EsU32, EsU16, EsU8, EsInt, EsI64, EsI32, EsI16, EsI8,
- EsBool, EsF64, EsF32, EsChar, EsStr, EsMapVal, EsEnumBody, EsUint,
- EsOpaque, EsLabel, EbmlEncoderTag };
+ use super::{ EsVec, EsMap, EsEnum, EsSub8, EsSub32, EsVecElt, EsMapKey,
+ EsU64, EsU32, EsU16, EsU8, EsI64, EsI32, EsI16, EsI8,
+ EsBool, EsF64, EsF32, EsChar, EsStr, EsMapVal,
+ EsOpaque, NUM_IMPLICIT_TAGS, NUM_TAGS };
+ use super::io::SeekableMemWriter;
use serialize;
pub type EncodeResult = old_io::IoResult<()>;
// rbml writing
- pub struct Encoder<'a, W:'a> {
- pub writer: &'a mut W,
+ pub struct Encoder<'a> {
+ pub writer: &'a mut SeekableMemWriter,
size_positions: Vec<uint>,
+ relax_limit: u64, // do not move encoded bytes before this position
+ }
+
+ fn write_tag<W: Writer>(w: &mut W, n: uint) -> EncodeResult {
+ if n < 0xf0 {
+ w.write_all(&[n as u8])
+ } else if 0x100 <= n && n < NUM_TAGS {
+ w.write_all(&[0xf0 | (n >> 8) as u8, n as u8])
+ } else {
+ Err(old_io::IoError {
+ kind: old_io::OtherIoError,
+ desc: "invalid tag",
+ detail: Some(format!("{}", n))
+ })
+ }
}
fn write_sized_vuint<W: Writer>(w: &mut W, n: uint, size: uint) -> EncodeResult {
})
}
- impl<'a, W: Writer + Seek> Encoder<'a, W> {
- pub fn new(w: &'a mut W) -> Encoder<'a, W> {
+ impl<'a> Encoder<'a> {
+ pub fn new(w: &'a mut SeekableMemWriter) -> Encoder<'a> {
Encoder {
writer: w,
size_positions: vec!(),
+ relax_limit: 0,
}
}
/// FIXME(pcwalton): Workaround for badness in trans. DO NOT USE ME.
- pub unsafe fn unsafe_clone(&self) -> Encoder<'a, W> {
+ pub unsafe fn unsafe_clone(&self) -> Encoder<'a> {
Encoder {
writer: mem::transmute_copy(&self.writer),
size_positions: self.size_positions.clone(),
+ relax_limit: self.relax_limit,
}
}
pub fn start_tag(&mut self, tag_id: uint) -> EncodeResult {
debug!("Start tag {:?}", tag_id);
+ assert!(tag_id >= NUM_IMPLICIT_TAGS);
// Write the enum ID:
- try!(write_vuint(self.writer, tag_id));
+ try!(write_tag(self.writer, tag_id));
// Write a placeholder four-byte size.
self.size_positions.push(try!(self.writer.tell()) as uint);
let cur_pos = try!(self.writer.tell());
try!(self.writer.seek(last_size_pos as i64, old_io::SeekSet));
let size = cur_pos as uint - last_size_pos - 4;
- try!(write_sized_vuint(self.writer, size, 4));
- let r = try!(self.writer.seek(cur_pos as i64, old_io::SeekSet));
+
+ // relax the size encoding for small tags (bigger tags are costly to move).
+ // we should never try to move the stable positions, however.
+ const RELAX_MAX_SIZE: uint = 0x100;
+ if size <= RELAX_MAX_SIZE && last_size_pos >= self.relax_limit as uint {
+ // we can't alter the buffer in place, so have a temporary buffer
+ let mut buf = [0u8; RELAX_MAX_SIZE];
+ {
+ let data = &self.writer.get_ref()[last_size_pos+4..cur_pos as uint];
+ bytes::copy_memory(&mut buf, data);
+ }
+
+ // overwrite the size and data and continue
+ try!(write_vuint(self.writer, size));
+ try!(self.writer.write_all(&buf[..size]));
+ } else {
+ // overwrite the size with an overlong encoding and skip past the data
+ try!(write_sized_vuint(self.writer, size, 4));
+ try!(self.writer.seek(cur_pos as i64, old_io::SeekSet));
+ }
debug!("End tag (size = {:?})", size);
- Ok(r)
+ Ok(())
}
pub fn wr_tag<F>(&mut self, tag_id: uint, blk: F) -> EncodeResult where
}
pub fn wr_tagged_bytes(&mut self, tag_id: uint, b: &[u8]) -> EncodeResult {
- try!(write_vuint(self.writer, tag_id));
+ assert!(tag_id >= NUM_IMPLICIT_TAGS);
+ try!(write_tag(self.writer, tag_id));
try!(write_vuint(self.writer, b.len()));
self.writer.write_all(b)
}
self.wr_tagged_bytes(tag_id, v.as_bytes())
}
+ // for auto-serialization
+ fn wr_tagged_raw_bytes(&mut self, tag_id: uint, b: &[u8]) -> EncodeResult {
+ try!(write_tag(self.writer, tag_id));
+ self.writer.write_all(b)
+ }
+
+ fn wr_tagged_raw_u64(&mut self, tag_id: uint, v: u64) -> EncodeResult {
+ let bytes: [u8; 8] = unsafe { mem::transmute(v.to_be()) };
+ self.wr_tagged_raw_bytes(tag_id, &bytes)
+ }
+
+ fn wr_tagged_raw_u32(&mut self, tag_id: uint, v: u32) -> EncodeResult{
+ let bytes: [u8; 4] = unsafe { mem::transmute(v.to_be()) };
+ self.wr_tagged_raw_bytes(tag_id, &bytes)
+ }
+
+ fn wr_tagged_raw_u16(&mut self, tag_id: uint, v: u16) -> EncodeResult {
+ let bytes: [u8; 2] = unsafe { mem::transmute(v.to_be()) };
+ self.wr_tagged_raw_bytes(tag_id, &bytes)
+ }
+
+ fn wr_tagged_raw_u8(&mut self, tag_id: uint, v: u8) -> EncodeResult {
+ self.wr_tagged_raw_bytes(tag_id, &[v])
+ }
+
+ fn wr_tagged_raw_i64(&mut self, tag_id: uint, v: i64) -> EncodeResult {
+ self.wr_tagged_raw_u64(tag_id, v as u64)
+ }
+
+ fn wr_tagged_raw_i32(&mut self, tag_id: uint, v: i32) -> EncodeResult {
+ self.wr_tagged_raw_u32(tag_id, v as u32)
+ }
+
+ fn wr_tagged_raw_i16(&mut self, tag_id: uint, v: i16) -> EncodeResult {
+ self.wr_tagged_raw_u16(tag_id, v as u16)
+ }
+
+ fn wr_tagged_raw_i8(&mut self, tag_id: uint, v: i8) -> EncodeResult {
+ self.wr_tagged_raw_bytes(tag_id, &[v as u8])
+ }
+
pub fn wr_bytes(&mut self, b: &[u8]) -> EncodeResult {
debug!("Write {:?} bytes", b.len());
self.writer.write_all(b)
debug!("Write str: {:?}", s);
self.writer.write_all(s.as_bytes())
}
- }
-
- // FIXME (#2743): optionally perform "relaxations" on end_tag to more
- // efficiently encode sizes; this is a fixed point iteration
-
- // Set to true to generate more debugging in EBML code.
- // Totally lame approach.
- #[cfg(not(ndebug))]
- static DEBUG: bool = true;
- #[cfg(ndebug)]
- static DEBUG: bool = false;
- impl<'a, W: Writer + Seek> Encoder<'a, W> {
- // used internally to emit things like the vector length and so on
- fn _emit_tagged_uint(&mut self, t: EbmlEncoderTag, v: uint) -> EncodeResult {
- assert!(v <= 0xFFFF_FFFF);
- self.wr_tagged_u32(t as uint, v as u32)
+ /// Returns the current position while marking it stable, i.e.
+ /// generated bytes so far woundn't be affected by relaxation.
+ pub fn mark_stable_position(&mut self) -> u64 {
+ let pos = self.writer.tell().unwrap();
+ if self.relax_limit < pos {
+ self.relax_limit = pos;
+ }
+ pos
}
+ }
- fn _emit_label(&mut self, label: &str) -> EncodeResult {
- // There are various strings that we have access to, such as
- // the name of a record field, which do not actually appear in
- // the encoded EBML (normally). This is just for
- // efficiency. When debugging, though, we can emit such
- // labels and then they will be checked by decoder to
- // try and check panics more quickly.
- if DEBUG { self.wr_tagged_str(EsLabel as uint, label) }
- else { Ok(()) }
+ impl<'a> Encoder<'a> {
+ // used internally to emit things like the vector length and so on
+ fn _emit_tagged_sub(&mut self, v: uint) -> EncodeResult {
+ if let Some(v) = v.to_u8() {
+ self.wr_tagged_raw_u8(EsSub8 as uint, v)
+ } else if let Some(v) = v.to_u32() {
+ self.wr_tagged_raw_u32(EsSub32 as uint, v)
+ } else {
+ Err(old_io::IoError {
+ kind: old_io::OtherIoError,
+ desc: "length or variant id too big",
+ detail: Some(format!("{}", v))
+ })
+ }
}
pub fn emit_opaque<F>(&mut self, f: F) -> EncodeResult where
- F: FnOnce(&mut Encoder<W>) -> EncodeResult,
+ F: FnOnce(&mut Encoder) -> EncodeResult,
{
try!(self.start_tag(EsOpaque as uint));
try!(f(self));
}
}
- impl<'a, W: Writer + Seek> serialize::Encoder for Encoder<'a, W> {
+ impl<'a> serialize::Encoder for Encoder<'a> {
type Error = old_io::IoError;
fn emit_nil(&mut self) -> EncodeResult {
}
fn emit_uint(&mut self, v: uint) -> EncodeResult {
- self.wr_tagged_u64(EsUint as uint, v as u64)
+ self.emit_u64(v as u64)
}
fn emit_u64(&mut self, v: u64) -> EncodeResult {
- self.wr_tagged_u64(EsU64 as uint, v)
+ match v.to_u32() {
+ Some(v) => self.emit_u32(v),
+ None => self.wr_tagged_raw_u64(EsU64 as uint, v)
+ }
}
fn emit_u32(&mut self, v: u32) -> EncodeResult {
- self.wr_tagged_u32(EsU32 as uint, v)
+ match v.to_u16() {
+ Some(v) => self.emit_u16(v),
+ None => self.wr_tagged_raw_u32(EsU32 as uint, v)
+ }
}
fn emit_u16(&mut self, v: u16) -> EncodeResult {
- self.wr_tagged_u16(EsU16 as uint, v)
+ match v.to_u8() {
+ Some(v) => self.emit_u8(v),
+ None => self.wr_tagged_raw_u16(EsU16 as uint, v)
+ }
}
fn emit_u8(&mut self, v: u8) -> EncodeResult {
- self.wr_tagged_u8(EsU8 as uint, v)
+ self.wr_tagged_raw_u8(EsU8 as uint, v)
}
fn emit_int(&mut self, v: int) -> EncodeResult {
- self.wr_tagged_i64(EsInt as uint, v as i64)
+ self.emit_i64(v as i64)
}
fn emit_i64(&mut self, v: i64) -> EncodeResult {
- self.wr_tagged_i64(EsI64 as uint, v)
+ match v.to_i32() {
+ Some(v) => self.emit_i32(v),
+ None => self.wr_tagged_raw_i64(EsI64 as uint, v)
+ }
}
fn emit_i32(&mut self, v: i32) -> EncodeResult {
- self.wr_tagged_i32(EsI32 as uint, v)
+ match v.to_i16() {
+ Some(v) => self.emit_i16(v),
+ None => self.wr_tagged_raw_i32(EsI32 as uint, v)
+ }
}
fn emit_i16(&mut self, v: i16) -> EncodeResult {
- self.wr_tagged_i16(EsI16 as uint, v)
+ match v.to_i8() {
+ Some(v) => self.emit_i8(v),
+ None => self.wr_tagged_raw_i16(EsI16 as uint, v)
+ }
}
fn emit_i8(&mut self, v: i8) -> EncodeResult {
- self.wr_tagged_i8(EsI8 as uint, v)
+ self.wr_tagged_raw_i8(EsI8 as uint, v)
}
fn emit_bool(&mut self, v: bool) -> EncodeResult {
- self.wr_tagged_u8(EsBool as uint, v as u8)
+ self.wr_tagged_raw_u8(EsBool as uint, v as u8)
}
fn emit_f64(&mut self, v: f64) -> EncodeResult {
let bits = unsafe { mem::transmute(v) };
- self.wr_tagged_u64(EsF64 as uint, bits)
+ self.wr_tagged_raw_u64(EsF64 as uint, bits)
}
fn emit_f32(&mut self, v: f32) -> EncodeResult {
let bits = unsafe { mem::transmute(v) };
- self.wr_tagged_u32(EsF32 as uint, bits)
+ self.wr_tagged_raw_u32(EsF32 as uint, bits)
}
fn emit_char(&mut self, v: char) -> EncodeResult {
- self.wr_tagged_u32(EsChar as uint, v as u32)
+ self.wr_tagged_raw_u32(EsChar as uint, v as u32)
}
fn emit_str(&mut self, v: &str) -> EncodeResult {
self.wr_tagged_str(EsStr as uint, v)
}
- fn emit_enum<F>(&mut self, name: &str, f: F) -> EncodeResult where
- F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
+ fn emit_enum<F>(&mut self, _name: &str, f: F) -> EncodeResult where
+ F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
- try!(self._emit_label(name));
try!(self.start_tag(EsEnum as uint));
try!(f(self));
self.end_tag()
v_id: uint,
_: uint,
f: F) -> EncodeResult where
- F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
+ F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
- try!(self._emit_tagged_uint(EsEnumVid, v_id));
- try!(self.start_tag(EsEnumBody as uint));
- try!(f(self));
- self.end_tag()
+ try!(self._emit_tagged_sub(v_id));
+ f(self)
}
fn emit_enum_variant_arg<F>(&mut self, _: uint, f: F) -> EncodeResult where
- F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
+ F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
f(self)
}
v_id: uint,
cnt: uint,
f: F) -> EncodeResult where
- F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
+ F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
self.emit_enum_variant(v_name, v_id, cnt, f)
}
_: &str,
idx: uint,
f: F) -> EncodeResult where
- F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
+ F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
self.emit_enum_variant_arg(idx, f)
}
fn emit_struct<F>(&mut self, _: &str, _len: uint, f: F) -> EncodeResult where
- F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
+ F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
f(self)
}
- fn emit_struct_field<F>(&mut self, name: &str, _: uint, f: F) -> EncodeResult where
- F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
+ fn emit_struct_field<F>(&mut self, _name: &str, _: uint, f: F) -> EncodeResult where
+ F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
- try!(self._emit_label(name));
f(self)
}
fn emit_tuple<F>(&mut self, len: uint, f: F) -> EncodeResult where
- F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
+ F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
self.emit_seq(len, f)
}
fn emit_tuple_arg<F>(&mut self, idx: uint, f: F) -> EncodeResult where
- F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
+ F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
self.emit_seq_elt(idx, f)
}
fn emit_tuple_struct<F>(&mut self, _: &str, len: uint, f: F) -> EncodeResult where
- F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
+ F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
self.emit_seq(len, f)
}
fn emit_tuple_struct_arg<F>(&mut self, idx: uint, f: F) -> EncodeResult where
- F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
+ F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
self.emit_seq_elt(idx, f)
}
fn emit_option<F>(&mut self, f: F) -> EncodeResult where
- F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
+ F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
self.emit_enum("Option", f)
}
self.emit_enum_variant("None", 0, 0, |_| Ok(()))
}
fn emit_option_some<F>(&mut self, f: F) -> EncodeResult where
- F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
+ F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
self.emit_enum_variant("Some", 1, 1, f)
}
fn emit_seq<F>(&mut self, len: uint, f: F) -> EncodeResult where
- F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
+ F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
+ if len == 0 {
+ // empty vector optimization
+ return self.wr_tagged_bytes(EsVec as uint, &[]);
+ }
try!(self.start_tag(EsVec as uint));
- try!(self._emit_tagged_uint(EsVecLen, len));
+ try!(self._emit_tagged_sub(len));
try!(f(self));
self.end_tag()
}
fn emit_seq_elt<F>(&mut self, _idx: uint, f: F) -> EncodeResult where
- F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
+ F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
try!(self.start_tag(EsVecElt as uint));
}
fn emit_map<F>(&mut self, len: uint, f: F) -> EncodeResult where
- F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
+ F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
+ if len == 0 {
+ // empty map optimization
+ return self.wr_tagged_bytes(EsMap as uint, &[]);
+ }
try!(self.start_tag(EsMap as uint));
- try!(self._emit_tagged_uint(EsMapLen, len));
+ try!(self._emit_tagged_sub(len));
try!(f(self));
self.end_tag()
}
fn emit_map_elt_key<F>(&mut self, _idx: uint, f: F) -> EncodeResult where
- F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
+ F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
try!(self.start_tag(EsMapKey as uint));
}
fn emit_map_elt_val<F>(&mut self, _idx: uint, f: F) -> EncodeResult where
- F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
+ F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
try!(self.start_tag(EsMapVal as uint));
try!(f(self));
})
}
- // FIXME(#10894) should continue recursing
fn visit_ty(&mut self, t: &ast::Ty) {
run_lints!(self, check_ty, t);
+ visit::walk_ty(self, t);
}
fn visit_ident(&mut self, sp: Span, id: ast::Ident) {
}
fn visit_trait_item(&mut self, m: &ast::TraitItem) {
- run_lints!(self, check_trait_method, m);
+ run_lints!(self, check_trait_item, m);
visit::walk_trait_item(self, m);
}
fn check_fn(&mut self, _: &Context,
_: FnKind, _: &ast::FnDecl, _: &ast::Block, _: Span, _: ast::NodeId) { }
fn check_ty_method(&mut self, _: &Context, _: &ast::TypeMethod) { }
- fn check_trait_method(&mut self, _: &Context, _: &ast::TraitItem) { }
+ fn check_trait_item(&mut self, _: &Context, _: &ast::TraitItem) { }
fn check_struct_def(&mut self, _: &Context,
_: &ast::StructDef, _: ast::Ident, _: &ast::Generics, _: ast::NodeId) { }
fn check_struct_def_post(&mut self, _: &Context,
-// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
+// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
use back::svh::Svh;
-// EBML enum definitions and utils shared by the encoder and decoder
+// RBML enum definitions and utils shared by the encoder and decoder
+//
+// 0x00..0x1f: reserved for RBML generic type tags
+// 0x20..0xef: free for use, preferred for frequent tags
+// 0xf0..0xff: internally used by RBML to encode 0x100..0xfff in two bytes
+// 0x100..0xfff: free for use, preferred for infrequent tags
-pub const tag_items: uint = 0x00;
+pub const tag_items: uint = 0x100; // top-level only
-pub const tag_paths_data_name: uint = 0x01;
+pub const tag_paths_data_name: uint = 0x20;
-pub const tag_def_id: uint = 0x02;
+pub const tag_def_id: uint = 0x21;
-pub const tag_items_data: uint = 0x03;
+pub const tag_items_data: uint = 0x22;
-pub const tag_items_data_item: uint = 0x04;
+pub const tag_items_data_item: uint = 0x23;
-pub const tag_items_data_item_family: uint = 0x05;
+pub const tag_items_data_item_family: uint = 0x24;
-pub const tag_items_data_item_type: uint = 0x07;
+pub const tag_items_data_item_type: uint = 0x25;
-pub const tag_items_data_item_symbol: uint = 0x08;
+pub const tag_items_data_item_symbol: uint = 0x26;
-pub const tag_items_data_item_variant: uint = 0x09;
+pub const tag_items_data_item_variant: uint = 0x27;
-pub const tag_items_data_parent_item: uint = 0x0a;
+pub const tag_items_data_parent_item: uint = 0x28;
-pub const tag_items_data_item_is_tuple_struct_ctor: uint = 0x0b;
+pub const tag_items_data_item_is_tuple_struct_ctor: uint = 0x29;
-pub const tag_index: uint = 0x0c;
+pub const tag_index: uint = 0x2a;
-pub const tag_index_buckets: uint = 0x0d;
+pub const tag_index_buckets: uint = 0x2b;
-pub const tag_index_buckets_bucket: uint = 0x0e;
+pub const tag_index_buckets_bucket: uint = 0x2c;
-pub const tag_index_buckets_bucket_elt: uint = 0x0f;
+pub const tag_index_buckets_bucket_elt: uint = 0x2d;
-pub const tag_index_table: uint = 0x10;
+pub const tag_index_table: uint = 0x2e;
-pub const tag_meta_item_name_value: uint = 0x11;
+pub const tag_meta_item_name_value: uint = 0x2f;
-pub const tag_meta_item_name: uint = 0x12;
+pub const tag_meta_item_name: uint = 0x30;
-pub const tag_meta_item_value: uint = 0x13;
+pub const tag_meta_item_value: uint = 0x31;
-pub const tag_attributes: uint = 0x14;
+pub const tag_attributes: uint = 0x101; // top-level only
-pub const tag_attribute: uint = 0x15;
+pub const tag_attribute: uint = 0x32;
-pub const tag_meta_item_word: uint = 0x16;
+pub const tag_meta_item_word: uint = 0x33;
-pub const tag_meta_item_list: uint = 0x17;
+pub const tag_meta_item_list: uint = 0x34;
// The list of crates that this crate depends on
-pub const tag_crate_deps: uint = 0x18;
+pub const tag_crate_deps: uint = 0x102; // top-level only
// A single crate dependency
-pub const tag_crate_dep: uint = 0x19;
+pub const tag_crate_dep: uint = 0x35;
-pub const tag_crate_hash: uint = 0x1a;
-pub const tag_crate_crate_name: uint = 0x1b;
+pub const tag_crate_hash: uint = 0x103; // top-level only
+pub const tag_crate_crate_name: uint = 0x104; // top-level only
-pub const tag_crate_dep_crate_name: uint = 0x1d;
-pub const tag_crate_dep_hash: uint = 0x1e;
+pub const tag_crate_dep_crate_name: uint = 0x36;
+pub const tag_crate_dep_hash: uint = 0x37;
-pub const tag_mod_impl: uint = 0x1f;
+pub const tag_mod_impl: uint = 0x38;
-pub const tag_item_trait_item: uint = 0x20;
+pub const tag_item_trait_item: uint = 0x39;
-pub const tag_item_trait_ref: uint = 0x21;
-pub const tag_item_super_trait_ref: uint = 0x22;
+pub const tag_item_trait_ref: uint = 0x3a;
+pub const tag_item_super_trait_ref: uint = 0x3b;
// discriminator value for variants
-pub const tag_disr_val: uint = 0x23;
+pub const tag_disr_val: uint = 0x3c;
// used to encode ast_map::PathElem
-pub const tag_path: uint = 0x24;
-pub const tag_path_len: uint = 0x25;
-pub const tag_path_elem_mod: uint = 0x26;
-pub const tag_path_elem_name: uint = 0x27;
-pub const tag_item_field: uint = 0x28;
-pub const tag_item_field_origin: uint = 0x29;
-
-pub const tag_item_variances: uint = 0x2a;
+pub const tag_path: uint = 0x3d;
+pub const tag_path_len: uint = 0x3e;
+pub const tag_path_elem_mod: uint = 0x3f;
+pub const tag_path_elem_name: uint = 0x40;
+pub const tag_item_field: uint = 0x41;
+pub const tag_item_field_origin: uint = 0x42;
+
+pub const tag_item_variances: uint = 0x43;
/*
trait items contain tag_item_trait_item elements,
impl items contain tag_item_impl_item elements, and classes
both, tag_item_trait_item and tag_item_impl_item have to be two
different tags.
*/
-pub const tag_item_impl_item: uint = 0x30;
-pub const tag_item_trait_method_explicit_self: uint = 0x31;
+pub const tag_item_impl_item: uint = 0x44;
+pub const tag_item_trait_method_explicit_self: uint = 0x45;
// Reexports are found within module tags. Each reexport contains def_ids
// and names.
-pub const tag_items_data_item_reexport: uint = 0x38;
-pub const tag_items_data_item_reexport_def_id: uint = 0x39;
-pub const tag_items_data_item_reexport_name: uint = 0x3a;
+pub const tag_items_data_item_reexport: uint = 0x46;
+pub const tag_items_data_item_reexport_def_id: uint = 0x47;
+pub const tag_items_data_item_reexport_name: uint = 0x48;
// used to encode crate_ctxt side tables
#[derive(Copy, PartialEq, FromPrimitive)]
#[repr(uint)]
-pub enum astencode_tag { // Reserves 0x40 -- 0x5f
- tag_ast = 0x40,
-
- tag_tree = 0x41,
-
- tag_id_range = 0x42,
-
- tag_table = 0x43,
- tag_table_id = 0x44,
- tag_table_val = 0x45,
- tag_table_def = 0x46,
- tag_table_node_type = 0x47,
- tag_table_item_subst = 0x48,
- tag_table_freevars = 0x49,
- tag_table_tcache = 0x4a,
- tag_table_param_defs = 0x4b,
- tag_table_mutbl = 0x4c,
- tag_table_last_use = 0x4d,
- tag_table_spill = 0x4e,
- tag_table_method_map = 0x4f,
- tag_table_vtable_map = 0x50,
- tag_table_adjustments = 0x51,
- tag_table_moves_map = 0x52,
- tag_table_capture_map = 0x53,
- tag_table_closure_tys = 0x54,
- tag_table_closure_kinds = 0x55,
- tag_table_upvar_capture_map = 0x56,
- tag_table_capture_modes = 0x57,
- tag_table_object_cast_map = 0x58,
- tag_table_const_qualif = 0x59,
+pub enum astencode_tag { // Reserves 0x50 -- 0x6f
+ tag_ast = 0x50,
+
+ tag_tree = 0x51,
+
+ tag_id_range = 0x52,
+
+ tag_table = 0x53,
+ // GAP 0x54, 0x55
+ tag_table_def = 0x56,
+ tag_table_node_type = 0x57,
+ tag_table_item_subst = 0x58,
+ tag_table_freevars = 0x59,
+ tag_table_tcache = 0x5a,
+ tag_table_param_defs = 0x5b,
+ tag_table_mutbl = 0x5c,
+ tag_table_last_use = 0x5d,
+ tag_table_spill = 0x5e,
+ tag_table_method_map = 0x5f,
+ tag_table_vtable_map = 0x60,
+ tag_table_adjustments = 0x61,
+ tag_table_moves_map = 0x62,
+ tag_table_capture_map = 0x63,
+ tag_table_closure_tys = 0x64,
+ tag_table_closure_kinds = 0x65,
+ tag_table_upvar_capture_map = 0x66,
+ tag_table_capture_modes = 0x67,
+ tag_table_object_cast_map = 0x68,
+ tag_table_const_qualif = 0x69,
}
-pub const tag_item_trait_item_sort: uint = 0x60;
+pub const tag_item_trait_item_sort: uint = 0x70;
-pub const tag_item_trait_parent_sort: uint = 0x61;
+pub const tag_item_trait_parent_sort: uint = 0x71;
-pub const tag_item_impl_type_basename: uint = 0x62;
+pub const tag_item_impl_type_basename: uint = 0x72;
-pub const tag_crate_triple: uint = 0x66;
+pub const tag_crate_triple: uint = 0x105; // top-level only
-pub const tag_dylib_dependency_formats: uint = 0x67;
+pub const tag_dylib_dependency_formats: uint = 0x106; // top-level only
// Language items are a top-level directory (for speed). Hierarchy:
//
// - tag_lang_items_item_id: u32
// - tag_lang_items_item_node_id: u32
-pub const tag_lang_items: uint = 0x70;
-pub const tag_lang_items_item: uint = 0x71;
-pub const tag_lang_items_item_id: uint = 0x72;
-pub const tag_lang_items_item_node_id: uint = 0x73;
-pub const tag_lang_items_missing: uint = 0x74;
+pub const tag_lang_items: uint = 0x107; // top-level only
+pub const tag_lang_items_item: uint = 0x73;
+pub const tag_lang_items_item_id: uint = 0x74;
+pub const tag_lang_items_item_node_id: uint = 0x75;
+pub const tag_lang_items_missing: uint = 0x76;
-pub const tag_item_unnamed_field: uint = 0x75;
-pub const tag_items_data_item_visibility: uint = 0x76;
+pub const tag_item_unnamed_field: uint = 0x77;
+pub const tag_items_data_item_visibility: uint = 0x78;
pub const tag_item_method_tps: uint = 0x79;
pub const tag_item_method_fty: uint = 0x7a;
pub const tag_mod_child: uint = 0x7b;
-pub const tag_misc_info: uint = 0x7c;
-pub const tag_misc_info_crate_items: uint = 0x7d;
-
-pub const tag_item_method_provided_source: uint = 0x7e;
-pub const tag_item_impl_vtables: uint = 0x7f;
+pub const tag_misc_info: uint = 0x108; // top-level only
+pub const tag_misc_info_crate_items: uint = 0x7c;
-pub const tag_impls: uint = 0x80;
-pub const tag_impls_impl: uint = 0x81;
+pub const tag_item_method_provided_source: uint = 0x7d;
+pub const tag_item_impl_vtables: uint = 0x7e;
-pub const tag_items_data_item_inherent_impl: uint = 0x82;
-pub const tag_items_data_item_extension_impl: uint = 0x83;
+pub const tag_impls: uint = 0x109; // top-level only
+pub const tag_impls_impl: uint = 0x7f;
-// GAP 0x84, 0x85, 0x86
+pub const tag_items_data_item_inherent_impl: uint = 0x80;
+pub const tag_items_data_item_extension_impl: uint = 0x81;
-pub const tag_native_libraries: uint = 0x87;
-pub const tag_native_libraries_lib: uint = 0x88;
-pub const tag_native_libraries_name: uint = 0x89;
-pub const tag_native_libraries_kind: uint = 0x8a;
+pub const tag_native_libraries: uint = 0x10a; // top-level only
+pub const tag_native_libraries_lib: uint = 0x82;
+pub const tag_native_libraries_name: uint = 0x83;
+pub const tag_native_libraries_kind: uint = 0x84;
-pub const tag_plugin_registrar_fn: uint = 0x8b;
+pub const tag_plugin_registrar_fn: uint = 0x10b; // top-level only
-// GAP 0x8c, 0x8d
+pub const tag_method_argument_names: uint = 0x85;
+pub const tag_method_argument_name: uint = 0x86;
-pub const tag_method_argument_names: uint = 0x8e;
-pub const tag_method_argument_name: uint = 0x8f;
+pub const tag_reachable_extern_fns: uint = 0x10c; // top-level only
+pub const tag_reachable_extern_fn_id: uint = 0x87;
-pub const tag_reachable_extern_fns: uint = 0x90;
-pub const tag_reachable_extern_fn_id: uint = 0x91;
+pub const tag_items_data_item_stability: uint = 0x88;
-pub const tag_items_data_item_stability: uint = 0x92;
-
-pub const tag_items_data_item_repr: uint = 0x93;
+pub const tag_items_data_item_repr: uint = 0x89;
#[derive(Clone, Debug)]
pub struct LinkMeta {
pub crate_hash: Svh,
}
-// GAP 0x94...0x98
-
-pub const tag_struct_fields: uint = 0x99;
-pub const tag_struct_field: uint = 0x9a;
-pub const tag_struct_field_id: uint = 0x9b;
+pub const tag_struct_fields: uint = 0x10d; // top-level only
+pub const tag_struct_field: uint = 0x8a;
+pub const tag_struct_field_id: uint = 0x8b;
-pub const tag_attribute_is_sugared_doc: uint = 0x9c;
+pub const tag_attribute_is_sugared_doc: uint = 0x8c;
-pub const tag_trait_def_bounds: uint = 0x9d;
+pub const tag_trait_def_bounds: uint = 0x8d;
-pub const tag_items_data_region: uint = 0x9e;
+pub const tag_items_data_region: uint = 0x8e;
-pub const tag_region_param_def: uint = 0xa0;
-pub const tag_region_param_def_ident: uint = 0xa1;
-pub const tag_region_param_def_def_id: uint = 0xa2;
-pub const tag_region_param_def_space: uint = 0xa3;
-pub const tag_region_param_def_index: uint = 0xa4;
+pub const tag_region_param_def: uint = 0x8f;
+pub const tag_region_param_def_ident: uint = 0x90;
+pub const tag_region_param_def_def_id: uint = 0x91;
+pub const tag_region_param_def_space: uint = 0x92;
+pub const tag_region_param_def_index: uint = 0x93;
-pub const tag_type_param_def: uint = 0xa5;
+pub const tag_type_param_def: uint = 0x94;
-pub const tag_item_generics: uint = 0xa6;
-pub const tag_method_ty_generics: uint = 0xa7;
+pub const tag_item_generics: uint = 0x95;
+pub const tag_method_ty_generics: uint = 0x96;
-pub const tag_predicate: uint = 0xa8;
-pub const tag_predicate_space: uint = 0xa9;
-pub const tag_predicate_data: uint = 0xb0;
+pub const tag_predicate: uint = 0x97;
+pub const tag_predicate_space: uint = 0x98;
+pub const tag_predicate_data: uint = 0x99;
-pub const tag_unsafety: uint = 0xb1;
+pub const tag_unsafety: uint = 0x9a;
-pub const tag_associated_type_names: uint = 0xb2;
-pub const tag_associated_type_name: uint = 0xb3;
+pub const tag_associated_type_names: uint = 0x9b;
+pub const tag_associated_type_name: uint = 0x9c;
-pub const tag_polarity: uint = 0xb4;
+pub const tag_polarity: uint = 0x9d;
-pub const tag_macro_defs: uint = 0xb5;
-pub const tag_macro_def: uint = 0xb6;
-pub const tag_macro_def_body: uint = 0xb7;
+pub const tag_macro_defs: uint = 0x10e; // top-level only
+pub const tag_macro_def: uint = 0x9e;
+pub const tag_macro_def_body: uint = 0x9f;
-pub const tag_paren_sugar: uint = 0xb8;
+pub const tag_paren_sugar: uint = 0xa0;
-// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
+// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
use syntax::visit::Visitor;
use syntax::visit;
use syntax;
-use rbml::writer;
+use rbml::writer::Encoder;
use rbml::io::SeekableMemWriter;
/// A borrowed version of `ast::InlinedItem`.
IIForeignRef(&'a ast::ForeignItem)
}
-pub type Encoder<'a> = writer::Encoder<'a, SeekableMemWriter>;
-
pub type EncodeInlinedItem<'a> =
Box<FnMut(&EncodeContext, &mut Encoder, InlinedItemRef) + 'a>;
};
rbml_w.start_tag(tag);
- tyencode::enc_trait_ref(rbml_w.writer, ty_str_ctxt, trait_ref);
+ tyencode::enc_trait_ref(rbml_w, ty_str_ctxt, trait_ref);
rbml_w.end_tag();
}
// Item info table encoding
fn encode_family(rbml_w: &mut Encoder, c: char) {
- rbml_w.start_tag(tag_items_data_item_family);
- rbml_w.writer.write_all(&[c as u8]);
- rbml_w.end_tag();
+ rbml_w.wr_tagged_u8(tag_items_data_item_family, c as u8);
}
pub fn def_to_string(did: DefId) -> String {
}
fn encode_variant_id(rbml_w: &mut Encoder, vid: DefId) {
- rbml_w.start_tag(tag_items_data_item_variant);
let s = def_to_string(vid);
- rbml_w.writer.write_all(s.as_bytes());
- rbml_w.end_tag();
-
- rbml_w.start_tag(tag_mod_child);
- rbml_w.wr_str(&s[..]);
- rbml_w.end_tag();
+ rbml_w.wr_tagged_str(tag_items_data_item_variant, &s[..]);
+ rbml_w.wr_tagged_str(tag_mod_child, &s[..]);
}
pub fn write_closure_type<'a, 'tcx>(ecx: &EncodeContext<'a, 'tcx>,
tcx: ecx.tcx,
abbrevs: &ecx.type_abbrevs
};
- tyencode::enc_closure_ty(rbml_w.writer, ty_str_ctxt, closure_type);
+ tyencode::enc_closure_ty(rbml_w, ty_str_ctxt, closure_type);
}
pub fn write_type<'a, 'tcx>(ecx: &EncodeContext<'a, 'tcx>,
tcx: ecx.tcx,
abbrevs: &ecx.type_abbrevs
};
- tyencode::enc_ty(rbml_w.writer, ty_str_ctxt, typ);
+ tyencode::enc_ty(rbml_w, ty_str_ctxt, typ);
}
pub fn write_trait_ref<'a, 'tcx>(ecx: &EncodeContext<'a, 'tcx>,
tcx: ecx.tcx,
abbrevs: &ecx.type_abbrevs
};
- tyencode::enc_trait_ref(rbml_w.writer, ty_str_ctxt, trait_ref);
+ tyencode::enc_trait_ref(rbml_w, ty_str_ctxt, trait_ref);
}
pub fn write_region(ecx: &EncodeContext,
tcx: ecx.tcx,
abbrevs: &ecx.type_abbrevs
};
- tyencode::enc_region(rbml_w.writer, ty_str_ctxt, r);
+ tyencode::enc_region(rbml_w, ty_str_ctxt, r);
}
fn encode_bounds<'a, 'tcx>(rbml_w: &mut Encoder,
ds: def_to_string,
tcx: ecx.tcx,
abbrevs: &ecx.type_abbrevs };
- tyencode::enc_bounds(rbml_w.writer, ty_str_ctxt, bounds);
+ tyencode::enc_bounds(rbml_w, ty_str_ctxt, bounds);
rbml_w.end_tag();
}
tcx: ecx.tcx,
abbrevs: &ecx.type_abbrevs
};
- tyencode::enc_bare_fn_ty(rbml_w.writer, ty_str_ctxt, typ);
+ tyencode::enc_bare_fn_ty(rbml_w, ty_str_ctxt, typ);
rbml_w.end_tag();
}
fn encode_symbol(ecx: &EncodeContext,
rbml_w: &mut Encoder,
id: NodeId) {
- rbml_w.start_tag(tag_items_data_item_symbol);
match ecx.item_symbols.borrow().get(&id) {
Some(x) => {
debug!("encode_symbol(id={}, str={})", id, *x);
- rbml_w.writer.write_all(x.as_bytes());
+ rbml_w.wr_tagged_str(tag_items_data_item_symbol, x);
}
None => {
ecx.diag.handler().bug(
&format!("encode_symbol: id not found {}", id));
}
}
- rbml_w.end_tag();
}
fn encode_disr_val(_: &EncodeContext,
rbml_w: &mut Encoder,
disr_val: ty::Disr) {
- rbml_w.start_tag(tag_disr_val);
- let s = disr_val.to_string();
- rbml_w.writer.write_all(s.as_bytes());
- rbml_w.end_tag();
+ rbml_w.wr_tagged_str(tag_disr_val, &disr_val.to_string());
}
fn encode_parent_item(rbml_w: &mut Encoder, id: DefId) {
- rbml_w.start_tag(tag_items_data_parent_item);
- let s = def_to_string(id);
- rbml_w.writer.write_all(s.as_bytes());
- rbml_w.end_tag();
+ rbml_w.wr_tagged_str(tag_items_data_parent_item, &def_to_string(id));
}
fn encode_struct_fields(rbml_w: &mut Encoder,
}
encode_struct_field_family(rbml_w, f.vis);
encode_def_id(rbml_w, f.id);
- rbml_w.start_tag(tag_item_field_origin);
- let s = def_to_string(origin);
- rbml_w.writer.write_all(s.as_bytes());
- rbml_w.end_tag();
+ rbml_w.wr_tagged_str(tag_item_field_origin, &def_to_string(origin));
rbml_w.end_tag();
}
}
let def_id = local_def(variant.node.id);
index.push(entry {
val: variant.node.id as i64,
- pos: rbml_w.writer.tell().unwrap(),
+ pos: rbml_w.mark_stable_position(),
});
rbml_w.start_tag(tag_items_data_item);
encode_def_id(rbml_w, def_id);
debug!("(encode reexported static method) {}::{}",
exp.name, token::get_name(method_name));
rbml_w.start_tag(tag_items_data_item_reexport);
- rbml_w.start_tag(tag_items_data_item_reexport_def_id);
- rbml_w.wr_str(&def_to_string(method_def_id));
- rbml_w.end_tag();
- rbml_w.start_tag(tag_items_data_item_reexport_name);
- rbml_w.wr_str(&format!("{}::{}",
- exp.name,
- token::get_name(method_name)));
- rbml_w.end_tag();
+ rbml_w.wr_tagged_str(tag_items_data_item_reexport_def_id,
+ &def_to_string(method_def_id));
+ rbml_w.wr_tagged_str(tag_items_data_item_reexport_name,
+ &format!("{}::{}", exp.name,
+ token::get_name(method_name)));
rbml_w.end_tag();
}
exp.def_id.node,
id);
rbml_w.start_tag(tag_items_data_item_reexport);
- rbml_w.start_tag(tag_items_data_item_reexport_def_id);
- rbml_w.wr_str(&def_to_string(exp.def_id));
- rbml_w.end_tag();
- rbml_w.start_tag(tag_items_data_item_reexport_name);
- rbml_w.wr_str(exp.name.as_str());
- rbml_w.end_tag();
+ rbml_w.wr_tagged_str(tag_items_data_item_reexport_def_id,
+ &def_to_string(exp.def_id));
+ rbml_w.wr_tagged_str(tag_items_data_item_reexport_name,
+ exp.name.as_str());
rbml_w.end_tag();
encode_reexported_static_methods(ecx, rbml_w, path.clone(), exp);
}
// Encode info about all the module children.
for item in &md.items {
- rbml_w.start_tag(tag_mod_child);
- rbml_w.wr_str(&def_to_string(local_def(item.id)));
- rbml_w.end_tag();
+ rbml_w.wr_tagged_str(tag_mod_child,
+ &def_to_string(local_def(item.id)));
each_auxiliary_node_id(&**item, |auxiliary_node_id| {
- rbml_w.start_tag(tag_mod_child);
- rbml_w.wr_str(&def_to_string(local_def(
- auxiliary_node_id)));
- rbml_w.end_tag();
+ rbml_w.wr_tagged_str(tag_mod_child,
+ &def_to_string(local_def(auxiliary_node_id)));
true
});
token::get_ident(ident),
did, ecx.tcx.map.node_to_string(did));
- rbml_w.start_tag(tag_mod_impl);
- rbml_w.wr_str(&def_to_string(local_def(did)));
- rbml_w.end_tag();
+ rbml_w.wr_tagged_str(tag_mod_impl,
+ &def_to_string(local_def(did)));
}
}
}
fn encode_visibility(rbml_w: &mut Encoder, visibility: ast::Visibility) {
- rbml_w.start_tag(tag_items_data_item_visibility);
let ch = match visibility {
ast::Public => 'y',
ast::Inherited => 'i',
};
- rbml_w.wr_str(&ch.to_string());
- rbml_w.end_tag();
+ rbml_w.wr_tagged_u8(tag_items_data_item_visibility, ch as u8);
}
fn encode_explicit_self(rbml_w: &mut Encoder,
explicit_self: &ty::ExplicitSelfCategory) {
- rbml_w.start_tag(tag_item_trait_method_explicit_self);
+ let tag = tag_item_trait_method_explicit_self;
// Encode the base self type.
match *explicit_self {
ty::StaticExplicitSelfCategory => {
- rbml_w.writer.write_all(&[ 's' as u8 ]);
+ rbml_w.wr_tagged_bytes(tag, &['s' as u8]);
}
ty::ByValueExplicitSelfCategory => {
- rbml_w.writer.write_all(&[ 'v' as u8 ]);
+ rbml_w.wr_tagged_bytes(tag, &['v' as u8]);
}
ty::ByBoxExplicitSelfCategory => {
- rbml_w.writer.write_all(&[ '~' as u8 ]);
+ rbml_w.wr_tagged_bytes(tag, &['~' as u8]);
}
ty::ByReferenceExplicitSelfCategory(_, m) => {
// FIXME(#4846) encode custom lifetime
- rbml_w.writer.write_all(&['&' as u8]);
- encode_mutability(rbml_w, m);
+ let ch = encode_mutability(m);
+ rbml_w.wr_tagged_bytes(tag, &['&' as u8, ch]);
}
}
- rbml_w.end_tag();
-
- fn encode_mutability(rbml_w: &mut Encoder,
- m: ast::Mutability) {
+ fn encode_mutability(m: ast::Mutability) -> u8 {
match m {
- ast::MutImmutable => { rbml_w.writer.write_all(&[ 'i' as u8 ]); }
- ast::MutMutable => { rbml_w.writer.write_all(&[ 'm' as u8 ]); }
+ ast::MutImmutable => 'i' as u8,
+ ast::MutMutable => 'm' as u8,
}
}
}
fn encode_item_sort(rbml_w: &mut Encoder, sort: char) {
- rbml_w.start_tag(tag_item_trait_item_sort);
- rbml_w.writer.write_all(&[ sort as u8 ]);
- rbml_w.end_tag();
+ rbml_w.wr_tagged_u8(tag_item_trait_item_sort, sort as u8);
}
fn encode_parent_sort(rbml_w: &mut Encoder, sort: char) {
- rbml_w.start_tag(tag_item_trait_parent_sort);
- rbml_w.writer.write_all(&[ sort as u8 ]);
- rbml_w.end_tag();
+ rbml_w.wr_tagged_u8(tag_item_trait_parent_sort, sort as u8);
}
fn encode_provided_source(rbml_w: &mut Encoder,
source_opt: Option<DefId>) {
if let Some(source) = source_opt {
- rbml_w.start_tag(tag_item_method_provided_source);
- let s = def_to_string(source);
- rbml_w.writer.write_all(s.as_bytes());
- rbml_w.end_tag();
+ rbml_w.wr_tagged_str(tag_item_method_provided_source,
+ &def_to_string(source));
}
}
let nm = field.name;
let id = field.id.node;
- index.push(entry {val: id as i64, pos: rbml_w.writer.tell().unwrap()});
+ let pos = rbml_w.mark_stable_position();
+ index.push(entry {val: id as i64, pos: pos});
global_index.push(entry {
val: id as i64,
- pos: rbml_w.writer.tell().unwrap(),
+ pos: pos,
});
rbml_w.start_tag(tag_items_data_item);
debug!("encode_info_for_struct: doing {} {}",
struct_id: NodeId) {
index.push(entry {
val: ctor_id as i64,
- pos: rbml_w.writer.tell().unwrap(),
+ pos: rbml_w.mark_stable_position(),
});
rbml_w.start_tag(tag_items_data_item);
// indicate that this is a tuple struct ctor, because downstream users will normally want
// the tuple struct definition, but without this there is no way for them to tell that
// they actually have a ctor rather than a normal function
- rbml_w.start_tag(tag_items_data_item_is_tuple_struct_ctor);
- rbml_w.end_tag();
+ rbml_w.wr_tagged_bytes(tag_items_data_item_is_tuple_struct_ctor, &[]);
rbml_w.end_tag();
}
};
for param in generics.types.iter() {
rbml_w.start_tag(tag_type_param_def);
- tyencode::enc_type_param_def(rbml_w.writer, ty_str_ctxt, param);
+ tyencode::enc_type_param_def(rbml_w, ty_str_ctxt, param);
rbml_w.end_tag();
}
rbml_w.wr_tagged_u8(tag_predicate_space, space as u8);
rbml_w.start_tag(tag_predicate_data);
- tyencode::enc_predicate(rbml_w.writer, ty_str_ctxt, predicate);
+ tyencode::enc_predicate(rbml_w, ty_str_ctxt, predicate);
rbml_w.end_tag();
rbml_w.end_tag();
decl: &ast::FnDecl) {
rbml_w.start_tag(tag_method_argument_names);
for arg in &decl.inputs {
- rbml_w.start_tag(tag_method_argument_name);
+ let tag = tag_method_argument_name;
if let ast::PatIdent(_, ref path1, _) = arg.pat.node {
let name = token::get_ident(path1.node);
- rbml_w.writer.write_all(name.as_bytes());
+ rbml_w.wr_tagged_bytes(tag, name.as_bytes());
+ } else {
+ rbml_w.wr_tagged_bytes(tag, &[]);
}
- rbml_w.end_tag();
}
rbml_w.end_tag();
}
vis: ast::Visibility) {
let tcx = ecx.tcx;
- fn add_to_index(item: &ast::Item, rbml_w: &Encoder,
+ fn add_to_index(item: &ast::Item, rbml_w: &mut Encoder,
index: &mut Vec<entry<i64>>) {
index.push(entry {
val: item.id as i64,
- pos: rbml_w.writer.tell().unwrap(),
+ pos: rbml_w.mark_stable_position(),
});
}
// Encode all the items in this module.
for foreign_item in &fm.items {
- rbml_w.start_tag(tag_mod_child);
- rbml_w.wr_str(&def_to_string(local_def(foreign_item.id)));
- rbml_w.end_tag();
+ rbml_w.wr_tagged_str(tag_mod_child,
+ &def_to_string(local_def(foreign_item.id)));
}
encode_visibility(rbml_w, vis);
encode_stability(rbml_w, stab);
index.push(entry {
val: trait_item_def_id.def_id().node as i64,
- pos: rbml_w.writer.tell().unwrap(),
+ pos: rbml_w.mark_stable_position(),
});
let trait_item_type =
}
rbml_w.end_tag();
- rbml_w.start_tag(tag_mod_child);
- rbml_w.wr_str(&def_to_string(method_def_id.def_id()));
- rbml_w.end_tag();
+ rbml_w.wr_tagged_str(tag_mod_child,
+ &def_to_string(method_def_id.def_id()));
}
encode_path(rbml_w, path.clone());
index.push(entry {
val: item_def_id.def_id().node as i64,
- pos: rbml_w.writer.tell().unwrap(),
+ pos: rbml_w.mark_stable_position(),
});
rbml_w.start_tag(tag_items_data_item);
abi: abi::Abi) {
index.push(entry {
val: nitem.id as i64,
- pos: rbml_w.writer.tell().unwrap(),
+ pos: rbml_w.mark_stable_position(),
});
rbml_w.start_tag(tag_items_data_item);
rbml_w.start_tag(tag_items_data);
index.push(entry {
val: ast::CRATE_NODE_ID as i64,
- pos: rbml_w.writer.tell().unwrap(),
+ pos: rbml_w.mark_stable_position(),
});
encode_info_for_mod(ecx,
rbml_w,
let mut bucket_locs = Vec::new();
rbml_w.start_tag(tag_index_buckets);
for bucket in &buckets {
- bucket_locs.push(rbml_w.writer.tell().unwrap());
+ bucket_locs.push(rbml_w.mark_stable_position());
rbml_w.start_tag(tag_index_buckets_bucket);
for elt in bucket {
rbml_w.start_tag(tag_index_buckets_bucket_elt);
match mi.node {
ast::MetaWord(ref name) => {
rbml_w.start_tag(tag_meta_item_word);
- rbml_w.start_tag(tag_meta_item_name);
- rbml_w.writer.write_all(name.as_bytes());
- rbml_w.end_tag();
+ rbml_w.wr_tagged_str(tag_meta_item_name, name);
rbml_w.end_tag();
}
ast::MetaNameValue(ref name, ref value) => {
match value.node {
ast::LitStr(ref value, _) => {
rbml_w.start_tag(tag_meta_item_name_value);
- rbml_w.start_tag(tag_meta_item_name);
- rbml_w.writer.write_all(name.as_bytes());
- rbml_w.end_tag();
- rbml_w.start_tag(tag_meta_item_value);
- rbml_w.writer.write_all(value.as_bytes());
- rbml_w.end_tag();
+ rbml_w.wr_tagged_str(tag_meta_item_name, name);
+ rbml_w.wr_tagged_str(tag_meta_item_value, value);
rbml_w.end_tag();
}
_ => {/* FIXME (#623): encode other variants */ }
}
ast::MetaList(ref name, ref items) => {
rbml_w.start_tag(tag_meta_item_list);
- rbml_w.start_tag(tag_meta_item_name);
- rbml_w.writer.write_all(name.as_bytes());
- rbml_w.end_tag();
+ rbml_w.wr_tagged_str(tag_meta_item_name, name);
for inner_item in items {
encode_meta_item(rbml_w, &**inner_item);
}
if let Some(id) = def_id {
if id.krate == ast::LOCAL_CRATE {
rbml_w.start_tag(tag_lang_items_item);
-
- rbml_w.start_tag(tag_lang_items_item_id);
- {
- let wr: &mut SeekableMemWriter = rbml_w.writer;
- wr.write_be_u32(i as u32);
- }
- rbml_w.end_tag(); // tag_lang_items_item_id
-
- rbml_w.start_tag(tag_lang_items_item_node_id);
- {
- let wr: &mut SeekableMemWriter = rbml_w.writer;
- wr.write_be_u32(id.node as u32);
- }
- rbml_w.end_tag(); // tag_lang_items_item_node_id
-
- rbml_w.end_tag(); // tag_lang_items_item
+ rbml_w.wr_tagged_u32(tag_lang_items_item_id, i as u32);
+ rbml_w.wr_tagged_u32(tag_lang_items_item_node_id, id.node as u32);
+ rbml_w.end_tag();
}
}
}
cstore::NativeStatic => {} // these libraries are not propagated
cstore::NativeFramework | cstore::NativeUnknown => {
rbml_w.start_tag(tag_native_libraries_lib);
-
- rbml_w.start_tag(tag_native_libraries_kind);
- rbml_w.writer.write_be_u32(kind as u32);
- rbml_w.end_tag();
-
- rbml_w.start_tag(tag_native_libraries_name);
- rbml_w.writer.write_all(lib.as_bytes());
- rbml_w.end_tag();
-
+ rbml_w.wr_tagged_u32(tag_native_libraries_kind, kind as u32);
+ rbml_w.wr_tagged_str(tag_native_libraries_name, lib);
rbml_w.end_tag();
}
}
encode_name(rbml_w, def.ident.name);
encode_attributes(rbml_w, &def.attrs);
- rbml_w.start_tag(tag_macro_def_body);
- rbml_w.wr_str(&pprust::tts_to_string(&def.body));
- rbml_w.end_tag();
+ rbml_w.wr_tagged_str(tag_macro_def_body,
+ &pprust::tts_to_string(&def.body));
rbml_w.end_tag();
}
rbml_w.start_tag(tag_misc_info);
rbml_w.start_tag(tag_misc_info_crate_items);
for item in &krate.module.items {
- rbml_w.start_tag(tag_mod_child);
- rbml_w.wr_str(&def_to_string(local_def(item.id)));
- rbml_w.end_tag();
+ rbml_w.wr_tagged_str(tag_mod_child,
+ &def_to_string(local_def(item.id)));
each_auxiliary_node_id(&**item, |auxiliary_node_id| {
- rbml_w.start_tag(tag_mod_child);
- rbml_w.wr_str(&def_to_string(local_def(
- auxiliary_node_id)));
- rbml_w.end_tag();
+ rbml_w.wr_tagged_str(tag_mod_child,
+ &def_to_string(local_def(auxiliary_node_id)));
true
});
}
fn encode_crate_dep(rbml_w: &mut Encoder,
dep: decoder::CrateDep) {
rbml_w.start_tag(tag_crate_dep);
- rbml_w.start_tag(tag_crate_dep_crate_name);
- rbml_w.writer.write_all(dep.name.as_bytes());
- rbml_w.end_tag();
- rbml_w.start_tag(tag_crate_dep_hash);
- rbml_w.writer.write_all(dep.hash.as_str().as_bytes());
- rbml_w.end_tag();
+ rbml_w.wr_tagged_str(tag_crate_dep_crate_name, &dep.name);
+ rbml_w.wr_tagged_str(tag_crate_dep_hash, dep.hash.as_str());
rbml_w.end_tag();
}
fn encode_hash(rbml_w: &mut Encoder, hash: &Svh) {
- rbml_w.start_tag(tag_crate_hash);
- rbml_w.writer.write_all(hash.as_str().as_bytes());
- rbml_w.end_tag();
+ rbml_w.wr_tagged_str(tag_crate_hash, hash.as_str());
}
fn encode_crate_name(rbml_w: &mut Encoder, crate_name: &str) {
- rbml_w.start_tag(tag_crate_crate_name);
- rbml_w.writer.write_all(crate_name.as_bytes());
- rbml_w.end_tag();
+ rbml_w.wr_tagged_str(tag_crate_crate_name, crate_name);
}
fn encode_crate_triple(rbml_w: &mut Encoder, triple: &str) {
- rbml_w.start_tag(tag_crate_triple);
- rbml_w.writer.write_all(triple.as_bytes());
- rbml_w.end_tag();
+ rbml_w.wr_tagged_str(tag_crate_triple, triple);
}
fn encode_dylib_dependency_formats(rbml_w: &mut Encoder, ecx: &EncodeContext) {
- rbml_w.start_tag(tag_dylib_dependency_formats);
+ let tag = tag_dylib_dependency_formats;
match ecx.tcx.dependency_formats.borrow().get(&config::CrateTypeDylib) {
Some(arr) => {
let s = arr.iter().enumerate().filter_map(|(i, slot)| {
cstore::RequireStatic => "s",
})).to_string())
}).collect::<Vec<String>>();
- rbml_w.writer.write_all(s.connect(",").as_bytes());
+ rbml_w.wr_tagged_str(tag, &s.connect(","));
+ }
+ None => {
+ rbml_w.wr_tagged_str(tag, "");
}
- None => {}
}
- rbml_w.end_tag();
}
// NB: Increment this as you change the metadata encoding version.
#[allow(non_upper_case_globals)]
-pub const metadata_encoding_version : &'static [u8] = &[b'r', b'u', b's', b't', 0, 0, 0, 1 ];
+pub const metadata_encoding_version : &'static [u8] = &[b'r', b'u', b's', b't', 0, 0, 0, 2 ];
pub fn encode_metadata(parms: EncodeParams, krate: &ast::Crate) -> Vec<u8> {
let mut wr = SeekableMemWriter::new();
encode_metadata_inner(&mut wr, parms, krate);
+
+ // RBML compacts the encoded bytes whenever appropriate,
+ // so there are some garbages left after the end of the data.
+ let metalen = wr.tell().unwrap() as uint;
let mut v = wr.unwrap();
+ v.truncate(metalen);
+ assert_eq!(v.len(), metalen);
// And here we run into yet another obscure archive bug: in which metadata
// loaded from archives may have trailing garbage bytes. Awhile back one of
reachable: reachable,
};
- let mut rbml_w = writer::Encoder::new(wr);
+ let mut rbml_w = Encoder::new(wr);
encode_crate_name(&mut rbml_w, &ecx.link_meta.crate_name);
encode_crate_triple(&mut rbml_w,
// Get the encoded string for a type
pub fn encoded_ty<'tcx>(tcx: &ty::ctxt<'tcx>, t: Ty<'tcx>) -> String {
let mut wr = SeekableMemWriter::new();
- tyencode::enc_ty(&mut wr, &tyencode::ctxt {
+ tyencode::enc_ty(&mut Encoder::new(&mut wr), &tyencode::ctxt {
diag: tcx.sess.diagnostic(),
ds: def_to_string,
tcx: tcx,
}
#[cfg(windows)]
-static PATH_ENTRY_SEPARATOR: &'static str = ";";
+const PATH_ENTRY_SEPARATOR: char = ';';
#[cfg(not(windows))]
-static PATH_ENTRY_SEPARATOR: &'static str = ":";
+const PATH_ENTRY_SEPARATOR: char = ':';
/// Returns RUST_PATH as a string, without default paths added
pub fn get_rust_path() -> Option<String> {
'k' => {
assert_eq!(next(st), '[');
let did = parse_def_(st, ClosureSource, conv);
- let region = parse_region_(st, conv);
let substs = parse_substs_(st, conv);
assert_eq!(next(st), ']');
- return ty::mk_closure(st.tcx, did,
- st.tcx.mk_region(region), st.tcx.mk_substs(substs));
+ return ty::mk_closure(st.tcx, did, st.tcx.mk_substs(substs));
}
'P' => {
assert_eq!(next(st), '[');
-// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
+// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
use syntax::diagnostic::SpanHandler;
use syntax::parse::token;
-use rbml::io::SeekableMemWriter;
+use rbml::writer::Encoder;
-macro_rules! mywrite { ($($arg:tt)*) => ({ write!($($arg)*); }) }
+macro_rules! mywrite { ($w:expr, $($arg:tt)*) => ({ write!($w.writer, $($arg)*); }) }
pub struct ctxt<'a, 'tcx: 'a> {
pub diag: &'a SpanHandler,
pub type abbrev_map<'tcx> = RefCell<FnvHashMap<Ty<'tcx>, ty_abbrev>>;
-pub fn enc_ty<'a, 'tcx>(w: &mut SeekableMemWriter, cx: &ctxt<'a, 'tcx>, t: Ty<'tcx>) {
+pub fn enc_ty<'a, 'tcx>(w: &mut Encoder, cx: &ctxt<'a, 'tcx>, t: Ty<'tcx>) {
match cx.abbrevs.borrow_mut().get(&t) {
- Some(a) => { w.write_all(a.s.as_bytes()); return; }
+ Some(a) => { w.writer.write_all(a.s.as_bytes()); return; }
None => {}
}
- let pos = w.tell().unwrap();
+
+ // type abbreviations needs a stable position
+ let pos = w.mark_stable_position();
match t.sty {
ty::ty_bool => mywrite!(w, "b"),
enc_substs(w, cx, substs);
mywrite!(w, "]");
}
- ty::ty_closure(def, region, substs) => {
+ ty::ty_closure(def, substs) => {
mywrite!(w, "k[{}|", (cx.ds)(def));
- enc_region(w, cx, *region);
enc_substs(w, cx, substs);
mywrite!(w, "]");
}
}
}
- let end = w.tell().unwrap();
+ let end = w.mark_stable_position();
let len = end - pos;
fn estimate_sz(u: u64) -> u64 {
let mut n = u;
}
}
-fn enc_mutability(w: &mut SeekableMemWriter, mt: ast::Mutability) {
+fn enc_mutability(w: &mut Encoder, mt: ast::Mutability) {
match mt {
ast::MutImmutable => (),
ast::MutMutable => mywrite!(w, "m"),
}
}
-fn enc_mt<'a, 'tcx>(w: &mut SeekableMemWriter, cx: &ctxt<'a, 'tcx>,
+fn enc_mt<'a, 'tcx>(w: &mut Encoder, cx: &ctxt<'a, 'tcx>,
mt: ty::mt<'tcx>) {
enc_mutability(w, mt.mutbl);
enc_ty(w, cx, mt.ty);
}
-fn enc_opt<T, F>(w: &mut SeekableMemWriter, t: Option<T>, enc_f: F) where
- F: FnOnce(&mut SeekableMemWriter, T),
+fn enc_opt<T, F>(w: &mut Encoder, t: Option<T>, enc_f: F) where
+ F: FnOnce(&mut Encoder, T),
{
match t {
None => mywrite!(w, "n"),
}
}
-fn enc_vec_per_param_space<'a, 'tcx, T, F>(w: &mut SeekableMemWriter,
+fn enc_vec_per_param_space<'a, 'tcx, T, F>(w: &mut Encoder,
cx: &ctxt<'a, 'tcx>,
v: &VecPerParamSpace<T>,
mut op: F) where
- F: FnMut(&mut SeekableMemWriter, &ctxt<'a, 'tcx>, &T),
+ F: FnMut(&mut Encoder, &ctxt<'a, 'tcx>, &T),
{
for &space in &subst::ParamSpace::all() {
mywrite!(w, "[");
}
}
-pub fn enc_substs<'a, 'tcx>(w: &mut SeekableMemWriter, cx: &ctxt<'a, 'tcx>,
+pub fn enc_substs<'a, 'tcx>(w: &mut Encoder, cx: &ctxt<'a, 'tcx>,
substs: &subst::Substs<'tcx>) {
enc_region_substs(w, cx, &substs.regions);
enc_vec_per_param_space(w, cx, &substs.types,
|w, cx, &ty| enc_ty(w, cx, ty));
}
-fn enc_region_substs(w: &mut SeekableMemWriter, cx: &ctxt, substs: &subst::RegionSubsts) {
+fn enc_region_substs(w: &mut Encoder, cx: &ctxt, substs: &subst::RegionSubsts) {
match *substs {
subst::ErasedRegions => {
mywrite!(w, "e");
}
}
-pub fn enc_region(w: &mut SeekableMemWriter, cx: &ctxt, r: ty::Region) {
+pub fn enc_region(w: &mut Encoder, cx: &ctxt, r: ty::Region) {
match r {
ty::ReLateBound(id, br) => {
mywrite!(w, "b[{}|", id.depth);
}
}
-fn enc_scope(w: &mut SeekableMemWriter, _cx: &ctxt, scope: region::CodeExtent) {
+fn enc_scope(w: &mut Encoder, _cx: &ctxt, scope: region::CodeExtent) {
match scope {
region::CodeExtent::Misc(node_id) => mywrite!(w, "M{}", node_id),
region::CodeExtent::Remainder(region::BlockRemainder {
}
}
-fn enc_destruction_scope_data(w: &mut SeekableMemWriter,
+fn enc_destruction_scope_data(w: &mut Encoder,
d: region::DestructionScopeData) {
mywrite!(w, "{}", d.node_id);
}
-fn enc_bound_region(w: &mut SeekableMemWriter, cx: &ctxt, br: ty::BoundRegion) {
+fn enc_bound_region(w: &mut Encoder, cx: &ctxt, br: ty::BoundRegion) {
match br {
ty::BrAnon(idx) => {
mywrite!(w, "a{}|", idx);
}
}
-pub fn enc_trait_ref<'a, 'tcx>(w: &mut SeekableMemWriter, cx: &ctxt<'a, 'tcx>,
+pub fn enc_trait_ref<'a, 'tcx>(w: &mut Encoder, cx: &ctxt<'a, 'tcx>,
s: &ty::TraitRef<'tcx>) {
mywrite!(w, "{}|", (cx.ds)(s.def_id));
enc_substs(w, cx, s.substs);
}
-fn enc_unsafety(w: &mut SeekableMemWriter, p: ast::Unsafety) {
+fn enc_unsafety(w: &mut Encoder, p: ast::Unsafety) {
match p {
ast::Unsafety::Normal => mywrite!(w, "n"),
ast::Unsafety::Unsafe => mywrite!(w, "u"),
}
}
-fn enc_abi(w: &mut SeekableMemWriter, abi: Abi) {
+fn enc_abi(w: &mut Encoder, abi: Abi) {
mywrite!(w, "[");
mywrite!(w, "{}", abi.name());
mywrite!(w, "]")
}
-pub fn enc_bare_fn_ty<'a, 'tcx>(w: &mut SeekableMemWriter, cx: &ctxt<'a, 'tcx>,
+pub fn enc_bare_fn_ty<'a, 'tcx>(w: &mut Encoder, cx: &ctxt<'a, 'tcx>,
ft: &ty::BareFnTy<'tcx>) {
enc_unsafety(w, ft.unsafety);
enc_abi(w, ft.abi);
enc_fn_sig(w, cx, &ft.sig);
}
-pub fn enc_closure_ty<'a, 'tcx>(w: &mut SeekableMemWriter, cx: &ctxt<'a, 'tcx>,
+pub fn enc_closure_ty<'a, 'tcx>(w: &mut Encoder, cx: &ctxt<'a, 'tcx>,
ft: &ty::ClosureTy<'tcx>) {
enc_unsafety(w, ft.unsafety);
enc_fn_sig(w, cx, &ft.sig);
enc_abi(w, ft.abi);
}
-fn enc_fn_sig<'a, 'tcx>(w: &mut SeekableMemWriter, cx: &ctxt<'a, 'tcx>,
+fn enc_fn_sig<'a, 'tcx>(w: &mut Encoder, cx: &ctxt<'a, 'tcx>,
fsig: &ty::PolyFnSig<'tcx>) {
mywrite!(w, "[");
for ty in &fsig.0.inputs {
}
}
-pub fn enc_builtin_bounds(w: &mut SeekableMemWriter, _cx: &ctxt, bs: &ty::BuiltinBounds) {
+pub fn enc_builtin_bounds(w: &mut Encoder, _cx: &ctxt, bs: &ty::BuiltinBounds) {
for bound in bs {
match bound {
ty::BoundSend => mywrite!(w, "S"),
mywrite!(w, ".");
}
-pub fn enc_existential_bounds<'a,'tcx>(w: &mut SeekableMemWriter,
+pub fn enc_existential_bounds<'a,'tcx>(w: &mut Encoder,
cx: &ctxt<'a,'tcx>,
bs: &ty::ExistentialBounds<'tcx>) {
let param_bounds = ty::ParamBounds { trait_bounds: vec!(),
enc_bounds(w, cx, ¶m_bounds);
}
-pub fn enc_bounds<'a, 'tcx>(w: &mut SeekableMemWriter, cx: &ctxt<'a, 'tcx>,
+pub fn enc_bounds<'a, 'tcx>(w: &mut Encoder, cx: &ctxt<'a, 'tcx>,
bs: &ty::ParamBounds<'tcx>) {
enc_builtin_bounds(w, cx, &bs.builtin_bounds);
mywrite!(w, ".");
}
-pub fn enc_region_bounds<'a, 'tcx>(w: &mut SeekableMemWriter,
+pub fn enc_region_bounds<'a, 'tcx>(w: &mut Encoder,
cx: &ctxt<'a, 'tcx>,
rs: &[ty::Region]) {
for &r in rs {
mywrite!(w, ".");
}
-pub fn enc_type_param_def<'a, 'tcx>(w: &mut SeekableMemWriter, cx: &ctxt<'a, 'tcx>,
+pub fn enc_type_param_def<'a, 'tcx>(w: &mut Encoder, cx: &ctxt<'a, 'tcx>,
v: &ty::TypeParameterDef<'tcx>) {
mywrite!(w, "{}:{}|{}|{}|",
token::get_name(v.name), (cx.ds)(v.def_id),
enc_object_lifetime_default(w, cx, v.object_lifetime_default);
}
-fn enc_object_lifetime_default<'a, 'tcx>(w: &mut SeekableMemWriter,
+fn enc_object_lifetime_default<'a, 'tcx>(w: &mut Encoder,
cx: &ctxt<'a, 'tcx>,
default: Option<ty::ObjectLifetimeDefault>)
{
}
}
-pub fn enc_predicate<'a, 'tcx>(w: &mut SeekableMemWriter,
+pub fn enc_predicate<'a, 'tcx>(w: &mut Encoder,
cx: &ctxt<'a, 'tcx>,
p: &ty::Predicate<'tcx>)
{
}
}
-fn enc_projection_predicate<'a, 'tcx>(w: &mut SeekableMemWriter,
+fn enc_projection_predicate<'a, 'tcx>(w: &mut Encoder,
cx: &ctxt<'a, 'tcx>,
data: &ty::ProjectionPredicate<'tcx>) {
enc_trait_ref(w, cx, &*data.projection_ty.trait_ref);
-// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
+// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
use std::num::FromPrimitive;
use std::rc::Rc;
-use rbml::io::SeekableMemWriter;
-use rbml::{reader, writer};
+use rbml::reader;
+use rbml::writer::Encoder;
use rbml;
use serialize;
use serialize::{Decodable, Decoder, DecoderHelpers, Encodable};
use serialize::{EncoderHelpers};
+#[cfg(test)] use rbml::io::SeekableMemWriter;
#[cfg(test)] use syntax::parse;
#[cfg(test)] use syntax::print::pprust;
fn tr_intern(&self, dcx: &DecodeContext) -> ast::DefId;
}
-pub type Encoder<'a> = writer::Encoder<'a, SeekableMemWriter>;
-
// ______________________________________________________________________
// Top-level methods.
// ______________________________________________________________________
// Encoding and decoding of ast::def
-fn decode_def(dcx: &DecodeContext, doc: rbml::Doc) -> def::Def {
- let mut dsr = reader::Decoder::new(doc);
- let def: def::Def = Decodable::decode(&mut dsr).unwrap();
+fn decode_def(dcx: &DecodeContext, dsr: &mut reader::Decoder) -> def::Def {
+ let def: def::Def = Decodable::decode(dsr).unwrap();
def.tr(dcx)
}
fn emit_type_param_def<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
type_param_def: &ty::TypeParameterDef<'tcx>) {
self.emit_opaque(|this| {
- Ok(tyencode::enc_type_param_def(this.writer,
+ Ok(tyencode::enc_type_param_def(this,
&ecx.ty_str_ctxt(),
type_param_def))
});
fn emit_predicate<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
predicate: &ty::Predicate<'tcx>) {
self.emit_opaque(|this| {
- Ok(tyencode::enc_predicate(this.writer,
+ Ok(tyencode::enc_predicate(this,
&ecx.ty_str_ctxt(),
predicate))
});
fn emit_existential_bounds<'b>(&mut self, ecx: &e::EncodeContext<'b,'tcx>,
bounds: &ty::ExistentialBounds<'tcx>) {
- self.emit_opaque(|this| Ok(tyencode::enc_existential_bounds(this.writer,
+ self.emit_opaque(|this| Ok(tyencode::enc_existential_bounds(this,
&ecx.ty_str_ctxt(),
bounds)));
}
fn emit_builtin_bounds(&mut self, ecx: &e::EncodeContext, bounds: &ty::BuiltinBounds) {
- self.emit_opaque(|this| Ok(tyencode::enc_builtin_bounds(this.writer,
+ self.emit_opaque(|this| Ok(tyencode::enc_builtin_bounds(this,
&ecx.ty_str_ctxt(),
bounds)));
}
fn emit_substs<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
substs: &subst::Substs<'tcx>) {
- self.emit_opaque(|this| Ok(tyencode::enc_substs(this.writer,
+ self.emit_opaque(|this| Ok(tyencode::enc_substs(this,
&ecx.ty_str_ctxt(),
substs)));
}
}
fn id(&mut self, id: ast::NodeId) {
- self.wr_tagged_u64(c::tag_table_id as uint, id as u64);
+ id.encode(self).unwrap();
}
}
if let Some(def) = tcx.def_map.borrow().get(&id).map(|d| d.full_def()) {
rbml_w.tag(c::tag_table_def, |rbml_w| {
rbml_w.id(id);
- rbml_w.tag(c::tag_table_val, |rbml_w| def.encode(rbml_w).unwrap());
+ def.encode(rbml_w).unwrap();
})
}
if let Some(ty) = tcx.node_types.borrow().get(&id) {
rbml_w.tag(c::tag_table_node_type, |rbml_w| {
rbml_w.id(id);
- rbml_w.tag(c::tag_table_val, |rbml_w| {
- rbml_w.emit_ty(ecx, *ty);
- })
+ rbml_w.emit_ty(ecx, *ty);
})
}
if let Some(item_substs) = tcx.item_substs.borrow().get(&id) {
rbml_w.tag(c::tag_table_item_subst, |rbml_w| {
rbml_w.id(id);
- rbml_w.tag(c::tag_table_val, |rbml_w| {
- rbml_w.emit_substs(ecx, &item_substs.substs);
- })
+ rbml_w.emit_substs(ecx, &item_substs.substs);
})
}
if let Some(fv) = tcx.freevars.borrow().get(&id) {
rbml_w.tag(c::tag_table_freevars, |rbml_w| {
rbml_w.id(id);
- rbml_w.tag(c::tag_table_val, |rbml_w| {
- rbml_w.emit_from_vec(fv, |rbml_w, fv_entry| {
- Ok(encode_freevar_entry(rbml_w, fv_entry))
- });
- })
+ rbml_w.emit_from_vec(fv, |rbml_w, fv_entry| {
+ Ok(encode_freevar_entry(rbml_w, fv_entry))
+ });
});
for freevar in fv {
rbml_w.tag(c::tag_table_upvar_capture_map, |rbml_w| {
rbml_w.id(id);
- rbml_w.tag(c::tag_table_val, |rbml_w| {
- let var_id = freevar.def.def_id().node;
- let upvar_id = ty::UpvarId {
- var_id: var_id,
- closure_expr_id: id
- };
- let upvar_capture = tcx.upvar_capture_map.borrow()[upvar_id].clone();
- var_id.encode(rbml_w);
- upvar_capture.encode(rbml_w);
- })
+
+ let var_id = freevar.def.def_id().node;
+ let upvar_id = ty::UpvarId {
+ var_id: var_id,
+ closure_expr_id: id
+ };
+ let upvar_capture = tcx.upvar_capture_map.borrow()[upvar_id].clone();
+ var_id.encode(rbml_w);
+ upvar_capture.encode(rbml_w);
})
}
}
if let Some(type_scheme) = tcx.tcache.borrow().get(&lid) {
rbml_w.tag(c::tag_table_tcache, |rbml_w| {
rbml_w.id(id);
- rbml_w.tag(c::tag_table_val, |rbml_w| {
- rbml_w.emit_type_scheme(ecx, type_scheme.clone());
- })
+ rbml_w.emit_type_scheme(ecx, type_scheme.clone());
})
}
if let Some(type_param_def) = tcx.ty_param_defs.borrow().get(&id) {
rbml_w.tag(c::tag_table_param_defs, |rbml_w| {
rbml_w.id(id);
- rbml_w.tag(c::tag_table_val, |rbml_w| {
- rbml_w.emit_type_param_def(ecx, type_param_def)
- })
+ rbml_w.emit_type_param_def(ecx, type_param_def)
})
}
if let Some(method) = tcx.method_map.borrow().get(&method_call) {
rbml_w.tag(c::tag_table_method_map, |rbml_w| {
rbml_w.id(id);
- rbml_w.tag(c::tag_table_val, |rbml_w| {
- encode_method_callee(ecx, rbml_w, method_call.adjustment, method)
- })
+ encode_method_callee(ecx, rbml_w, method_call.adjustment, method)
})
}
if let Some(trait_ref) = tcx.object_cast_map.borrow().get(&id) {
rbml_w.tag(c::tag_table_object_cast_map, |rbml_w| {
rbml_w.id(id);
- rbml_w.tag(c::tag_table_val, |rbml_w| {
- rbml_w.emit_trait_ref(ecx, &*trait_ref.0);
- })
+ rbml_w.emit_trait_ref(ecx, &*trait_ref.0);
})
}
if let Some(method) = tcx.method_map.borrow().get(&method_call) {
rbml_w.tag(c::tag_table_method_map, |rbml_w| {
rbml_w.id(id);
- rbml_w.tag(c::tag_table_val, |rbml_w| {
- encode_method_callee(ecx, rbml_w, method_call.adjustment, method)
- })
+ encode_method_callee(ecx, rbml_w, method_call.adjustment, method)
})
}
}
if let Some(method) = tcx.method_map.borrow().get(&method_call) {
rbml_w.tag(c::tag_table_method_map, |rbml_w| {
rbml_w.id(id);
- rbml_w.tag(c::tag_table_val, |rbml_w| {
- encode_method_callee(ecx, rbml_w,
- method_call.adjustment, method)
- })
+ encode_method_callee(ecx, rbml_w,
+ method_call.adjustment, method)
})
}
}
rbml_w.tag(c::tag_table_adjustments, |rbml_w| {
rbml_w.id(id);
- rbml_w.tag(c::tag_table_val, |rbml_w| {
- rbml_w.emit_auto_adjustment(ecx, adjustment);
- })
+ rbml_w.emit_auto_adjustment(ecx, adjustment);
})
}
if let Some(closure_type) = tcx.closure_tys.borrow().get(&ast_util::local_def(id)) {
rbml_w.tag(c::tag_table_closure_tys, |rbml_w| {
rbml_w.id(id);
- rbml_w.tag(c::tag_table_val, |rbml_w| {
- rbml_w.emit_closure_type(ecx, closure_type);
- })
+ rbml_w.emit_closure_type(ecx, closure_type);
})
}
if let Some(closure_kind) = tcx.closure_kinds.borrow().get(&ast_util::local_def(id)) {
rbml_w.tag(c::tag_table_closure_kinds, |rbml_w| {
rbml_w.id(id);
- rbml_w.tag(c::tag_table_val, |rbml_w| {
- encode_closure_kind(rbml_w, *closure_kind)
- })
+ encode_closure_kind(rbml_w, *closure_kind)
})
}
for &qualif in tcx.const_qualif_map.borrow().get(&id).iter() {
rbml_w.tag(c::tag_table_const_qualif, |rbml_w| {
rbml_w.id(id);
- rbml_w.tag(c::tag_table_val, |rbml_w| {
- qualif.encode(rbml_w).unwrap()
- })
+ qualif.encode(rbml_w).unwrap()
})
}
}
ast_doc: rbml::Doc) {
let tbl_doc = ast_doc.get(c::tag_table as uint);
reader::docs(tbl_doc, |tag, entry_doc| {
- let id0 = entry_doc.get(c::tag_table_id as uint).as_int();
- let id = dcx.tr_id(id0 as ast::NodeId);
+ let mut entry_dsr = reader::Decoder::new(entry_doc);
+ let id0: ast::NodeId = Decodable::decode(&mut entry_dsr).unwrap();
+ let id = dcx.tr_id(id0);
debug!(">> Side table document with tag 0x{:x} \
found for id {} (orig {})",
tag, id, id0);
- let decoded_tag: Option<c::astencode_tag> = FromPrimitive::from_uint(tag);
+ let decoded_tag: Option<c::astencode_tag> = FromPrimitive::from_usize(tag);
match decoded_tag {
None => {
dcx.tcx.sess.bug(
tag));
}
Some(value) => {
- let val_doc = entry_doc.get(c::tag_table_val as uint);
- let mut val_dsr = reader::Decoder::new(val_doc);
- let val_dsr = &mut val_dsr;
+ let val_dsr = &mut entry_dsr;
match value {
c::tag_table_def => {
- let def = decode_def(dcx, val_doc);
+ let def = decode_def(dcx, val_dsr);
dcx.tcx.def_map.borrow_mut().insert(id, def::PathResolution {
base_def: def,
// This doesn't matter cross-crate.
fn roundtrip(in_item: Option<P<ast::Item>>) {
let in_item = in_item.unwrap();
let mut wr = SeekableMemWriter::new();
- encode_item_ast(&mut writer::Encoder::new(&mut wr), &*in_item);
+ encode_item_ast(&mut Encoder::new(&mut wr), &*in_item);
let rbml_doc = rbml::Doc::new(wr.get_ref());
let out_item = decode_item_ast(rbml_doc);
oper: O,
id_range: IdRange,
bits_per_id: uint) -> DataFlowContext<'a, 'tcx, O> {
- let words_per_id = (bits_per_id + usize::BITS - 1) / usize::BITS;
+ let words_per_id = (bits_per_id + usize::BITS as usize - 1) / usize::BITS as usize;
let num_nodes = cfg.graph.all_nodes().len();
debug!("DataFlowContext::new(analysis_name: {}, id_range={:?}, \
for (word_index, &word) in words.iter().enumerate() {
if word != 0 {
- let base_index = word_index * usize::BITS;
+ let base_index = word_index * usize::BITS as usize;
for offset in 0..usize::BITS {
let bit = 1 << offset;
if (word & bit) != 0 {
// whether the bit_index is greater than the
// actual value the user specified and stop
// iterating if so.
- let bit_index = base_index + offset;
+ let bit_index = base_index + offset as usize;
if bit_index >= self.bits_per_id {
return true;
} else if !f(bit_index) {
fn set_bit(words: &mut [uint], bit: uint) -> bool {
debug!("set_bit: words={} bit={}",
mut_bits_to_string(words), bit_str(bit));
- let word = bit / usize::BITS;
- let bit_in_word = bit % usize::BITS;
+ let word = bit / usize::BITS as usize;
+ let bit_in_word = bit % usize::BITS as usize;
let bit_mask = 1 << bit_in_word;
debug!("word={} bit_in_word={} bit_mask={}", word, bit_in_word, word);
let oldv = words[word];
let def_id = tcx.lang_items.owned_box().unwrap();
Some(StructSimplifiedType(def_id))
}
- ty::ty_closure(def_id, _, _) => {
+ ty::ty_closure(def_id, _) => {
Some(ClosureSimplifiedType(def_id))
}
ty::ty_tup(ref tys) => {
Ok(ty::mk_struct(tcx, a_id, tcx.mk_substs(substs)))
}
- (&ty::ty_closure(a_id, a_region, a_substs),
- &ty::ty_closure(b_id, b_region, b_substs))
+ (&ty::ty_closure(a_id, a_substs),
+ &ty::ty_closure(b_id, b_substs))
if a_id == b_id => {
// All ty_closure types with the same id represent
// the (anonymous) type of the same closure expression. So
// all of their regions should be equated.
- let region = try!(this.equate().regions(*a_region, *b_region));
let substs = try!(this.substs_variances(None, a_substs, b_substs));
- Ok(ty::mk_closure(tcx, a_id, tcx.mk_region(region), tcx.mk_substs(substs)))
+ Ok(ty::mk_closure(tcx, a_id, tcx.mk_substs(substs)))
}
(&ty::ty_uniq(a_inner), &ty::ty_uniq(b_inner)) => {
}
pub fn item_name(index: uint) -> &'static str {
- let item: Option<LangItem> = FromPrimitive::from_uint(index);
+ let item: Option<LangItem> = FromPrimitive::from_usize(index);
match item {
$( Some($variant) => $name, )*
None => "???"
//! enclosing function. On the way down the tree, it identifies those AST
//! nodes and variable IDs that will be needed for the liveness analysis
//! and assigns them contiguous IDs. The liveness id for an AST node is
-//! called a `live_node` (it's a newtype'd uint) and the id for a variable
-//! is called a `variable` (another newtype'd uint).
+//! called a `live_node` (it's a newtype'd usize) and the id for a variable
+//! is called a `variable` (another newtype'd usize).
//!
//! On the way back up the tree, as we are about to exit from a function
//! declaration we allocate a `liveness` instance. Now that we know
use lint;
use util::nodemap::NodeMap;
-use std::{fmt, old_io, uint};
+use std::{fmt, old_io, usize};
use std::rc::Rc;
use std::iter::repeat;
use syntax::ast::{self, NodeId, Expr};
}
#[derive(Copy, PartialEq)]
-struct Variable(uint);
+struct Variable(usize);
#[derive(Copy, PartialEq)]
-struct LiveNode(uint);
+struct LiveNode(usize);
impl Variable {
- fn get(&self) -> uint { let Variable(v) = *self; v }
+ fn get(&self) -> usize { let Variable(v) = *self; v }
}
impl LiveNode {
- fn get(&self) -> uint { let LiveNode(v) = *self; v }
+ fn get(&self) -> usize { let LiveNode(v) = *self; v }
}
impl Clone for LiveNode {
impl LiveNode {
fn is_valid(&self) -> bool {
- self.get() != uint::MAX
+ self.get() != usize::MAX
}
}
-fn invalid_node() -> LiveNode { LiveNode(uint::MAX) }
+fn invalid_node() -> LiveNode { LiveNode(usize::MAX) }
struct CaptureInfo {
ln: LiveNode,
struct IrMaps<'a, 'tcx: 'a> {
tcx: &'a ty::ctxt<'tcx>,
- num_live_nodes: uint,
- num_vars: uint,
+ num_live_nodes: usize,
+ num_vars: usize,
live_node_map: NodeMap<LiveNode>,
variable_map: NodeMap<Variable>,
capture_info_map: NodeMap<Rc<Vec<CaptureInfo>>>,
clean_exit_var: Variable
}
-static ACC_READ: uint = 1;
-static ACC_WRITE: uint = 2;
-static ACC_USE: uint = 4;
+const ACC_READ: u32 = 1;
+const ACC_WRITE: u32 = 2;
+const ACC_USE: u32 = 4;
struct Liveness<'a, 'tcx: 'a> {
ir: &'a mut IrMaps<'a, 'tcx>,
succ
}
- fn idx(&self, ln: LiveNode, var: Variable) -> uint {
+ fn idx(&self, ln: LiveNode, var: Variable) -> usize {
ln.get() * self.ir.num_vars + var.get()
}
}
fn indices2<F>(&mut self, ln: LiveNode, succ_ln: LiveNode, mut op: F) where
- F: FnMut(&mut Liveness<'a, 'tcx>, uint, uint),
+ F: FnMut(&mut Liveness<'a, 'tcx>, usize, usize),
{
let node_base_idx = self.idx(ln, Variable(0));
let succ_base_idx = self.idx(succ_ln, Variable(0));
ln: LiveNode,
mut test: F)
-> old_io::IoResult<()> where
- F: FnMut(uint) -> LiveNode,
+ F: FnMut(usize) -> LiveNode,
{
let node_base_idx = self.idx(ln, Variable(0));
for var_idx in 0..self.ir.num_vars {
}
// Either read, write, or both depending on the acc bitset
- fn acc(&mut self, ln: LiveNode, var: Variable, acc: uint) {
+ fn acc(&mut self, ln: LiveNode, var: Variable, acc: u32) {
debug!("{:?} accesses[{:x}] {:?}: {}",
ln, acc, var, self.ln_str(ln));
}
// see comment on propagate_through_lvalue()
- fn write_lvalue(&mut self, expr: &Expr, succ: LiveNode, acc: uint)
+ fn write_lvalue(&mut self, expr: &Expr, succ: LiveNode, acc: u32)
-> LiveNode {
match expr.node {
ast::ExprPath(..) => {
}
}
- fn access_path(&mut self, expr: &Expr, succ: LiveNode, acc: uint)
+ fn access_path(&mut self, expr: &Expr, succ: LiveNode, acc: u32)
-> LiveNode {
match self.ir.tcx.def_map.borrow()[expr.id].full_def() {
DefLocal(nid) => {
fn fn_ret(&self, id: NodeId) -> ty::PolyFnOutput<'tcx> {
let fn_ty = ty::node_id_to_type(self.ir.tcx, id);
match fn_ty.sty {
- ty::ty_closure(closure_def_id, _, substs) =>
+ ty::ty_closure(closure_def_id, substs) =>
self.ir.tcx.closure_type(closure_def_id, substs).sig.output(),
_ =>
ty::ty_fn_ret(fn_ty),
def::DefUpvar(var_id, fn_node_id) => {
let ty = try!(self.node_ty(fn_node_id));
match ty.sty {
- ty::ty_closure(closure_id, _, _) => {
+ ty::ty_closure(closure_id, _) => {
match self.typer.closure_kind(closure_id) {
Some(kind) => {
self.cat_upvar(id, span, var_id, fn_node_id, kind)
#[derive(Debug, Copy)]
pub struct Context {
+ /// the scope that contains any new variables declared
var_parent: InnermostDeclaringBlock,
+ /// region parent of expressions etc
parent: InnermostEnclosingExpr,
}
debug!("consider_unification_despite_ambiguity: self_ty.sty={:?}",
self_ty.sty);
match self_ty.sty {
- ty::ty_closure(closure_def_id, _, substs) => {
+ ty::ty_closure(closure_def_id, substs) => {
let closure_typer = selcx.closure_typer();
let closure_type = closure_typer.closure_type(closure_def_id, substs);
let ty::Binder((_, ret_type)) =
// lifetimes can appear inside the self-type.
let self_ty = self.infcx.shallow_resolve(obligation.self_ty());
let (closure_def_id, substs) = match self_ty.sty {
- ty::ty_closure(id, _, ref substs) => (id, substs.clone()),
+ ty::ty_closure(id, ref substs) => (id, substs.clone()),
_ => { return; }
};
assert!(!substs.has_escaping_regions());
let self_ty = self.infcx.shallow_resolve(obligation.self_ty());
let (closure_def_id, substs) = match self_ty.sty {
- ty::ty_closure(id, _, ref substs) => (id, substs.clone()),
+ ty::ty_closure(id, ref substs) => (id, substs.clone()),
ty::ty_infer(ty::TyVar(_)) => {
debug!("assemble_unboxed_closure_candidates: ambiguous self-type");
candidates.ambiguous = true;
// (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
ty::ty_tup(ref tys) => Ok(If(tys.clone())),
- ty::ty_closure(def_id, _, substs) => {
+ ty::ty_closure(def_id, substs) => {
// FIXME -- This case is tricky. In the case of by-ref
// closures particularly, we need the results of
// inference to decide how to reflect the type of each
Some(tys.clone())
}
- ty::ty_closure(def_id, _, substs) => {
+ ty::ty_closure(def_id, substs) => {
assert_eq!(def_id.krate, ast::LOCAL_CRATE);
match self.closure_typer.closure_upvars(def_id, substs) {
use std::mem;
use std::ops;
use std::rc::Rc;
-use std::vec::{CowVec, IntoIter};
+use std::vec::IntoIter;
use collections::enum_set::{EnumSet, CLike};
use std::collections::{HashMap, HashSet};
use syntax::abi;
ty_trait(Box<TyTrait<'tcx>>),
ty_struct(DefId, &'tcx Substs<'tcx>),
- ty_closure(DefId, &'tcx Region, &'tcx Substs<'tcx>),
+ ty_closure(DefId, &'tcx Substs<'tcx>),
ty_tup(Vec<Ty<'tcx>>),
}
}
- &ty_closure(_, region, substs) => {
- self.add_region(*region);
+ &ty_closure(_, substs) => {
self.add_substs(substs);
}
mk_t(cx, ty_struct(struct_id, substs))
}
-pub fn mk_closure<'tcx>(cx: &ctxt<'tcx>, closure_id: ast::DefId,
- region: &'tcx Region, substs: &'tcx Substs<'tcx>)
+pub fn mk_closure<'tcx>(cx: &ctxt<'tcx>, closure_id: ast::DefId, substs: &'tcx Substs<'tcx>)
-> Ty<'tcx> {
- mk_t(cx, ty_closure(closure_id, region, substs))
+ mk_t(cx, ty_closure(closure_id, substs))
}
pub fn mk_var<'tcx>(cx: &ctxt<'tcx>, v: TyVid) -> Ty<'tcx> {
apply_lang_items(cx, did, res)
}
- ty_closure(did, r, substs) => {
+ ty_closure(did, substs) => {
// FIXME(#14449): `borrowed_contents` below assumes `&mut` closure.
let param_env = ty::empty_parameter_environment(cx);
let upvars = closure_upvars(¶m_env, did, substs).unwrap();
- TypeContents::union(&upvars,
- |f| tc_ty(cx, &f.ty, cache))
- | borrowed_contents(*r, MutMutable)
+ TypeContents::union(&upvars, |f| tc_ty(cx, &f.ty, cache))
}
ty_tup(ref tys) => {
Some(tt.principal_def_id()),
ty_struct(id, _) |
ty_enum(id, _) |
- ty_closure(id, _, _) =>
+ ty_closure(id, _) =>
Some(id),
_ =>
None
/// Get the attributes of a definition.
pub fn get_attrs<'tcx>(tcx: &'tcx ctxt, did: DefId)
- -> CowVec<'tcx, ast::Attribute> {
+ -> Cow<'tcx, [ast::Attribute]> {
if is_local(did) {
let item = tcx.map.expect_item(did.node);
Cow::Borrowed(&item.attrs)
pub fn is_binopable<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>, op: ast::BinOp) -> bool {
#![allow(non_upper_case_globals)]
- static tycat_other: int = 0;
- static tycat_bool: int = 1;
- static tycat_char: int = 2;
- static tycat_int: int = 3;
- static tycat_float: int = 4;
- static tycat_raw_ptr: int = 6;
-
- static opcat_add: int = 0;
- static opcat_sub: int = 1;
- static opcat_mult: int = 2;
- static opcat_shift: int = 3;
- static opcat_rel: int = 4;
- static opcat_eq: int = 5;
- static opcat_bit: int = 6;
- static opcat_logic: int = 7;
- static opcat_mod: int = 8;
+ const tycat_other: int = 0;
+ const tycat_bool: int = 1;
+ const tycat_char: int = 2;
+ const tycat_int: int = 3;
+ const tycat_float: int = 4;
+ const tycat_raw_ptr: int = 6;
+
+ const opcat_add: int = 0;
+ const opcat_sub: int = 1;
+ const opcat_mult: int = 2;
+ const opcat_shift: int = 3;
+ const opcat_rel: int = 4;
+ const opcat_eq: int = 5;
+ const opcat_bit: int = 6;
+ const opcat_logic: int = 7;
+ const opcat_mod: int = 8;
fn opcat(op: ast::BinOp) -> int {
match op.node {
}
}
- static t: bool = true;
- static f: bool = false;
+ const t: bool = true;
+ const f: bool = false;
let tbl = [
// +, -, *, shift, rel, ==, bit, logic, mod
}
ty_infer(_) => unreachable!(),
ty_err => byte!(21),
- ty_closure(d, r, _) => {
+ ty_closure(d, _) => {
byte!(22);
did(state, d);
- region(state, *r);
}
ty_projection(ref data) => {
byte!(23);
ty_struct(_, substs) => {
accum_substs(accumulator, substs);
}
- ty_closure(_, region, substs) => {
- accumulator.push(*region);
+ ty_closure(_, substs) => {
accum_substs(accumulator, substs);
}
ty_bool |
let substs = substs.fold_with(this);
ty::ty_struct(did, this.tcx().mk_substs(substs))
}
- ty::ty_closure(did, ref region, ref substs) => {
- let r = region.fold_with(this);
+ ty::ty_closure(did, ref substs) => {
let s = substs.fold_with(this);
- ty::ty_closure(did, this.tcx().mk_region(r), this.tcx().mk_substs(s))
+ ty::ty_closure(did, this.tcx().mk_substs(s))
}
ty::ty_projection(ref data) => {
ty::ty_projection(data.fold_with(this))
}
ty::ty_enum(_, ref substs) |
ty::ty_struct(_, ref substs) |
- ty::ty_closure(_, _, ref substs) => {
+ ty::ty_closure(_, ref substs) => {
self.push_reversed(substs.types.as_slice());
}
ty::ty_tup(ref ts) => {
data.item_name.user_string(cx))
}
ty_str => "str".to_string(),
- ty_closure(ref did, _, substs) => {
+ ty_closure(ref did, substs) => {
let closure_tys = cx.closure_tys.borrow();
closure_tys.get(did).map(|closure_type| {
closure_to_string(cx, &closure_type.subst(cx, substs))
use std::str;
use syntax::diagnostic::Handler as ErrorHandler;
-pub static METADATA_FILENAME: &'static str = "rust.metadata.bin";
+pub const METADATA_FILENAME: &'static str = "rust.metadata.bin";
pub struct ArchiveConfig<'a> {
pub handler: &'a ErrorHandler,
// Don't allow the total size of `args` to grow beyond 32,000 bytes.
// Windows will raise an error if the argument string is longer than
// 32,768, and we leave a bit of extra space for the program name.
- static ARG_LENGTH_LIMIT: uint = 32000;
+ const ARG_LENGTH_LIMIT: uint = 32_000;
for member_name in &self.members {
let len = member_name.as_vec().len();
/// Returns an absolute path in the filesystem that `path` points to. The
/// returned path does not contain any symlinks in its hierarchy.
pub fn realpath(original: &Path) -> old_io::IoResult<Path> {
- static MAX_LINKS_FOLLOWED: uint = 256;
+ const MAX_LINKS_FOLLOWED: uint = 256;
let original = try!(os::getcwd()).join(original);
// Right now lstat on windows doesn't work quite well
// FIXME (pnkfelix): See discussion here
// https://github.com/pnkfelix/rust/commit/
// b2b39e8700e37ad32b486b9a8409b50a8a53aa51#commitcomment-7892003
-static DOWNCAST_PRINTED_OPERATOR : &'static str = " as ";
+const DOWNCAST_PRINTED_OPERATOR: &'static str = " as ";
// A local, "cleaned" version of `mc::InteriorKind` that drops
// information that is not relevant to loan-path analysis. (In
}
#[allow(non_upper_case_globals)]
-static InvalidMovePathIndex: MovePathIndex =
- MovePathIndex(usize::MAX);
+const InvalidMovePathIndex: MovePathIndex = MovePathIndex(usize::MAX);
/// Index into `MoveData.moves`, used like a pointer
#[derive(Copy, PartialEq)]
}
#[allow(non_upper_case_globals)]
-static InvalidMoveIndex: MoveIndex =
- MoveIndex(usize::MAX);
+const InvalidMoveIndex: MoveIndex = MoveIndex(usize::MAX);
pub struct MovePath<'tcx> {
/// Loan path corresponding to this move path
pub mod pretty;
-static BUG_REPORT_URL: &'static str =
+const BUG_REPORT_URL: &'static str =
"https://github.com/rust-lang/rust/blob/master/CONTRIBUTING.md#bug-reports";
/// The diagnostic emitter yielded to the procedure should be used for reporting
/// errors of the compiler.
pub fn monitor<F:FnOnce()+Send+'static>(f: F) {
- static STACK_SIZE: uint = 8 * 1024 * 1024; // 8MB
+ const STACK_SIZE: uint = 8 * 1024 * 1024; // 8MB
let (tx, rx) = channel();
let w = old_io::ChanWriter::new(tx);
sub: &'a [RH<'a>]
}
-static EMPTY_SOURCE_STR: &'static str = "#![feature(no_std)] #![no_std]";
+const EMPTY_SOURCE_STR: &'static str = "#![feature(no_std)] #![no_std]";
struct ExpectErrorEmitter {
messages: Vec<String>
//! Use the former for unit-like structs and the latter for structs with
//! a `pub fn new()`.
-use self::MethodContext::*;
-
use metadata::{csearch, decoder};
use middle::def::*;
use middle::subst::Substs;
ast::LitInt(v, ast::UnsuffixedIntLit(ast::Plus)) => {
let int_type = if let ast::TyIs(_) = t {
cx.sess().target.int_type
- } else { t };
+ } else {
+ t
+ };
let (min, max) = int_ty_range(int_type);
let negative = self.negated_expr_id == e.id;
ty::ty_uint(t) => {
let uint_type = if let ast::TyUs(_) = t {
cx.sess().target.uint_type
- } else { t };
+ } else {
+ t
+ };
let (min, max) = uint_ty_range(uint_type);
let lit_val: u64 = match lit.node {
ast::LitByte(_v) => return, // _v is u8, within range by definition
ast::LitInt(v, _) => v,
_ => panic!()
};
- if lit_val < min || lit_val > max {
+ if lit_val < min || lit_val > max {
cx.span_lint(OVERFLOWING_LITERALS, e.span,
&*format!("literal out of range for {:?}", t));
}
let lit_val: f64 = match lit.node {
ast::LitFloat(ref v, _) |
ast::LitFloatUnsuffixed(ref v) => {
- match v.parse().ok() {
- Some(f) => f,
- None => return
+ match v.parse() {
+ Ok(f) => f,
+ Err(_) => return
}
}
_ => panic!()
})
}
- // for int & uint, be conservative with the warnings, so that the
+ // for isize & usize, be conservative with the warnings, so that the
// warnings are consistent between 32- and 64-bit platforms
fn int_ty_range(int_ty: ast::IntTy) -> (i64, i64) {
match int_ty {
- ast::TyIs(_) => (i64::MIN, i64::MAX),
- ast::TyI8 => (i8::MIN as i64, i8::MAX as i64),
- ast::TyI16 => (i16::MIN as i64, i16::MAX as i64),
- ast::TyI32 => (i32::MIN as i64, i32::MAX as i64),
- ast::TyI64 => (i64::MIN, i64::MAX)
+ ast::TyIs(_) => (i64::MIN, i64::MAX),
+ ast::TyI8 => (i8::MIN as i64, i8::MAX as i64),
+ ast::TyI16 => (i16::MIN as i64, i16::MAX as i64),
+ ast::TyI32 => (i32::MIN as i64, i32::MAX as i64),
+ ast::TyI64 => (i64::MIN, i64::MAX)
}
}
fn uint_ty_range(uint_ty: ast::UintTy) -> (u64, u64) {
match uint_ty {
- ast::TyUs(_) => (u64::MIN, u64::MAX),
- ast::TyU8 => (u8::MIN as u64, u8::MAX as u64),
- ast::TyU16 => (u16::MIN as u64, u16::MAX as u64),
- ast::TyU32 => (u32::MIN as u64, u32::MAX as u64),
- ast::TyU64 => (u64::MIN, u64::MAX)
+ ast::TyUs(_) => (u64::MIN, u64::MAX),
+ ast::TyU8 => (u8::MIN as u64, u8::MAX as u64),
+ ast::TyU16 => (u16::MIN as u64, u16::MAX as u64),
+ ast::TyU32 => (u32::MIN as u64, u32::MAX as u64),
+ ast::TyU64 => (u64::MIN, u64::MAX)
}
}
fn float_ty_range(float_ty: ast::FloatTy) -> (f64, f64) {
match float_ty {
- ast::TyF32 => (f32::MIN as f64, f32::MAX as f64),
- ast::TyF64 => (f64::MIN, f64::MAX)
+ ast::TyF32 => (f32::MIN as f64, f32::MAX as f64),
+ ast::TyF64 => (f64::MIN, f64::MAX)
}
}
fn int_ty_bits(int_ty: ast::IntTy, target_int_ty: ast::IntTy) -> u64 {
match int_ty {
- ast::TyIs(_) => int_ty_bits(target_int_ty, target_int_ty),
- ast::TyI8 => i8::BITS as u64,
- ast::TyI16 => i16::BITS as u64,
- ast::TyI32 => i32::BITS as u64,
- ast::TyI64 => i64::BITS as u64
+ ast::TyIs(_) => int_ty_bits(target_int_ty, target_int_ty),
+ ast::TyI8 => i8::BITS as u64,
+ ast::TyI16 => i16::BITS as u64,
+ ast::TyI32 => i32::BITS as u64,
+ ast::TyI64 => i64::BITS as u64
}
}
fn uint_ty_bits(uint_ty: ast::UintTy, target_uint_ty: ast::UintTy) -> u64 {
match uint_ty {
- ast::TyUs(_) => uint_ty_bits(target_uint_ty, target_uint_ty),
- ast::TyU8 => u8::BITS as u64,
- ast::TyU16 => u16::BITS as u64,
- ast::TyU32 => u32::BITS as u64,
- ast::TyU64 => u64::BITS as u64
+ ast::TyUs(_) => uint_ty_bits(target_uint_ty, target_uint_ty),
+ ast::TyU8 => u8::BITS as u64,
+ ast::TyU16 => u16::BITS as u64,
+ ast::TyU32 => u32::BITS as u64,
+ ast::TyU64 => u64::BITS as u64
}
}
};
// Normalize the binop so that the literal is always on the RHS in
// the comparison
- let norm_binop = if swap { rev_binop(binop) } else { binop };
+ let norm_binop = if swap {
+ rev_binop(binop)
+ } else {
+ binop
+ };
match ty::expr_ty(tcx, expr).sty {
ty::ty_int(int_ty) => {
let (min, max) = int_ty_range(int_ty);
if !ty::is_ffi_safe(self.cx.tcx, tty) {
self.cx.span_lint(IMPROPER_CTYPES, sp,
- "found type without foreign-function-safe
- representation annotation in foreign module, consider \
- adding a #[repr(...)] attribute to the type");
+ "found type without foreign-function-safe \
+ representation annotation in foreign module, consider \
+ adding a #[repr(...)] attribute to the type");
}
}
_ => ()
impl<'a, 'tcx, 'v> Visitor<'v> for RawPtrDeriveVisitor<'a, 'tcx> {
fn visit_ty(&mut self, ty: &ast::Ty) {
- static MSG: &'static str = "use of `#[derive]` with a raw pointer";
+ const MSG: &'static str = "use of `#[derive]` with a raw pointer";
if let ast::TyPtr(..) = ty.node {
self.cx.span_lint(RAW_POINTER_DERIVE, ty.span, MSG);
}
fn check_item(&mut self, cx: &Context, item: &ast::Item) {
if !attr::contains_name(&item.attrs, "automatically_derived") {
- return
+ return;
}
let did = match item.node {
ast::ItemImpl(_, _, _, ref t_ref_opt, _, _) => {
if let &Some(ref trait_ref) = t_ref_opt {
let def_id = ty::trait_ref_to_def_id(cx.tcx, trait_ref);
if Some(def_id) == cx.tcx.lang_items.copy_trait() {
- return
+ return;
}
}
}
_ => return,
};
- if !ast_util::is_local(did) { return }
+ if !ast_util::is_local(did) {
+ return;
+ }
let item = match cx.tcx.map.find(did.node) {
Some(ast_map::NodeItem(item)) => item,
_ => return,
};
- if !self.checked_raw_pointers.insert(item.id) { return }
+ if !self.checked_raw_pointers.insert(item.id) {
+ return;
+ }
match item.node {
ast::ItemStruct(..) | ast::ItemEnum(..) => {
let mut visitor = RawPtrDeriveVisitor { cx: cx };
}
fn check_attribute(&mut self, cx: &Context, attr: &ast::Attribute) {
+ // Note that check_name() marks the attribute as used if it matches.
for &(ref name, ty) in KNOWN_ATTRIBUTES {
match ty {
AttributeType::Whitelisted
}
let t = ty::expr_ty(cx.tcx, expr);
- let mut warned = false;
- match t.sty {
+ let warned = match t.sty {
ty::ty_tup(ref tys) if tys.is_empty() => return,
ty::ty_bool => return,
ty::ty_struct(did, _) |
ty::ty_enum(did, _) => {
if ast_util::is_local(did) {
if let ast_map::NodeItem(it) = cx.tcx.map.get(did.node) {
- warned |= check_must_use(cx, &it.attrs, s.span);
+ check_must_use(cx, &it.attrs, s.span)
+ } else {
+ false
}
} else {
let attrs = csearch::get_item_attrs(&cx.sess().cstore, did);
- warned |= check_must_use(cx, &attrs[..], s.span);
+ check_must_use(cx, &attrs[..], s.span)
}
}
- _ => {}
- }
+ _ => false,
+ };
if !warned {
cx.span_lint(UNUSED_RESULTS, s.span, "unused result");
}
fn check_case(&self, cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
fn is_camel_case(ident: ast::Ident) -> bool {
let ident = token::get_ident(ident);
- if ident.is_empty() { return true; }
+ if ident.is_empty() {
+ return true;
+ }
let ident = ident.trim_matches('_');
// start with a non-lowercase letter rather than non-uppercase
fn to_camel_case(s: &str) -> String {
s.split('_').flat_map(|word| word.chars().enumerate().map(|(i, c)|
- if i == 0 { c.to_uppercase() }
- else { c }
+ if i == 0 {
+ c.to_uppercase()
+ } else {
+ c
+ }
)).collect()
}
}
fn check_item(&mut self, cx: &Context, it: &ast::Item) {
- let has_extern_repr = it.attrs.iter().map(|attr| {
+ let has_extern_repr = it.attrs.iter().any(|attr| {
attr::find_repr_attrs(cx.tcx.sess.diagnostic(), attr).iter()
.any(|r| r == &attr::ReprExtern)
- }).any(|x| x);
- if has_extern_repr { return }
+ });
+ if has_extern_repr {
+ return;
+ }
match it.node {
ast::ItemTy(..) | ast::ItemStruct(..) => {
self.check_case(cx, "trait", it.ident, it.span)
}
ast::ItemEnum(ref enum_definition, _) => {
- if has_extern_repr { return }
+ if has_extern_repr {
+ return;
+ }
self.check_case(cx, "type", it.ident, it.span);
for variant in &enum_definition.variants {
self.check_case(cx, "variant", variant.node.name, variant.span);
match cx.tcx.impl_or_trait_items.borrow().get(&did).cloned() {
None => cx.sess().span_bug(m.span, "missing method descriptor?!"),
- Some(md) => {
- match md {
- ty::MethodTraitItem(md) => {
- match md.container {
- ty::TraitContainer(..) => TraitDefaultImpl,
- ty::ImplContainer(cid) => {
- match ty::impl_trait_ref(cx.tcx, cid) {
- Some(..) => TraitImpl,
- None => PlainImpl
- }
- }
+ Some(ty::MethodTraitItem(md)) => {
+ match md.container {
+ ty::TraitContainer(..) => MethodContext::TraitDefaultImpl,
+ ty::ImplContainer(cid) => {
+ match ty::impl_trait_ref(cx.tcx, cid) {
+ Some(..) => MethodContext::TraitImpl,
+ None => MethodContext::PlainImpl
}
}
- ty::TypeTraitItem(typedef) => {
- match typedef.container {
- ty::TraitContainer(..) => TraitDefaultImpl,
- ty::ImplContainer(cid) => {
- match ty::impl_trait_ref(cx.tcx, cid) {
- Some(..) => TraitImpl,
- None => PlainImpl
- }
- }
+ }
+ },
+ Some(ty::TypeTraitItem(typedef)) => {
+ match typedef.container {
+ ty::TraitContainer(..) => MethodContext::TraitDefaultImpl,
+ ty::ImplContainer(cid) => {
+ match ty::impl_trait_ref(cx.tcx, cid) {
+ Some(..) => MethodContext::TraitImpl,
+ None => MethodContext::PlainImpl
}
}
}
- }
+ },
}
}
if c == '_' {
words.push(String::new());
true
- } else { false }
+ } else {
+ false
+ }
});
for s in str.split('_') {
let mut last_upper = false;
let mut buf = String::new();
- if s.is_empty() { continue; }
+ if s.is_empty() {
+ continue;
+ }
for ch in s.chars() {
if !buf.is_empty() && buf != "'"
&& ch.is_uppercase()
fn check_snake_case(&self, cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
fn is_snake_case(ident: ast::Ident) -> bool {
let ident = token::get_ident(ident);
- if ident.is_empty() { return true; }
+ if ident.is_empty() {
+ return true;
+ }
let ident = ident.trim_left_matches('\'');
let ident = ident.trim_matches('_');
_: &ast::Block, span: Span, _: ast::NodeId) {
match fk {
visit::FkMethod(ident, _, m) => match method_context(cx, m) {
- PlainImpl
- => self.check_snake_case(cx, "method", ident, span),
- TraitDefaultImpl
- => self.check_snake_case(cx, "trait method", ident, span),
+ MethodContext::PlainImpl => {
+ self.check_snake_case(cx, "method", ident, span)
+ },
+ MethodContext::TraitDefaultImpl => {
+ self.check_snake_case(cx, "trait method", ident, span)
+ },
_ => (),
},
- visit::FkItemFn(ident, _, _, _)
- => self.check_snake_case(cx, "function", ident, span),
+ visit::FkItemFn(ident, _, _, _) => {
+ self.check_snake_case(cx, "function", ident, span)
+ },
_ => (),
}
}
}
fn check_struct_def(&mut self, cx: &Context, s: &ast::StructDef,
- _: ast::Ident, _: &ast::Generics, _: ast::NodeId) {
+ _: ast::Ident, _: &ast::Generics, _: ast::NodeId) {
for sf in &s.fields {
if let ast::StructField_ { kind: ast::NamedField(ident, _), .. } = sf.node {
self.check_snake_case(cx, "structure field", ident, sf.span);
impl UnusedParens {
fn check_unused_parens_core(&self, cx: &Context, value: &ast::Expr, msg: &str,
- struct_lit_needs_parens: bool) {
+ struct_lit_needs_parens: bool) {
if let ast::ExprParen(ref inner) = value.node {
let necessary = struct_lit_needs_parens && contains_exterior_struct_lit(&**inner);
if !necessary {
cx.span_lint(UNUSED_PARENS, value.span,
- &format!("unnecessary parentheses around {}",
- msg))
+ &format!("unnecessary parentheses around {}", msg))
}
}
}
fn check_item(&mut self, cx: &Context, item: &ast::Item) {
- match item.node {
- ast::ItemUse(ref view_path) => {
- match view_path.node {
- ast::ViewPathList(_, ref items) => {
- if items.len() == 1 {
- match items[0].node {
- ast::PathListIdent {ref name, ..} => {
- let m = format!("braces around {} is unnecessary",
- &token::get_ident(*name));
- cx.span_lint(UNUSED_IMPORT_BRACES, item.span,
- &m[..]);
- },
- _ => ()
- }
- }
+ if let ast::ItemUse(ref view_path) = item.node {
+ if let ast::ViewPathList(_, ref items) = view_path.node {
+ if items.len() == 1 {
+ if let ast::PathListIdent {ref name, ..} = items[0].node {
+ let m = format!("braces around {} is unnecessary",
+ &token::get_ident(*name));
+ cx.span_lint(UNUSED_IMPORT_BRACES, item.span,
+ &m[..]);
}
- _ => ()
}
- },
- _ => ()
+ }
}
}
}
fn check_pat(&mut self, cx: &Context, pat: &ast::Pat) {
let def_map = cx.tcx.def_map.borrow();
if let ast::PatStruct(_, ref v, _) = pat.node {
- let field_pats = v.iter()
- .filter(|fieldpat| !fieldpat.node.is_shorthand)
- .filter(|fieldpat| {
+ let field_pats = v.iter().filter(|fieldpat| {
+ if fieldpat.node.is_shorthand {
+ return false;
+ }
let def = def_map.get(&fieldpat.node.pat.id).map(|d| d.full_def());
def == Some(def::DefLocal(fieldpat.node.pat.id))
});
desc: &'static str) {
// If we're building a test harness, then warning about
// documentation is probably not really relevant right now.
- if cx.sess().opts.test { return }
+ if cx.sess().opts.test {
+ return;
+ }
// `#[doc(hidden)]` disables missing_docs check.
- if self.doc_hidden() { return }
+ if self.doc_hidden() {
+ return;
+ }
// Only check publicly-visible items, using the result from the privacy pass.
// It's an option so the crate root can also use this function (it doesn't
});
if !has_doc {
cx.span_lint(MISSING_DOCS, sp,
- &format!("missing documentation for {}", desc));
+ &format!("missing documentation for {}", desc));
}
}
}
self.doc_hidden_stack.pop().expect("empty doc_hidden_stack");
}
- fn check_struct_def(&mut self, _: &Context,
- _: &ast::StructDef, _: ast::Ident, _: &ast::Generics, id: ast::NodeId) {
+ fn check_struct_def(&mut self, _: &Context, _: &ast::StructDef,
+ _: ast::Ident, _: &ast::Generics, id: ast::NodeId) {
self.struct_def_stack.push(id);
}
- fn check_struct_def_post(&mut self, _: &Context,
- _: &ast::StructDef, _: ast::Ident, _: &ast::Generics, id: ast::NodeId) {
+ fn check_struct_def_post(&mut self, _: &Context, _: &ast::StructDef,
+ _: ast::Ident, _: &ast::Generics, id: ast::NodeId) {
let popped = self.struct_def_stack.pop().expect("empty struct_def_stack");
assert!(popped == id);
}
fn check_crate(&mut self, cx: &Context, krate: &ast::Crate) {
- self.check_missing_docs_attrs(cx, None, &krate.attrs,
- krate.span, "crate");
+ self.check_missing_docs_attrs(cx, None, &krate.attrs, krate.span, "crate");
}
fn check_item(&mut self, cx: &Context, it: &ast::Item) {
ast::ItemTy(..) => "a type alias",
_ => return
};
- self.check_missing_docs_attrs(cx, Some(it.id), &it.attrs,
- it.span, desc);
+ self.check_missing_docs_attrs(cx, Some(it.id), &it.attrs, it.span, desc);
}
- fn check_fn(&mut self, cx: &Context,
- fk: visit::FnKind, _: &ast::FnDecl,
- _: &ast::Block, _: Span, _: ast::NodeId) {
+ fn check_fn(&mut self, cx: &Context, fk: visit::FnKind, _: &ast::FnDecl,
+ _: &ast::Block, _: Span, _: ast::NodeId) {
if let visit::FkMethod(_, _, m) = fk {
// If the method is an impl for a trait, don't doc.
- if method_context(cx, m) == TraitImpl { return; }
+ if method_context(cx, m) == MethodContext::TraitImpl {
+ return;
+ }
// Otherwise, doc according to privacy. This will also check
// doc for default methods defined on traits.
- self.check_missing_docs_attrs(cx, Some(m.id), &m.attrs,
- m.span, "a method");
+ self.check_missing_docs_attrs(cx, Some(m.id), &m.attrs, m.span, "a method");
}
}
fn check_ty_method(&mut self, cx: &Context, tm: &ast::TypeMethod) {
- self.check_missing_docs_attrs(cx, Some(tm.id), &tm.attrs,
- tm.span, "a type method");
+ self.check_missing_docs_attrs(cx, Some(tm.id), &tm.attrs, tm.span, "a type method");
}
- fn check_trait_method(&mut self, cx: &Context, it: &ast::TraitItem) {
+ fn check_trait_item(&mut self, cx: &Context, it: &ast::TraitItem) {
if let ast::TraitItem::TypeTraitItem(ref ty) = *it {
let assoc_ty = &ty.ty_param;
self.check_missing_docs_attrs(cx, Some(assoc_ty.id), &ty.attrs,
}
fn check_variant(&mut self, cx: &Context, v: &ast::Variant, _: &ast::Generics) {
- self.check_missing_docs_attrs(cx, Some(v.node.id), &v.node.attrs,
- v.span, "a variant");
+ self.check_missing_docs_attrs(cx, Some(v.node.id), &v.node.attrs, v.span, "a variant");
assert!(!self.in_variant);
self.in_variant = true;
}
fn check_item(&mut self, cx: &Context, item: &ast::Item) {
if !cx.exported_items.contains(&item.id) {
- return
+ return;
}
if cx.tcx
.destructor_for_type
.borrow()
.contains_key(&ast_util::local_def(item.id)) {
- return
+ return;
}
let ty = match item.node {
ast::ItemStruct(_, ref ast_generics) => {
if ast_generics.is_parameterized() {
- return
+ return;
}
ty::mk_struct(cx.tcx,
ast_util::local_def(item.id),
}
ast::ItemEnum(_, ref ast_generics) => {
if ast_generics.is_parameterized() {
- return
+ return;
}
ty::mk_enum(cx.tcx,
ast_util::local_def(item.id),
};
let parameter_environment = ty::empty_parameter_environment(cx.tcx);
if !ty::type_moves_by_default(¶meter_environment, item.span, ty) {
- return
+ return;
}
if ty::can_type_implement_copy(¶meter_environment, item.span, ty).is_ok() {
cx.span_lint(MISSING_COPY_IMPLEMENTATIONS,
let impls = match impls.get(&debug) {
Some(impls) => {
impls.borrow().iter()
- .filter(|d| d.krate == ast::LOCAL_CRATE)
- .filter_map(|d| ty::ty_to_def_id(ty::node_id_to_type(cx.tcx, d.node)))
- .map(|d| d.node)
- .collect()
+ .filter(|d| d.krate == ast::LOCAL_CRATE)
+ .filter_map(|d| ty::ty_to_def_id(ty::node_id_to_type(cx.tcx, d.node)))
+ .map(|d| d.node)
+ .collect()
}
None => NodeSet(),
};
impl Stability {
fn lint(&self, cx: &Context, _id: ast::DefId, span: Span, stability: &Option<attr::Stability>) {
-
- // deprecated attributes apply in-crate and cross-crate
+ // Deprecated attributes apply in-crate and cross-crate.
let (lint, label) = match *stability {
Some(attr::Stability { deprecated_since: Some(_), .. }) =>
(DEPRECATED, "deprecated"),
let mut visited = BitSet::new();
while let Some(idx) = work_queue.pop() {
- let cfg_id = idx.node_id();
if idx == cfg.exit {
// found a path!
reached_exit_without_self_call = true;
- break
- } else if visited.contains(&cfg_id) {
+ break;
+ }
+
+ let cfg_id = idx.node_id();
+ if visited.contains(&cfg_id) {
// already done
- continue
+ continue;
}
visited.insert(cfg_id);
+
let node_id = cfg.graph.node_data(idx).id();
// is this a recursive call?
if node_id != ast::DUMMY_NODE_ID && checker(cx.tcx, impl_node_id, id, name, node_id) {
-
self_call_spans.push(cx.tcx.map.span(node_id));
// this is a self call, so we shouldn't explore past
// this node in the CFG.
- continue
+ continue;
}
// add the successors of this node to explore the graph further.
cfg.graph.each_outgoing_edge(idx, |_, edge| {
});
}
- // check the number of sell calls because a function that
+ // Check the number of self calls because a function that
// doesn't return (e.g. calls a `-> !` function or `loop { /*
// no break */ }`) shouldn't be linted unless it actually
// recurs.
_: ast::Ident,
id: ast::NodeId) -> bool {
tcx.def_map.borrow().get(&id)
- .map_or(false, |def| def.def_id() == ast_util::local_def(fn_id))
+ .map_or(false, |def| def.def_id() == ast_util::local_def(fn_id))
}
// check if the method call `id` refers to method `method_id`
tcx.map.span(id),
"non-method call expr behaving like a method call?")
};
- // it matches if it comes from the same impl,
+ // It matches if it comes from the same impl,
// and has the same method name.
return ast_util::is_local(impl_def_id)
&& impl_def_id.node == impl_id
if decoder::get_plugin_registrar_fn(md.data()).is_some() {
cx.span_lint(PLUGIN_AS_LIBRARY, it.span,
- "compiler plugin used as an ordinary library");
+ "compiler plugin used as an ordinary library");
}
}
}
// Const items do not refer to a particular location in memory, and therefore
// don't have anything to attach a symbol to
let msg = "const items should never be #[no_mangle], consider instead using \
- `pub static`";
+ `pub static`";
cx.span_lint(NO_MANGLE_CONST_ITEMS, it.span, msg);
}
}
#[derive(Copy)]
pub struct UnstableFeatures;
-declare_lint!(UNSTABLE_FEATURES, Allow,
- "enabling unstable features");
+declare_lint! {
+ UNSTABLE_FEATURES,
+ Allow,
+ "enabling unstable features"
+}
impl LintPass for UnstableFeatures {
fn get_lints(&self) -> LintArray {
lint_array!(UNSTABLE_FEATURES)
}
fn check_attribute(&mut self, ctx: &Context, attr: &ast::Attribute) {
- use syntax::attr;
if attr::contains_name(&[attr.node.value.clone()], "feature") {
ctx.span_lint(UNSTABLE_FEATURES, attr.span, "unstable feature");
}
}
}
Some(ref tr) => {
- // Any private types in a trait impl fall into two
+ // Any private types in a trait impl fall into three
// categories.
// 1. mentioned in the trait definition
// 2. mentioned in the type params/generics
+ // 3. mentioned in the associated types of the impl
//
// Those in 1. can only occur if the trait is in
// this crate and will've been warned about on the
// Those in 2. are warned via walk_generics and this
// call here.
visit::walk_path(self, &tr.path);
+
+ // Those in 3. are warned with this call.
+ for impl_item in impl_items {
+ match *impl_item {
+ ast::MethodImplItem(..) => {},
+ ast::TypeImplItem(ref typedef) => {
+ self.visit_ty(&typedef.typ);
+ }
+ }
+ }
}
}
} else if trait_ref.is_none() && self_is_public_path {
// e.g. `fn foo() { { fn a() {} } { fn a() {} } }`, so we
// generate unique characters from the node id. For now
// hopefully 3 characters is enough to avoid collisions.
- static EXTRA_CHARS: &'static str =
+ const EXTRA_CHARS: &'static str =
"abcdefghijklmnopqrstuvwxyz\
ABCDEFGHIJKLMNOPQRSTUVWXYZ\
0123456789";
// Irrefutable columns always go first, they'd only be duplicated in the branches.
if total_score == 0 {
- std::uint::MAX
+ std::usize::MAX
} else {
total_score
}
Univariant(mk_struct(cx, &ftys[..], packed, t), dtor)
}
- ty::ty_closure(def_id, _, substs) => {
+ ty::ty_closure(def_id, substs) => {
let typer = NormalizingClosureTyper::new(cx.tcx());
let upvars = typer.closure_upvars(def_id, substs).unwrap();
let upvar_types = upvars.iter().map(|u| u.ty).collect::<Vec<_>>();
debug!("range_to_inttype: {:?} {:?}", hint, bounds);
// Lists of sizes to try. u64 is always allowed as a fallback.
#[allow(non_upper_case_globals)]
- static choose_shortest: &'static[IntType] = &[
+ const choose_shortest: &'static [IntType] = &[
attr::UnsignedInt(ast::TyU8), attr::SignedInt(ast::TyI8),
attr::UnsignedInt(ast::TyU16), attr::SignedInt(ast::TyI16),
attr::UnsignedInt(ast::TyU32), attr::SignedInt(ast::TyI32)];
#[allow(non_upper_case_globals)]
- static at_least_32: &'static[IntType] = &[
+ const at_least_32: &'static [IntType] = &[
attr::UnsignedInt(ast::TyU32), attr::SignedInt(ast::TyI32)];
let attempts;
let fcx = bcx.fcx;
let custom_cleanup_scope = fcx.push_custom_cleanup_scope();
let scratch = unpack_datum!(bcx, datum::lvalue_scratch_datum(
- bcx, tcx.types.bool, "drop_flag", false,
+ bcx, tcx.types.bool, "drop_flag",
cleanup::CustomScope(custom_cleanup_scope), (), |_, bcx, _| bcx
));
bcx = fold_variants(bcx, r, val, |variant_cx, st, value| {
ty::ty_bare_fn(_, ref f) => {
(&f.sig, f.abi, None)
}
- ty::ty_closure(closure_did, _, substs) => {
+ ty::ty_closure(closure_did, substs) => {
let typer = common::NormalizingClosureTyper::new(ccx.tcx());
function_type = typer.closure_type(closure_did, substs);
let self_type = self_type_for_closure(ccx, closure_did, fn_ty);
}
})
}
- ty::ty_closure(def_id, _, substs) => {
+ ty::ty_closure(def_id, substs) => {
let repr = adt::represent_type(cx.ccx(), t);
let typer = common::NormalizingClosureTyper::new(cx.tcx());
let upvars = typer.closure_upvars(def_id, substs).unwrap();
Alloca(cx, ty, name)
}
-pub fn alloca_zeroed<'blk, 'tcx>(cx: Block<'blk, 'tcx>, ty: Ty<'tcx>,
- name: &str) -> ValueRef {
- let llty = type_of::type_of(cx.ccx(), ty);
- if cx.unreachable.get() {
- unsafe {
- return llvm::LLVMGetUndef(llty.ptr_to().to_ref());
- }
- }
- let p = alloca_no_lifetime(cx, llty, name);
- let b = cx.fcx.ccx.builder();
- b.position_before(cx.fcx.alloca_insert_pt.get().unwrap());
- memzero(&b, p, ty);
- p
-}
-
// Creates the alloca slot which holds the pointer to the slot for the final return value
pub fn make_return_slot_pointer<'a, 'tcx>(fcx: &FunctionContext<'a, 'tcx>,
output_type: Ty<'tcx>) -> ValueRef {
datum::lvalue_scratch_datum(bcx,
arg_ty,
"tupled_args",
- false,
tuple_args_scope_id,
(),
|(),
use middle::ty::{BrAnon, ReLateBound};
let function_type;
- let (fn_sig, abi, has_env) = match fn_ty.sty {
- ty::ty_bare_fn(_, ref f) => (&f.sig, f.abi, false),
- ty::ty_closure(closure_did, _, substs) => {
+ let (fn_sig, abi, env_ty) = match fn_ty.sty {
+ ty::ty_bare_fn(_, ref f) => (&f.sig, f.abi, None),
+ ty::ty_closure(closure_did, substs) => {
let typer = common::NormalizingClosureTyper::new(ccx.tcx());
function_type = typer.closure_type(closure_did, substs);
- (&function_type.sig, RustCall, true)
+ let self_type = self_type_for_closure(ccx, closure_did, fn_ty);
+ (&function_type.sig, RustCall, Some(self_type))
}
_ => ccx.sess().bug("expected closure or function.")
};
let fn_sig = ty::erase_late_bound_regions(ccx.tcx(), fn_sig);
- // Since index 0 is the return value of the llvm func, we start
- // at either 1 or 2 depending on whether there's an env slot or not
- let mut first_arg_offset = if has_env { 2 } else { 1 };
let mut attrs = llvm::AttrBuilder::new();
let ret_ty = fn_sig.output;
// These have an odd calling convention, so we need to manually
// unpack the input ty's
let input_tys = match fn_ty.sty {
- ty::ty_closure(_, _, _) => {
+ ty::ty_closure(..) => {
assert!(abi == RustCall);
match fn_sig.inputs[0].sty {
- ty::ty_tup(ref inputs) => inputs.clone(),
+ ty::ty_tup(ref inputs) => {
+ let mut full_inputs = vec![env_ty.expect("Missing closure environment")];
+ full_inputs.push_all(inputs);
+ full_inputs
+ }
_ => ccx.sess().bug("expected tuple'd inputs")
}
},
_ => fn_sig.inputs.clone()
};
+ // Index 0 is the return value of the llvm func, so we start at 1
+ let mut first_arg_offset = 1;
if let ty::FnConverging(ret_ty) = ret_ty {
// A function pointer is called without the declaration
// available, so we have to apply any attributes with ABI
let _icx = push_ctxt("trans_method_call");
debug!("trans_method_call(call_expr={})", call_expr.repr(bcx.tcx()));
let method_call = MethodCall::expr(call_expr.id);
- let method_ty = (*bcx.tcx().method_map.borrow())[method_call].ty;
+ let method_ty = match bcx.tcx().method_map.borrow().get(&method_call) {
+ Some(method) => match method.origin {
+ ty::MethodTraitObject(_) => match method.ty.sty {
+ ty::ty_bare_fn(_, ref fty) => {
+ ty::mk_bare_fn(bcx.tcx(), None, meth::opaque_method_ty(bcx.tcx(), fty))
+ }
+ _ => method.ty
+ },
+ _ => method.ty
+ },
+ None => panic!("method not found in trans_method_call")
+ };
trans_call_inner(
bcx,
call_expr.debug_loc(),
tuple_expr.id));
let repr = adt::represent_type(bcx.ccx(), tuple_type);
let repr_ptr = &*repr;
- for i in 0..field_types.len() {
+ llargs.extend(field_types.iter().enumerate().map(|(i, field_type)| {
let arg_datum = tuple_lvalue_datum.get_element(
bcx,
- field_types[i],
+ field_type,
|srcval| {
adt::trans_field_ptr(bcx, repr_ptr, srcval, 0, i)
- });
- let arg_datum = arg_datum.to_expr_datum();
- let arg_datum =
- unpack_datum!(bcx, arg_datum.to_rvalue_datum(bcx, "arg"));
- let arg_datum =
- unpack_datum!(bcx, arg_datum.to_appropriate_datum(bcx));
- llargs.push(arg_datum.add_clean(bcx.fcx, arg_cleanup_scope));
- }
+ }).to_expr_datum();
+ unpack_result!(bcx, trans_arg_datum(
+ bcx,
+ field_type,
+ arg_datum,
+ arg_cleanup_scope,
+ DontAutorefArg)
+ )
+ }));
}
_ => {
bcx.sess().span_bug(tuple_expr.span,
// duplicate declarations
let function_type = erase_regions(ccx.tcx(), &function_type);
let params = match function_type.sty {
- ty::ty_closure(_, _, substs) => &substs.types,
+ ty::ty_closure(_, substs) => &substs.types,
_ => unreachable!()
};
let mono_id = MonoId {
/// Allocates temporary space on the stack using alloca() and returns a by-ref Datum pointing to
/// it. The memory will be dropped upon exit from `scope`. The callback `populate` should
-/// initialize the memory. If `zero` is true, the space will be zeroed when it is allocated; this
-/// is not necessary unless `bcx` does not dominate the end of `scope`.
+/// initialize the memory.
pub fn lvalue_scratch_datum<'blk, 'tcx, A, F>(bcx: Block<'blk, 'tcx>,
ty: Ty<'tcx>,
name: &str,
- zero: bool,
scope: cleanup::ScopeId,
arg: A,
populate: F)
-> DatumBlock<'blk, 'tcx, Lvalue> where
F: FnOnce(A, Block<'blk, 'tcx>, ValueRef) -> Block<'blk, 'tcx>,
{
- let scratch = if zero {
- alloca_zeroed(bcx, ty, name)
- } else {
- let llty = type_of::type_of(bcx.ccx(), ty);
- alloca(bcx, llty, name)
- };
+ let llty = type_of::type_of(bcx.ccx(), ty);
+ let scratch = alloca(bcx, llty, name);
// Subtle. Populate the scratch memory *before* scheduling cleanup.
let bcx = populate(arg, bcx, scratch);
ByValue => {
lvalue_scratch_datum(
- bcx, self.ty, name, false, scope, self,
+ bcx, self.ty, name, scope, self,
|this, bcx, llval| this.store_to(bcx, llval))
}
}
}
}
},
- ty::ty_closure(def_id, _, substs) => {
+ ty::ty_closure(def_id, substs) => {
let typer = NormalizingClosureTyper::new(cx.tcx());
let closure_ty = typer.closure_type(def_id, substs);
self.get_unique_type_id_of_closure_type(cx,
ty::ty_bare_fn(_, ref barefnty) => {
subroutine_type_metadata(cx, unique_type_id, &barefnty.sig, usage_site_span)
}
- ty::ty_closure(def_id, _, substs) => {
+ ty::ty_closure(def_id, substs) => {
let typer = NormalizingClosureTyper::new(cx.tcx());
let sig = typer.closure_type(def_id, substs).sig;
subroutine_type_metadata(cx, unique_type_id, &sig, usage_site_span)
ty::mk_nil(bcx.tcx()));
let (_, variant_cx) = invoke(variant_cx, dtor_addr, &args[..], dtor_ty, DebugLoc::None);
- variant_cx.fcx.pop_and_trans_custom_cleanup_scope(variant_cx, field_scope);
- variant_cx
+ variant_cx.fcx.pop_and_trans_custom_cleanup_scope(variant_cx, field_scope)
})
}
use syntax::codemap::DUMMY_SP;
// drop_glue pointer, size, align.
-static VTABLE_OFFSET: uint = 3;
+const VTABLE_OFFSET: uint = 3;
/// The main "translation" pass for methods. Generates code
/// for non-monomorphized methods only. Other methods will
};
let fty = monomorphize::apply_param_substs(tcx, &object_substs, &method_ty.fty);
let fty = tcx.mk_bare_fn(fty);
- debug!("trans_object_shim: fty={}", fty.repr(tcx));
+ let method_ty = opaque_method_ty(tcx, fty);
+ debug!("trans_object_shim: fty={} method_ty={}", fty.repr(tcx), method_ty.repr(tcx));
//
- let method_bare_fn_ty =
- ty::mk_bare_fn(tcx, None, fty);
+ let shim_fn_ty = ty::mk_bare_fn(tcx, None, fty);
+ let method_bare_fn_ty = ty::mk_bare_fn(tcx, None, method_ty);
let function_name =
- link::mangle_internal_name_by_type_and_seq(ccx, method_bare_fn_ty, "object_shim");
+ link::mangle_internal_name_by_type_and_seq(ccx, shim_fn_ty, "object_shim");
let llfn =
- decl_internal_rust_fn(ccx, method_bare_fn_ty, &function_name);
+ decl_internal_rust_fn(ccx, shim_fn_ty, &function_name);
let sig = ty::erase_late_bound_regions(ccx.tcx(), &fty.sig);
bcx
}
+
+/// Replace the self type (&Self or Box<Self>) with an opaque pointer.
+pub fn opaque_method_ty<'tcx>(tcx: &ty::ctxt<'tcx>, method_ty: &ty::BareFnTy<'tcx>)
+ -> &'tcx ty::BareFnTy<'tcx> {
+ let mut inputs = method_ty.sig.0.inputs.clone();
+ inputs[0] = ty::mk_mut_ptr(tcx, ty::mk_mach_int(tcx, ast::TyI8));
+
+ tcx.mk_bare_fn(ty::BareFnTy {
+ unsafety: method_ty.unsafety,
+ abi: method_ty.abi,
+ sig: ty::Binder(ty::FnSig {
+ inputs: inputs,
+ output: method_ty.sig.0.output,
+ variadic: method_ty.sig.0.variadic,
+ }),
+ })
+}
return Some(CallStep::Builtin);
}
- ty::ty_closure(def_id, _, substs) => {
+ ty::ty_closure(def_id, substs) => {
assert_eq!(def_id.krate, ast::LOCAL_CRATE);
// Check whether this is a call to a closure where we
use middle::region;
use middle::subst;
use middle::ty::{self, ToPolyTraitRef, Ty};
-use rscope::RegionScope;
use syntax::abi;
use syntax::ast;
use syntax::ast_util;
abi::RustCall,
expected_sig);
- let region = match fcx.anon_regions(expr.span, 1) {
- Err(_) => {
- fcx.ccx.tcx.sess.span_bug(expr.span,
- "can't make anon regions here?!")
- }
- Ok(regions) => regions[0],
- };
-
let closure_type = ty::mk_closure(fcx.ccx.tcx,
expr_def_id,
- fcx.ccx.tcx.mk_region(region),
fcx.ccx.tcx.mk_substs(
fcx.inh.param_env.free_substs.clone()));
use middle::region;
use middle::subst;
use middle::ty::{self, Ty};
-use util::ppaux::{Repr};
+use util::ppaux::{Repr, UserString};
+use syntax::ast;
use syntax::codemap::Span;
pub fn check_safety_of_destructor_if_necessary<'a, 'tcx>(rcx: &mut Rcx<'a, 'tcx>,
// types that have been traversed so far by `traverse_type_if_unseen`
let mut breadcrumbs: Vec<Ty<'tcx>> = Vec::new();
- iterate_over_potentially_unsafe_regions_in_type(
+ let result = iterate_over_potentially_unsafe_regions_in_type(
rcx,
&mut breadcrumbs,
+ TypeContext::Root,
typ,
span,
scope,
+ 0,
0);
+ match result {
+ Ok(()) => {}
+ Err(Error::Overflow(ref ctxt, ref detected_on_typ)) => {
+ let tcx = rcx.tcx();
+ span_err!(tcx.sess, span, E0320,
+ "overflow while adding drop-check rules for {}",
+ typ.user_string(rcx.tcx()));
+ match *ctxt {
+ TypeContext::Root => {
+ // no need for an additional note if the overflow
+ // was somehow on the root.
+ }
+ TypeContext::EnumVariant { def_id, variant, arg_index } => {
+ // FIXME (pnkfelix): eventually lookup arg_name
+ // for the given index on struct variants.
+ span_note!(
+ rcx.tcx().sess,
+ span,
+ "overflowed on enum {} variant {} argument {} type: {}",
+ ty::item_path_str(tcx, def_id),
+ variant,
+ arg_index,
+ detected_on_typ.user_string(rcx.tcx()));
+ }
+ TypeContext::Struct { def_id, field } => {
+ span_note!(
+ rcx.tcx().sess,
+ span,
+ "overflowed on struct {} field {} type: {}",
+ ty::item_path_str(tcx, def_id),
+ field,
+ detected_on_typ.user_string(rcx.tcx()));
+ }
+ }
+ }
+ }
+}
+
+enum Error<'tcx> {
+ Overflow(TypeContext, ty::Ty<'tcx>),
+}
+
+enum TypeContext {
+ Root,
+ EnumVariant {
+ def_id: ast::DefId,
+ variant: ast::Name,
+ arg_index: usize,
+ },
+ Struct {
+ def_id: ast::DefId,
+ field: ast::Name,
+ }
}
+// The `depth` counts the number of calls to this function;
+// the `xref_depth` counts the subset of such calls that go
+// across a `Box<T>` or `PhantomData<T>`.
fn iterate_over_potentially_unsafe_regions_in_type<'a, 'tcx>(
rcx: &mut Rcx<'a, 'tcx>,
breadcrumbs: &mut Vec<Ty<'tcx>>,
+ context: TypeContext,
ty_root: ty::Ty<'tcx>,
span: Span,
scope: region::CodeExtent,
- depth: uint)
+ depth: uint,
+ xref_depth: uint) -> Result<(), Error<'tcx>>
{
+ // Issue #22443: Watch out for overflow. While we are careful to
+ // handle regular types properly, non-regular ones cause problems.
+ let recursion_limit = rcx.tcx().sess.recursion_limit.get();
+ if xref_depth >= recursion_limit {
+ return Err(Error::Overflow(context, ty_root))
+ }
+
let origin = || infer::SubregionOrigin::SafeDestructor(span);
let mut walker = ty_root.walk();
let opt_phantom_data_def_id = rcx.tcx().lang_items.phantom_data();
let destructor_for_type = rcx.tcx().destructor_for_type.borrow();
+ let xref_depth_orig = xref_depth;
+
while let Some(typ) = walker.next() {
// Avoid recursing forever.
if breadcrumbs.contains(&typ) {
// If we encounter `PhantomData<T>`, then we should replace it
// with `T`, the type it represents as owned by the
// surrounding context, before doing further analysis.
- let typ = if let ty::ty_struct(struct_did, substs) = typ.sty {
- if opt_phantom_data_def_id == Some(struct_did) {
- let item_type = ty::lookup_item_type(rcx.tcx(), struct_did);
- let tp_def = item_type.generics.types
- .opt_get(subst::TypeSpace, 0).unwrap();
- let new_typ = substs.type_for_def(tp_def);
- debug!("replacing phantom {} with {}",
+ let (typ, xref_depth) = match typ.sty {
+ ty::ty_struct(struct_did, substs) => {
+ if opt_phantom_data_def_id == Some(struct_did) {
+ let item_type = ty::lookup_item_type(rcx.tcx(), struct_did);
+ let tp_def = item_type.generics.types
+ .opt_get(subst::TypeSpace, 0).unwrap();
+ let new_typ = substs.type_for_def(tp_def);
+ debug!("replacing phantom {} with {}",
+ typ.repr(rcx.tcx()), new_typ.repr(rcx.tcx()));
+ (new_typ, xref_depth_orig + 1)
+ } else {
+ (typ, xref_depth_orig)
+ }
+ }
+
+ // Note: When ty_uniq is removed from compiler, the
+ // definition of `Box<T>` must carry a PhantomData that
+ // puts us into the previous case.
+ ty::ty_uniq(new_typ) => {
+ debug!("replacing ty_uniq {} with {}",
typ.repr(rcx.tcx()), new_typ.repr(rcx.tcx()));
- new_typ
- } else {
- typ
+ (new_typ, xref_depth_orig + 1)
+ }
+
+ _ => {
+ (typ, xref_depth_orig)
}
- } else {
- typ
};
let opt_type_did = match typ.sty {
opt_type_did.and_then(|did| destructor_for_type.get(&did));
debug!("iterate_over_potentially_unsafe_regions_in_type \
- {}typ: {} scope: {:?} opt_dtor: {:?}",
+ {}typ: {} scope: {:?} opt_dtor: {:?} xref: {}",
(0..depth).map(|_| ' ').collect::<String>(),
- typ.repr(rcx.tcx()), scope, opt_dtor);
+ typ.repr(rcx.tcx()), scope, opt_dtor, xref_depth);
// If `typ` has a destructor, then we must ensure that all
// borrowed data reachable via `typ` must outlive the parent
match typ.sty {
ty::ty_struct(struct_did, substs) => {
+ debug!("typ: {} is struct; traverse structure and not type-expression",
+ typ.repr(rcx.tcx()));
// Don't recurse; we extract type's substructure,
// so do not process subparts of type expression.
walker.skip_current_subtree();
struct_did,
field.id,
substs);
- iterate_over_potentially_unsafe_regions_in_type(
+ try!(iterate_over_potentially_unsafe_regions_in_type(
rcx,
breadcrumbs,
+ TypeContext::Struct {
+ def_id: struct_did,
+ field: field.name,
+ },
field_type,
span,
scope,
- depth+1)
+ depth+1,
+ xref_depth))
}
}
ty::ty_enum(enum_did, substs) => {
+ debug!("typ: {} is enum; traverse structure and not type-expression",
+ typ.repr(rcx.tcx()));
// Don't recurse; we extract type's substructure,
// so do not process subparts of type expression.
walker.skip_current_subtree();
enum_did,
substs);
for variant_info in all_variant_info.iter() {
- for argument_type in variant_info.args.iter() {
- iterate_over_potentially_unsafe_regions_in_type(
+ for (i, arg_type) in variant_info.args.iter().enumerate() {
+ try!(iterate_over_potentially_unsafe_regions_in_type(
rcx,
breadcrumbs,
- *argument_type,
+ TypeContext::EnumVariant {
+ def_id: enum_did,
+ variant: variant_info.name,
+ arg_index: i,
+ },
+ *arg_type,
span,
scope,
- depth+1)
+ depth+1,
+ xref_depth));
}
}
}
// is done.
}
}
+
+ return Ok(());
}
pub enum Implication<'tcx> {
RegionSubRegion(Option<Ty<'tcx>>, ty::Region, ty::Region),
RegionSubGeneric(Option<Ty<'tcx>>, ty::Region, GenericKind<'tcx>),
+ RegionSubClosure(Option<Ty<'tcx>>, ty::Region, ast::DefId, &'tcx Substs<'tcx>),
Predicate(ast::DefId, ty::Predicate<'tcx>),
}
// No borrowed content reachable here.
}
- ty::ty_closure(_, region, _) => {
- // An "closure type" is basically
- // modeled here as equivalent to a struct like
- //
- // struct TheClosure<'b> {
- // ...
- // }
- //
- // where the `'b` is the lifetime bound of the
- // contents (i.e., all contents must outlive 'b).
- //
- // Even though closures are glorified structs
- // of upvars, we do not need to consider them as they
- // can't generate any new constraints. The
- // substitutions on the closure are equal to the free
- // substitutions of the enclosing parameter
- // environment. An upvar captured by value has the
- // same type as the original local variable which is
- // already checked for consistency. If the upvar is
- // captured by reference it must also outlive the
- // region bound on the closure, but this is explicitly
- // handled by logic in regionck.
- self.push_region_constraint_from_top(*region);
+ ty::ty_closure(def_id, substs) => {
+ let &(r_a, opt_ty) = self.stack.last().unwrap();
+ self.out.push(Implication::RegionSubClosure(opt_ty, r_a, def_id, substs));
}
ty::ty_trait(ref t) => {
p.repr(tcx))
}
+ Implication::RegionSubClosure(_, ref a, ref b, ref c) => {
+ format!("RegionSubClosure({}, {}, {})",
+ a.repr(tcx),
+ b.repr(tcx),
+ c.repr(tcx))
+ }
+
Implication::Predicate(ref def_id, ref p) => {
format!("Predicate({}, {})",
def_id.repr(tcx),
}
ty::ty_enum(did, _) |
ty::ty_struct(did, _) |
- ty::ty_closure(did, _, _) => {
+ ty::ty_closure(did, _) => {
self.assemble_inherent_impl_candidates_for_type(did);
}
ty::ty_uniq(_) => {
// If so, add "synthetic impls".
let steps = self.steps.clone();
for step in &*steps {
- let (closure_def_id, _, _) = match step.self_ty.sty {
- ty::ty_closure(a, b, ref c) => (a, b, c),
+ let closure_def_id = match step.self_ty.sty {
+ ty::ty_closure(a, _) => a,
_ => continue,
};
use check::FnCtxt;
use check::implicator;
use check::vtable;
-use middle::def;
use middle::mem_categorization as mc;
use middle::region::CodeExtent;
+use middle::subst::Substs;
use middle::traits;
-use middle::ty::{ReScope};
-use middle::ty::{self, Ty, MethodCall};
+use middle::ty::{self, ClosureTyper, ReScope, Ty, MethodCall};
use middle::infer::{self, GenericKind};
use middle::pat_util;
use util::ppaux::{ty_to_string, Repr};
}
-/// Returns the validity region of `def` -- that is, how long is `def` valid?
-fn region_of_def(fcx: &FnCtxt, def: def::Def) -> ty::Region {
- let tcx = fcx.tcx();
- match def {
- def::DefLocal(node_id) | def::DefUpvar(node_id, _) => {
- tcx.region_maps.var_region(node_id)
- }
- _ => {
- tcx.sess.bug(&format!("unexpected def in region_of_def: {:?}",
- def))
- }
- }
-}
-
struct RepeatingScope(ast::NodeId);
pub enum SubjectNode { Subject(ast::NodeId), None }
ty::ReInfer(ty::ReVar(vid_b))) => {
self.fcx.inh.infcx.add_given(free_a, vid_b);
}
- implicator::Implication::RegionSubRegion(..) => {
+ implicator::Implication::RegionSubGeneric(_, r_a, ref generic_b) => {
+ debug!("RegionSubGeneric: {} <= {}",
+ r_a.repr(tcx), generic_b.repr(tcx));
+
+ self.region_bound_pairs.push((r_a, generic_b.clone()));
+ }
+ implicator::Implication::RegionSubRegion(..) |
+ implicator::Implication::RegionSubClosure(..) |
+ implicator::Implication::Predicate(..) => {
// In principle, we could record (and take
// advantage of) every relationship here, but
// we are also free not to -- it simply means
// relationship that arises here, but
// presently we do not.)
}
- implicator::Implication::RegionSubGeneric(_, r_a, ref generic_b) => {
- debug!("RegionSubGeneric: {} <= {}",
- r_a.repr(tcx), generic_b.repr(tcx));
-
- self.region_bound_pairs.push((r_a, generic_b.clone()));
- }
- implicator::Implication::Predicate(..) => { }
}
}
}
fn check_expr_fn_block(rcx: &mut Rcx,
expr: &ast::Expr,
body: &ast::Block) {
- let tcx = rcx.fcx.tcx();
- let function_type = rcx.resolve_node_type(expr.id);
-
- match function_type.sty {
- ty::ty_closure(_, region, _) => {
- ty::with_freevars(tcx, expr.id, |freevars| {
- constrain_captured_variables(rcx, *region, expr, freevars);
- })
- }
- _ => { }
- }
-
let repeating_scope = rcx.set_repeating_scope(body.id);
visit::walk_expr(rcx, expr);
rcx.set_repeating_scope(repeating_scope);
-
- match function_type.sty {
- ty::ty_closure(_, region, _) => {
- ty::with_freevars(tcx, expr.id, |freevars| {
- let bounds = ty::region_existential_bound(*region);
- ensure_free_variable_types_outlive_closure_bound(rcx, &bounds, expr, freevars);
- })
- }
- _ => {}
- }
-
- /// Make sure that the type of all free variables referenced inside a closure/proc outlive the
- /// closure/proc's lifetime bound. This is just a special case of the usual rules about closed
- /// over values outliving the object's lifetime bound.
- fn ensure_free_variable_types_outlive_closure_bound(
- rcx: &mut Rcx,
- bounds: &ty::ExistentialBounds,
- expr: &ast::Expr,
- freevars: &[ty::Freevar])
- {
- let tcx = rcx.fcx.ccx.tcx;
-
- debug!("ensure_free_variable_types_outlive_closure_bound({}, {})",
- bounds.region_bound.repr(tcx), expr.repr(tcx));
-
- for freevar in freevars {
- let var_node_id = {
- let def_id = freevar.def.def_id();
- assert!(def_id.krate == ast::LOCAL_CRATE);
- def_id.node
- };
-
- // Compute the type of the field in the environment that
- // represents `var_node_id`. For a by-value closure, this
- // will be the same as the type of the variable. For a
- // by-reference closure, this will be `&T` where `T` is
- // the type of the variable.
- let raw_var_ty = rcx.resolve_node_type(var_node_id);
- let upvar_id = ty::UpvarId { var_id: var_node_id,
- closure_expr_id: expr.id };
- let var_ty = match rcx.fcx.inh.upvar_capture_map.borrow()[upvar_id] {
- ty::UpvarCapture::ByRef(ref upvar_borrow) => {
- ty::mk_rptr(rcx.tcx(),
- rcx.tcx().mk_region(upvar_borrow.region),
- ty::mt { mutbl: upvar_borrow.kind.to_mutbl_lossy(),
- ty: raw_var_ty })
- }
- ty::UpvarCapture::ByValue => raw_var_ty,
- };
-
- // Check that the type meets the criteria of the existential bounds:
- for builtin_bound in &bounds.builtin_bounds {
- let code = traits::ClosureCapture(var_node_id, expr.span, builtin_bound);
- let cause = traits::ObligationCause::new(freevar.span, rcx.fcx.body_id, code);
- rcx.fcx.register_builtin_bound(var_ty, builtin_bound, cause);
- }
-
- type_must_outlive(
- rcx, infer::FreeVariable(expr.span, var_node_id),
- var_ty, bounds.region_bound);
- }
- }
-
- /// Make sure that all free variables referenced inside the closure outlive the closure's
- /// lifetime bound. Also, create an entry in the upvar_borrows map with a region.
- fn constrain_captured_variables(
- rcx: &mut Rcx,
- region_bound: ty::Region,
- expr: &ast::Expr,
- freevars: &[ty::Freevar])
- {
- let tcx = rcx.fcx.ccx.tcx;
- debug!("constrain_captured_variables({}, {})",
- region_bound.repr(tcx), expr.repr(tcx));
- for freevar in freevars {
- debug!("constrain_captured_variables: freevar.def={:?}", freevar.def);
-
- // Identify the variable being closed over and its node-id.
- let def = freevar.def;
- let var_node_id = {
- let def_id = def.def_id();
- assert!(def_id.krate == ast::LOCAL_CRATE);
- def_id.node
- };
- let upvar_id = ty::UpvarId { var_id: var_node_id,
- closure_expr_id: expr.id };
-
- match rcx.fcx.inh.upvar_capture_map.borrow()[upvar_id] {
- ty::UpvarCapture::ByValue => { }
- ty::UpvarCapture::ByRef(upvar_borrow) => {
- rcx.fcx.mk_subr(infer::FreeVariable(freevar.span, var_node_id),
- region_bound, upvar_borrow.region);
-
- // Guarantee that the closure does not outlive the variable itself.
- let enclosing_region = region_of_def(rcx.fcx, def);
- debug!("constrain_captured_variables: enclosing_region = {}",
- enclosing_region.repr(tcx));
- rcx.fcx.mk_subr(infer::FreeVariable(freevar.span, var_node_id),
- region_bound, enclosing_region);
- }
- }
- }
- }
}
fn constrain_callee(rcx: &mut Rcx,
let o1 = infer::ReferenceOutlivesReferent(ty, origin.span());
generic_must_outlive(rcx, o1, r_a, generic_b);
}
+ implicator::Implication::RegionSubClosure(_, r_a, def_id, substs) => {
+ closure_must_outlive(rcx, origin.clone(), r_a, def_id, substs);
+ }
implicator::Implication::Predicate(def_id, predicate) => {
let cause = traits::ObligationCause::new(origin.span(),
rcx.body_id,
}
}
+fn closure_must_outlive<'a, 'tcx>(rcx: &mut Rcx<'a, 'tcx>,
+ origin: infer::SubregionOrigin<'tcx>,
+ region: ty::Region,
+ def_id: ast::DefId,
+ substs: &'tcx Substs<'tcx>) {
+ debug!("closure_must_outlive(region={}, def_id={}, substs={})",
+ region.repr(rcx.tcx()), def_id.repr(rcx.tcx()), substs.repr(rcx.tcx()));
+
+ let upvars = rcx.fcx.closure_upvars(def_id, substs).unwrap();
+ for upvar in upvars {
+ let var_id = upvar.def.def_id().local_id();
+ type_must_outlive(
+ rcx, infer::FreeVariable(origin.span(), var_id),
+ upvar.ty, region);
+ }
+}
+
fn generic_must_outlive<'a, 'tcx>(rcx: &Rcx<'a, 'tcx>,
origin: infer::SubregionOrigin<'tcx>,
region: ty::Region,
match self_type.ty.sty {
ty::ty_enum(type_def_id, _) |
ty::ty_struct(type_def_id, _) |
- ty::ty_closure(type_def_id, _, _) => {
+ ty::ty_closure(type_def_id, _) => {
tcx.destructor_for_type
.borrow_mut()
.insert(type_def_id, method_def_id.def_id());
E0249, // expected constant expr for array length
E0250, // expected constant expr for array length
E0318, // can't create default impls for traits outside their crates
- E0319 // trait impls for defaulted traits allowed just for structs/enums
+ E0319, // trait impls for defaulted traits allowed just for structs/enums
+ E0320 // recursive overflow during dropck
}
__build_diagnostic_array! { DIAGNOSTICS }
use std::os;
use std::ptr;
- static LOCKFILE_EXCLUSIVE_LOCK: libc::DWORD = 0x00000002;
+ const LOCKFILE_EXCLUSIVE_LOCK: libc::DWORD = 0x00000002;
#[allow(non_snake_case)]
extern "system" {
fn(clean::Crate) -> plugins::PluginResult, // fn
&'static str); // description
-static PASSES: &'static [Pass] = &[
+const PASSES: &'static [Pass] = &[
("strip-hidden", passes::strip_hidden,
"strips all doc(hidden) items from the output"),
("unindent-comments", passes::unindent_comments,
"strips all private items from a crate which cannot be seen externally"),
];
-static DEFAULT_PASSES: &'static [&'static str] = &[
+const DEFAULT_PASSES: &'static [&'static str] = &[
"strip-hidden",
"strip-private",
"collapse-docs",
fn to_hex(&self) -> String;
}
-static CHARS: &'static[u8] = b"0123456789abcdef";
+const CHARS: &'static [u8] = b"0123456789abcdef";
impl ToHex for [u8] {
/// Turn a vector of `u8` bytes into a hexadecimal string.
use core::prelude::*;
-use borrow::{Borrow, ToOwned};
+use borrow::{Borrow, Cow, ToOwned};
use fmt::{self, Debug};
use mem;
-use string::{String, CowString};
+use string::String;
use ops;
use cmp;
use hash::{Hash, Hasher};
self.inner.to_str()
}
- /// Convert an `OsStr` to a `CowString`.
+ /// Convert an `OsStr` to a `Cow<str>`.
///
/// Any non-Unicode sequences are replaced with U+FFFD REPLACEMENT CHARACTER.
- pub fn to_string_lossy(&self) -> CowString {
+ pub fn to_string_lossy(&self) -> Cow<str> {
self.inner.to_string_lossy()
}
--- /dev/null
+// Copyright 2015 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.
+
+use prelude::v1::*;
+
+use boxed;
+use cell::UnsafeCell;
+use rt;
+use sync::{StaticMutex, Arc};
+
+pub struct Lazy<T> {
+ pub lock: StaticMutex,
+ pub ptr: UnsafeCell<*mut Arc<T>>,
+ pub init: fn() -> Arc<T>,
+}
+
+unsafe impl<T> Sync for Lazy<T> {}
+
+macro_rules! lazy_init {
+ ($init:expr) => (::io::lazy::Lazy {
+ lock: ::sync::MUTEX_INIT,
+ ptr: ::cell::UnsafeCell { value: 0 as *mut _ },
+ init: $init,
+ })
+}
+
+impl<T: Send + Sync + 'static> Lazy<T> {
+ pub fn get(&'static self) -> Option<Arc<T>> {
+ let _g = self.lock.lock();
+ unsafe {
+ let mut ptr = *self.ptr.get();
+ if ptr.is_null() {
+ ptr = boxed::into_raw(self.init());
+ *self.ptr.get() = ptr;
+ } else if ptr as usize == 1 {
+ return None
+ }
+ Some((*ptr).clone())
+ }
+ }
+
+ fn init(&'static self) -> Box<Arc<T>> {
+ rt::at_exit(move || unsafe {
+ let g = self.lock.lock();
+ let ptr = *self.ptr.get();
+ *self.ptr.get() = 1 as *mut _;
+ drop(g);
+ drop(Box::from_raw(ptr))
+ });
+ Box::new((self.init)())
+ }
+}
pub use self::cursor::Cursor;
pub use self::error::{Result, Error, ErrorKind};
pub use self::util::{copy, sink, Sink, empty, Empty, repeat, Repeat};
+pub use self::stdio::{stdin, stdout, stderr, Stdin, Stdout, Stderr};
+pub use self::stdio::{StdoutLock, StderrLock, StdinLock};
+
+#[macro_use] mod lazy;
pub mod prelude;
mod buffered;
mod error;
mod impls;
mod util;
+mod stdio;
const DEFAULT_BUF_SIZE: usize = 64 * 1024;
--- /dev/null
+// Copyright 2015 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.
+
+use prelude::v1::*;
+use io::prelude::*;
+
+use cmp;
+use fmt;
+use io::lazy::Lazy;
+use io::{self, BufReader, LineWriter};
+use sync::{Arc, Mutex, MutexGuard};
+use sys::stdio;
+
+/// A handle to a raw instance of the standard input stream of this process.
+///
+/// This handle is not synchronized or buffered in any fashion. Constructed via
+/// the `std::io::stdin_raw` function.
+pub struct StdinRaw(stdio::Stdin);
+
+/// A handle to a raw instance of the standard output stream of this process.
+///
+/// This handle is not synchronized or buffered in any fashion. Constructed via
+/// the `std::io::stdout_raw` function.
+pub struct StdoutRaw(stdio::Stdout);
+
+/// A handle to a raw instance of the standard output stream of this process.
+///
+/// This handle is not synchronized or buffered in any fashion. Constructed via
+/// the `std::io::stderr_raw` function.
+pub struct StderrRaw(stdio::Stderr);
+
+/// Construct a new raw handle to the standard input of this process.
+///
+/// The returned handle does not interact with any other handles created nor
+/// handles returned by `std::io::stdin`. Data buffered by the `std::io::stdin`
+/// handles is **not** available to raw handles returned from this function.
+///
+/// The returned handle has no external synchronization or buffering.
+pub fn stdin_raw() -> StdinRaw { StdinRaw(stdio::Stdin::new()) }
+
+/// Construct a new raw handle to the standard input stream of this process.
+///
+/// The returned handle does not interact with any other handles created nor
+/// handles returned by `std::io::stdout`. Note that data is buffered by the
+/// `std::io::stdin` handles so writes which happen via this raw handle may
+/// appear before previous writes.
+///
+/// The returned handle has no external synchronization or buffering layered on
+/// top.
+pub fn stdout_raw() -> StdoutRaw { StdoutRaw(stdio::Stdout::new()) }
+
+/// Construct a new raw handle to the standard input stream of this process.
+///
+/// The returned handle does not interact with any other handles created nor
+/// handles returned by `std::io::stdout`.
+///
+/// The returned handle has no external synchronization or buffering layered on
+/// top.
+pub fn stderr_raw() -> StderrRaw { StderrRaw(stdio::Stderr::new()) }
+
+impl Read for StdinRaw {
+ fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) }
+}
+impl Write for StdoutRaw {
+ fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }
+ fn flush(&mut self) -> io::Result<()> { Ok(()) }
+}
+impl Write for StderrRaw {
+ fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }
+ fn flush(&mut self) -> io::Result<()> { Ok(()) }
+}
+
+/// A handle to the standard input stream of a process.
+///
+/// Each handle is a shared reference to a global buffer of input data to this
+/// process. A handle can be `lock`'d to gain full access to `BufRead` methods
+/// (e.g. `.lines()`). Writes to this handle are otherwise locked with respect
+/// to other writes.
+///
+/// This handle implements the `Read` trait, but beware that concurrent reads
+/// of `Stdin` must be executed with care.
+pub struct Stdin {
+ inner: Arc<Mutex<BufReader<StdinRaw>>>,
+}
+
+/// A locked reference to the a `Stdin` handle.
+///
+/// This handle implements both the `Read` and `BufRead` traits and is
+/// constructed via the `lock` method on `Stdin`.
+pub struct StdinLock<'a> {
+ inner: MutexGuard<'a, BufReader<StdinRaw>>,
+}
+
+/// Create a new handle to the global standard input stream of this process.
+///
+/// The handle returned refers to a globally shared buffer between all threads.
+/// Access is synchronized and can be explicitly controlled with the `lock()`
+/// method.
+///
+/// The `Read` trait is implemented for the returned value but the `BufRead`
+/// trait is not due to the global nature of the standard input stream. The
+/// locked version, `StdinLock`, implements both `Read` and `BufRead`, however.
+///
+/// To avoid locking and buffering altogether, it is recommended to use the
+/// `stdin_raw` constructor.
+pub fn stdin() -> Stdin {
+ static INSTANCE: Lazy<Mutex<BufReader<StdinRaw>>> = lazy_init!(stdin_init);
+ return Stdin {
+ inner: INSTANCE.get().expect("cannot access stdin during shutdown"),
+ };
+
+ fn stdin_init() -> Arc<Mutex<BufReader<StdinRaw>>> {
+ // The default buffer capacity is 64k, but apparently windows
+ // doesn't like 64k reads on stdin. See #13304 for details, but the
+ // idea is that on windows we use a slightly smaller buffer that's
+ // been seen to be acceptable.
+ Arc::new(Mutex::new(if cfg!(windows) {
+ BufReader::with_capacity(8 * 1024, stdin_raw())
+ } else {
+ BufReader::new(stdin_raw())
+ }))
+ }
+}
+
+impl Stdin {
+ /// Lock this handle to the standard input stream, returning a readable
+ /// guard.
+ ///
+ /// The lock is released when the returned lock goes out of scope. The
+ /// returned guard also implements the `Read` and `BufRead` traits for
+ /// accessing the underlying data.
+ pub fn lock(&self) -> StdinLock {
+ StdinLock { inner: self.inner.lock().unwrap() }
+ }
+}
+
+impl Read for Stdin {
+ fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
+ self.lock().read(buf)
+ }
+
+ fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<()> {
+ self.lock().read_to_end(buf)
+ }
+
+ fn read_to_string(&mut self, buf: &mut String) -> io::Result<()> {
+ self.lock().read_to_string(buf)
+ }
+}
+
+impl<'a> Read for StdinLock<'a> {
+ fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
+ // Flush stdout so that weird issues like a print!'d prompt not being
+ // shown until after the user hits enter.
+ drop(stdout().flush());
+ self.inner.read(buf)
+ }
+}
+impl<'a> BufRead for StdinLock<'a> {
+ fn fill_buf(&mut self) -> io::Result<&[u8]> { self.inner.fill_buf() }
+ fn consume(&mut self, n: usize) { self.inner.consume(n) }
+}
+
+// As with stdin on windows, stdout often can't handle writes of large
+// sizes. For an example, see #14940. For this reason, don't try to
+// write the entire output buffer on windows. On unix we can just
+// write the whole buffer all at once.
+//
+// For some other references, it appears that this problem has been
+// encountered by others [1] [2]. We choose the number 8KB just because
+// libuv does the same.
+//
+// [1]: https://tahoe-lafs.org/trac/tahoe-lafs/ticket/1232
+// [2]: http://www.mail-archive.com/log4net-dev@logging.apache.org/msg00661.html
+#[cfg(windows)]
+const OUT_MAX: usize = 8192;
+#[cfg(unix)]
+const OUT_MAX: usize = ::usize::MAX;
+
+/// A handle to the global standard output stream of the current process.
+///
+/// Each handle shares a global buffer of data to be written to the standard
+/// output stream. Access is also synchronized via a lock and explicit control
+/// over locking is available via the `lock` method.
+pub struct Stdout {
+ // FIXME: this should be LineWriter or BufWriter depending on the state of
+ // stdout (tty or not). Note that if this is not line buffered it
+ // should also flush-on-panic or some form of flush-on-abort.
+ inner: Arc<Mutex<LineWriter<StdoutRaw>>>,
+}
+
+/// A locked reference to the a `Stdout` handle.
+///
+/// This handle implements the `Write` trait and is constructed via the `lock`
+/// method on `Stdout`.
+pub struct StdoutLock<'a> {
+ inner: MutexGuard<'a, LineWriter<StdoutRaw>>,
+}
+
+/// Constructs a new reference to the standard output of the current process.
+///
+/// Each handle returned is a reference to a shared global buffer whose access
+/// is synchronized via a mutex. Explicit control over synchronization is
+/// provided via the `lock` method.
+///
+/// The returned handle implements the `Write` trait.
+///
+/// To avoid locking and buffering altogether, it is recommended to use the
+/// `stdout_raw` constructor.
+pub fn stdout() -> Stdout {
+ static INSTANCE: Lazy<Mutex<LineWriter<StdoutRaw>>> = lazy_init!(stdout_init);
+ return Stdout {
+ inner: INSTANCE.get().expect("cannot access stdout during shutdown"),
+ };
+
+ fn stdout_init() -> Arc<Mutex<LineWriter<StdoutRaw>>> {
+ Arc::new(Mutex::new(LineWriter::new(stdout_raw())))
+ }
+}
+
+impl Stdout {
+ /// Lock this handle to the standard output stream, returning a writable
+ /// guard.
+ ///
+ /// The lock is released when the returned lock goes out of scope. The
+ /// returned guard also implements the `Write` trait for writing data.
+ pub fn lock(&self) -> StdoutLock {
+ StdoutLock { inner: self.inner.lock().unwrap() }
+ }
+}
+
+impl Write for Stdout {
+ fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
+ self.lock().write(buf)
+ }
+ fn flush(&mut self) -> io::Result<()> {
+ self.lock().flush()
+ }
+ fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
+ self.lock().write_all(buf)
+ }
+ fn write_fmt(&mut self, fmt: fmt::Arguments) -> io::Result<()> {
+ self.lock().write_fmt(fmt)
+ }
+}
+impl<'a> Write for StdoutLock<'a> {
+ fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
+ self.inner.write(&buf[..cmp::min(buf.len(), OUT_MAX)])
+ }
+ fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
+}
+
+/// A handle to the standard error stream of a process.
+///
+/// For more information, see `stderr`
+pub struct Stderr {
+ inner: Arc<Mutex<StderrRaw>>,
+}
+
+/// A locked reference to the a `Stderr` handle.
+///
+/// This handle implements the `Write` trait and is constructed via the `lock`
+/// method on `Stderr`.
+pub struct StderrLock<'a> {
+ inner: MutexGuard<'a, StderrRaw>,
+}
+
+/// Constructs a new reference to the standard error stream of a process.
+///
+/// Each returned handle is synchronized amongst all other handles created from
+/// this function. No handles are buffered, however.
+///
+/// The returned handle implements the `Write` trait.
+///
+/// To avoid locking altogether, it is recommended to use the `stderr_raw`
+/// constructor.
+pub fn stderr() -> Stderr {
+ static INSTANCE: Lazy<Mutex<StderrRaw>> = lazy_init!(stderr_init);
+ return Stderr {
+ inner: INSTANCE.get().expect("cannot access stderr during shutdown"),
+ };
+
+ fn stderr_init() -> Arc<Mutex<StderrRaw>> {
+ Arc::new(Mutex::new(stderr_raw()))
+ }
+}
+
+impl Stderr {
+ /// Lock this handle to the standard error stream, returning a writable
+ /// guard.
+ ///
+ /// The lock is released when the returned lock goes out of scope. The
+ /// returned guard also implements the `Write` trait for writing data.
+ pub fn lock(&self) -> StderrLock {
+ StderrLock { inner: self.inner.lock().unwrap() }
+ }
+}
+
+impl Write for Stderr {
+ fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
+ self.lock().write(buf)
+ }
+ fn flush(&mut self) -> io::Result<()> {
+ self.lock().flush()
+ }
+ fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
+ self.lock().write_all(buf)
+ }
+ fn write_fmt(&mut self, fmt: fmt::Arguments) -> io::Result<()> {
+ self.lock().write_fmt(fmt)
+ }
+}
+impl<'a> Write for StderrLock<'a> {
+ fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
+ self.inner.write(&buf[..cmp::min(buf.len(), OUT_MAX)])
+ }
+ fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
+}
#![feature(box_syntax)]
#![feature(collections)]
#![feature(core)]
-#![feature(int_uint)]
+#![feature(hash)]
#![feature(lang_items)]
#![feature(libc)]
#![feature(linkage, thread_local, asm)]
mod uint_macros;
#[path = "num/isize.rs"] pub mod isize;
-pub use isize as int;
#[path = "num/i8.rs"] pub mod i8;
#[path = "num/i16.rs"] pub mod i16;
#[path = "num/i32.rs"] pub mod i32;
#[path = "num/i64.rs"] pub mod i64;
#[path = "num/usize.rs"] pub mod usize;
-pub use usize as uint;
#[path = "num/u8.rs"] pub mod u8;
#[path = "num/u16.rs"] pub mod u16;
#[path = "num/u32.rs"] pub mod u32;
#[test]
fn multiple_connect_interleaved_lazy_schedule_ip4() {
- static MAX: usize = 10;
+ const MAX: usize = 10;
each_ip(&mut |addr| {
let acceptor = t!(TcpListener::bind(&addr));
deccum = deccum / radix_gen;
deccum = deccum.trunc();
- buf.push(char::from_digit(current_digit.to_int().unwrap() as u32, radix)
+ buf.push(char::from_digit(current_digit.to_isize().unwrap() as u32, radix)
.unwrap() as u8);
// No more digits to calculate for the non-fractional part -> break
let current_digit = deccum.trunc().abs();
buf.push(char::from_digit(
- current_digit.to_int().unwrap() as u32, radix).unwrap() as u8);
+ current_digit.to_isize().unwrap() as u32, radix).unwrap() as u8);
// Decrease the deccumulator one fractional digit at a time
deccum = deccum.fract();
// Some constants for from_str_bytes_common's input validation,
// they define minimum radix values for which the character is a valid digit.
-static DIGIT_P_RADIX: u32 = ('p' as u32) - ('a' as u32) + 11;
-static DIGIT_E_RADIX: u32 = ('e' as u32) - ('a' as u32) + 11;
+const DIGIT_P_RADIX: u32 = ('p' as u32) - ('a' as u32) + 11;
+const DIGIT_E_RADIX: u32 = ('e' as u32) - ('a' as u32) + 11;
#[cfg(test)]
mod tests {
///
/// The number of bytes returned is system-dependent.
fn read_le_uint(&mut self) -> IoResult<uint> {
- self.read_le_uint_n(usize::BYTES).map(|i| i as uint)
+ self.read_le_uint_n(usize::BYTES as usize).map(|i| i as uint)
}
/// Reads a little-endian integer.
///
/// The number of bytes returned is system-dependent.
fn read_le_int(&mut self) -> IoResult<int> {
- self.read_le_int_n(isize::BYTES).map(|i| i as int)
+ self.read_le_int_n(isize::BYTES as usize).map(|i| i as int)
}
/// Reads a big-endian unsigned integer.
///
/// The number of bytes returned is system-dependent.
fn read_be_uint(&mut self) -> IoResult<uint> {
- self.read_be_uint_n(usize::BYTES).map(|i| i as uint)
+ self.read_be_uint_n(usize::BYTES as usize).map(|i| i as uint)
}
/// Reads a big-endian integer.
///
/// The number of bytes returned is system-dependent.
fn read_be_int(&mut self) -> IoResult<int> {
- self.read_be_int_n(isize::BYTES).map(|i| i as int)
+ self.read_be_int_n(isize::BYTES as usize).map(|i| i as int)
}
/// Reads a big-endian `u64`.
/// Write a little-endian uint (number of bytes depends on system).
#[inline]
fn write_le_uint(&mut self, n: uint) -> IoResult<()> {
- extensions::u64_to_le_bytes(n as u64, usize::BYTES, |v| self.write_all(v))
+ extensions::u64_to_le_bytes(n as u64, usize::BYTES as usize, |v| self.write_all(v))
}
/// Write a little-endian int (number of bytes depends on system).
#[inline]
fn write_le_int(&mut self, n: int) -> IoResult<()> {
- extensions::u64_to_le_bytes(n as u64, isize::BYTES, |v| self.write_all(v))
+ extensions::u64_to_le_bytes(n as u64, isize::BYTES as usize, |v| self.write_all(v))
}
/// Write a big-endian uint (number of bytes depends on system).
#[inline]
fn write_be_uint(&mut self, n: uint) -> IoResult<()> {
- extensions::u64_to_be_bytes(n as u64, usize::BYTES, |v| self.write_all(v))
+ extensions::u64_to_be_bytes(n as u64, usize::BYTES as usize, |v| self.write_all(v))
}
/// Write a big-endian int (number of bytes depends on system).
#[inline]
fn write_be_int(&mut self, n: int) -> IoResult<()> {
- extensions::u64_to_be_bytes(n as u64, isize::BYTES, |v| self.write_all(v))
+ extensions::u64_to_be_bytes(n as u64, isize::BYTES as usize, |v| self.write_all(v))
}
/// Write a big-endian u64 (8 bytes).
unsafe {
ONCE.call_once(|| {
- // The default buffer capacity is 64k, but apparently windows doesn't like
- // 64k reads on stdin. See #13304 for details, but the idea is that on
- // windows we use a slightly smaller buffer that's been seen to be
- // acceptable.
+ // The default buffer capacity is 64k, but apparently windows
+ // doesn't like 64k reads on stdin. See #13304 for details, but the
+ // idea is that on windows we use a slightly smaller buffer that's
+ // been seen to be acceptable.
let stdin = if cfg!(windows) {
BufferedReader::with_capacity(8 * 1024, stdin_raw())
} else {
//! Working with processes.
-#![unstable(feature = "process", reason = "recently added via RFC 579")]
+#![stable(feature = "process", since = "1.0.0")]
#![allow(non_upper_case_globals)]
use prelude::v1::*;
/// let contents = output.stdout;
/// assert!(output.status.success());
/// ```
+#[stable(feature = "process", since = "1.0.0")]
pub struct Child {
handle: ProcessImp,
status: Option<ExitStatusImp>,
/// The handle for writing to the child's stdin, if it has been captured
+ #[stable(feature = "process", since = "1.0.0")]
pub stdin: Option<ChildStdin>,
/// The handle for reading from the child's stdout, if it has been captured
+ #[stable(feature = "process", since = "1.0.0")]
pub stdout: Option<ChildStdout>,
/// The handle for reading from the child's stderr, if it has been captured
+ #[stable(feature = "process", since = "1.0.0")]
pub stderr: Option<ChildStderr>,
}
/// A handle to a child procesess's stdin
+#[stable(feature = "process", since = "1.0.0")]
pub struct ChildStdin {
inner: AnonPipe
}
+#[stable(feature = "process", since = "1.0.0")]
impl Write for ChildStdin {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.inner.write(buf)
}
/// A handle to a child procesess's stdout
+#[stable(feature = "process", since = "1.0.0")]
pub struct ChildStdout {
inner: AnonPipe
}
+#[stable(feature = "process", since = "1.0.0")]
impl Read for ChildStdout {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.inner.read(buf)
}
/// A handle to a child procesess's stderr
+#[stable(feature = "process", since = "1.0.0")]
pub struct ChildStderr {
inner: AnonPipe
}
+#[stable(feature = "process", since = "1.0.0")]
impl Read for ChildStderr {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.inner.read(buf)
/// to be changed (for example, by adding arguments) prior to spawning:
///
/// ```
-/// # #![feature(process)]
-///
/// use std::process::Command;
///
/// let output = Command::new("sh").arg("-c").arg("echo hello").output().unwrap_or_else(|e| {
/// });
/// let hello = output.stdout;
/// ```
+#[stable(feature = "process", since = "1.0.0")]
pub struct Command {
inner: CommandImp,
///
/// Builder methods are provided to change these defaults and
/// otherwise configure the process.
+ #[stable(feature = "process", since = "1.0.0")]
pub fn new<S: AsOsStr + ?Sized>(program: &S) -> Command {
Command {
inner: CommandImp::new(program.as_os_str()),
}
/// Add an argument to pass to the program.
+ #[stable(feature = "process", since = "1.0.0")]
pub fn arg<S: AsOsStr + ?Sized>(&mut self, arg: &S) -> &mut Command {
self.inner.arg(arg.as_os_str());
self
}
/// Add multiple arguments to pass to the program.
+ #[stable(feature = "process", since = "1.0.0")]
pub fn args<S: AsOsStr>(&mut self, args: &[S]) -> &mut Command {
self.inner.args(args.iter().map(AsOsStr::as_os_str));
self
///
/// Note that environment variable names are case-insensitive (but case-preserving) on Windows,
/// and case-sensitive on all other platforms.
- pub fn env<S: ?Sized, T: ?Sized>(&mut self, key: &S, val: &T) -> &mut Command where
- S: AsOsStr, T: AsOsStr
+ #[stable(feature = "process", since = "1.0.0")]
+ pub fn env<K: ?Sized, V: ?Sized>(&mut self, key: &K, val: &V) -> &mut Command
+ where K: AsOsStr, V: AsOsStr
{
self.inner.env(key.as_os_str(), val.as_os_str());
self
}
/// Removes an environment variable mapping.
- pub fn env_remove<S: ?Sized + AsOsStr>(&mut self, key: &S) -> &mut Command {
+ #[stable(feature = "process", since = "1.0.0")]
+ pub fn env_remove<K: ?Sized + AsOsStr>(&mut self, key: &K) -> &mut Command {
self.inner.env_remove(key.as_os_str());
self
}
/// Clears the entire environment map for the child process.
+ #[stable(feature = "process", since = "1.0.0")]
pub fn env_clear(&mut self) -> &mut Command {
self.inner.env_clear();
self
}
/// Set the working directory for the child process.
+ #[stable(feature = "process", since = "1.0.0")]
pub fn current_dir<P: AsPath + ?Sized>(&mut self, dir: &P) -> &mut Command {
self.inner.cwd(dir.as_path().as_os_str());
self
/// Configuration for the child process's stdin handle (file descriptor 0).
/// Defaults to `CreatePipe(true, false)` so the input can be written to.
+ #[stable(feature = "process", since = "1.0.0")]
pub fn stdin(&mut self, cfg: Stdio) -> &mut Command {
self.stdin = Some(cfg.0);
self
/// Configuration for the child process's stdout handle (file descriptor 1).
/// Defaults to `CreatePipe(false, true)` so the output can be collected.
+ #[stable(feature = "process", since = "1.0.0")]
pub fn stdout(&mut self, cfg: Stdio) -> &mut Command {
self.stdout = Some(cfg.0);
self
/// Configuration for the child process's stderr handle (file descriptor 2).
/// Defaults to `CreatePipe(false, true)` so the output can be collected.
+ #[stable(feature = "process", since = "1.0.0")]
pub fn stderr(&mut self, cfg: Stdio) -> &mut Command {
self.stderr = Some(cfg.0);
self
/// Executes the command as a child process, returning a handle to it.
///
/// By default, stdin, stdout and stderr are inherited by the parent.
+ #[stable(feature = "process", since = "1.0.0")]
pub fn spawn(&mut self) -> io::Result<Child> {
self.spawn_inner(StdioImp::Inherit)
}
/// println!("stdout: {}", String::from_utf8_lossy(output.stdout.as_slice()));
/// println!("stderr: {}", String::from_utf8_lossy(output.stderr.as_slice()));
/// ```
+ #[stable(feature = "process", since = "1.0.0")]
pub fn output(&mut self) -> io::Result<Output> {
- self.spawn_inner(StdioImp::Capture).and_then(|p| p.wait_with_output())
+ self.spawn_inner(StdioImp::Piped).and_then(|p| p.wait_with_output())
}
/// Executes a command as a child process, waiting for it to finish and
///
/// println!("process exited with: {}", status);
/// ```
+ #[stable(feature = "process", since = "1.0.0")]
pub fn status(&mut self) -> io::Result<ExitStatus> {
self.spawn().and_then(|mut p| p.wait())
}
Inherit => {
(Some(AnonPipe::from_fd(fd)), None)
}
- Capture => {
+ Piped => {
let (reader, writer) = try!(unsafe { pipe2::anon_pipe() });
if readable {
(Some(reader), Some(writer))
/// The output of a finished process.
#[derive(PartialEq, Eq, Clone)]
+#[stable(feature = "process", since = "1.0.0")]
pub struct Output {
/// The status (exit code) of the process.
+ #[stable(feature = "process", since = "1.0.0")]
pub status: ExitStatus,
/// The data that the process wrote to stdout.
+ #[stable(feature = "process", since = "1.0.0")]
pub stdout: Vec<u8>,
/// The data that the process wrote to stderr.
+ #[stable(feature = "process", since = "1.0.0")]
pub stderr: Vec<u8>,
}
/// Describes what to do with a standard io stream for a child process.
+#[stable(feature = "process", since = "1.0.0")]
pub struct Stdio(StdioImp);
// The internal enum for stdio setup; see below for descriptions.
#[derive(Clone)]
enum StdioImp {
- Capture,
+ Piped,
Inherit,
Null,
}
impl Stdio {
/// A new pipe should be arranged to connect the parent and child processes.
- pub fn capture() -> Stdio { Stdio(StdioImp::Capture) }
+ #[unstable(feature = "process_capture")]
+ #[deprecated(since = "1.0.0", reason = "renamed to `Stdio::piped`")]
+ pub fn capture() -> Stdio { Stdio::piped() }
+
+ /// A new pipe should be arranged to connect the parent and child processes.
+ #[stable(feature = "process", since = "1.0.0")]
+ pub fn piped() -> Stdio { Stdio(StdioImp::Piped) }
/// The child inherits from the corresponding parent descriptor.
+ #[stable(feature = "process", since = "1.0.0")]
pub fn inherit() -> Stdio { Stdio(StdioImp::Inherit) }
/// This stream will be ignored. This is the equivalent of attaching the
/// stream to `/dev/null`
+ #[stable(feature = "process", since = "1.0.0")]
pub fn null() -> Stdio { Stdio(StdioImp::Null) }
}
/// Describes the result of a process after it has terminated.
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
+#[stable(feature = "process", since = "1.0.0")]
pub struct ExitStatus(ExitStatusImp);
impl ExitStatus {
/// Was termination successful? Signal termination not considered a success,
/// and success is defined as a zero exit status.
+ #[stable(feature = "process", since = "1.0.0")]
pub fn success(&self) -> bool {
self.0.success()
}
/// On Unix, this will return `None` if the process was terminated
/// by a signal; `std::os::unix` provides an extension trait for
/// extracting the signal and other details from the `ExitStatus`.
+ #[stable(feature = "process", since = "1.0.0")]
pub fn code(&self) -> Option<i32> {
self.0.code()
}
fn as_inner(&self) -> &ExitStatusImp { &self.0 }
}
+#[stable(feature = "process", since = "1.0.0")]
impl fmt::Display for ExitStatus {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
impl Child {
/// Forces the child to exit. This is equivalent to sending a
/// SIGKILL on unix platforms.
+ #[stable(feature = "process", since = "1.0.0")]
pub fn kill(&mut self) -> io::Result<()> {
#[cfg(unix)] fn collect_status(p: &mut Child) {
// On Linux (and possibly other unices), a process that has exited will
/// before waiting. This helps avoid deadlock: it ensures that the
/// child does not block waiting for input from the parent, while
/// the parent waits for the child to exit.
+ #[stable(feature = "process", since = "1.0.0")]
pub fn wait(&mut self) -> io::Result<ExitStatus> {
drop(self.stdin.take());
match self.status {
/// before waiting. This helps avoid deadlock: it ensures that the
/// child does not block waiting for input from the parent, while
/// the parent waits for the child to exit.
+ #[stable(feature = "process", since = "1.0.0")]
pub fn wait_with_output(mut self) -> io::Result<Output> {
drop(self.stdin.take());
fn read<T: Read + Send + 'static>(stream: Option<T>) -> Receiver<io::Result<Vec<u8>>> {
#[test]
fn stdout_works() {
let mut cmd = Command::new("echo");
- cmd.arg("foobar").stdout(Stdio::capture());
+ cmd.arg("foobar").stdout(Stdio::piped());
assert_eq!(run_output(cmd), "foobar\n");
}
let mut cmd = Command::new("/bin/sh");
cmd.arg("-c").arg("pwd")
.current_dir("/")
- .stdout(Stdio::capture());
+ .stdout(Stdio::piped());
assert_eq!(run_output(cmd), "/\n");
}
fn stdin_works() {
let mut p = Command::new("/bin/sh")
.arg("-c").arg("read line; echo $line")
- .stdin(Stdio::capture())
- .stdout(Stdio::capture())
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
.spawn().unwrap();
p.stdin.as_mut().unwrap().write("foobar".as_bytes()).unwrap();
drop(p.stdin.take());
#[cfg(not(target_os="android"))]
#[test]
fn test_wait_with_output_once() {
- let prog = Command::new("echo").arg("hello").stdout(Stdio::capture())
+ let prog = Command::new("echo").arg("hello").stdout(Stdio::piped())
.spawn().unwrap();
let Output {status, stdout, stderr} = prog.wait_with_output().unwrap();
let output_str = str::from_utf8(stdout.as_slice()).unwrap();
}
}
}
-static THREAD_RNG_RESEED_THRESHOLD: usize = 32_768;
+const THREAD_RNG_RESEED_THRESHOLD: usize = 32_768;
type ThreadRngInner = reseeding::ReseedingRng<StdRng, ThreadRngReseeder>;
/// The thread-local RNG.
}
}
-#[cfg(test)]
-static RAND_BENCH_N: u64 = 100;
-
#[cfg(test)]
mod bench {
extern crate test;
use prelude::v1::*;
use self::test::Bencher;
- use super::{XorShiftRng, StdRng, IsaacRng, Isaac64Rng, Rng, RAND_BENCH_N};
+ use super::{XorShiftRng, StdRng, IsaacRng, Isaac64Rng, Rng};
use super::{OsRng, weak_rng};
use mem::size_of;
+ const RAND_BENCH_N: u64 = 100;
+
#[bench]
fn rand_xorshift(b: &mut Bencher) {
let mut rng: XorShiftRng = OsRng::new().unwrap().gen();
hcryptprov: HCRYPTPROV
}
- static PROV_RSA_FULL: DWORD = 1;
- static CRYPT_SILENT: DWORD = 64;
- static CRYPT_VERIFYCONTEXT: DWORD = 0xF0000000;
+ const PROV_RSA_FULL: DWORD = 1;
+ const CRYPT_SILENT: DWORD = 64;
+ const CRYPT_VERIFYCONTEXT: DWORD = 0xF0000000;
#[allow(non_snake_case)]
extern "system" {
#[test]
fn stress_shared() {
- static AMT: u32 = 10000;
- static NTHREADS: u32 = 8;
+ const AMT: u32 = 10000;
+ const NTHREADS: u32 = 8;
let (tx, rx) = channel::<i32>();
let t = thread::spawn(move|| {
#[test]
fn stress_shared() {
- static AMT: u32 = 1000;
- static NTHREADS: u32 = 8;
+ const AMT: u32 = 1000;
+ const NTHREADS: u32 = 8;
let (tx, rx) = sync_channel::<i32>(0);
let (dtx, drx) = sync_channel::<()>(0);
#[test]
fn stress() {
- static AMT: i32 = 10000;
+ const AMT: i32 = 10000;
let (tx1, rx1) = channel::<i32>();
let (tx2, rx2) = channel::<i32>();
let (tx3, rx3) = channel::<()>();
fn lots_and_lots() {
static M: StaticMutex = MUTEX_INIT;
static mut CNT: u32 = 0;
- static J: u32 = 1000;
- static K: u32 = 3;
+ const J: u32 = 1000;
+ const K: u32 = 3;
fn inc() {
for _ in 0..J {
#[test]
fn frob() {
static R: StaticRwLock = RW_LOCK_INIT;
- static N: usize = 10;
- static M: usize = 1000;
+ const N: usize = 10;
+ const M: usize = 1000;
let (tx, rx) = channel::<()>();
for _ in 0..N {
use ops;
use slice;
use str;
-use string::{String, CowString};
+use string::String;
use sys_common::AsInner;
use unicode::str::{Utf16Item, utf16_items};
use vec::Vec;
-static UTF8_REPLACEMENT_CHARACTER: &'static [u8] = b"\xEF\xBF\xBD";
+const UTF8_REPLACEMENT_CHARACTER: &'static [u8] = b"\xEF\xBF\xBD";
/// A Unicode code point: from U+0000 to U+10FFFF.
///
/// Surrogates are replaced with `"\u{FFFD}"` (the replacement character “�”).
///
/// This only copies the data if necessary (if it contains any surrogate).
- pub fn to_string_lossy(&self) -> CowString {
+ pub fn to_string_lossy(&self) -> Cow<str> {
let surrogate_pos = match self.next_surrogate(0) {
None => return Cow::Borrowed(unsafe { str::from_utf8_unchecked(&self.bytes) }),
Some((pos, _)) => pos,
use borrow::Cow;
use super::*;
use mem::transmute;
- use string::CowString;
#[test]
fn code_point_from_u32() {
assert_eq!(Wtf8::from_str("aé 💩").to_string_lossy(), Cow::Borrowed("aé 💩"));
let mut string = Wtf8Buf::from_str("aé 💩");
string.push(CodePoint::from_u32(0xD800).unwrap());
- let expected: CowString = Cow::Owned(String::from_str("aé 💩�"));
+ let expected: Cow<str> = Cow::Owned(String::from_str("aé 💩�"));
assert_eq!(string.to_string_lossy(), expected);
}
#[repr(C)]
pub struct fd_set {
// FIXME: shouldn't this be a c_ulong?
- fds_bits: [libc::uintptr_t; (FD_SETSIZE / usize::BITS)]
+ fds_bits: [libc::uintptr_t; (FD_SETSIZE / usize::BITS as usize)]
}
pub fn fd_set(set: &mut fd_set, fd: i32) {
let fd = fd as uint;
- set.fds_bits[fd / usize::BITS] |= 1 << (fd % usize::BITS);
+ set.fds_bits[fd / usize::BITS as usize] |= 1 << (fd % usize::BITS as usize);
}
}
pub mod timer;
pub mod tty;
pub mod udp;
+pub mod stdio;
pub mod addrinfo {
pub use sys_common::net::get_host_addresses;
use core::prelude::*;
+use borrow::Cow;
use fmt::{self, Debug};
use vec::Vec;
use slice::SliceExt as StdSliceExt;
use str;
-use string::{String, CowString};
+use string::String;
use mem;
#[derive(Clone, Hash)]
str::from_utf8(&self.inner).ok()
}
- pub fn to_string_lossy(&self) -> CowString {
+ pub fn to_string_lossy(&self) -> Cow<str> {
String::from_utf8_lossy(&self.inner)
}
--- /dev/null
+// Copyright 2015 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.
+
+use prelude::v1::*;
+
+use io;
+use libc;
+use sys::fd::FileDesc;
+
+pub struct Stdin(());
+pub struct Stdout(());
+pub struct Stderr(());
+
+impl Stdin {
+ pub fn new() -> Stdin { Stdin(()) }
+
+ pub fn read(&self, data: &mut [u8]) -> io::Result<usize> {
+ let fd = FileDesc::new(libc::STDIN_FILENO);
+ let ret = fd.read(data);
+ fd.into_raw();
+ return ret;
+ }
+}
+
+impl Stdout {
+ pub fn new() -> Stdout { Stdout(()) }
+
+ pub fn write(&self, data: &[u8]) -> io::Result<usize> {
+ let fd = FileDesc::new(libc::STDOUT_FILENO);
+ let ret = fd.write(data);
+ fd.into_raw();
+ return ret;
+ }
+}
+
+impl Stderr {
+ pub fn new() -> Stderr { Stderr(()) }
+
+ pub fn write(&self, data: &[u8]) -> io::Result<usize> {
+ let fd = FileDesc::new(libc::STDERR_FILENO);
+ let ret = fd.write(data);
+ fd.into_raw();
+ return ret;
+ }
+}
pub const ERROR_NO_MORE_FILES: libc::DWORD = 18;
pub const TOKEN_READ: libc::DWORD = 0x20008;
+// Note that these are not actually HANDLEs, just values to pass to GetStdHandle
+pub const STD_INPUT_HANDLE: libc::DWORD = -10;
+pub const STD_OUTPUT_HANDLE: libc::DWORD = -11;
+pub const STD_ERROR_HANDLE: libc::DWORD = -12;
+
#[repr(C)]
#[cfg(target_arch = "x86")]
pub struct WSADATA {
DesiredAccess: libc::DWORD,
TokenHandle: *mut libc::HANDLE) -> libc::BOOL;
pub fn GetCurrentProcess() -> libc::HANDLE;
+ pub fn GetStdHandle(which: libc::DWORD) -> libc::HANDLE;
}
#[link(name = "userenv")]
use prelude::v1::*;
-use libc::{self, HANDLE};
-use io;
use io::ErrorKind;
+use io;
+use libc::{self, HANDLE};
+use mem;
use ptr;
use sys::cvt;
pub fn raw(&self) -> HANDLE { self.0 }
+ pub fn into_raw(self) -> HANDLE {
+ let ret = self.0;
+ unsafe { mem::forget(self) }
+ return ret;
+ }
+
pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
read(self.0, buf)
}
pub mod timer;
pub mod tty;
pub mod udp;
+pub mod stdio;
pub mod addrinfo {
pub use sys_common::net::get_host_addresses;
-> DWORD;
}
- static FORMAT_MESSAGE_FROM_SYSTEM: DWORD = 0x00001000;
- static FORMAT_MESSAGE_IGNORE_INSERTS: DWORD = 0x00000200;
+ const FORMAT_MESSAGE_FROM_SYSTEM: DWORD = 0x00001000;
+ const FORMAT_MESSAGE_IGNORE_INSERTS: DWORD = 0x00000200;
// This value is calculated from the macro
// MAKELANGID(LANG_SYSTEM_DEFAULT, SUBLANG_SYS_DEFAULT)
/// The underlying OsString/OsStr implementation on Windows is a
/// wrapper around the "WTF-8" encoding; see the `wtf8` module for more.
+use borrow::Cow;
use fmt::{self, Debug};
use sys_common::wtf8::{Wtf8, Wtf8Buf};
-use string::{String, CowString};
+use string::String;
use result::Result;
use option::Option;
use mem;
self.inner.as_str()
}
- pub fn to_string_lossy(&self) -> CowString {
+ pub fn to_string_lossy(&self) -> Cow<str> {
self.inner.to_string_lossy()
}
--- /dev/null
+// Copyright 2015 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.
+
+use prelude::v1::*;
+use io::prelude::*;
+
+use io::{self, Cursor};
+use iter::repeat;
+use libc;
+use ptr;
+use str;
+use sync::Mutex;
+use sys::c;
+use sys::cvt;
+use sys::handle::Handle;
+
+struct NoClose(Option<Handle>);
+
+enum Output {
+ Console(NoClose),
+ Pipe(NoClose),
+}
+
+pub struct Stdin {
+ handle: Output,
+ utf8: Mutex<io::Cursor<Vec<u8>>>,
+}
+pub struct Stdout(Output);
+pub struct Stderr(Output);
+
+fn get(handle: libc::DWORD) -> io::Result<Output> {
+ let handle = unsafe { c::GetStdHandle(handle) };
+ if handle == libc::INVALID_HANDLE_VALUE {
+ Err(io::Error::last_os_error())
+ } else if handle.is_null() {
+ Err(io::Error::new(io::ErrorKind::Other,
+ "no stdio handle available for this process", None))
+ } else {
+ let ret = NoClose::new(handle);
+ let mut out = 0;
+ match unsafe { c::GetConsoleMode(handle, &mut out) } {
+ 0 => Ok(Output::Pipe(ret)),
+ _ => Ok(Output::Console(ret)),
+ }
+ }
+}
+
+fn write(out: &Output, data: &[u8]) -> io::Result<usize> {
+ let handle = match *out {
+ Output::Console(ref c) => c.get().raw(),
+ Output::Pipe(ref p) => return p.get().write(data),
+ };
+ let utf16 = match str::from_utf8(data).ok() {
+ Some(utf8) => utf8.utf16_units().collect::<Vec<u16>>(),
+ None => return Err(invalid_encoding()),
+ };
+ let mut written = 0;
+ try!(cvt(unsafe {
+ c::WriteConsoleW(handle,
+ utf16.as_ptr() as libc::LPCVOID,
+ utf16.len() as u32,
+ &mut written,
+ ptr::null_mut())
+ }));
+
+ // FIXME if this only partially writes the utf16 buffer then we need to
+ // figure out how many bytes of `data` were actually written
+ assert_eq!(written as usize, utf16.len());
+ Ok(data.len())
+}
+
+impl Stdin {
+ pub fn new() -> Stdin {
+ Stdin {
+ handle: get(c::STD_INPUT_HANDLE).unwrap(),
+ utf8: Mutex::new(Cursor::new(Vec::new())),
+ }
+ }
+
+ pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
+ let handle = match self.handle {
+ Output::Console(ref c) => c.get().raw(),
+ Output::Pipe(ref p) => return p.get().read(buf),
+ };
+ let mut utf8 = self.utf8.lock().unwrap();
+ // Read more if the buffer is empty
+ if utf8.position() as usize == utf8.get_ref().len() {
+ let mut utf16: Vec<u16> = repeat(0u16).take(0x1000).collect();
+ let mut num = 0;
+ try!(cvt(unsafe {
+ c::ReadConsoleW(handle,
+ utf16.as_mut_ptr() as libc::LPVOID,
+ utf16.len() as u32,
+ &mut num,
+ ptr::null_mut())
+ }));
+ utf16.truncate(num as usize);
+ // FIXME: what to do about this data that has already been read?
+ let data = match String::from_utf16(&utf16) {
+ Ok(utf8) => utf8.into_bytes(),
+ Err(..) => return Err(invalid_encoding()),
+ };
+ *utf8 = Cursor::new(data);
+ }
+
+ // MemReader shouldn't error here since we just filled it
+ utf8.read(buf)
+ }
+}
+
+impl Stdout {
+ pub fn new() -> Stdout {
+ Stdout(get(c::STD_OUTPUT_HANDLE).unwrap())
+ }
+
+ pub fn write(&self, data: &[u8]) -> io::Result<usize> {
+ write(&self.0, data)
+ }
+}
+
+impl Stderr {
+ pub fn new() -> Stderr {
+ Stderr(get(c::STD_ERROR_HANDLE).unwrap())
+ }
+
+ pub fn write(&self, data: &[u8]) -> io::Result<usize> {
+ write(&self.0, data)
+ }
+}
+
+impl NoClose {
+ fn new(handle: libc::HANDLE) -> NoClose {
+ NoClose(Some(Handle::new(handle)))
+ }
+
+ fn get(&self) -> &Handle { self.0.as_ref().unwrap() }
+}
+
+impl Drop for NoClose {
+ fn drop(&mut self) {
+ self.0.take().unwrap().into_raw();
+ }
+}
+
+fn invalid_encoding() -> io::Error {
+ io::Error::new(io::ErrorKind::InvalidInput, "text was not valid unicode",
+ None)
+}
//! a thread will unwind the stack, running destructors and freeing
//! owned resources. Thread panic is unrecoverable from within
//! the panicking thread (i.e. there is no 'try/catch' in Rust), but
-//! panic may optionally be detected from a different thread. If
-//! the main thread panics the application will exit with a non-zero
+//! the panic may optionally be detected from a different thread. If
+//! the main thread panics, the application will exit with a non-zero
//! exit code.
//!
//! When the main thread of a Rust program terminates, the entire program shuts
//! down, even if other threads are still running. However, this module provides
//! convenient facilities for automatically waiting for the termination of a
-//! child thread (i.e., join), described below.
+//! child thread (i.e., join).
//!
//! ## The `Thread` type
//!
-//! Already-running threads are represented via the `Thread` type, which you can
+//! Threads are represented via the `Thread` type, which you can
//! get in one of two ways:
//!
-//! * By spawning a new thread, e.g. using the `thread::spawn` constructor;
+//! * By spawning a new thread, e.g. using the `thread::spawn` function.
//! * By requesting the current thread, using the `thread::current` function.
//!
//! Threads can be named, and provide some built-in support for low-level
-//! synchronization described below.
+//! synchronization (described below).
//!
//! The `thread::current()` function is available even for threads not spawned
//! by the APIs of this module.
//! use std::thread;
//!
//! thread::spawn(move || {
-//! println!("Hello, World!");
-//! // some computation here
+//! // some work here
//! });
//! ```
//!
//! In this example, the spawned thread is "detached" from the current
-//! thread, meaning that it can outlive the thread that spawned
-//! it. (Note, however, that when the main thread terminates all
-//! detached threads are terminated as well.)
+//! thread. This means that it can outlive its parent (the thread that spawned
+//! it), unless this parent is the main thread.
//!
//! ## Scoped threads
//!
//! Often a parent thread uses a child thread to perform some particular task,
//! and at some point must wait for the child to complete before continuing.
-//! For this scenario, use the `scoped` constructor:
+//! For this scenario, use the `thread::scoped` function:
//!
//! ```rust
//! use std::thread;
//!
//! let guard = thread::scoped(move || {
-//! println!("Hello, World!");
-//! // some computation here
+//! // some work here
//! });
+//!
//! // do some other work in the meantime
//! let output = guard.join();
//! ```
//! terminates) when it is dropped. You can join the child thread in
//! advance by calling the `join` method on the guard, which will also
//! return the result produced by the thread. A handle to the thread
-//! itself is available via the `thread` method on the join guard.
-//!
-//! (Note: eventually, the `scoped` constructor will allow the parent and child
-//! threads to data that lives on the parent thread's stack, but some language
-//! changes are needed before this is possible.)
+//! itself is available via the `thread` method of the join guard.
//!
//! ## Configuring threads
//!
//! use std::thread;
//!
//! thread::Builder::new().name("child1".to_string()).spawn(move || {
-//! println!("Hello, world!")
+//! println!("Hello, world!");
//! });
//! ```
//!
//! initially not present:
//!
//! * The `thread::park()` function blocks the current thread unless or until
-//! the token is available for its thread handle, at which point It atomically
+//! the token is available for its thread handle, at which point it atomically
//! consumes the token. It may also return *spuriously*, without consuming the
//! token. `thread::park_timeout()` does the same, but allows specifying a
//! maximum time to block the thread for.
//! * It avoids the need to allocate mutexes and condvars when building new
//! synchronization primitives; the threads already provide basic blocking/signaling.
//!
-//! * It can be implemented highly efficiently on many platforms.
+//! * It can be implemented very efficiently on many platforms.
#![stable(feature = "rust1", since = "1.0.0")]
// A name for the thread-to-be, for identification in panic messages
name: Option<String>,
// The size of the stack for the spawned thread
- stack_size: Option<uint>,
+ stack_size: Option<usize>,
// Thread-local stdout
stdout: Option<Box<Writer + Send + 'static>>,
// Thread-local stderr
/// Set the size of the stack for the new thread.
#[stable(feature = "rust1", since = "1.0.0")]
- pub fn stack_size(mut self, size: uint) -> Builder {
+ pub fn stack_size(mut self, size: usize) -> Builder {
self.stack_size = Some(size);
self
}
// address at which our stack started).
let main = move || {
let something_around_the_top_of_the_stack = 1;
- let addr = &something_around_the_top_of_the_stack as *const int;
- let my_stack_top = addr as uint;
+ let addr = &something_around_the_top_of_the_stack as *const isize;
+ let my_stack_top = addr as usize;
let my_stack_bottom = my_stack_top - stack_size + 1024;
unsafe {
stack::record_os_managed_stack_bounds(my_stack_bottom, my_stack_top);
let (tx, rx) = channel();
- fn f(i: int, tx: Sender<()>) {
+ fn f(i: i32, tx: Sender<()>) {
let tx = tx.clone();
thread::spawn(move|| {
if i == 0 {
}
fn avoid_copying_the_body<F>(spawnfn: F) where F: FnOnce(Thunk<'static>) {
- let (tx, rx) = channel::<uint>();
+ let (tx, rx) = channel::<u32>();
let x = box 1;
- let x_in_parent = (&*x) as *const int as uint;
+ let x_in_parent = (&*x) as *const isize as u32;
spawnfn(Thunk::new(move|| {
- let x_in_child = (&*x) as *const int as uint;
+ let x_in_child = (&*x) as *const isize as u32;
tx.send(x_in_child).unwrap();
}));
// climbing the task tree to dereference each ancestor. (See #1789)
// (well, it would if the constant were 8000+ - I lowered it to be more
// valgrind-friendly. try this at home, instead..!)
- static GENERATIONS: uint = 16;
- fn child_no(x: uint) -> Thunk<'static> {
+ const GENERATIONS: usize = 16;
+ fn child_no(x: usize) -> Thunk<'static> {
return Thunk::new(move|| {
if x < GENERATIONS {
thread::spawn(move|| child_no(x+1).invoke(()));
const _INIT: __Key<$t> = __Key {
inner: ::std::thread_local::scoped::__impl::KeyInner {
inner: ::std::thread_local::scoped::__impl::OS_INIT,
- marker: ::std::marker::InvariantType,
+ marker: ::std::marker::PhantomData::<::std::cell::Cell<$t>>,
}
};
target_arch = "aarch64"))]
mod imp {
use marker;
+ use std::cell::Cell;
use sys_common::thread_local::StaticKey as OsStaticKey;
#[doc(hidden)]
pub struct KeyInner<T> {
pub inner: OsStaticKey,
- pub marker: marker::InvariantType<T>,
+ pub marker: marker::PhantomData<Cell<T>>,
}
unsafe impl<T> ::marker::Sync for KeyInner<T> { }
}
#[allow(non_upper_case_globals)]
-static AbiDatas: &'static [AbiData] = &[
+const AbiDatas: &'static [AbiData] = &[
// Platform-specific ABIs
AbiData {abi: Cdecl, name: "cdecl" },
AbiData {abi: Stdcall, name: "stdcall" },
- AbiData {abi: Fastcall, name:"fastcall" },
+ AbiData {abi: Fastcall, name: "fastcall" },
AbiData {abi: Aapcs, name: "aapcs" },
AbiData {abi: Win64, name: "win64" },
use term;
/// maximum number of lines we will print for each error; arbitrary.
-static MAX_LINES: usize = 6;
+const MAX_LINES: usize = 6;
#[derive(Clone, Copy)]
pub enum RenderSpan {
}
}
-static OPTIONS: &'static [&'static str] = &["volatile", "alignstack", "intel"];
+const OPTIONS: &'static [&'static str] = &["volatile", "alignstack", "intel"];
pub fn expand_asm<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
-> Box<base::MacResult+'cx> {
// stable (active).
// NB: The featureck.py script parses this information directly out of the source
// so take care when modifying it.
-static KNOWN_FEATURES: &'static [(&'static str, &'static str, Status)] = &[
+const KNOWN_FEATURES: &'static [(&'static str, &'static str, Status)] = &[
("globs", "1.0.0", Accepted),
("macro_rules", "1.0.0", Accepted),
("struct_variant", "1.0.0", Accepted),
// Allows the use of rustc_* attributes; RFC 572
("rustc_attrs", "1.0.0", Active),
+
+ // Allows the use of `static_assert`
+ ("static_assert", "1.0.0", Active),
];
// (changing above list without updating src/doc/reference.md makes @cmr sad)
}
// Attributes that have a special meaning to rustc or rustdoc
-pub static KNOWN_ATTRIBUTES: &'static [(&'static str, AttributeType)] = &[
+pub const KNOWN_ATTRIBUTES: &'static [(&'static str, AttributeType)] = &[
// Normal attributes
("warn", Normal),
("plugin_registrar", Normal),
("cfg", Normal),
+ ("cfg_attr", Normal),
("main", Normal),
("start", Normal),
("test", Normal),
("no_split_stack", Whitelisted),
("no_stack_check", Whitelisted),
("packed", Whitelisted),
- ("static_assert", Whitelisted),
+ ("static_assert", Gated("static_assert",
+ "`#[static_assert]` is an experimental feature, and has a poor API")),
("no_debug", Whitelisted),
("omit_gdb_pretty_printer_section", Whitelisted),
("unsafe_no_drop_flag", Gated("unsafe_no_drop_flag",
|ctx, krate| visit::walk_crate(&mut PostExpansionVisitor { context: ctx },
krate))
}
-
}
// one-line comments lose their prefix
- static ONLINERS: &'static [&'static str] = &["///!", "///", "//!", "//"];
- for prefix in ONLINERS {
+ const ONELINERS: &'static [&'static str] = &["///!", "///", "//!", "//"];
+ for prefix in ONELINERS {
if comment.starts_with(*prefix) {
return (&comment[prefix.len()..]).to_string();
}
$( ($rk_name:expr, $rk_variant:ident, $rk_str:expr); )*
}
) => {
- static STRICT_KEYWORD_START: ast::Name = first!($( ast::Name($sk_name), )*);
- static STRICT_KEYWORD_FINAL: ast::Name = last!($( ast::Name($sk_name), )*);
- static RESERVED_KEYWORD_START: ast::Name = first!($( ast::Name($rk_name), )*);
- static RESERVED_KEYWORD_FINAL: ast::Name = last!($( ast::Name($rk_name), )*);
+ const STRICT_KEYWORD_START: ast::Name = first!($( ast::Name($sk_name), )*);
+ const STRICT_KEYWORD_FINAL: ast::Name = last!($( ast::Name($sk_name), )*);
+ const RESERVED_KEYWORD_START: ast::Name = first!($( ast::Name($rk_name), )*);
+ const RESERVED_KEYWORD_FINAL: ast::Name = last!($( ast::Name($rk_name), )*);
pub mod special_idents {
use ast;
pbreak: PrintStackBreak
}
-static SIZE_INFINITY: isize = 0xffff;
+const SIZE_INFINITY: isize = 0xffff;
pub fn mk_printer(out: Box<old_io::Writer+'static>, linewidth: usize) -> Printer {
// Yes 3, it makes the ring buffers big enough to never
fn mean(&self) -> T {
assert!(self.len() != 0);
- self.sum() / FromPrimitive::from_uint(self.len()).unwrap()
+ self.sum() / FromPrimitive::from_usize(self.len()).unwrap()
}
fn median(&self) -> T {
- self.percentile(FromPrimitive::from_uint(50).unwrap())
+ self.percentile(FromPrimitive::from_usize(50).unwrap())
}
fn var(&self) -> T {
// NB: this is _supposed to be_ len-1, not len. If you
// change it back to len, you will be calculating a
// population variance, not a sample variance.
- let denom = FromPrimitive::from_uint(self.len()-1).unwrap();
+ let denom = FromPrimitive::from_usize(self.len()-1).unwrap();
v/denom
}
}
}
fn std_dev_pct(&self) -> T {
- let hundred = FromPrimitive::from_uint(100).unwrap();
+ let hundred = FromPrimitive::from_usize(100).unwrap();
(self.std_dev() / self.mean()) * hundred
}
}
fn median_abs_dev_pct(&self) -> T {
- let hundred = FromPrimitive::from_uint(100).unwrap();
+ let hundred = FromPrimitive::from_usize(100).unwrap();
(self.median_abs_dev() / self.median()) * hundred
}
fn quartiles(&self) -> (T,T,T) {
let mut tmp = self.to_vec();
local_sort(&mut tmp);
- let first = FromPrimitive::from_uint(25).unwrap();
+ let first = FromPrimitive::from_usize(25).unwrap();
let a = percentile_of_sorted(&tmp, first);
- let secound = FromPrimitive::from_uint(50).unwrap();
+ let secound = FromPrimitive::from_usize(50).unwrap();
let b = percentile_of_sorted(&tmp, secound);
- let third = FromPrimitive::from_uint(75).unwrap();
+ let third = FromPrimitive::from_usize(75).unwrap();
let c = percentile_of_sorted(&tmp, third);
(a,b,c)
}
}
let zero: T = Float::zero();
assert!(zero <= pct);
- let hundred = FromPrimitive::from_uint(100).unwrap();
+ let hundred = FromPrimitive::from_usize(100).unwrap();
assert!(pct <= hundred);
if pct == hundred {
return sorted_samples[sorted_samples.len() - 1];
}
- let length = FromPrimitive::from_uint(sorted_samples.len() - 1).unwrap();
+ let length = FromPrimitive::from_usize(sorted_samples.len() - 1).unwrap();
let rank = (pct / hundred) * length;
let lrank = rank.floor();
let d = rank - lrank;
- let n = lrank.to_uint().unwrap();
+ let n = lrank.to_usize().unwrap();
let lo = sorted_samples[n];
let hi = sorted_samples[n+1];
lo + (hi - lo) * d
let mut tmp = samples.to_vec();
local_sort(&mut tmp);
let lo = percentile_of_sorted(&tmp, pct);
- let hundred: T = FromPrimitive::from_uint(100).unwrap();
+ let hundred: T = FromPrimitive::from_usize(100).unwrap();
let hi = percentile_of_sorted(&tmp, hundred-pct);
for samp in samples {
if *samp > hi {
}
pub mod general_category {
- pub static C_table: &'static [(char, char)] = &[
+ pub const C_table: &'static [(char, char)] = &[
('\u{0}', '\u{1f}'), ('\u{7f}', '\u{9f}'), ('\u{ad}', '\u{ad}'), ('\u{378}', '\u{379}'),
('\u{380}', '\u{383}'), ('\u{38b}', '\u{38b}'), ('\u{38d}', '\u{38d}'), ('\u{3a2}',
'\u{3a2}'), ('\u{530}', '\u{530}'), ('\u{557}', '\u{558}'), ('\u{560}', '\u{560}'),
('\u{e01f0}', '\u{10ffff}')
];
- pub static Cc_table: &'static [(char, char)] = &[
+ pub const Cc_table: &'static [(char, char)] = &[
('\u{0}', '\u{1f}'), ('\u{7f}', '\u{9f}')
];
super::bsearch_range_table(c, Cc_table)
}
- pub static Cf_table: &'static [(char, char)] = &[
+ pub const Cf_table: &'static [(char, char)] = &[
('\u{ad}', '\u{ad}'), ('\u{600}', '\u{605}'), ('\u{61c}', '\u{61c}'), ('\u{6dd}',
'\u{6dd}'), ('\u{70f}', '\u{70f}'), ('\u{180e}', '\u{180e}'), ('\u{200b}', '\u{200f}'),
('\u{202a}', '\u{202e}'), ('\u{2060}', '\u{2064}'), ('\u{2066}', '\u{206f}'), ('\u{feff}',
'\u{e007f}')
];
- pub static Cn_table: &'static [(char, char)] = &[
+ pub const Cn_table: &'static [(char, char)] = &[
('\u{378}', '\u{379}'), ('\u{380}', '\u{383}'), ('\u{38b}', '\u{38b}'), ('\u{38d}',
'\u{38d}'), ('\u{3a2}', '\u{3a2}'), ('\u{530}', '\u{530}'), ('\u{557}', '\u{558}'),
('\u{560}', '\u{560}'), ('\u{588}', '\u{588}'), ('\u{58b}', '\u{58c}'), ('\u{590}',
('\u{10fffe}', '\u{10ffff}')
];
- pub static Co_table: &'static [(char, char)] = &[
+ pub const Co_table: &'static [(char, char)] = &[
('\u{e000}', '\u{e000}'), ('\u{f8ff}', '\u{f8ff}'), ('\u{f0000}', '\u{f0000}'),
('\u{ffffd}', '\u{ffffd}'), ('\u{100000}', '\u{100000}'), ('\u{10fffd}', '\u{10fffd}')
];
- pub static L_table: &'static [(char, char)] = &[
+ pub const L_table: &'static [(char, char)] = &[
('\u{41}', '\u{5a}'), ('\u{61}', '\u{7a}'), ('\u{aa}', '\u{aa}'), ('\u{b5}', '\u{b5}'),
('\u{ba}', '\u{ba}'), ('\u{c0}', '\u{d6}'), ('\u{d8}', '\u{f6}'), ('\u{f8}', '\u{2c1}'),
('\u{2c6}', '\u{2d1}'), ('\u{2e0}', '\u{2e4}'), ('\u{2ec}', '\u{2ec}'), ('\u{2ee}',
('\u{2b81d}', '\u{2b81d}'), ('\u{2f800}', '\u{2fa1d}')
];
- pub static LC_table: &'static [(char, char)] = &[
+ pub const LC_table: &'static [(char, char)] = &[
('\u{41}', '\u{5a}'), ('\u{61}', '\u{7a}'), ('\u{b5}', '\u{b5}'), ('\u{c0}', '\u{d6}'),
('\u{d8}', '\u{f6}'), ('\u{f8}', '\u{1ba}'), ('\u{1bc}', '\u{1bf}'), ('\u{1c4}', '\u{293}'),
('\u{295}', '\u{2af}'), ('\u{370}', '\u{373}'), ('\u{376}', '\u{377}'), ('\u{37b}',
('\u{1d7aa}', '\u{1d7c2}'), ('\u{1d7c4}', '\u{1d7cb}')
];
- pub static Ll_table: &'static [(char, char)] = &[
+ pub const Ll_table: &'static [(char, char)] = &[
('\u{61}', '\u{7a}'), ('\u{b5}', '\u{b5}'), ('\u{df}', '\u{f6}'), ('\u{f8}', '\u{ff}'),
('\u{101}', '\u{101}'), ('\u{103}', '\u{103}'), ('\u{105}', '\u{105}'), ('\u{107}',
'\u{107}'), ('\u{109}', '\u{109}'), ('\u{10b}', '\u{10b}'), ('\u{10d}', '\u{10d}'),
'\u{1d7c2}'), ('\u{1d7c4}', '\u{1d7c9}'), ('\u{1d7cb}', '\u{1d7cb}')
];
- pub static Lm_table: &'static [(char, char)] = &[
+ pub const Lm_table: &'static [(char, char)] = &[
('\u{2b0}', '\u{2c1}'), ('\u{2c6}', '\u{2d1}'), ('\u{2e0}', '\u{2e4}'), ('\u{2ec}',
'\u{2ec}'), ('\u{2ee}', '\u{2ee}'), ('\u{374}', '\u{374}'), ('\u{37a}', '\u{37a}'),
('\u{559}', '\u{559}'), ('\u{640}', '\u{640}'), ('\u{6e5}', '\u{6e6}'), ('\u{7f4}',
'\u{16f9f}')
];
- pub static Lo_table: &'static [(char, char)] = &[
+ pub const Lo_table: &'static [(char, char)] = &[
('\u{aa}', '\u{aa}'), ('\u{ba}', '\u{ba}'), ('\u{1bb}', '\u{1bb}'), ('\u{1c0}', '\u{1c3}'),
('\u{294}', '\u{294}'), ('\u{5d0}', '\u{5ea}'), ('\u{5f0}', '\u{5f2}'), ('\u{620}',
'\u{63f}'), ('\u{641}', '\u{64a}'), ('\u{66e}', '\u{66f}'), ('\u{671}', '\u{6d3}'),
('\u{2b740}', '\u{2b740}'), ('\u{2b81d}', '\u{2b81d}'), ('\u{2f800}', '\u{2fa1d}')
];
- pub static Lt_table: &'static [(char, char)] = &[
+ pub const Lt_table: &'static [(char, char)] = &[
('\u{1c5}', '\u{1c5}'), ('\u{1c8}', '\u{1c8}'), ('\u{1cb}', '\u{1cb}'), ('\u{1f2}',
'\u{1f2}'), ('\u{1f88}', '\u{1f8f}'), ('\u{1f98}', '\u{1f9f}'), ('\u{1fa8}', '\u{1faf}'),
('\u{1fbc}', '\u{1fbc}'), ('\u{1fcc}', '\u{1fcc}'), ('\u{1ffc}', '\u{1ffc}')
];
- pub static Lu_table: &'static [(char, char)] = &[
+ pub const Lu_table: &'static [(char, char)] = &[
('\u{41}', '\u{5a}'), ('\u{c0}', '\u{d6}'), ('\u{d8}', '\u{de}'), ('\u{100}', '\u{100}'),
('\u{102}', '\u{102}'), ('\u{104}', '\u{104}'), ('\u{106}', '\u{106}'), ('\u{108}',
'\u{108}'), ('\u{10a}', '\u{10a}'), ('\u{10c}', '\u{10c}'), ('\u{10e}', '\u{10e}'),
'\u{1d7ca}')
];
- pub static M_table: &'static [(char, char)] = &[
+ pub const M_table: &'static [(char, char)] = &[
('\u{300}', '\u{36f}'), ('\u{483}', '\u{489}'), ('\u{591}', '\u{5bd}'), ('\u{5bf}',
'\u{5bf}'), ('\u{5c1}', '\u{5c2}'), ('\u{5c4}', '\u{5c5}'), ('\u{5c7}', '\u{5c7}'),
('\u{610}', '\u{61a}'), ('\u{64b}', '\u{65f}'), ('\u{670}', '\u{670}'), ('\u{6d6}',
('\u{1e8d0}', '\u{1e8d6}'), ('\u{e0100}', '\u{e01ef}')
];
- pub static Mc_table: &'static [(char, char)] = &[
+ pub const Mc_table: &'static [(char, char)] = &[
('\u{903}', '\u{903}'), ('\u{93b}', '\u{93b}'), ('\u{93e}', '\u{940}'), ('\u{949}',
'\u{94c}'), ('\u{94e}', '\u{94f}'), ('\u{982}', '\u{983}'), ('\u{9be}', '\u{9c0}'),
('\u{9c7}', '\u{9c8}'), ('\u{9cb}', '\u{9cc}'), ('\u{9d7}', '\u{9d7}'), ('\u{a03}',
('\u{1d165}', '\u{1d166}'), ('\u{1d16d}', '\u{1d172}')
];
- pub static Me_table: &'static [(char, char)] = &[
+ pub const Me_table: &'static [(char, char)] = &[
('\u{488}', '\u{489}'), ('\u{1abe}', '\u{1abe}'), ('\u{20dd}', '\u{20e0}'), ('\u{20e2}',
'\u{20e4}'), ('\u{a670}', '\u{a672}')
];
- pub static Mn_table: &'static [(char, char)] = &[
+ pub const Mn_table: &'static [(char, char)] = &[
('\u{300}', '\u{36f}'), ('\u{483}', '\u{487}'), ('\u{591}', '\u{5bd}'), ('\u{5bf}',
'\u{5bf}'), ('\u{5c1}', '\u{5c2}'), ('\u{5c4}', '\u{5c5}'), ('\u{5c7}', '\u{5c7}'),
('\u{610}', '\u{61a}'), ('\u{64b}', '\u{65f}'), ('\u{670}', '\u{670}'), ('\u{6d6}',
'\u{1e8d6}'), ('\u{e0100}', '\u{e01ef}')
];
- pub static N_table: &'static [(char, char)] = &[
+ pub const N_table: &'static [(char, char)] = &[
('\u{30}', '\u{39}'), ('\u{660}', '\u{669}'), ('\u{6f0}', '\u{6f9}'), ('\u{7c0}',
'\u{7c9}'), ('\u{966}', '\u{96f}'), ('\u{9e6}', '\u{9ef}'), ('\u{a66}', '\u{a6f}'),
('\u{ae6}', '\u{aef}'), ('\u{b66}', '\u{b6f}'), ('\u{be6}', '\u{bef}'), ('\u{c66}',
super::bsearch_range_table(c, N_table)
}
- pub static Nd_table: &'static [(char, char)] = &[
+ pub const Nd_table: &'static [(char, char)] = &[
('\u{30}', '\u{39}'), ('\u{660}', '\u{669}'), ('\u{6f0}', '\u{6f9}'), ('\u{7c0}',
'\u{7c9}'), ('\u{966}', '\u{96f}'), ('\u{9e6}', '\u{9ef}'), ('\u{a66}', '\u{a6f}'),
('\u{ae6}', '\u{aef}'), ('\u{b66}', '\u{b6f}'), ('\u{be6}', '\u{bef}'), ('\u{c66}',
('\u{16a60}', '\u{16a69}'), ('\u{16b50}', '\u{16b59}'), ('\u{1d7ce}', '\u{1d7ff}')
];
- pub static Nl_table: &'static [(char, char)] = &[
+ pub const Nl_table: &'static [(char, char)] = &[
('\u{16ee}', '\u{16f0}'), ('\u{2160}', '\u{2182}'), ('\u{2185}', '\u{2188}'), ('\u{3007}',
'\u{3007}'), ('\u{3021}', '\u{3029}'), ('\u{3038}', '\u{303a}'), ('\u{a6e6}', '\u{a6ef}'),
('\u{10140}', '\u{10174}'), ('\u{10341}', '\u{10341}'), ('\u{1034a}', '\u{1034a}'),
('\u{103d1}', '\u{103d5}'), ('\u{12400}', '\u{1246e}')
];
- pub static No_table: &'static [(char, char)] = &[
+ pub const No_table: &'static [(char, char)] = &[
('\u{b2}', '\u{b3}'), ('\u{b9}', '\u{b9}'), ('\u{bc}', '\u{be}'), ('\u{9f4}', '\u{9f9}'),
('\u{b72}', '\u{b77}'), ('\u{bf0}', '\u{bf2}'), ('\u{c78}', '\u{c7e}'), ('\u{d70}',
'\u{d75}'), ('\u{f2a}', '\u{f33}'), ('\u{1369}', '\u{137c}'), ('\u{17f0}', '\u{17f9}'),
'\u{1d371}'), ('\u{1e8c7}', '\u{1e8cf}'), ('\u{1f100}', '\u{1f10c}')
];
- pub static P_table: &'static [(char, char)] = &[
+ pub const P_table: &'static [(char, char)] = &[
('\u{21}', '\u{23}'), ('\u{25}', '\u{2a}'), ('\u{2c}', '\u{2f}'), ('\u{3a}', '\u{3b}'),
('\u{3f}', '\u{40}'), ('\u{5b}', '\u{5d}'), ('\u{5f}', '\u{5f}'), ('\u{7b}', '\u{7b}'),
('\u{7d}', '\u{7d}'), ('\u{a1}', '\u{a1}'), ('\u{a7}', '\u{a7}'), ('\u{ab}', '\u{ab}'),
'\u{1bc9f}')
];
- pub static Pc_table: &'static [(char, char)] = &[
+ pub const Pc_table: &'static [(char, char)] = &[
('\u{5f}', '\u{5f}'), ('\u{203f}', '\u{2040}'), ('\u{2054}', '\u{2054}'), ('\u{fe33}',
'\u{fe34}'), ('\u{fe4d}', '\u{fe4f}'), ('\u{ff3f}', '\u{ff3f}')
];
- pub static Pd_table: &'static [(char, char)] = &[
+ pub const Pd_table: &'static [(char, char)] = &[
('\u{2d}', '\u{2d}'), ('\u{58a}', '\u{58a}'), ('\u{5be}', '\u{5be}'), ('\u{1400}',
'\u{1400}'), ('\u{1806}', '\u{1806}'), ('\u{2010}', '\u{2015}'), ('\u{2e17}', '\u{2e17}'),
('\u{2e1a}', '\u{2e1a}'), ('\u{2e3a}', '\u{2e3b}'), ('\u{2e40}', '\u{2e40}'), ('\u{301c}',
('\u{fe58}', '\u{fe58}'), ('\u{fe63}', '\u{fe63}'), ('\u{ff0d}', '\u{ff0d}')
];
- pub static Pe_table: &'static [(char, char)] = &[
+ pub const Pe_table: &'static [(char, char)] = &[
('\u{29}', '\u{29}'), ('\u{5d}', '\u{5d}'), ('\u{7d}', '\u{7d}'), ('\u{f3b}', '\u{f3b}'),
('\u{f3d}', '\u{f3d}'), ('\u{169c}', '\u{169c}'), ('\u{2046}', '\u{2046}'), ('\u{207e}',
'\u{207e}'), ('\u{208e}', '\u{208e}'), ('\u{2309}', '\u{2309}'), ('\u{230b}', '\u{230b}'),
'\u{ff60}'), ('\u{ff63}', '\u{ff63}')
];
- pub static Pf_table: &'static [(char, char)] = &[
+ pub const Pf_table: &'static [(char, char)] = &[
('\u{bb}', '\u{bb}'), ('\u{2019}', '\u{2019}'), ('\u{201d}', '\u{201d}'), ('\u{203a}',
'\u{203a}'), ('\u{2e03}', '\u{2e03}'), ('\u{2e05}', '\u{2e05}'), ('\u{2e0a}', '\u{2e0a}'),
('\u{2e0d}', '\u{2e0d}'), ('\u{2e1d}', '\u{2e1d}'), ('\u{2e21}', '\u{2e21}')
];
- pub static Pi_table: &'static [(char, char)] = &[
+ pub const Pi_table: &'static [(char, char)] = &[
('\u{ab}', '\u{ab}'), ('\u{2018}', '\u{2018}'), ('\u{201b}', '\u{201c}'), ('\u{201f}',
'\u{201f}'), ('\u{2039}', '\u{2039}'), ('\u{2e02}', '\u{2e02}'), ('\u{2e04}', '\u{2e04}'),
('\u{2e09}', '\u{2e09}'), ('\u{2e0c}', '\u{2e0c}'), ('\u{2e1c}', '\u{2e1c}'), ('\u{2e20}',
'\u{2e20}')
];
- pub static Po_table: &'static [(char, char)] = &[
+ pub const Po_table: &'static [(char, char)] = &[
('\u{21}', '\u{23}'), ('\u{25}', '\u{27}'), ('\u{2a}', '\u{2a}'), ('\u{2c}', '\u{2c}'),
('\u{2e}', '\u{2f}'), ('\u{3a}', '\u{3b}'), ('\u{3f}', '\u{40}'), ('\u{5c}', '\u{5c}'),
('\u{a1}', '\u{a1}'), ('\u{a7}', '\u{a7}'), ('\u{b6}', '\u{b7}'), ('\u{bf}', '\u{bf}'),
'\u{1bc9f}')
];
- pub static Ps_table: &'static [(char, char)] = &[
+ pub const Ps_table: &'static [(char, char)] = &[
('\u{28}', '\u{28}'), ('\u{5b}', '\u{5b}'), ('\u{7b}', '\u{7b}'), ('\u{f3a}', '\u{f3a}'),
('\u{f3c}', '\u{f3c}'), ('\u{169b}', '\u{169b}'), ('\u{201a}', '\u{201a}'), ('\u{201e}',
'\u{201e}'), ('\u{2045}', '\u{2045}'), ('\u{207d}', '\u{207d}'), ('\u{208d}', '\u{208d}'),
('\u{ff62}', '\u{ff62}')
];
- pub static S_table: &'static [(char, char)] = &[
+ pub const S_table: &'static [(char, char)] = &[
('\u{24}', '\u{24}'), ('\u{2b}', '\u{2b}'), ('\u{3c}', '\u{3e}'), ('\u{5e}', '\u{5e}'),
('\u{60}', '\u{60}'), ('\u{7c}', '\u{7c}'), ('\u{7e}', '\u{7e}'), ('\u{a2}', '\u{a6}'),
('\u{a8}', '\u{a9}'), ('\u{ac}', '\u{ac}'), ('\u{ae}', '\u{b1}'), ('\u{b4}', '\u{b4}'),
'\u{1f887}'), ('\u{1f890}', '\u{1f8ad}')
];
- pub static Sc_table: &'static [(char, char)] = &[
+ pub const Sc_table: &'static [(char, char)] = &[
('\u{24}', '\u{24}'), ('\u{a2}', '\u{a5}'), ('\u{58f}', '\u{58f}'), ('\u{60b}', '\u{60b}'),
('\u{9f2}', '\u{9f3}'), ('\u{9fb}', '\u{9fb}'), ('\u{af1}', '\u{af1}'), ('\u{bf9}',
'\u{bf9}'), ('\u{e3f}', '\u{e3f}'), ('\u{17db}', '\u{17db}'), ('\u{20a0}', '\u{20bd}'),
'\u{ff04}'), ('\u{ffe0}', '\u{ffe1}'), ('\u{ffe5}', '\u{ffe6}')
];
- pub static Sk_table: &'static [(char, char)] = &[
+ pub const Sk_table: &'static [(char, char)] = &[
('\u{5e}', '\u{5e}'), ('\u{60}', '\u{60}'), ('\u{a8}', '\u{a8}'), ('\u{af}', '\u{af}'),
('\u{b4}', '\u{b4}'), ('\u{b8}', '\u{b8}'), ('\u{2c2}', '\u{2c5}'), ('\u{2d2}', '\u{2df}'),
('\u{2e5}', '\u{2eb}'), ('\u{2ed}', '\u{2ed}'), ('\u{2ef}', '\u{2ff}'), ('\u{375}',
'\u{ff3e}'), ('\u{ff40}', '\u{ff40}'), ('\u{ffe3}', '\u{ffe3}')
];
- pub static Sm_table: &'static [(char, char)] = &[
+ pub const Sm_table: &'static [(char, char)] = &[
('\u{2b}', '\u{2b}'), ('\u{3c}', '\u{3e}'), ('\u{7c}', '\u{7c}'), ('\u{7e}', '\u{7e}'),
('\u{ac}', '\u{ac}'), ('\u{b1}', '\u{b1}'), ('\u{d7}', '\u{d7}'), ('\u{f7}', '\u{f7}'),
('\u{3f6}', '\u{3f6}'), ('\u{606}', '\u{608}'), ('\u{2044}', '\u{2044}'), ('\u{2052}',
'\u{1d7c3}'), ('\u{1eef0}', '\u{1eef1}')
];
- pub static So_table: &'static [(char, char)] = &[
+ pub const So_table: &'static [(char, char)] = &[
('\u{a6}', '\u{a6}'), ('\u{a9}', '\u{a9}'), ('\u{ae}', '\u{ae}'), ('\u{b0}', '\u{b0}'),
('\u{482}', '\u{482}'), ('\u{58d}', '\u{58e}'), ('\u{60e}', '\u{60f}'), ('\u{6de}',
'\u{6de}'), ('\u{6e9}', '\u{6e9}'), ('\u{6fd}', '\u{6fe}'), ('\u{7f6}', '\u{7f6}'),
'\u{1f887}'), ('\u{1f890}', '\u{1f8ad}')
];
- pub static Z_table: &'static [(char, char)] = &[
+ pub const Z_table: &'static [(char, char)] = &[
('\u{20}', '\u{20}'), ('\u{a0}', '\u{a0}'), ('\u{1680}', '\u{1680}'), ('\u{2000}',
'\u{200a}'), ('\u{2028}', '\u{2029}'), ('\u{202f}', '\u{202f}'), ('\u{205f}', '\u{205f}'),
('\u{3000}', '\u{3000}')
];
- pub static Zl_table: &'static [(char, char)] = &[
+ pub const Zl_table: &'static [(char, char)] = &[
('\u{2028}', '\u{2028}')
];
- pub static Zp_table: &'static [(char, char)] = &[
+ pub const Zp_table: &'static [(char, char)] = &[
('\u{2029}', '\u{2029}')
];
- pub static Zs_table: &'static [(char, char)] = &[
+ pub const Zs_table: &'static [(char, char)] = &[
('\u{20}', '\u{20}'), ('\u{a0}', '\u{a0}'), ('\u{1680}', '\u{1680}'), ('\u{2000}',
'\u{200a}'), ('\u{202f}', '\u{202f}'), ('\u{205f}', '\u{205f}'), ('\u{3000}', '\u{3000}')
];
}
pub mod derived_property {
- pub static Alphabetic_table: &'static [(char, char)] = &[
+ pub const Alphabetic_table: &'static [(char, char)] = &[
('\u{41}', '\u{5a}'), ('\u{61}', '\u{7a}'), ('\u{aa}', '\u{aa}'), ('\u{b5}', '\u{b5}'),
('\u{ba}', '\u{ba}'), ('\u{c0}', '\u{d6}'), ('\u{d8}', '\u{f6}'), ('\u{f8}', '\u{1ba}'),
('\u{1bb}', '\u{1bb}'), ('\u{1bc}', '\u{1bf}'), ('\u{1c0}', '\u{1c3}'), ('\u{1c4}',
super::bsearch_range_table(c, Alphabetic_table)
}
- pub static Default_Ignorable_Code_Point_table: &'static [(char, char)] = &[
+ pub const Default_Ignorable_Code_Point_table: &'static [(char, char)] = &[
('\u{ad}', '\u{ad}'), ('\u{34f}', '\u{34f}'), ('\u{61c}', '\u{61c}'), ('\u{115f}',
'\u{1160}'), ('\u{17b4}', '\u{17b5}'), ('\u{180b}', '\u{180d}'), ('\u{180e}', '\u{180e}'),
('\u{200b}', '\u{200f}'), ('\u{202a}', '\u{202e}'), ('\u{2060}', '\u{2064}'), ('\u{2065}',
'\u{e00ff}'), ('\u{e0100}', '\u{e01ef}'), ('\u{e01f0}', '\u{e0fff}')
];
- pub static Lowercase_table: &'static [(char, char)] = &[
+ pub const Lowercase_table: &'static [(char, char)] = &[
('\u{61}', '\u{7a}'), ('\u{aa}', '\u{aa}'), ('\u{b5}', '\u{b5}'), ('\u{ba}', '\u{ba}'),
('\u{df}', '\u{f6}'), ('\u{f8}', '\u{ff}'), ('\u{101}', '\u{101}'), ('\u{103}', '\u{103}'),
('\u{105}', '\u{105}'), ('\u{107}', '\u{107}'), ('\u{109}', '\u{109}'), ('\u{10b}',
super::bsearch_range_table(c, Lowercase_table)
}
- pub static Uppercase_table: &'static [(char, char)] = &[
+ pub const Uppercase_table: &'static [(char, char)] = &[
('\u{41}', '\u{5a}'), ('\u{c0}', '\u{d6}'), ('\u{d8}', '\u{de}'), ('\u{100}', '\u{100}'),
('\u{102}', '\u{102}'), ('\u{104}', '\u{104}'), ('\u{106}', '\u{106}'), ('\u{108}',
'\u{108}'), ('\u{10a}', '\u{10a}'), ('\u{10c}', '\u{10c}'), ('\u{10e}', '\u{10e}'),
super::bsearch_range_table(c, Uppercase_table)
}
- pub static XID_Continue_table: &'static [(char, char)] = &[
+ pub const XID_Continue_table: &'static [(char, char)] = &[
('\u{30}', '\u{39}'), ('\u{41}', '\u{5a}'), ('\u{5f}', '\u{5f}'), ('\u{61}', '\u{7a}'),
('\u{aa}', '\u{aa}'), ('\u{b5}', '\u{b5}'), ('\u{b7}', '\u{b7}'), ('\u{ba}', '\u{ba}'),
('\u{c0}', '\u{d6}'), ('\u{d8}', '\u{f6}'), ('\u{f8}', '\u{1ba}'), ('\u{1bb}', '\u{1bb}'),
super::bsearch_range_table(c, XID_Continue_table)
}
- pub static XID_Start_table: &'static [(char, char)] = &[
+ pub const XID_Start_table: &'static [(char, char)] = &[
('\u{41}', '\u{5a}'), ('\u{61}', '\u{7a}'), ('\u{aa}', '\u{aa}'), ('\u{b5}', '\u{b5}'),
('\u{ba}', '\u{ba}'), ('\u{c0}', '\u{d6}'), ('\u{d8}', '\u{f6}'), ('\u{f8}', '\u{1ba}'),
('\u{1bb}', '\u{1bb}'), ('\u{1bc}', '\u{1bf}'), ('\u{1c0}', '\u{1c3}'), ('\u{1c4}',
}
pub mod script {
- pub static Arabic_table: &'static [(char, char)] = &[
+ pub const Arabic_table: &'static [(char, char)] = &[
('\u{600}', '\u{604}'), ('\u{606}', '\u{608}'), ('\u{609}', '\u{60a}'), ('\u{60b}',
'\u{60b}'), ('\u{60d}', '\u{60d}'), ('\u{60e}', '\u{60f}'), ('\u{610}', '\u{61a}'),
('\u{61e}', '\u{61e}'), ('\u{620}', '\u{63f}'), ('\u{641}', '\u{64a}'), ('\u{656}',
('\u{1eef0}', '\u{1eef1}')
];
- pub static Armenian_table: &'static [(char, char)] = &[
+ pub const Armenian_table: &'static [(char, char)] = &[
('\u{531}', '\u{556}'), ('\u{559}', '\u{559}'), ('\u{55a}', '\u{55f}'), ('\u{561}',
'\u{587}'), ('\u{58a}', '\u{58a}'), ('\u{58d}', '\u{58e}'), ('\u{58f}', '\u{58f}'),
('\u{fb13}', '\u{fb17}')
];
- pub static Avestan_table: &'static [(char, char)] = &[
+ pub const Avestan_table: &'static [(char, char)] = &[
('\u{10b00}', '\u{10b35}'), ('\u{10b39}', '\u{10b3f}')
];
- pub static Balinese_table: &'static [(char, char)] = &[
+ pub const Balinese_table: &'static [(char, char)] = &[
('\u{1b00}', '\u{1b03}'), ('\u{1b04}', '\u{1b04}'), ('\u{1b05}', '\u{1b33}'), ('\u{1b34}',
'\u{1b34}'), ('\u{1b35}', '\u{1b35}'), ('\u{1b36}', '\u{1b3a}'), ('\u{1b3b}', '\u{1b3b}'),
('\u{1b3c}', '\u{1b3c}'), ('\u{1b3d}', '\u{1b41}'), ('\u{1b42}', '\u{1b42}'), ('\u{1b43}',
('\u{1b61}', '\u{1b6a}'), ('\u{1b6b}', '\u{1b73}'), ('\u{1b74}', '\u{1b7c}')
];
- pub static Bamum_table: &'static [(char, char)] = &[
+ pub const Bamum_table: &'static [(char, char)] = &[
('\u{a6a0}', '\u{a6e5}'), ('\u{a6e6}', '\u{a6ef}'), ('\u{a6f0}', '\u{a6f1}'), ('\u{a6f2}',
'\u{a6f7}'), ('\u{16800}', '\u{16a38}')
];
- pub static Bassa_Vah_table: &'static [(char, char)] = &[
+ pub const Bassa_Vah_table: &'static [(char, char)] = &[
('\u{16ad0}', '\u{16aed}'), ('\u{16af0}', '\u{16af4}'), ('\u{16af5}', '\u{16af5}')
];
- pub static Batak_table: &'static [(char, char)] = &[
+ pub const Batak_table: &'static [(char, char)] = &[
('\u{1bc0}', '\u{1be5}'), ('\u{1be6}', '\u{1be6}'), ('\u{1be7}', '\u{1be7}'), ('\u{1be8}',
'\u{1be9}'), ('\u{1bea}', '\u{1bec}'), ('\u{1bed}', '\u{1bed}'), ('\u{1bee}', '\u{1bee}'),
('\u{1bef}', '\u{1bf1}'), ('\u{1bf2}', '\u{1bf3}'), ('\u{1bfc}', '\u{1bff}')
];
- pub static Bengali_table: &'static [(char, char)] = &[
+ pub const Bengali_table: &'static [(char, char)] = &[
('\u{980}', '\u{980}'), ('\u{981}', '\u{981}'), ('\u{982}', '\u{983}'), ('\u{985}',
'\u{98c}'), ('\u{98f}', '\u{990}'), ('\u{993}', '\u{9a8}'), ('\u{9aa}', '\u{9b0}'),
('\u{9b2}', '\u{9b2}'), ('\u{9b6}', '\u{9b9}'), ('\u{9bc}', '\u{9bc}'), ('\u{9bd}',
'\u{9f9}'), ('\u{9fa}', '\u{9fa}'), ('\u{9fb}', '\u{9fb}')
];
- pub static Bopomofo_table: &'static [(char, char)] = &[
+ pub const Bopomofo_table: &'static [(char, char)] = &[
('\u{2ea}', '\u{2eb}'), ('\u{3105}', '\u{312d}'), ('\u{31a0}', '\u{31ba}')
];
- pub static Brahmi_table: &'static [(char, char)] = &[
+ pub const Brahmi_table: &'static [(char, char)] = &[
('\u{11000}', '\u{11000}'), ('\u{11001}', '\u{11001}'), ('\u{11002}', '\u{11002}'),
('\u{11003}', '\u{11037}'), ('\u{11038}', '\u{11046}'), ('\u{11047}', '\u{1104d}'),
('\u{11052}', '\u{11065}'), ('\u{11066}', '\u{1106f}'), ('\u{1107f}', '\u{1107f}')
];
- pub static Braille_table: &'static [(char, char)] = &[
+ pub const Braille_table: &'static [(char, char)] = &[
('\u{2800}', '\u{28ff}')
];
- pub static Buginese_table: &'static [(char, char)] = &[
+ pub const Buginese_table: &'static [(char, char)] = &[
('\u{1a00}', '\u{1a16}'), ('\u{1a17}', '\u{1a18}'), ('\u{1a19}', '\u{1a1a}'), ('\u{1a1b}',
'\u{1a1b}'), ('\u{1a1e}', '\u{1a1f}')
];
- pub static Buhid_table: &'static [(char, char)] = &[
+ pub const Buhid_table: &'static [(char, char)] = &[
('\u{1740}', '\u{1751}'), ('\u{1752}', '\u{1753}')
];
- pub static Canadian_Aboriginal_table: &'static [(char, char)] = &[
+ pub const Canadian_Aboriginal_table: &'static [(char, char)] = &[
('\u{1400}', '\u{1400}'), ('\u{1401}', '\u{166c}'), ('\u{166d}', '\u{166e}'), ('\u{166f}',
'\u{167f}'), ('\u{18b0}', '\u{18f5}')
];
- pub static Carian_table: &'static [(char, char)] = &[
+ pub const Carian_table: &'static [(char, char)] = &[
('\u{102a0}', '\u{102d0}')
];
- pub static Caucasian_Albanian_table: &'static [(char, char)] = &[
+ pub const Caucasian_Albanian_table: &'static [(char, char)] = &[
('\u{10530}', '\u{10563}'), ('\u{1056f}', '\u{1056f}')
];
- pub static Chakma_table: &'static [(char, char)] = &[
+ pub const Chakma_table: &'static [(char, char)] = &[
('\u{11100}', '\u{11102}'), ('\u{11103}', '\u{11126}'), ('\u{11127}', '\u{1112b}'),
('\u{1112c}', '\u{1112c}'), ('\u{1112d}', '\u{11134}'), ('\u{11136}', '\u{1113f}'),
('\u{11140}', '\u{11143}')
];
- pub static Cham_table: &'static [(char, char)] = &[
+ pub const Cham_table: &'static [(char, char)] = &[
('\u{aa00}', '\u{aa28}'), ('\u{aa29}', '\u{aa2e}'), ('\u{aa2f}', '\u{aa30}'), ('\u{aa31}',
'\u{aa32}'), ('\u{aa33}', '\u{aa34}'), ('\u{aa35}', '\u{aa36}'), ('\u{aa40}', '\u{aa42}'),
('\u{aa43}', '\u{aa43}'), ('\u{aa44}', '\u{aa4b}'), ('\u{aa4c}', '\u{aa4c}'), ('\u{aa4d}',
'\u{aa4d}'), ('\u{aa50}', '\u{aa59}'), ('\u{aa5c}', '\u{aa5f}')
];
- pub static Cherokee_table: &'static [(char, char)] = &[
+ pub const Cherokee_table: &'static [(char, char)] = &[
('\u{13a0}', '\u{13f4}')
];
- pub static Common_table: &'static [(char, char)] = &[
+ pub const Common_table: &'static [(char, char)] = &[
('\u{0}', '\u{1f}'), ('\u{20}', '\u{20}'), ('\u{21}', '\u{23}'), ('\u{24}', '\u{24}'),
('\u{25}', '\u{27}'), ('\u{28}', '\u{28}'), ('\u{29}', '\u{29}'), ('\u{2a}', '\u{2a}'),
('\u{2b}', '\u{2b}'), ('\u{2c}', '\u{2c}'), ('\u{2d}', '\u{2d}'), ('\u{2e}', '\u{2f}'),
('\u{1f890}', '\u{1f8ad}'), ('\u{e0001}', '\u{e0001}'), ('\u{e0020}', '\u{e007f}')
];
- pub static Coptic_table: &'static [(char, char)] = &[
+ pub const Coptic_table: &'static [(char, char)] = &[
('\u{3e2}', '\u{3ef}'), ('\u{2c80}', '\u{2ce4}'), ('\u{2ce5}', '\u{2cea}'), ('\u{2ceb}',
'\u{2cee}'), ('\u{2cef}', '\u{2cf1}'), ('\u{2cf2}', '\u{2cf3}'), ('\u{2cf9}', '\u{2cfc}'),
('\u{2cfd}', '\u{2cfd}'), ('\u{2cfe}', '\u{2cff}')
];
- pub static Cuneiform_table: &'static [(char, char)] = &[
+ pub const Cuneiform_table: &'static [(char, char)] = &[
('\u{12000}', '\u{12398}'), ('\u{12400}', '\u{1246e}'), ('\u{12470}', '\u{12474}')
];
- pub static Cypriot_table: &'static [(char, char)] = &[
+ pub const Cypriot_table: &'static [(char, char)] = &[
('\u{10800}', '\u{10805}'), ('\u{10808}', '\u{10808}'), ('\u{1080a}', '\u{10835}'),
('\u{10837}', '\u{10838}'), ('\u{1083c}', '\u{1083c}'), ('\u{1083f}', '\u{1083f}')
];
- pub static Cyrillic_table: &'static [(char, char)] = &[
+ pub const Cyrillic_table: &'static [(char, char)] = &[
('\u{400}', '\u{481}'), ('\u{482}', '\u{482}'), ('\u{483}', '\u{484}'), ('\u{487}',
'\u{487}'), ('\u{488}', '\u{489}'), ('\u{48a}', '\u{52f}'), ('\u{1d2b}', '\u{1d2b}'),
('\u{1d78}', '\u{1d78}'), ('\u{2de0}', '\u{2dff}'), ('\u{a640}', '\u{a66d}'), ('\u{a66e}',
'\u{a69b}'), ('\u{a69c}', '\u{a69d}'), ('\u{a69f}', '\u{a69f}')
];
- pub static Deseret_table: &'static [(char, char)] = &[
+ pub const Deseret_table: &'static [(char, char)] = &[
('\u{10400}', '\u{1044f}')
];
- pub static Devanagari_table: &'static [(char, char)] = &[
+ pub const Devanagari_table: &'static [(char, char)] = &[
('\u{900}', '\u{902}'), ('\u{903}', '\u{903}'), ('\u{904}', '\u{939}'), ('\u{93a}',
'\u{93a}'), ('\u{93b}', '\u{93b}'), ('\u{93c}', '\u{93c}'), ('\u{93d}', '\u{93d}'),
('\u{93e}', '\u{940}'), ('\u{941}', '\u{948}'), ('\u{949}', '\u{94c}'), ('\u{94d}',
('\u{a8f2}', '\u{a8f7}'), ('\u{a8f8}', '\u{a8fa}'), ('\u{a8fb}', '\u{a8fb}')
];
- pub static Duployan_table: &'static [(char, char)] = &[
+ pub const Duployan_table: &'static [(char, char)] = &[
('\u{1bc00}', '\u{1bc6a}'), ('\u{1bc70}', '\u{1bc7c}'), ('\u{1bc80}', '\u{1bc88}'),
('\u{1bc90}', '\u{1bc99}'), ('\u{1bc9c}', '\u{1bc9c}'), ('\u{1bc9d}', '\u{1bc9e}'),
('\u{1bc9f}', '\u{1bc9f}')
];
- pub static Egyptian_Hieroglyphs_table: &'static [(char, char)] = &[
+ pub const Egyptian_Hieroglyphs_table: &'static [(char, char)] = &[
('\u{13000}', '\u{1342e}')
];
- pub static Elbasan_table: &'static [(char, char)] = &[
+ pub const Elbasan_table: &'static [(char, char)] = &[
('\u{10500}', '\u{10527}')
];
- pub static Ethiopic_table: &'static [(char, char)] = &[
+ pub const Ethiopic_table: &'static [(char, char)] = &[
('\u{1200}', '\u{1248}'), ('\u{124a}', '\u{124d}'), ('\u{1250}', '\u{1256}'), ('\u{1258}',
'\u{1258}'), ('\u{125a}', '\u{125d}'), ('\u{1260}', '\u{1288}'), ('\u{128a}', '\u{128d}'),
('\u{1290}', '\u{12b0}'), ('\u{12b2}', '\u{12b5}'), ('\u{12b8}', '\u{12be}'), ('\u{12c0}',
'\u{ab0e}'), ('\u{ab11}', '\u{ab16}'), ('\u{ab20}', '\u{ab26}'), ('\u{ab28}', '\u{ab2e}')
];
- pub static Georgian_table: &'static [(char, char)] = &[
+ pub const Georgian_table: &'static [(char, char)] = &[
('\u{10a0}', '\u{10c5}'), ('\u{10c7}', '\u{10c7}'), ('\u{10cd}', '\u{10cd}'), ('\u{10d0}',
'\u{10fa}'), ('\u{10fc}', '\u{10fc}'), ('\u{10fd}', '\u{10ff}'), ('\u{2d00}', '\u{2d25}'),
('\u{2d27}', '\u{2d27}'), ('\u{2d2d}', '\u{2d2d}')
];
- pub static Glagolitic_table: &'static [(char, char)] = &[
+ pub const Glagolitic_table: &'static [(char, char)] = &[
('\u{2c00}', '\u{2c2e}'), ('\u{2c30}', '\u{2c5e}')
];
- pub static Gothic_table: &'static [(char, char)] = &[
+ pub const Gothic_table: &'static [(char, char)] = &[
('\u{10330}', '\u{10340}'), ('\u{10341}', '\u{10341}'), ('\u{10342}', '\u{10349}'),
('\u{1034a}', '\u{1034a}')
];
- pub static Grantha_table: &'static [(char, char)] = &[
+ pub const Grantha_table: &'static [(char, char)] = &[
('\u{11301}', '\u{11301}'), ('\u{11302}', '\u{11303}'), ('\u{11305}', '\u{1130c}'),
('\u{1130f}', '\u{11310}'), ('\u{11313}', '\u{11328}'), ('\u{1132a}', '\u{11330}'),
('\u{11332}', '\u{11333}'), ('\u{11335}', '\u{11339}'), ('\u{1133c}', '\u{1133c}'),
('\u{11366}', '\u{1136c}'), ('\u{11370}', '\u{11374}')
];
- pub static Greek_table: &'static [(char, char)] = &[
+ pub const Greek_table: &'static [(char, char)] = &[
('\u{370}', '\u{373}'), ('\u{375}', '\u{375}'), ('\u{376}', '\u{377}'), ('\u{37a}',
'\u{37a}'), ('\u{37b}', '\u{37d}'), ('\u{37f}', '\u{37f}'), ('\u{384}', '\u{384}'),
('\u{386}', '\u{386}'), ('\u{388}', '\u{38a}'), ('\u{38c}', '\u{38c}'), ('\u{38e}',
'\u{1d245}')
];
- pub static Gujarati_table: &'static [(char, char)] = &[
+ pub const Gujarati_table: &'static [(char, char)] = &[
('\u{a81}', '\u{a82}'), ('\u{a83}', '\u{a83}'), ('\u{a85}', '\u{a8d}'), ('\u{a8f}',
'\u{a91}'), ('\u{a93}', '\u{aa8}'), ('\u{aaa}', '\u{ab0}'), ('\u{ab2}', '\u{ab3}'),
('\u{ab5}', '\u{ab9}'), ('\u{abc}', '\u{abc}'), ('\u{abd}', '\u{abd}'), ('\u{abe}',
('\u{af1}', '\u{af1}')
];
- pub static Gurmukhi_table: &'static [(char, char)] = &[
+ pub const Gurmukhi_table: &'static [(char, char)] = &[
('\u{a01}', '\u{a02}'), ('\u{a03}', '\u{a03}'), ('\u{a05}', '\u{a0a}'), ('\u{a0f}',
'\u{a10}'), ('\u{a13}', '\u{a28}'), ('\u{a2a}', '\u{a30}'), ('\u{a32}', '\u{a33}'),
('\u{a35}', '\u{a36}'), ('\u{a38}', '\u{a39}'), ('\u{a3c}', '\u{a3c}'), ('\u{a3e}',
'\u{a6f}'), ('\u{a70}', '\u{a71}'), ('\u{a72}', '\u{a74}'), ('\u{a75}', '\u{a75}')
];
- pub static Han_table: &'static [(char, char)] = &[
+ pub const Han_table: &'static [(char, char)] = &[
('\u{2e80}', '\u{2e99}'), ('\u{2e9b}', '\u{2ef3}'), ('\u{2f00}', '\u{2fd5}'), ('\u{3005}',
'\u{3005}'), ('\u{3007}', '\u{3007}'), ('\u{3021}', '\u{3029}'), ('\u{3038}', '\u{303a}'),
('\u{303b}', '\u{303b}'), ('\u{3400}', '\u{4db5}'), ('\u{4e00}', '\u{9fcc}'), ('\u{f900}',
'\u{2b734}'), ('\u{2b740}', '\u{2b81d}'), ('\u{2f800}', '\u{2fa1d}')
];
- pub static Hangul_table: &'static [(char, char)] = &[
+ pub const Hangul_table: &'static [(char, char)] = &[
('\u{1100}', '\u{11ff}'), ('\u{302e}', '\u{302f}'), ('\u{3131}', '\u{318e}'), ('\u{3200}',
'\u{321e}'), ('\u{3260}', '\u{327e}'), ('\u{a960}', '\u{a97c}'), ('\u{ac00}', '\u{d7a3}'),
('\u{d7b0}', '\u{d7c6}'), ('\u{d7cb}', '\u{d7fb}'), ('\u{ffa0}', '\u{ffbe}'), ('\u{ffc2}',
'\u{ffc7}'), ('\u{ffca}', '\u{ffcf}'), ('\u{ffd2}', '\u{ffd7}'), ('\u{ffda}', '\u{ffdc}')
];
- pub static Hanunoo_table: &'static [(char, char)] = &[
+ pub const Hanunoo_table: &'static [(char, char)] = &[
('\u{1720}', '\u{1731}'), ('\u{1732}', '\u{1734}')
];
- pub static Hebrew_table: &'static [(char, char)] = &[
+ pub const Hebrew_table: &'static [(char, char)] = &[
('\u{591}', '\u{5bd}'), ('\u{5be}', '\u{5be}'), ('\u{5bf}', '\u{5bf}'), ('\u{5c0}',
'\u{5c0}'), ('\u{5c1}', '\u{5c2}'), ('\u{5c3}', '\u{5c3}'), ('\u{5c4}', '\u{5c5}'),
('\u{5c6}', '\u{5c6}'), ('\u{5c7}', '\u{5c7}'), ('\u{5d0}', '\u{5ea}'), ('\u{5f0}',
('\u{fb46}', '\u{fb4f}')
];
- pub static Hiragana_table: &'static [(char, char)] = &[
+ pub const Hiragana_table: &'static [(char, char)] = &[
('\u{3041}', '\u{3096}'), ('\u{309d}', '\u{309e}'), ('\u{309f}', '\u{309f}'), ('\u{1b001}',
'\u{1b001}'), ('\u{1f200}', '\u{1f200}')
];
- pub static Imperial_Aramaic_table: &'static [(char, char)] = &[
+ pub const Imperial_Aramaic_table: &'static [(char, char)] = &[
('\u{10840}', '\u{10855}'), ('\u{10857}', '\u{10857}'), ('\u{10858}', '\u{1085f}')
];
- pub static Inherited_table: &'static [(char, char)] = &[
+ pub const Inherited_table: &'static [(char, char)] = &[
('\u{300}', '\u{36f}'), ('\u{485}', '\u{486}'), ('\u{64b}', '\u{655}'), ('\u{670}',
'\u{670}'), ('\u{951}', '\u{952}'), ('\u{1ab0}', '\u{1abd}'), ('\u{1abe}', '\u{1abe}'),
('\u{1cd0}', '\u{1cd2}'), ('\u{1cd4}', '\u{1ce0}'), ('\u{1ce2}', '\u{1ce8}'), ('\u{1ced}',
'\u{1d1ad}'), ('\u{e0100}', '\u{e01ef}')
];
- pub static Inscriptional_Pahlavi_table: &'static [(char, char)] = &[
+ pub const Inscriptional_Pahlavi_table: &'static [(char, char)] = &[
('\u{10b60}', '\u{10b72}'), ('\u{10b78}', '\u{10b7f}')
];
- pub static Inscriptional_Parthian_table: &'static [(char, char)] = &[
+ pub const Inscriptional_Parthian_table: &'static [(char, char)] = &[
('\u{10b40}', '\u{10b55}'), ('\u{10b58}', '\u{10b5f}')
];
- pub static Javanese_table: &'static [(char, char)] = &[
+ pub const Javanese_table: &'static [(char, char)] = &[
('\u{a980}', '\u{a982}'), ('\u{a983}', '\u{a983}'), ('\u{a984}', '\u{a9b2}'), ('\u{a9b3}',
'\u{a9b3}'), ('\u{a9b4}', '\u{a9b5}'), ('\u{a9b6}', '\u{a9b9}'), ('\u{a9ba}', '\u{a9bb}'),
('\u{a9bc}', '\u{a9bc}'), ('\u{a9bd}', '\u{a9c0}'), ('\u{a9c1}', '\u{a9cd}'), ('\u{a9d0}',
'\u{a9d9}'), ('\u{a9de}', '\u{a9df}')
];
- pub static Kaithi_table: &'static [(char, char)] = &[
+ pub const Kaithi_table: &'static [(char, char)] = &[
('\u{11080}', '\u{11081}'), ('\u{11082}', '\u{11082}'), ('\u{11083}', '\u{110af}'),
('\u{110b0}', '\u{110b2}'), ('\u{110b3}', '\u{110b6}'), ('\u{110b7}', '\u{110b8}'),
('\u{110b9}', '\u{110ba}'), ('\u{110bb}', '\u{110bc}'), ('\u{110bd}', '\u{110bd}'),
('\u{110be}', '\u{110c1}')
];
- pub static Kannada_table: &'static [(char, char)] = &[
+ pub const Kannada_table: &'static [(char, char)] = &[
('\u{c81}', '\u{c81}'), ('\u{c82}', '\u{c83}'), ('\u{c85}', '\u{c8c}'), ('\u{c8e}',
'\u{c90}'), ('\u{c92}', '\u{ca8}'), ('\u{caa}', '\u{cb3}'), ('\u{cb5}', '\u{cb9}'),
('\u{cbc}', '\u{cbc}'), ('\u{cbd}', '\u{cbd}'), ('\u{cbe}', '\u{cbe}'), ('\u{cbf}',
('\u{cf1}', '\u{cf2}')
];
- pub static Katakana_table: &'static [(char, char)] = &[
+ pub const Katakana_table: &'static [(char, char)] = &[
('\u{30a1}', '\u{30fa}'), ('\u{30fd}', '\u{30fe}'), ('\u{30ff}', '\u{30ff}'), ('\u{31f0}',
'\u{31ff}'), ('\u{32d0}', '\u{32fe}'), ('\u{3300}', '\u{3357}'), ('\u{ff66}', '\u{ff6f}'),
('\u{ff71}', '\u{ff9d}'), ('\u{1b000}', '\u{1b000}')
];
- pub static Kayah_Li_table: &'static [(char, char)] = &[
+ pub const Kayah_Li_table: &'static [(char, char)] = &[
('\u{a900}', '\u{a909}'), ('\u{a90a}', '\u{a925}'), ('\u{a926}', '\u{a92d}'), ('\u{a92f}',
'\u{a92f}')
];
- pub static Kharoshthi_table: &'static [(char, char)] = &[
+ pub const Kharoshthi_table: &'static [(char, char)] = &[
('\u{10a00}', '\u{10a00}'), ('\u{10a01}', '\u{10a03}'), ('\u{10a05}', '\u{10a06}'),
('\u{10a0c}', '\u{10a0f}'), ('\u{10a10}', '\u{10a13}'), ('\u{10a15}', '\u{10a17}'),
('\u{10a19}', '\u{10a33}'), ('\u{10a38}', '\u{10a3a}'), ('\u{10a3f}', '\u{10a3f}'),
('\u{10a40}', '\u{10a47}'), ('\u{10a50}', '\u{10a58}')
];
- pub static Khmer_table: &'static [(char, char)] = &[
+ pub const Khmer_table: &'static [(char, char)] = &[
('\u{1780}', '\u{17b3}'), ('\u{17b4}', '\u{17b5}'), ('\u{17b6}', '\u{17b6}'), ('\u{17b7}',
'\u{17bd}'), ('\u{17be}', '\u{17c5}'), ('\u{17c6}', '\u{17c6}'), ('\u{17c7}', '\u{17c8}'),
('\u{17c9}', '\u{17d3}'), ('\u{17d4}', '\u{17d6}'), ('\u{17d7}', '\u{17d7}'), ('\u{17d8}',
('\u{17e0}', '\u{17e9}'), ('\u{17f0}', '\u{17f9}'), ('\u{19e0}', '\u{19ff}')
];
- pub static Khojki_table: &'static [(char, char)] = &[
+ pub const Khojki_table: &'static [(char, char)] = &[
('\u{11200}', '\u{11211}'), ('\u{11213}', '\u{1122b}'), ('\u{1122c}', '\u{1122e}'),
('\u{1122f}', '\u{11231}'), ('\u{11232}', '\u{11233}'), ('\u{11234}', '\u{11234}'),
('\u{11235}', '\u{11235}'), ('\u{11236}', '\u{11237}'), ('\u{11238}', '\u{1123d}')
];
- pub static Khudawadi_table: &'static [(char, char)] = &[
+ pub const Khudawadi_table: &'static [(char, char)] = &[
('\u{112b0}', '\u{112de}'), ('\u{112df}', '\u{112df}'), ('\u{112e0}', '\u{112e2}'),
('\u{112e3}', '\u{112ea}'), ('\u{112f0}', '\u{112f9}')
];
- pub static Lao_table: &'static [(char, char)] = &[
+ pub const Lao_table: &'static [(char, char)] = &[
('\u{e81}', '\u{e82}'), ('\u{e84}', '\u{e84}'), ('\u{e87}', '\u{e88}'), ('\u{e8a}',
'\u{e8a}'), ('\u{e8d}', '\u{e8d}'), ('\u{e94}', '\u{e97}'), ('\u{e99}', '\u{e9f}'),
('\u{ea1}', '\u{ea3}'), ('\u{ea5}', '\u{ea5}'), ('\u{ea7}', '\u{ea7}'), ('\u{eaa}',
('\u{edc}', '\u{edf}')
];
- pub static Latin_table: &'static [(char, char)] = &[
+ pub const Latin_table: &'static [(char, char)] = &[
('\u{41}', '\u{5a}'), ('\u{61}', '\u{7a}'), ('\u{aa}', '\u{aa}'), ('\u{ba}', '\u{ba}'),
('\u{c0}', '\u{d6}'), ('\u{d8}', '\u{f6}'), ('\u{f8}', '\u{1ba}'), ('\u{1bb}', '\u{1bb}'),
('\u{1bc}', '\u{1bf}'), ('\u{1c0}', '\u{1c3}'), ('\u{1c4}', '\u{293}'), ('\u{294}',
'\u{ab64}'), ('\u{fb00}', '\u{fb06}'), ('\u{ff21}', '\u{ff3a}'), ('\u{ff41}', '\u{ff5a}')
];
- pub static Lepcha_table: &'static [(char, char)] = &[
+ pub const Lepcha_table: &'static [(char, char)] = &[
('\u{1c00}', '\u{1c23}'), ('\u{1c24}', '\u{1c2b}'), ('\u{1c2c}', '\u{1c33}'), ('\u{1c34}',
'\u{1c35}'), ('\u{1c36}', '\u{1c37}'), ('\u{1c3b}', '\u{1c3f}'), ('\u{1c40}', '\u{1c49}'),
('\u{1c4d}', '\u{1c4f}')
];
- pub static Limbu_table: &'static [(char, char)] = &[
+ pub const Limbu_table: &'static [(char, char)] = &[
('\u{1900}', '\u{191e}'), ('\u{1920}', '\u{1922}'), ('\u{1923}', '\u{1926}'), ('\u{1927}',
'\u{1928}'), ('\u{1929}', '\u{192b}'), ('\u{1930}', '\u{1931}'), ('\u{1932}', '\u{1932}'),
('\u{1933}', '\u{1938}'), ('\u{1939}', '\u{193b}'), ('\u{1940}', '\u{1940}'), ('\u{1944}',
'\u{1945}'), ('\u{1946}', '\u{194f}')
];
- pub static Linear_A_table: &'static [(char, char)] = &[
+ pub const Linear_A_table: &'static [(char, char)] = &[
('\u{10600}', '\u{10736}'), ('\u{10740}', '\u{10755}'), ('\u{10760}', '\u{10767}')
];
- pub static Linear_B_table: &'static [(char, char)] = &[
+ pub const Linear_B_table: &'static [(char, char)] = &[
('\u{10000}', '\u{1000b}'), ('\u{1000d}', '\u{10026}'), ('\u{10028}', '\u{1003a}'),
('\u{1003c}', '\u{1003d}'), ('\u{1003f}', '\u{1004d}'), ('\u{10050}', '\u{1005d}'),
('\u{10080}', '\u{100fa}')
];
- pub static Lisu_table: &'static [(char, char)] = &[
+ pub const Lisu_table: &'static [(char, char)] = &[
('\u{a4d0}', '\u{a4f7}'), ('\u{a4f8}', '\u{a4fd}'), ('\u{a4fe}', '\u{a4ff}')
];
- pub static Lycian_table: &'static [(char, char)] = &[
+ pub const Lycian_table: &'static [(char, char)] = &[
('\u{10280}', '\u{1029c}')
];
- pub static Lydian_table: &'static [(char, char)] = &[
+ pub const Lydian_table: &'static [(char, char)] = &[
('\u{10920}', '\u{10939}'), ('\u{1093f}', '\u{1093f}')
];
- pub static Mahajani_table: &'static [(char, char)] = &[
+ pub const Mahajani_table: &'static [(char, char)] = &[
('\u{11150}', '\u{11172}'), ('\u{11173}', '\u{11173}'), ('\u{11174}', '\u{11175}'),
('\u{11176}', '\u{11176}')
];
- pub static Malayalam_table: &'static [(char, char)] = &[
+ pub const Malayalam_table: &'static [(char, char)] = &[
('\u{d01}', '\u{d01}'), ('\u{d02}', '\u{d03}'), ('\u{d05}', '\u{d0c}'), ('\u{d0e}',
'\u{d10}'), ('\u{d12}', '\u{d3a}'), ('\u{d3d}', '\u{d3d}'), ('\u{d3e}', '\u{d40}'),
('\u{d41}', '\u{d44}'), ('\u{d46}', '\u{d48}'), ('\u{d4a}', '\u{d4c}'), ('\u{d4d}',
'\u{d79}'), ('\u{d7a}', '\u{d7f}')
];
- pub static Mandaic_table: &'static [(char, char)] = &[
+ pub const Mandaic_table: &'static [(char, char)] = &[
('\u{840}', '\u{858}'), ('\u{859}', '\u{85b}'), ('\u{85e}', '\u{85e}')
];
- pub static Manichaean_table: &'static [(char, char)] = &[
+ pub const Manichaean_table: &'static [(char, char)] = &[
('\u{10ac0}', '\u{10ac7}'), ('\u{10ac8}', '\u{10ac8}'), ('\u{10ac9}', '\u{10ae4}'),
('\u{10ae5}', '\u{10ae6}'), ('\u{10aeb}', '\u{10aef}'), ('\u{10af0}', '\u{10af6}')
];
- pub static Meetei_Mayek_table: &'static [(char, char)] = &[
+ pub const Meetei_Mayek_table: &'static [(char, char)] = &[
('\u{aae0}', '\u{aaea}'), ('\u{aaeb}', '\u{aaeb}'), ('\u{aaec}', '\u{aaed}'), ('\u{aaee}',
'\u{aaef}'), ('\u{aaf0}', '\u{aaf1}'), ('\u{aaf2}', '\u{aaf2}'), ('\u{aaf3}', '\u{aaf4}'),
('\u{aaf5}', '\u{aaf5}'), ('\u{aaf6}', '\u{aaf6}'), ('\u{abc0}', '\u{abe2}'), ('\u{abe3}',
'\u{abed}'), ('\u{abf0}', '\u{abf9}')
];
- pub static Mende_Kikakui_table: &'static [(char, char)] = &[
+ pub const Mende_Kikakui_table: &'static [(char, char)] = &[
('\u{1e800}', '\u{1e8c4}'), ('\u{1e8c7}', '\u{1e8cf}'), ('\u{1e8d0}', '\u{1e8d6}')
];
- pub static Meroitic_Cursive_table: &'static [(char, char)] = &[
+ pub const Meroitic_Cursive_table: &'static [(char, char)] = &[
('\u{109a0}', '\u{109b7}'), ('\u{109be}', '\u{109bf}')
];
- pub static Meroitic_Hieroglyphs_table: &'static [(char, char)] = &[
+ pub const Meroitic_Hieroglyphs_table: &'static [(char, char)] = &[
('\u{10980}', '\u{1099f}')
];
- pub static Miao_table: &'static [(char, char)] = &[
+ pub const Miao_table: &'static [(char, char)] = &[
('\u{16f00}', '\u{16f44}'), ('\u{16f50}', '\u{16f50}'), ('\u{16f51}', '\u{16f7e}'),
('\u{16f8f}', '\u{16f92}'), ('\u{16f93}', '\u{16f9f}')
];
- pub static Modi_table: &'static [(char, char)] = &[
+ pub const Modi_table: &'static [(char, char)] = &[
('\u{11600}', '\u{1162f}'), ('\u{11630}', '\u{11632}'), ('\u{11633}', '\u{1163a}'),
('\u{1163b}', '\u{1163c}'), ('\u{1163d}', '\u{1163d}'), ('\u{1163e}', '\u{1163e}'),
('\u{1163f}', '\u{11640}'), ('\u{11641}', '\u{11643}'), ('\u{11644}', '\u{11644}'),
('\u{11650}', '\u{11659}')
];
- pub static Mongolian_table: &'static [(char, char)] = &[
+ pub const Mongolian_table: &'static [(char, char)] = &[
('\u{1800}', '\u{1801}'), ('\u{1804}', '\u{1804}'), ('\u{1806}', '\u{1806}'), ('\u{1807}',
'\u{180a}'), ('\u{180b}', '\u{180d}'), ('\u{180e}', '\u{180e}'), ('\u{1810}', '\u{1819}'),
('\u{1820}', '\u{1842}'), ('\u{1843}', '\u{1843}'), ('\u{1844}', '\u{1877}'), ('\u{1880}',
'\u{18a8}'), ('\u{18a9}', '\u{18a9}'), ('\u{18aa}', '\u{18aa}')
];
- pub static Mro_table: &'static [(char, char)] = &[
+ pub const Mro_table: &'static [(char, char)] = &[
('\u{16a40}', '\u{16a5e}'), ('\u{16a60}', '\u{16a69}'), ('\u{16a6e}', '\u{16a6f}')
];
- pub static Myanmar_table: &'static [(char, char)] = &[
+ pub const Myanmar_table: &'static [(char, char)] = &[
('\u{1000}', '\u{102a}'), ('\u{102b}', '\u{102c}'), ('\u{102d}', '\u{1030}'), ('\u{1031}',
'\u{1031}'), ('\u{1032}', '\u{1037}'), ('\u{1038}', '\u{1038}'), ('\u{1039}', '\u{103a}'),
('\u{103b}', '\u{103c}'), ('\u{103d}', '\u{103e}'), ('\u{103f}', '\u{103f}'), ('\u{1040}',
('\u{aa7e}', '\u{aa7f}')
];
- pub static Nabataean_table: &'static [(char, char)] = &[
+ pub const Nabataean_table: &'static [(char, char)] = &[
('\u{10880}', '\u{1089e}'), ('\u{108a7}', '\u{108af}')
];
- pub static New_Tai_Lue_table: &'static [(char, char)] = &[
+ pub const New_Tai_Lue_table: &'static [(char, char)] = &[
('\u{1980}', '\u{19ab}'), ('\u{19b0}', '\u{19c0}'), ('\u{19c1}', '\u{19c7}'), ('\u{19c8}',
'\u{19c9}'), ('\u{19d0}', '\u{19d9}'), ('\u{19da}', '\u{19da}'), ('\u{19de}', '\u{19df}')
];
- pub static Nko_table: &'static [(char, char)] = &[
+ pub const Nko_table: &'static [(char, char)] = &[
('\u{7c0}', '\u{7c9}'), ('\u{7ca}', '\u{7ea}'), ('\u{7eb}', '\u{7f3}'), ('\u{7f4}',
'\u{7f5}'), ('\u{7f6}', '\u{7f6}'), ('\u{7f7}', '\u{7f9}'), ('\u{7fa}', '\u{7fa}')
];
- pub static Ogham_table: &'static [(char, char)] = &[
+ pub const Ogham_table: &'static [(char, char)] = &[
('\u{1680}', '\u{1680}'), ('\u{1681}', '\u{169a}'), ('\u{169b}', '\u{169b}'), ('\u{169c}',
'\u{169c}')
];
- pub static Ol_Chiki_table: &'static [(char, char)] = &[
+ pub const Ol_Chiki_table: &'static [(char, char)] = &[
('\u{1c50}', '\u{1c59}'), ('\u{1c5a}', '\u{1c77}'), ('\u{1c78}', '\u{1c7d}'), ('\u{1c7e}',
'\u{1c7f}')
];
- pub static Old_Italic_table: &'static [(char, char)] = &[
+ pub const Old_Italic_table: &'static [(char, char)] = &[
('\u{10300}', '\u{1031f}'), ('\u{10320}', '\u{10323}')
];
- pub static Old_North_Arabian_table: &'static [(char, char)] = &[
+ pub const Old_North_Arabian_table: &'static [(char, char)] = &[
('\u{10a80}', '\u{10a9c}'), ('\u{10a9d}', '\u{10a9f}')
];
- pub static Old_Permic_table: &'static [(char, char)] = &[
+ pub const Old_Permic_table: &'static [(char, char)] = &[
('\u{10350}', '\u{10375}'), ('\u{10376}', '\u{1037a}')
];
- pub static Old_Persian_table: &'static [(char, char)] = &[
+ pub const Old_Persian_table: &'static [(char, char)] = &[
('\u{103a0}', '\u{103c3}'), ('\u{103c8}', '\u{103cf}'), ('\u{103d0}', '\u{103d0}'),
('\u{103d1}', '\u{103d5}')
];
- pub static Old_South_Arabian_table: &'static [(char, char)] = &[
+ pub const Old_South_Arabian_table: &'static [(char, char)] = &[
('\u{10a60}', '\u{10a7c}'), ('\u{10a7d}', '\u{10a7e}'), ('\u{10a7f}', '\u{10a7f}')
];
- pub static Old_Turkic_table: &'static [(char, char)] = &[
+ pub const Old_Turkic_table: &'static [(char, char)] = &[
('\u{10c00}', '\u{10c48}')
];
- pub static Oriya_table: &'static [(char, char)] = &[
+ pub const Oriya_table: &'static [(char, char)] = &[
('\u{b01}', '\u{b01}'), ('\u{b02}', '\u{b03}'), ('\u{b05}', '\u{b0c}'), ('\u{b0f}',
'\u{b10}'), ('\u{b13}', '\u{b28}'), ('\u{b2a}', '\u{b30}'), ('\u{b32}', '\u{b33}'),
('\u{b35}', '\u{b39}'), ('\u{b3c}', '\u{b3c}'), ('\u{b3d}', '\u{b3d}'), ('\u{b3e}',
'\u{b71}'), ('\u{b72}', '\u{b77}')
];
- pub static Osmanya_table: &'static [(char, char)] = &[
+ pub const Osmanya_table: &'static [(char, char)] = &[
('\u{10480}', '\u{1049d}'), ('\u{104a0}', '\u{104a9}')
];
- pub static Pahawh_Hmong_table: &'static [(char, char)] = &[
+ pub const Pahawh_Hmong_table: &'static [(char, char)] = &[
('\u{16b00}', '\u{16b2f}'), ('\u{16b30}', '\u{16b36}'), ('\u{16b37}', '\u{16b3b}'),
('\u{16b3c}', '\u{16b3f}'), ('\u{16b40}', '\u{16b43}'), ('\u{16b44}', '\u{16b44}'),
('\u{16b45}', '\u{16b45}'), ('\u{16b50}', '\u{16b59}'), ('\u{16b5b}', '\u{16b61}'),
('\u{16b63}', '\u{16b77}'), ('\u{16b7d}', '\u{16b8f}')
];
- pub static Palmyrene_table: &'static [(char, char)] = &[
+ pub const Palmyrene_table: &'static [(char, char)] = &[
('\u{10860}', '\u{10876}'), ('\u{10877}', '\u{10878}'), ('\u{10879}', '\u{1087f}')
];
- pub static Pau_Cin_Hau_table: &'static [(char, char)] = &[
+ pub const Pau_Cin_Hau_table: &'static [(char, char)] = &[
('\u{11ac0}', '\u{11af8}')
];
- pub static Phags_Pa_table: &'static [(char, char)] = &[
+ pub const Phags_Pa_table: &'static [(char, char)] = &[
('\u{a840}', '\u{a873}'), ('\u{a874}', '\u{a877}')
];
- pub static Phoenician_table: &'static [(char, char)] = &[
+ pub const Phoenician_table: &'static [(char, char)] = &[
('\u{10900}', '\u{10915}'), ('\u{10916}', '\u{1091b}'), ('\u{1091f}', '\u{1091f}')
];
- pub static Psalter_Pahlavi_table: &'static [(char, char)] = &[
+ pub const Psalter_Pahlavi_table: &'static [(char, char)] = &[
('\u{10b80}', '\u{10b91}'), ('\u{10b99}', '\u{10b9c}'), ('\u{10ba9}', '\u{10baf}')
];
- pub static Rejang_table: &'static [(char, char)] = &[
+ pub const Rejang_table: &'static [(char, char)] = &[
('\u{a930}', '\u{a946}'), ('\u{a947}', '\u{a951}'), ('\u{a952}', '\u{a953}'), ('\u{a95f}',
'\u{a95f}')
];
- pub static Runic_table: &'static [(char, char)] = &[
+ pub const Runic_table: &'static [(char, char)] = &[
('\u{16a0}', '\u{16ea}'), ('\u{16ee}', '\u{16f0}'), ('\u{16f1}', '\u{16f8}')
];
- pub static Samaritan_table: &'static [(char, char)] = &[
+ pub const Samaritan_table: &'static [(char, char)] = &[
('\u{800}', '\u{815}'), ('\u{816}', '\u{819}'), ('\u{81a}', '\u{81a}'), ('\u{81b}',
'\u{823}'), ('\u{824}', '\u{824}'), ('\u{825}', '\u{827}'), ('\u{828}', '\u{828}'),
('\u{829}', '\u{82d}'), ('\u{830}', '\u{83e}')
];
- pub static Saurashtra_table: &'static [(char, char)] = &[
+ pub const Saurashtra_table: &'static [(char, char)] = &[
('\u{a880}', '\u{a881}'), ('\u{a882}', '\u{a8b3}'), ('\u{a8b4}', '\u{a8c3}'), ('\u{a8c4}',
'\u{a8c4}'), ('\u{a8ce}', '\u{a8cf}'), ('\u{a8d0}', '\u{a8d9}')
];
- pub static Sharada_table: &'static [(char, char)] = &[
+ pub const Sharada_table: &'static [(char, char)] = &[
('\u{11180}', '\u{11181}'), ('\u{11182}', '\u{11182}'), ('\u{11183}', '\u{111b2}'),
('\u{111b3}', '\u{111b5}'), ('\u{111b6}', '\u{111be}'), ('\u{111bf}', '\u{111c0}'),
('\u{111c1}', '\u{111c4}'), ('\u{111c5}', '\u{111c8}'), ('\u{111cd}', '\u{111cd}'),
('\u{111d0}', '\u{111d9}'), ('\u{111da}', '\u{111da}')
];
- pub static Shavian_table: &'static [(char, char)] = &[
+ pub const Shavian_table: &'static [(char, char)] = &[
('\u{10450}', '\u{1047f}')
];
- pub static Siddham_table: &'static [(char, char)] = &[
+ pub const Siddham_table: &'static [(char, char)] = &[
('\u{11580}', '\u{115ae}'), ('\u{115af}', '\u{115b1}'), ('\u{115b2}', '\u{115b5}'),
('\u{115b8}', '\u{115bb}'), ('\u{115bc}', '\u{115bd}'), ('\u{115be}', '\u{115be}'),
('\u{115bf}', '\u{115c0}'), ('\u{115c1}', '\u{115c9}')
];
- pub static Sinhala_table: &'static [(char, char)] = &[
+ pub const Sinhala_table: &'static [(char, char)] = &[
('\u{d82}', '\u{d83}'), ('\u{d85}', '\u{d96}'), ('\u{d9a}', '\u{db1}'), ('\u{db3}',
'\u{dbb}'), ('\u{dbd}', '\u{dbd}'), ('\u{dc0}', '\u{dc6}'), ('\u{dca}', '\u{dca}'),
('\u{dcf}', '\u{dd1}'), ('\u{dd2}', '\u{dd4}'), ('\u{dd6}', '\u{dd6}'), ('\u{dd8}',
('\u{111e1}', '\u{111f4}')
];
- pub static Sora_Sompeng_table: &'static [(char, char)] = &[
+ pub const Sora_Sompeng_table: &'static [(char, char)] = &[
('\u{110d0}', '\u{110e8}'), ('\u{110f0}', '\u{110f9}')
];
- pub static Sundanese_table: &'static [(char, char)] = &[
+ pub const Sundanese_table: &'static [(char, char)] = &[
('\u{1b80}', '\u{1b81}'), ('\u{1b82}', '\u{1b82}'), ('\u{1b83}', '\u{1ba0}'), ('\u{1ba1}',
'\u{1ba1}'), ('\u{1ba2}', '\u{1ba5}'), ('\u{1ba6}', '\u{1ba7}'), ('\u{1ba8}', '\u{1ba9}'),
('\u{1baa}', '\u{1baa}'), ('\u{1bab}', '\u{1bad}'), ('\u{1bae}', '\u{1baf}'), ('\u{1bb0}',
'\u{1bb9}'), ('\u{1bba}', '\u{1bbf}'), ('\u{1cc0}', '\u{1cc7}')
];
- pub static Syloti_Nagri_table: &'static [(char, char)] = &[
+ pub const Syloti_Nagri_table: &'static [(char, char)] = &[
('\u{a800}', '\u{a801}'), ('\u{a802}', '\u{a802}'), ('\u{a803}', '\u{a805}'), ('\u{a806}',
'\u{a806}'), ('\u{a807}', '\u{a80a}'), ('\u{a80b}', '\u{a80b}'), ('\u{a80c}', '\u{a822}'),
('\u{a823}', '\u{a824}'), ('\u{a825}', '\u{a826}'), ('\u{a827}', '\u{a827}'), ('\u{a828}',
'\u{a82b}')
];
- pub static Syriac_table: &'static [(char, char)] = &[
+ pub const Syriac_table: &'static [(char, char)] = &[
('\u{700}', '\u{70d}'), ('\u{70f}', '\u{70f}'), ('\u{710}', '\u{710}'), ('\u{711}',
'\u{711}'), ('\u{712}', '\u{72f}'), ('\u{730}', '\u{74a}'), ('\u{74d}', '\u{74f}')
];
- pub static Tagalog_table: &'static [(char, char)] = &[
+ pub const Tagalog_table: &'static [(char, char)] = &[
('\u{1700}', '\u{170c}'), ('\u{170e}', '\u{1711}'), ('\u{1712}', '\u{1714}')
];
- pub static Tagbanwa_table: &'static [(char, char)] = &[
+ pub const Tagbanwa_table: &'static [(char, char)] = &[
('\u{1760}', '\u{176c}'), ('\u{176e}', '\u{1770}'), ('\u{1772}', '\u{1773}')
];
- pub static Tai_Le_table: &'static [(char, char)] = &[
+ pub const Tai_Le_table: &'static [(char, char)] = &[
('\u{1950}', '\u{196d}'), ('\u{1970}', '\u{1974}')
];
- pub static Tai_Tham_table: &'static [(char, char)] = &[
+ pub const Tai_Tham_table: &'static [(char, char)] = &[
('\u{1a20}', '\u{1a54}'), ('\u{1a55}', '\u{1a55}'), ('\u{1a56}', '\u{1a56}'), ('\u{1a57}',
'\u{1a57}'), ('\u{1a58}', '\u{1a5e}'), ('\u{1a60}', '\u{1a60}'), ('\u{1a61}', '\u{1a61}'),
('\u{1a62}', '\u{1a62}'), ('\u{1a63}', '\u{1a64}'), ('\u{1a65}', '\u{1a6c}'), ('\u{1a6d}',
'\u{1aad}')
];
- pub static Tai_Viet_table: &'static [(char, char)] = &[
+ pub const Tai_Viet_table: &'static [(char, char)] = &[
('\u{aa80}', '\u{aaaf}'), ('\u{aab0}', '\u{aab0}'), ('\u{aab1}', '\u{aab1}'), ('\u{aab2}',
'\u{aab4}'), ('\u{aab5}', '\u{aab6}'), ('\u{aab7}', '\u{aab8}'), ('\u{aab9}', '\u{aabd}'),
('\u{aabe}', '\u{aabf}'), ('\u{aac0}', '\u{aac0}'), ('\u{aac1}', '\u{aac1}'), ('\u{aac2}',
'\u{aac2}'), ('\u{aadb}', '\u{aadc}'), ('\u{aadd}', '\u{aadd}'), ('\u{aade}', '\u{aadf}')
];
- pub static Takri_table: &'static [(char, char)] = &[
+ pub const Takri_table: &'static [(char, char)] = &[
('\u{11680}', '\u{116aa}'), ('\u{116ab}', '\u{116ab}'), ('\u{116ac}', '\u{116ac}'),
('\u{116ad}', '\u{116ad}'), ('\u{116ae}', '\u{116af}'), ('\u{116b0}', '\u{116b5}'),
('\u{116b6}', '\u{116b6}'), ('\u{116b7}', '\u{116b7}'), ('\u{116c0}', '\u{116c9}')
];
- pub static Tamil_table: &'static [(char, char)] = &[
+ pub const Tamil_table: &'static [(char, char)] = &[
('\u{b82}', '\u{b82}'), ('\u{b83}', '\u{b83}'), ('\u{b85}', '\u{b8a}'), ('\u{b8e}',
'\u{b90}'), ('\u{b92}', '\u{b95}'), ('\u{b99}', '\u{b9a}'), ('\u{b9c}', '\u{b9c}'),
('\u{b9e}', '\u{b9f}'), ('\u{ba3}', '\u{ba4}'), ('\u{ba8}', '\u{baa}'), ('\u{bae}',
('\u{bf3}', '\u{bf8}'), ('\u{bf9}', '\u{bf9}'), ('\u{bfa}', '\u{bfa}')
];
- pub static Telugu_table: &'static [(char, char)] = &[
+ pub const Telugu_table: &'static [(char, char)] = &[
('\u{c00}', '\u{c00}'), ('\u{c01}', '\u{c03}'), ('\u{c05}', '\u{c0c}'), ('\u{c0e}',
'\u{c10}'), ('\u{c12}', '\u{c28}'), ('\u{c2a}', '\u{c39}'), ('\u{c3d}', '\u{c3d}'),
('\u{c3e}', '\u{c40}'), ('\u{c41}', '\u{c44}'), ('\u{c46}', '\u{c48}'), ('\u{c4a}',
'\u{c7f}')
];
- pub static Thaana_table: &'static [(char, char)] = &[
+ pub const Thaana_table: &'static [(char, char)] = &[
('\u{780}', '\u{7a5}'), ('\u{7a6}', '\u{7b0}'), ('\u{7b1}', '\u{7b1}')
];
- pub static Thai_table: &'static [(char, char)] = &[
+ pub const Thai_table: &'static [(char, char)] = &[
('\u{e01}', '\u{e30}'), ('\u{e31}', '\u{e31}'), ('\u{e32}', '\u{e33}'), ('\u{e34}',
'\u{e3a}'), ('\u{e40}', '\u{e45}'), ('\u{e46}', '\u{e46}'), ('\u{e47}', '\u{e4e}'),
('\u{e4f}', '\u{e4f}'), ('\u{e50}', '\u{e59}'), ('\u{e5a}', '\u{e5b}')
];
- pub static Tibetan_table: &'static [(char, char)] = &[
+ pub const Tibetan_table: &'static [(char, char)] = &[
('\u{f00}', '\u{f00}'), ('\u{f01}', '\u{f03}'), ('\u{f04}', '\u{f12}'), ('\u{f13}',
'\u{f13}'), ('\u{f14}', '\u{f14}'), ('\u{f15}', '\u{f17}'), ('\u{f18}', '\u{f19}'),
('\u{f1a}', '\u{f1f}'), ('\u{f20}', '\u{f29}'), ('\u{f2a}', '\u{f33}'), ('\u{f34}',
('\u{fd0}', '\u{fd4}'), ('\u{fd9}', '\u{fda}')
];
- pub static Tifinagh_table: &'static [(char, char)] = &[
+ pub const Tifinagh_table: &'static [(char, char)] = &[
('\u{2d30}', '\u{2d67}'), ('\u{2d6f}', '\u{2d6f}'), ('\u{2d70}', '\u{2d70}'), ('\u{2d7f}',
'\u{2d7f}')
];
- pub static Tirhuta_table: &'static [(char, char)] = &[
+ pub const Tirhuta_table: &'static [(char, char)] = &[
('\u{11480}', '\u{114af}'), ('\u{114b0}', '\u{114b2}'), ('\u{114b3}', '\u{114b8}'),
('\u{114b9}', '\u{114b9}'), ('\u{114ba}', '\u{114ba}'), ('\u{114bb}', '\u{114be}'),
('\u{114bf}', '\u{114c0}'), ('\u{114c1}', '\u{114c1}'), ('\u{114c2}', '\u{114c3}'),
('\u{114d0}', '\u{114d9}')
];
- pub static Ugaritic_table: &'static [(char, char)] = &[
+ pub const Ugaritic_table: &'static [(char, char)] = &[
('\u{10380}', '\u{1039d}'), ('\u{1039f}', '\u{1039f}')
];
- pub static Vai_table: &'static [(char, char)] = &[
+ pub const Vai_table: &'static [(char, char)] = &[
('\u{a500}', '\u{a60b}'), ('\u{a60c}', '\u{a60c}'), ('\u{a60d}', '\u{a60f}'), ('\u{a610}',
'\u{a61f}'), ('\u{a620}', '\u{a629}'), ('\u{a62a}', '\u{a62b}')
];
- pub static Warang_Citi_table: &'static [(char, char)] = &[
+ pub const Warang_Citi_table: &'static [(char, char)] = &[
('\u{118a0}', '\u{118df}'), ('\u{118e0}', '\u{118e9}'), ('\u{118ea}', '\u{118f2}'),
('\u{118ff}', '\u{118ff}')
];
- pub static Yi_table: &'static [(char, char)] = &[
+ pub const Yi_table: &'static [(char, char)] = &[
('\u{a000}', '\u{a014}'), ('\u{a015}', '\u{a015}'), ('\u{a016}', '\u{a48c}'), ('\u{a490}',
'\u{a4c6}')
];
}
pub mod property {
- pub static Join_Control_table: &'static [(char, char)] = &[
+ pub const Join_Control_table: &'static [(char, char)] = &[
('\u{200c}', '\u{200d}')
];
- pub static Noncharacter_Code_Point_table: &'static [(char, char)] = &[
+ pub const Noncharacter_Code_Point_table: &'static [(char, char)] = &[
('\u{fdd0}', '\u{fdef}'), ('\u{fffe}', '\u{ffff}'), ('\u{1fffe}', '\u{1ffff}'),
('\u{2fffe}', '\u{2ffff}'), ('\u{3fffe}', '\u{3ffff}'), ('\u{4fffe}', '\u{4ffff}'),
('\u{5fffe}', '\u{5ffff}'), ('\u{6fffe}', '\u{6ffff}'), ('\u{7fffe}', '\u{7ffff}'),
('\u{efffe}', '\u{effff}'), ('\u{ffffe}', '\u{fffff}')
];
- pub static White_Space_table: &'static [(char, char)] = &[
+ pub const White_Space_table: &'static [(char, char)] = &[
('\u{9}', '\u{d}'), ('\u{20}', '\u{20}'), ('\u{85}', '\u{85}'), ('\u{a0}', '\u{a0}'),
('\u{1680}', '\u{1680}'), ('\u{2000}', '\u{200a}'), ('\u{2028}', '\u{2028}'), ('\u{2029}',
'\u{2029}'), ('\u{202f}', '\u{202f}'), ('\u{205f}', '\u{205f}'), ('\u{3000}', '\u{3000}')
}
pub mod regex {
- pub static UNICODE_CLASSES: &'static [(&'static str, &'static &'static [(char, char)])] = &[
- ("Alphabetic", &super::derived_property::Alphabetic_table), ("Arabic",
- &super::script::Arabic_table), ("Armenian", &super::script::Armenian_table), ("Avestan",
- &super::script::Avestan_table), ("Balinese", &super::script::Balinese_table), ("Bamum",
- &super::script::Bamum_table), ("Bassa_Vah", &super::script::Bassa_Vah_table), ("Batak",
- &super::script::Batak_table), ("Bengali", &super::script::Bengali_table), ("Bopomofo",
- &super::script::Bopomofo_table), ("Brahmi", &super::script::Brahmi_table), ("Braille",
- &super::script::Braille_table), ("Buginese", &super::script::Buginese_table), ("Buhid",
- &super::script::Buhid_table), ("C", &super::general_category::C_table),
- ("Canadian_Aboriginal", &super::script::Canadian_Aboriginal_table), ("Carian",
- &super::script::Carian_table), ("Caucasian_Albanian",
- &super::script::Caucasian_Albanian_table), ("Cc", &super::general_category::Cc_table),
- ("Cf", &super::general_category::Cf_table), ("Chakma", &super::script::Chakma_table),
- ("Cham", &super::script::Cham_table), ("Cherokee", &super::script::Cherokee_table), ("Cn",
- &super::general_category::Cn_table), ("Co", &super::general_category::Co_table), ("Common",
- &super::script::Common_table), ("Coptic", &super::script::Coptic_table), ("Cuneiform",
- &super::script::Cuneiform_table), ("Cypriot", &super::script::Cypriot_table), ("Cyrillic",
- &super::script::Cyrillic_table), ("Default_Ignorable_Code_Point",
- &super::derived_property::Default_Ignorable_Code_Point_table), ("Deseret",
- &super::script::Deseret_table), ("Devanagari", &super::script::Devanagari_table),
- ("Duployan", &super::script::Duployan_table), ("Egyptian_Hieroglyphs",
- &super::script::Egyptian_Hieroglyphs_table), ("Elbasan", &super::script::Elbasan_table),
- ("Ethiopic", &super::script::Ethiopic_table), ("Georgian", &super::script::Georgian_table),
- ("Glagolitic", &super::script::Glagolitic_table), ("Gothic", &super::script::Gothic_table),
- ("Grantha", &super::script::Grantha_table), ("Greek", &super::script::Greek_table),
- ("Gujarati", &super::script::Gujarati_table), ("Gurmukhi", &super::script::Gurmukhi_table),
- ("Han", &super::script::Han_table), ("Hangul", &super::script::Hangul_table), ("Hanunoo",
- &super::script::Hanunoo_table), ("Hebrew", &super::script::Hebrew_table), ("Hiragana",
- &super::script::Hiragana_table), ("Imperial_Aramaic",
- &super::script::Imperial_Aramaic_table), ("Inherited", &super::script::Inherited_table),
- ("Inscriptional_Pahlavi", &super::script::Inscriptional_Pahlavi_table),
- ("Inscriptional_Parthian", &super::script::Inscriptional_Parthian_table), ("Javanese",
- &super::script::Javanese_table), ("Join_Control", &super::property::Join_Control_table),
- ("Kaithi", &super::script::Kaithi_table), ("Kannada", &super::script::Kannada_table),
- ("Katakana", &super::script::Katakana_table), ("Kayah_Li", &super::script::Kayah_Li_table),
- ("Kharoshthi", &super::script::Kharoshthi_table), ("Khmer", &super::script::Khmer_table),
- ("Khojki", &super::script::Khojki_table), ("Khudawadi", &super::script::Khudawadi_table),
- ("L", &super::general_category::L_table), ("LC", &super::general_category::LC_table),
- ("Lao", &super::script::Lao_table), ("Latin", &super::script::Latin_table), ("Lepcha",
- &super::script::Lepcha_table), ("Limbu", &super::script::Limbu_table), ("Linear_A",
- &super::script::Linear_A_table), ("Linear_B", &super::script::Linear_B_table), ("Lisu",
- &super::script::Lisu_table), ("Ll", &super::general_category::Ll_table), ("Lm",
- &super::general_category::Lm_table), ("Lo", &super::general_category::Lo_table),
- ("Lowercase", &super::derived_property::Lowercase_table), ("Lt",
- &super::general_category::Lt_table), ("Lu", &super::general_category::Lu_table), ("Lycian",
- &super::script::Lycian_table), ("Lydian", &super::script::Lydian_table), ("M",
- &super::general_category::M_table), ("Mahajani", &super::script::Mahajani_table),
- ("Malayalam", &super::script::Malayalam_table), ("Mandaic", &super::script::Mandaic_table),
- ("Manichaean", &super::script::Manichaean_table), ("Mc",
- &super::general_category::Mc_table), ("Me", &super::general_category::Me_table),
- ("Meetei_Mayek", &super::script::Meetei_Mayek_table), ("Mende_Kikakui",
- &super::script::Mende_Kikakui_table), ("Meroitic_Cursive",
- &super::script::Meroitic_Cursive_table), ("Meroitic_Hieroglyphs",
- &super::script::Meroitic_Hieroglyphs_table), ("Miao", &super::script::Miao_table), ("Mn",
- &super::general_category::Mn_table), ("Modi", &super::script::Modi_table), ("Mongolian",
- &super::script::Mongolian_table), ("Mro", &super::script::Mro_table), ("Myanmar",
- &super::script::Myanmar_table), ("N", &super::general_category::N_table), ("Nabataean",
- &super::script::Nabataean_table), ("Nd", &super::general_category::Nd_table),
- ("New_Tai_Lue", &super::script::New_Tai_Lue_table), ("Nko", &super::script::Nko_table),
- ("Nl", &super::general_category::Nl_table), ("No", &super::general_category::No_table),
- ("Noncharacter_Code_Point", &super::property::Noncharacter_Code_Point_table), ("Ogham",
- &super::script::Ogham_table), ("Ol_Chiki", &super::script::Ol_Chiki_table), ("Old_Italic",
- &super::script::Old_Italic_table), ("Old_North_Arabian",
- &super::script::Old_North_Arabian_table), ("Old_Permic", &super::script::Old_Permic_table),
- ("Old_Persian", &super::script::Old_Persian_table), ("Old_South_Arabian",
- &super::script::Old_South_Arabian_table), ("Old_Turkic", &super::script::Old_Turkic_table),
- ("Oriya", &super::script::Oriya_table), ("Osmanya", &super::script::Osmanya_table), ("P",
- &super::general_category::P_table), ("Pahawh_Hmong", &super::script::Pahawh_Hmong_table),
- ("Palmyrene", &super::script::Palmyrene_table), ("Pau_Cin_Hau",
- &super::script::Pau_Cin_Hau_table), ("Pc", &super::general_category::Pc_table), ("Pd",
- &super::general_category::Pd_table), ("Pe", &super::general_category::Pe_table), ("Pf",
- &super::general_category::Pf_table), ("Phags_Pa", &super::script::Phags_Pa_table),
- ("Phoenician", &super::script::Phoenician_table), ("Pi",
- &super::general_category::Pi_table), ("Po", &super::general_category::Po_table), ("Ps",
- &super::general_category::Ps_table), ("Psalter_Pahlavi",
- &super::script::Psalter_Pahlavi_table), ("Rejang", &super::script::Rejang_table), ("Runic",
- &super::script::Runic_table), ("S", &super::general_category::S_table), ("Samaritan",
- &super::script::Samaritan_table), ("Saurashtra", &super::script::Saurashtra_table), ("Sc",
- &super::general_category::Sc_table), ("Sharada", &super::script::Sharada_table), ("Shavian",
- &super::script::Shavian_table), ("Siddham", &super::script::Siddham_table), ("Sinhala",
- &super::script::Sinhala_table), ("Sk", &super::general_category::Sk_table), ("Sm",
- &super::general_category::Sm_table), ("So", &super::general_category::So_table),
- ("Sora_Sompeng", &super::script::Sora_Sompeng_table), ("Sundanese",
- &super::script::Sundanese_table), ("Syloti_Nagri", &super::script::Syloti_Nagri_table),
- ("Syriac", &super::script::Syriac_table), ("Tagalog", &super::script::Tagalog_table),
- ("Tagbanwa", &super::script::Tagbanwa_table), ("Tai_Le", &super::script::Tai_Le_table),
- ("Tai_Tham", &super::script::Tai_Tham_table), ("Tai_Viet", &super::script::Tai_Viet_table),
- ("Takri", &super::script::Takri_table), ("Tamil", &super::script::Tamil_table), ("Telugu",
- &super::script::Telugu_table), ("Thaana", &super::script::Thaana_table), ("Thai",
- &super::script::Thai_table), ("Tibetan", &super::script::Tibetan_table), ("Tifinagh",
- &super::script::Tifinagh_table), ("Tirhuta", &super::script::Tirhuta_table), ("Ugaritic",
- &super::script::Ugaritic_table), ("Uppercase", &super::derived_property::Uppercase_table),
- ("Vai", &super::script::Vai_table), ("Warang_Citi", &super::script::Warang_Citi_table),
- ("White_Space", &super::property::White_Space_table), ("XID_Continue",
- &super::derived_property::XID_Continue_table), ("XID_Start",
- &super::derived_property::XID_Start_table), ("Yi", &super::script::Yi_table), ("Z",
- &super::general_category::Z_table), ("Zl", &super::general_category::Zl_table), ("Zp",
- &super::general_category::Zp_table), ("Zs", &super::general_category::Zs_table)
- ];
-
- pub static PERLD: &'static &'static [(char, char)] = &super::general_category::Nd_table;
-
- pub static PERLS: &'static &'static [(char, char)] = &super::property::White_Space_table;
-
- pub static PERLW: &'static [(char, char)] = &[
+ pub const UNICODE_CLASSES: &'static [(&'static str, &'static [(char, char)])] = &[
+ ("Alphabetic", super::derived_property::Alphabetic_table), ("Arabic",
+ super::script::Arabic_table), ("Armenian", super::script::Armenian_table), ("Avestan",
+ super::script::Avestan_table), ("Balinese", super::script::Balinese_table), ("Bamum",
+ super::script::Bamum_table), ("Bassa_Vah", super::script::Bassa_Vah_table), ("Batak",
+ super::script::Batak_table), ("Bengali", super::script::Bengali_table), ("Bopomofo",
+ super::script::Bopomofo_table), ("Brahmi", super::script::Brahmi_table), ("Braille",
+ super::script::Braille_table), ("Buginese", super::script::Buginese_table), ("Buhid",
+ super::script::Buhid_table), ("C", super::general_category::C_table),
+ ("Canadian_Aboriginal", super::script::Canadian_Aboriginal_table), ("Carian",
+ super::script::Carian_table), ("Caucasian_Albanian",
+ super::script::Caucasian_Albanian_table), ("Cc", super::general_category::Cc_table), ("Cf",
+ super::general_category::Cf_table), ("Chakma", super::script::Chakma_table), ("Cham",
+ super::script::Cham_table), ("Cherokee", super::script::Cherokee_table), ("Cn",
+ super::general_category::Cn_table), ("Co", super::general_category::Co_table), ("Common",
+ super::script::Common_table), ("Coptic", super::script::Coptic_table), ("Cuneiform",
+ super::script::Cuneiform_table), ("Cypriot", super::script::Cypriot_table), ("Cyrillic",
+ super::script::Cyrillic_table), ("Default_Ignorable_Code_Point",
+ super::derived_property::Default_Ignorable_Code_Point_table), ("Deseret",
+ super::script::Deseret_table), ("Devanagari", super::script::Devanagari_table), ("Duployan",
+ super::script::Duployan_table), ("Egyptian_Hieroglyphs",
+ super::script::Egyptian_Hieroglyphs_table), ("Elbasan", super::script::Elbasan_table),
+ ("Ethiopic", super::script::Ethiopic_table), ("Georgian", super::script::Georgian_table),
+ ("Glagolitic", super::script::Glagolitic_table), ("Gothic", super::script::Gothic_table),
+ ("Grantha", super::script::Grantha_table), ("Greek", super::script::Greek_table),
+ ("Gujarati", super::script::Gujarati_table), ("Gurmukhi", super::script::Gurmukhi_table),
+ ("Han", super::script::Han_table), ("Hangul", super::script::Hangul_table), ("Hanunoo",
+ super::script::Hanunoo_table), ("Hebrew", super::script::Hebrew_table), ("Hiragana",
+ super::script::Hiragana_table), ("Imperial_Aramaic", super::script::Imperial_Aramaic_table),
+ ("Inherited", super::script::Inherited_table), ("Inscriptional_Pahlavi",
+ super::script::Inscriptional_Pahlavi_table), ("Inscriptional_Parthian",
+ super::script::Inscriptional_Parthian_table), ("Javanese", super::script::Javanese_table),
+ ("Join_Control", super::property::Join_Control_table), ("Kaithi",
+ super::script::Kaithi_table), ("Kannada", super::script::Kannada_table), ("Katakana",
+ super::script::Katakana_table), ("Kayah_Li", super::script::Kayah_Li_table), ("Kharoshthi",
+ super::script::Kharoshthi_table), ("Khmer", super::script::Khmer_table), ("Khojki",
+ super::script::Khojki_table), ("Khudawadi", super::script::Khudawadi_table), ("L",
+ super::general_category::L_table), ("LC", super::general_category::LC_table), ("Lao",
+ super::script::Lao_table), ("Latin", super::script::Latin_table), ("Lepcha",
+ super::script::Lepcha_table), ("Limbu", super::script::Limbu_table), ("Linear_A",
+ super::script::Linear_A_table), ("Linear_B", super::script::Linear_B_table), ("Lisu",
+ super::script::Lisu_table), ("Ll", super::general_category::Ll_table), ("Lm",
+ super::general_category::Lm_table), ("Lo", super::general_category::Lo_table), ("Lowercase",
+ super::derived_property::Lowercase_table), ("Lt", super::general_category::Lt_table), ("Lu",
+ super::general_category::Lu_table), ("Lycian", super::script::Lycian_table), ("Lydian",
+ super::script::Lydian_table), ("M", super::general_category::M_table), ("Mahajani",
+ super::script::Mahajani_table), ("Malayalam", super::script::Malayalam_table), ("Mandaic",
+ super::script::Mandaic_table), ("Manichaean", super::script::Manichaean_table), ("Mc",
+ super::general_category::Mc_table), ("Me", super::general_category::Me_table),
+ ("Meetei_Mayek", super::script::Meetei_Mayek_table), ("Mende_Kikakui",
+ super::script::Mende_Kikakui_table), ("Meroitic_Cursive",
+ super::script::Meroitic_Cursive_table), ("Meroitic_Hieroglyphs",
+ super::script::Meroitic_Hieroglyphs_table), ("Miao", super::script::Miao_table), ("Mn",
+ super::general_category::Mn_table), ("Modi", super::script::Modi_table), ("Mongolian",
+ super::script::Mongolian_table), ("Mro", super::script::Mro_table), ("Myanmar",
+ super::script::Myanmar_table), ("N", super::general_category::N_table), ("Nabataean",
+ super::script::Nabataean_table), ("Nd", super::general_category::Nd_table), ("New_Tai_Lue",
+ super::script::New_Tai_Lue_table), ("Nko", super::script::Nko_table), ("Nl",
+ super::general_category::Nl_table), ("No", super::general_category::No_table),
+ ("Noncharacter_Code_Point", super::property::Noncharacter_Code_Point_table), ("Ogham",
+ super::script::Ogham_table), ("Ol_Chiki", super::script::Ol_Chiki_table), ("Old_Italic",
+ super::script::Old_Italic_table), ("Old_North_Arabian",
+ super::script::Old_North_Arabian_table), ("Old_Permic", super::script::Old_Permic_table),
+ ("Old_Persian", super::script::Old_Persian_table), ("Old_South_Arabian",
+ super::script::Old_South_Arabian_table), ("Old_Turkic", super::script::Old_Turkic_table),
+ ("Oriya", super::script::Oriya_table), ("Osmanya", super::script::Osmanya_table), ("P",
+ super::general_category::P_table), ("Pahawh_Hmong", super::script::Pahawh_Hmong_table),
+ ("Palmyrene", super::script::Palmyrene_table), ("Pau_Cin_Hau",
+ super::script::Pau_Cin_Hau_table), ("Pc", super::general_category::Pc_table), ("Pd",
+ super::general_category::Pd_table), ("Pe", super::general_category::Pe_table), ("Pf",
+ super::general_category::Pf_table), ("Phags_Pa", super::script::Phags_Pa_table),
+ ("Phoenician", super::script::Phoenician_table), ("Pi", super::general_category::Pi_table),
+ ("Po", super::general_category::Po_table), ("Ps", super::general_category::Ps_table),
+ ("Psalter_Pahlavi", super::script::Psalter_Pahlavi_table), ("Rejang",
+ super::script::Rejang_table), ("Runic", super::script::Runic_table), ("S",
+ super::general_category::S_table), ("Samaritan", super::script::Samaritan_table),
+ ("Saurashtra", super::script::Saurashtra_table), ("Sc", super::general_category::Sc_table),
+ ("Sharada", super::script::Sharada_table), ("Shavian", super::script::Shavian_table),
+ ("Siddham", super::script::Siddham_table), ("Sinhala", super::script::Sinhala_table), ("Sk",
+ super::general_category::Sk_table), ("Sm", super::general_category::Sm_table), ("So",
+ super::general_category::So_table), ("Sora_Sompeng", super::script::Sora_Sompeng_table),
+ ("Sundanese", super::script::Sundanese_table), ("Syloti_Nagri",
+ super::script::Syloti_Nagri_table), ("Syriac", super::script::Syriac_table), ("Tagalog",
+ super::script::Tagalog_table), ("Tagbanwa", super::script::Tagbanwa_table), ("Tai_Le",
+ super::script::Tai_Le_table), ("Tai_Tham", super::script::Tai_Tham_table), ("Tai_Viet",
+ super::script::Tai_Viet_table), ("Takri", super::script::Takri_table), ("Tamil",
+ super::script::Tamil_table), ("Telugu", super::script::Telugu_table), ("Thaana",
+ super::script::Thaana_table), ("Thai", super::script::Thai_table), ("Tibetan",
+ super::script::Tibetan_table), ("Tifinagh", super::script::Tifinagh_table), ("Tirhuta",
+ super::script::Tirhuta_table), ("Ugaritic", super::script::Ugaritic_table), ("Uppercase",
+ super::derived_property::Uppercase_table), ("Vai", super::script::Vai_table),
+ ("Warang_Citi", super::script::Warang_Citi_table), ("White_Space",
+ super::property::White_Space_table), ("XID_Continue",
+ super::derived_property::XID_Continue_table), ("XID_Start",
+ super::derived_property::XID_Start_table), ("Yi", super::script::Yi_table), ("Z",
+ super::general_category::Z_table), ("Zl", super::general_category::Zl_table), ("Zp",
+ super::general_category::Zp_table), ("Zs", super::general_category::Zs_table)
+ ];
+
+ pub const PERLD: &'static [(char, char)] = super::general_category::Nd_table;
+
+ pub const PERLS: &'static [(char, char)] = super::property::White_Space_table;
+
+ pub const PERLW: &'static [(char, char)] = &[
('\u{30}', '\u{39}'), ('\u{41}', '\u{5a}'), ('\u{5f}', '\u{5f}'), ('\u{61}', '\u{7a}'),
('\u{aa}', '\u{aa}'), ('\u{b5}', '\u{b5}'), ('\u{ba}', '\u{ba}'), ('\u{c0}', '\u{d6}'),
('\u{d8}', '\u{f6}'), ('\u{f8}', '\u{2c1}'), ('\u{2c6}', '\u{2d1}'), ('\u{2e0}', '\u{2e4}'),
pub mod normalization {
// Canonical decompositions
- pub static canonical_table: &'static [(char, &'static [char])] = &[
+ pub const canonical_table: &'static [(char, &'static [char])] = &[
('\u{c0}', &['\u{41}', '\u{300}']), ('\u{c1}', &['\u{41}', '\u{301}']), ('\u{c2}',
&['\u{41}', '\u{302}']), ('\u{c3}', &['\u{41}', '\u{303}']), ('\u{c4}', &['\u{41}',
'\u{308}']), ('\u{c5}', &['\u{41}', '\u{30a}']), ('\u{c7}', &['\u{43}', '\u{327}']),
];
// Compatibility decompositions
- pub static compatibility_table: &'static [(char, &'static [char])] = &[
+ pub const compatibility_table: &'static [(char, &'static [char])] = &[
('\u{a0}', &['\u{20}']), ('\u{a8}', &['\u{20}', '\u{308}']), ('\u{aa}', &['\u{61}']),
('\u{af}', &['\u{20}', '\u{304}']), ('\u{b2}', &['\u{32}']), ('\u{b3}', &['\u{33}']),
('\u{b4}', &['\u{20}', '\u{301}']), ('\u{b5}', &['\u{3bc}']), ('\u{b8}', &['\u{20}',
];
// Canonical compositions
- pub static composition_table: &'static [(char, &'static [(char, char)])] = &[
+ pub const composition_table: &'static [(char, &'static [(char, char)])] = &[
('\u{3c}', &[('\u{338}', '\u{226e}')]), ('\u{3d}', &[('\u{338}', '\u{2260}')]), ('\u{3e}',
&[('\u{338}', '\u{226f}')]), ('\u{41}', &[('\u{300}', '\u{c0}'), ('\u{301}', '\u{c1}'),
('\u{302}', '\u{c2}'), ('\u{303}', '\u{c3}'), ('\u{304}', '\u{100}'), ('\u{306}',
}
}
- static combining_class_table: &'static [(char, char, u8)] = &[
+ const combining_class_table: &'static [(char, char, u8)] = &[
('\u{300}', '\u{314}', 230), ('\u{315}', '\u{315}', 232), ('\u{316}', '\u{319}', 220),
('\u{31a}', '\u{31a}', 232), ('\u{31b}', '\u{31b}', 216), ('\u{31c}', '\u{320}', 220),
('\u{321}', '\u{322}', 202), ('\u{323}', '\u{326}', 220), ('\u{327}', '\u{328}', 202),
}
}
- static LuLl_table: &'static [(char, char)] = &[
+ const LuLl_table: &'static [(char, char)] = &[
('\u{41}', '\u{61}'), ('\u{42}', '\u{62}'), ('\u{43}', '\u{63}'), ('\u{44}', '\u{64}'),
('\u{45}', '\u{65}'), ('\u{46}', '\u{66}'), ('\u{47}', '\u{67}'), ('\u{48}', '\u{68}'),
('\u{49}', '\u{69}'), ('\u{4a}', '\u{6a}'), ('\u{4b}', '\u{6b}'), ('\u{4c}', '\u{6c}'),
('\u{118be}', '\u{118de}'), ('\u{118bf}', '\u{118df}')
];
- static LlLu_table: &'static [(char, char)] = &[
+ const LlLu_table: &'static [(char, char)] = &[
('\u{61}', '\u{41}'), ('\u{62}', '\u{42}'), ('\u{63}', '\u{43}'), ('\u{64}', '\u{44}'),
('\u{65}', '\u{45}'), ('\u{66}', '\u{46}'), ('\u{67}', '\u{47}'), ('\u{68}', '\u{48}'),
('\u{69}', '\u{49}'), ('\u{6a}', '\u{4a}'), ('\u{6b}', '\u{4b}'), ('\u{6c}', '\u{4c}'),
// character width table. Based on Markus Kuhn's free wcwidth() implementation,
// http://www.cl.cam.ac.uk/~mgk25/ucs/wcwidth.c
- static charwidth_table: &'static [(char, char, u8, u8)] = &[
+ const charwidth_table: &'static [(char, char, u8, u8)] = &[
('\u{a1}', '\u{a1}', 1, 2), ('\u{a4}', '\u{a4}', 1, 2), ('\u{a7}', '\u{a8}', 1, 2),
('\u{aa}', '\u{aa}', 1, 2), ('\u{ae}', '\u{ae}', 1, 2), ('\u{b0}', '\u{b4}', 1, 2),
('\u{b6}', '\u{ba}', 1, 2), ('\u{bc}', '\u{bf}', 1, 2), ('\u{c6}', '\u{c6}', 1, 2),
bsearch_range_value_table(c, grapheme_cat_table)
}
- static grapheme_cat_table: &'static [(char, char, GraphemeCat)] = &[
+ const grapheme_cat_table: &'static [(char, char, GraphemeCat)] = &[
('\u{0}', '\u{1f}', GC_Control), ('\u{7f}', '\u{9f}', GC_Control), ('\u{ad}', '\u{ad}',
GC_Control), ('\u{300}', '\u{36f}', GC_Extend), ('\u{483}', '\u{487}', GC_Extend),
('\u{488}', '\u{489}', GC_Extend), ('\u{591}', '\u{5bd}', GC_Extend), ('\u{5bf}', '\u{5bf}',
#![feature(box_syntax)]
use std::ascii::OwnedAsciiExt;
+use std::env;
+use std::fs::File;
+use std::io::prelude::*;
+use std::io;
use std::slice;
use std::sync::Arc;
use std::thread;
static TABLE: [u8;4] = [ 'A' as u8, 'C' as u8, 'G' as u8, 'T' as u8 ];
-static TABLE_SIZE: uint = 2 << 16;
+static TABLE_SIZE: usize = 2 << 16;
static OCCURRENCES: [&'static str;5] = [
"GGT",
Code((self.hash() << 2) + (pack_symbol(c) as u64))
}
- fn rotate(&self, c: u8, frame: uint) -> Code {
+ fn rotate(&self, c: u8, frame: usize) -> Code {
Code(self.push_char(c).hash() & ((1u64 << (2 * frame)) - 1))
}
string.bytes().fold(Code(0u64), |a, b| a.push_char(b))
}
- fn unpack(&self, frame: uint) -> String {
+ fn unpack(&self, frame: usize) -> String {
let mut key = self.hash();
let mut result = Vec::new();
for _ in 0..frame {
impl TableCallback for PrintCallback {
fn f(&self, entry: &mut Entry) {
let PrintCallback(s) = *self;
- println!("{}\t{}", entry.count as int, s);
+ println!("{}\t{}", entry.count, s);
}
}
struct Entry {
code: Code,
- count: uint,
+ count: usize,
next: Option<Box<Entry>>,
}
let index = key.hash() % (TABLE_SIZE as u64);
{
- if self.items[index as uint].is_none() {
+ if self.items[index as usize].is_none() {
let mut entry = box Entry {
code: key,
count: 0,
next: None,
};
c.f(&mut *entry);
- self.items[index as uint] = Some(entry);
+ self.items[index as usize] = Some(entry);
return;
}
}
{
- let entry = self.items[index as uint].as_mut().unwrap();
+ let entry = self.items[index as usize].as_mut().unwrap();
if entry.code == key {
c.f(&mut **entry);
return;
}
fn unpack_symbol(c: u8) -> u8 {
- TABLE[c as uint]
+ TABLE[c as usize]
}
-fn generate_frequencies(mut input: &[u8], frame: uint) -> Table {
+fn generate_frequencies(mut input: &[u8], frame: usize) -> Table {
let mut frequencies = Table::new();
if input.len() < frame { return frequencies; }
let mut code = Code(0);
frequencies
}
-fn print_frequencies(frequencies: &Table, frame: uint) {
+fn print_frequencies(frequencies: &Table, frame: usize) {
let mut vector = Vec::new();
for entry in frequencies.iter() {
vector.push((entry.count, entry.code));
frequencies.lookup(Code::pack(occurrence), PrintCallback(occurrence))
}
-fn get_sequence<R: Buffer>(r: &mut R, key: &str) -> Vec<u8> {
+fn get_sequence<R: BufRead>(r: &mut R, key: &str) -> Vec<u8> {
let mut res = Vec::new();
- for l in r.lines().map(|l| l.ok().unwrap())
+ for l in r.lines().map(|l| l.unwrap())
.skip_while(|l| key != &l[..key.len()]).skip(1)
{
res.push_all(l.trim().as_bytes());
}
fn main() {
- let input = if std::env::var_os("RUST_BENCH").is_some() {
- let fd = std::old_io::File::open(&Path::new("shootout-k-nucleotide.data"));
- get_sequence(&mut std::old_io::BufferedReader::new(fd), ">THREE")
+ let input = if env::var_os("RUST_BENCH").is_some() {
+ let f = File::open("shootout-k-nucleotide.data").unwrap();
+ get_sequence(&mut io::BufReader::new(f), ">THREE")
} else {
- let mut stdin = std::old_io::stdin();
+ let stdin = io::stdin();
let mut stdin = stdin.lock();
- get_sequence(&mut *stdin, ">THREE")
+ get_sequence(&mut stdin, ">THREE")
};
let input = Arc::new(input);
#![feature(box_syntax)]
#![allow(non_snake_case)]
-use std::old_io::BufferedReader;
-use std::old_io::stdio::StdReader;
-use std::old_io;
+use std::io::prelude::*;
+use std::io;
use std::iter::repeat;
use std::num::Int;
use std::env;
//
// internal type of sudoku grids
-type grid = Vec<Vec<u8> > ;
+type grid = Vec<Vec<u8>>;
struct Sudoku {
grid: grid
return Sudoku::new(g)
}
- pub fn read(mut reader: &mut BufferedReader<StdReader>) -> Sudoku {
+ pub fn read(reader: &mut BufRead) -> Sudoku {
/* assert first line is exactly "9,9" */
- assert!(reader.read_line().unwrap() == "9,9".to_string());
+ let mut s = String::new();
+ reader.read_line(&mut s).unwrap();
+ assert_eq!(s, "9,9\n");
let mut g = repeat(vec![0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8])
.take(10).collect::<Vec<_>>();
if comps.len() == 3 {
let row = comps[0].parse::<u8>().unwrap();
let col = comps[1].parse::<u8>().unwrap();
- g[row as uint][col as uint] = comps[2].parse().unwrap();
+ g[row as usize][col as usize] = comps[2].parse().unwrap();
}
else {
panic!("Invalid sudoku file");
return Sudoku::new(g)
}
- pub fn write(&self, writer: &mut old_io::Writer) {
+ pub fn write(&self, writer: &mut Write) {
for row in 0u8..9u8 {
- write!(writer, "{}", self.grid[row as uint][0]);
+ write!(writer, "{}", self.grid[row as usize][0]);
for col in 1u8..9u8 {
- write!(writer, " {}", self.grid[row as uint][col as uint]);
+ write!(writer, " {}", self.grid[row as usize][col as usize]);
}
write!(writer, "\n");
}
let mut work: Vec<(u8, u8)> = Vec::new(); /* queue of uncolored fields */
for row in 0u8..9u8 {
for col in 0u8..9u8 {
- let color = self.grid[row as uint][col as uint];
+ let color = self.grid[row as usize][col as usize];
if color == 0u8 {
work.push((row, col));
}
while ptr < end {
let (row, col) = work[ptr];
// is there another color to try?
- let the_color = self.grid[row as uint][col as uint] +
+ let the_color = self.grid[row as usize][col as usize] +
(1 as u8);
if self.next_color(row, col, the_color) {
// yes: advance work list
// find first remaining color that is available
let next = avail.next();
- self.grid[row as uint][col as uint] = next;
+ self.grid[row as usize][col as usize] = next;
return 0u8 != next;
}
- self.grid[row as uint][col as uint] = 0u8;
+ self.grid[row as usize][col as usize] = 0u8;
return false;
}
fn drop_colors(&mut self, avail: &mut Colors, row: u8, col: u8) {
for idx in 0u8..9u8 {
/* check same column fields */
- avail.remove(self.grid[idx as uint][col as uint]);
+ avail.remove(self.grid[idx as usize][col as usize]);
/* check same row fields */
- avail.remove(self.grid[row as uint][idx as uint]);
+ avail.remove(self.grid[row as usize][idx as usize]);
}
// check same block fields
let col0 = (col / 3u8) * 3u8;
for alt_row in row0..row0 + 3u8 {
for alt_col in col0..col0 + 3u8 {
- avail.remove(self.grid[alt_row as uint][alt_col as uint]);
+ avail.remove(self.grid[alt_row as usize][alt_col as usize]);
}
}
}
impl Colors {
fn new(start_color: u8) -> Colors {
// Sets bits 9..start_color
- let tails = !0u16 << start_color as uint;
+ let tails = !0u16 << start_color as usize;
return Colors(HEADS & tails);
}
fn remove(&mut self, color: u8) {
if color != 0u8 {
let Colors(val) = *self;
- let mask = !(1u16 << color as uint);
+ let mask = !(1u16 << color as usize);
*self = Colors(val & mask);
}
}
}
fn main() {
- let args = env::args();
+ let args = env::args();
let use_default = args.len() == 1;
let mut sudoku = if use_default {
Sudoku::from_vec(&DEFAULT_SUDOKU)
} else {
- let mut stdin = old_io::stdin();
- let mut stdin = stdin.lock();
- Sudoku::read(&mut *stdin)
+ let stdin = io::stdin();
+ let mut locked = stdin.lock();
+ Sudoku::read(&mut locked)
};
sudoku.solve();
- sudoku.write(&mut old_io::stdout());
+ let out = io::stdout();
+ sudoku.write(&mut out.lock());
}
// ignore-android
-#![feature(asm)]
+#![feature(asm, rustc_attrs)]
#![allow(dead_code, non_upper_case_globals)]
#[cfg(any(target_arch = "x86",
target_arch = "x86_64"))]
-pub fn main() {
+#[rustc_error]
+pub fn main() { //~ ERROR compilation successful
// assignment not dead
let mut x: isize = 0;
unsafe {
}
assert_eq!(x, 13);
}
-
-// At least one error is needed so that compilation fails
-#[static_assert]
-static b: bool = false; //~ ERROR static assertion failed
--- /dev/null
+// Copyright 2015 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.
+
+// Issue 22443: Reject code using non-regular types that would
+// otherwise cause dropck to loop infinitely.
+
+use std::marker::PhantomData;
+
+struct Digit<T> {
+ elem: T
+}
+
+struct Node<T:'static> { m: PhantomData<&'static T> }
+
+
+enum FingerTree<T:'static> {
+ Single(T),
+ // Bug report said Digit after Box would stack overflow (versus
+ // Digit before Box; see dropck_no_diverge_on_nonregular_2).
+ Deep(
+ Box<FingerTree<Node<T>>>,
+ Digit<T>,
+ )
+}
+
+fn main() {
+ let ft = //~ ERROR overflow while adding drop-check rules for FingerTree
+ FingerTree::Single(1);
+ //~^ ERROR overflow while adding drop-check rules for FingerTree
+}
--- /dev/null
+// Copyright 2015 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.
+
+// Issue 22443: Reject code using non-regular types that would
+// otherwise cause dropck to loop infinitely.
+
+use std::marker::PhantomData;
+
+struct Digit<T> {
+ elem: T
+}
+
+struct Node<T:'static> { m: PhantomData<&'static T> }
+
+enum FingerTree<T:'static> {
+ Single(T),
+ // Bug report said Digit before Box would infinite loop (versus
+ // Digit after Box; see dropck_no_diverge_on_nonregular_1).
+ Deep(
+ Digit<T>,
+ Box<FingerTree<Node<T>>>,
+ )
+}
+
+fn main() {
+ let ft = //~ ERROR overflow while adding drop-check rules for FingerTree
+ FingerTree::Single(1);
+ //~^ ERROR overflow while adding drop-check rules for FingerTree
+}
--- /dev/null
+// Copyright 2015 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.
+
+// Issue 22443: Reject code using non-regular types that would
+// otherwise cause dropck to loop infinitely.
+//
+// This version is just checking that we still sanely handle a trivial
+// wrapper around the non-regular type. (It also demonstrates how the
+// error messages will report different types depending on which type
+// dropck is analyzing.)
+
+use std::marker::PhantomData;
+
+struct Digit<T> {
+ elem: T
+}
+
+struct Node<T:'static> { m: PhantomData<&'static T> }
+
+enum FingerTree<T:'static> {
+ Single(T),
+ // According to the bug report, Digit before Box would infinite loop.
+ Deep(
+ Digit<T>,
+ Box<FingerTree<Node<T>>>,
+ )
+}
+
+enum Wrapper<T:'static> {
+ Simple,
+ Other(FingerTree<T>),
+}
+
+fn main() {
+ let w = //~ ERROR overflow while adding drop-check rules for core::option
+ Some(Wrapper::Simple::<u32>);
+ //~^ ERROR overflow while adding drop-check rules for core::option::Option
+ //~| ERROR overflow while adding drop-check rules for Wrapper
+}
--- /dev/null
+// Copyright 2015 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.
+
+#[static_assert] //~ ERROR `#[static_assert]` is an experimental feature
+static X: bool = true;
+
+fn main() {}
// except according to those terms.
// error-pattern: too big for the current
+#![allow(exceeding_bitshifts)]
fn main() {
let fat : [u8; (1<<61)+(1<<31)] = [0; (1u64<<61) as usize +(1u64<<31) as usize];
--- /dev/null
+// Copyright 2015 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.
+
+pub struct PublicType;
+struct PrivateType;
+
+pub trait PublicTrait {
+ type Item;
+}
+
+trait PrivateTrait {
+ type Item;
+}
+
+impl PublicTrait for PublicType {
+ type Item = PrivateType; //~ ERROR private type in exported type signature
+}
+
+// OK
+impl PublicTrait for PrivateType {
+ type Item = PrivateType;
+}
+
+// OK
+impl PrivateTrait for PublicType {
+ type Item = PrivateType;
+}
+
+// OK
+impl PrivateTrait for PrivateType {
+ type Item = PrivateType;
+}
+
+fn main() {}
fn id<T>(t: T) -> T { t }
fn f<'r, T>(v: &'r T) -> Box<FnMut() -> T + 'r> {
- id(box || *v) //~ ERROR cannot infer
+ id(box || *v)
+ //~^ ERROR `v` does not live long enough
+ //~| ERROR cannot move out of borrowed content
}
fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(rustc_attrs)]
#![allow(dead_code)]
// Matching against NaN should result in a warning
use std::f64::NAN;
-fn main() {
+#[rustc_error]
+fn main() { //~ ERROR compilation successful
let x = NAN;
match x {
NAN => {},
};
//~^^^ WARNING unmatchable NaN in pattern, use the is_nan method in a guard instead
}
-
-// At least one error is needed so that compilation fails
-#[static_assert]
-static B: bool = false; //~ ERROR static assertion failed
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use std::{int, i8, i16, i32, i64};
+use std::{isize, i8, i16, i32, i64};
use std::thread;
fn main() {
- assert!(thread::spawn(move|| { int::MIN / -1; }).join().is_err());
+ assert!(thread::spawn(move|| { isize::MIN / -1; }).join().is_err());
//~^ ERROR attempted to divide with overflow in a constant expression
assert!(thread::spawn(move|| { i8::MIN / -1; }).join().is_err());
//~^ ERROR attempted to divide with overflow in a constant expression
//~^ ERROR attempted to divide by zero in a constant expression
assert!(thread::spawn(move|| { 1i64 / 0; }).join().is_err());
//~^ ERROR attempted to divide by zero in a constant expression
- assert!(thread::spawn(move|| { int::MIN % -1; }).join().is_err());
+ assert!(thread::spawn(move|| { isize::MIN % -1; }).join().is_err());
//~^ ERROR attempted remainder with overflow in a constant expression
assert!(thread::spawn(move|| { i8::MIN % -1; }).join().is_err());
//~^ ERROR attempted remainder with overflow in a constant expression
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(static_assert)]
#![allow(dead_code)]
#[static_assert]
fn static_proc(x: &isize) -> Box<FnMut()->(isize) + 'static> {
// This is illegal, because the region bound on `proc` is 'static.
- box move|| { *x } //~ ERROR cannot infer
+ box move|| { *x } //~ ERROR captured variable `x` does not outlive the enclosing closure
}
fn main() { }
}
fn main() {
- let cl_box = {
+ let mut cl_box = {
let mut i = 3;
- box_it(box || i += 1) //~ ERROR cannot infer
+ box_it(box || i += 1) //~ ERROR `i` does not live long enough
};
cl_box.cl.call_mut(());
}
fn main() {
let bad = {
let x = 1;
- let y = &x;
+ let y = &x; //~ ERROR `x` does not live long enough
- thread::scoped(|| { //~ ERROR cannot infer an appropriate lifetime
+ thread::scoped(|| {
+ //~^ ERROR `y` does not live long enough
let _z = y;
})
};
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(static_assert)]
#![allow(dead_code)]
#[static_assert]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(static_assert)]
#![allow(dead_code)]
#[static_assert]
fn main() {
let _f = {
let x = 0_usize;
- || x //~ ERROR cannot infer an appropriate lifetime due to conflicting requirements
+ || x //~ ERROR `x` does not live long enough
};
}
// except according to those terms.
fn main() {
- pub use std::uint; //~ ERROR: visibility has no effect
+ pub use std::usize; //~ ERROR: visibility has no effect
pub struct A; //~ ERROR: visibility has no effect
pub enum B {} //~ ERROR: visibility has no effect
pub trait C { //~ ERROR: visibility has no effect
// error-pattern:index out of bounds: the len is 3 but the index is
-use std::uint;
+use std::usize;
use std::mem::size_of;
fn main() {
let xs = [1, 2, 3];
- xs[uint::MAX / size_of::<int>() + 1];
+ xs[usize::MAX / size_of::<isize>() + 1];
}
// error-pattern:capacity overflow
use std::collections::hash_map::HashMap;
-use std::uint;
+use std::usize;
use std::mem::size_of;
fn main() {
- let threshold = uint::MAX / size_of::<(u64, u64, u64)>();
+ let threshold = usize::MAX / size_of::<(u64, u64, u64)>();
let mut h = HashMap::<u64, u64>::with_capacity(threshold + 100);
h.insert(0, 0);
}
fn main() {
let _ = std::old_io::stdin();
+ let _ = std::io::stdin();
}
}
#[derive(PartialEq)]
-struct Bar;
+pub struct Bar;
impl Foo for int {
type A = uint;
fn boo(&self) -> <Self as Foo>::A;
}
-struct Bar;
+pub struct Bar;
impl Foo for char {
type A = Bar;
}
#[derive(PartialEq)]
-struct Bar;
+pub struct Bar;
impl Foo for int {
type A = uint;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-// ignore-fast
-
use std::env;
-use std::old_io;
+use std::io::prelude::*;
+use std::io;
+use std::process::{Command, Stdio};
use std::str;
fn main() {
fn parent() {
let args: Vec<String> = env::args().collect();
- let mut p = old_io::process::Command::new(&args[0])
- .arg("child").spawn().unwrap();
- p.stdin.as_mut().unwrap().write_str("test1\ntest2\ntest3").unwrap();
+ let mut p = Command::new(&args[0]).arg("child")
+ .stdout(Stdio::capture())
+ .stdin(Stdio::capture())
+ .spawn().unwrap();
+ p.stdin.as_mut().unwrap().write_all(b"test1\ntest2\ntest3").unwrap();
let out = p.wait_with_output().unwrap();
assert!(out.status.success());
- let s = str::from_utf8(&out.output).unwrap();
- assert_eq!(s, "test1\n\ntest2\n\ntest3\n");
+ let s = str::from_utf8(&out.stdout).unwrap();
+ assert_eq!(s, "test1\ntest2\ntest3\n");
}
fn child() {
- let mut stdin = old_io::stdin();
+ let mut stdin = io::stdin();
for line in stdin.lock().lines() {
println!("{}", line.unwrap());
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-
-use std::old_io::process;
-use std::old_io::Command;
-use std::old_io;
use std::env;
+use std::io::prelude::*;
+use std::io;
+use std::process::{Command, Stdio};
fn main() {
let args: Vec<String> = env::args().collect();
}
test();
-
}
fn child() {
- old_io::stdout().write_line("foo").unwrap();
- old_io::stderr().write_line("bar").unwrap();
- let mut stdin = old_io::stdin();
- assert_eq!(stdin.lock().read_line().err().unwrap().kind, old_io::EndOfFile);
+ writeln!(&mut io::stdout(), "foo").unwrap();
+ writeln!(&mut io::stderr(), "bar").unwrap();
+ let mut stdin = io::stdin();
+ let mut s = String::new();
+ stdin.lock().read_line(&mut s).unwrap();
+ assert_eq!(s.len(), 0);
}
fn test() {
let args: Vec<String> = env::args().collect();
let mut p = Command::new(&args[0]).arg("child")
- .stdin(process::Ignored)
- .stdout(process::Ignored)
- .stderr(process::Ignored)
+ .stdin(Stdio::capture())
+ .stdout(Stdio::capture())
+ .stderr(Stdio::capture())
.spawn().unwrap();
assert!(p.wait().unwrap().success());
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// DON'T REENABLE THIS UNLESS YOU'VE ACTUALLY FIXED THE UNDERLYING ISSUE
+// ignore-android seems to block forever
#![forbid(warnings)]
// A var moved into a proc, that has a mutable loan path should
// not trigger a misleading unused_mut warning.
+use std::io::prelude::*;
use std::thread;
pub fn main() {
- let mut stdin = std::old_io::stdin();
+ let mut stdin = std::io::stdin();
thread::spawn(move|| {
- let _ = stdin.read_to_end();
- });
+ let mut v = Vec::new();
+ let _ = stdin.read_to_end(&mut v);
+ }).join().ok().unwrap();
}
#![allow(unknown_features)]
#![feature(box_syntax)]
-use std::old_io;
+use std::io::{self, Write};
-fn f(wr: &mut Writer) {
- wr.write_str("hello").ok().expect("failed");
+fn f(wr: &mut Write) {
+ wr.write_all(b"hello").ok().expect("failed");
}
fn main() {
- let mut wr = box old_io::stdout() as Box<Writer + 'static>;
+ let mut wr = box io::stdout() as Box<Write>;
f(&mut wr);
}
--- /dev/null
+// Copyright 2015 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.
+
+// This test is reduced from libsyntax. It is just checking that we
+// can successfully deal with a "deep" structure, which the drop-check
+// was hitting a recursion limit on at one point.
+
+#![allow(non_camel_case_types)]
+
+pub fn noop_fold_impl_item() -> SmallVector<ImplItem> {
+ loop { }
+}
+
+pub struct SmallVector<T>(P<T>);
+pub struct ImplItem(P<S01_Method>);
+
+struct P<T>(Box<T>);
+
+struct S01_Method(P<S02_Generics>);
+struct S02_Generics(P<S03_TyParam>);
+struct S03_TyParam(P<S04_TyParamBound>);
+struct S04_TyParamBound(S05_PolyTraitRef);
+struct S05_PolyTraitRef(S06_TraitRef);
+struct S06_TraitRef(S07_Path);
+struct S07_Path(Vec<S08_PathSegment>);
+struct S08_PathSegment(S09_PathParameters);
+struct S09_PathParameters(P<S10_ParenthesizedParameterData>);
+struct S10_ParenthesizedParameterData(Option<P<S11_Ty>>);
+struct S11_Ty(P<S12_Expr>);
+struct S12_Expr(P<S13_Block>);
+struct S13_Block(Vec<P<S14_Stmt>>);
+struct S14_Stmt(P<S15_Decl>);
+struct S15_Decl(P<S16_Local>);
+struct S16_Local(P<S17_Pat>);
+struct S17_Pat(P<S18_Mac>);
+struct S18_Mac(Vec<P<S19_TokenTree>>);
+struct S19_TokenTree(P<S20_Token>);
+struct S20_Token(P<S21_Nonterminal>);
+struct S21_Nonterminal(P<S22_Item>);
+struct S22_Item(P<S23_EnumDef>);
+struct S23_EnumDef(Vec<P<S24_Variant>>);
+struct S24_Variant(P<S25_VariantKind>);
+struct S25_VariantKind(P<S26_StructDef>);
+struct S26_StructDef(Vec<P<S27_StructField>>);
+struct S27_StructField(P<S28_StructFieldKind>);
+struct S28_StructFieldKind;
+
+pub fn main() {}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use std::old_io;
+use std::io;
pub fn main() {
- let stdout = &mut old_io::stdout() as &mut old_io::Writer;
+ let stdout = &mut io::stdout() as &mut io::Write;
stdout.write(b"Hello!");
}
// ignore-pretty - token trees can't pretty print
+#![feature(custom_attribute)]
+
macro_rules! compiles_fine {
(#[$at:meta]) => {
// test that the different types of attributes work
// non-ASCII characters. The child process ensures all the strings are
// intact.
-use std::old_io;
-use std::old_io::fs;
-use std::old_io::Command;
+use std::io::prelude::*;
+use std::io;
+use std::fs;
+use std::process::Command;
use std::os;
use std::env;
-use std::old_path::Path;
+use std::path::{Path, PathBuf};
fn main() {
let my_args = env::args().collect::<Vec<_>>();
- let my_cwd = os::getcwd().unwrap();
+ let my_cwd = PathBuf::new(os::getcwd().unwrap().as_str().unwrap());
let my_env = env::vars().collect::<Vec<_>>();
- let my_path = Path::new(os::self_exe_name().unwrap());
- let my_dir = my_path.dir_path();
- let my_ext = my_path.extension_str().unwrap_or("");
+ let my_path = PathBuf::new(os::self_exe_name().unwrap().as_str().unwrap());
+ let my_dir = my_path.parent().unwrap();
+ let my_ext = my_path.extension().and_then(|s| s.to_str()).unwrap_or("");
// some non-ASCII characters
- let blah = "\u03c0\u042f\u97f3\u00e6\u221e";
+ let blah = "\u{3c0}\u{42f}\u{97f3}\u{e6}\u{221e}";
let child_name = "child";
let child_dir = format!("process-spawn-with-unicode-params-{}", blah);
// parameters sent to child / expected to be received from parent
let arg = blah;
- let cwd = my_dir.join(Path::new(child_dir.clone()));
+ let cwd = my_dir.join(&child_dir);
let env = ("RUST_TEST_PROC_SPAWN_UNICODE".to_string(), blah.to_string());
// am I the parent or the child?
let child_filestem = Path::new(child_name);
let child_filename = child_filestem.with_extension(my_ext);
- let child_path = cwd.join(child_filename);
+ let child_path = cwd.join(&child_filename);
// make a separate directory for the child
- drop(fs::mkdir(&cwd, old_io::USER_RWX).is_ok());
- assert!(fs::copy(&my_path, &child_path).is_ok());
- let mut my_env = my_env;
- my_env.push(env);
+ let _ = fs::create_dir(&cwd);
+ fs::copy(&my_path, &child_path).unwrap();
// run child
let p = Command::new(&child_path)
.arg(arg)
- .cwd(&cwd)
- .env_set_all(&my_env)
+ .current_dir(&cwd)
+ .env(&env.0, &env.1)
.spawn().unwrap().wait_with_output().unwrap();
// display the output
- assert!(old_io::stdout().write(&p.output).is_ok());
- assert!(old_io::stderr().write(&p.error).is_ok());
+ io::stdout().write_all(&p.stdout).unwrap();
+ io::stderr().write_all(&p.stderr).unwrap();
// make sure the child succeeded
assert!(p.status.success());
} else { // child
// check working directory (don't try to compare with `cwd` here!)
- assert!(my_cwd.ends_with_path(&Path::new(child_dir)));
+ assert!(my_cwd.ends_with(&child_dir));
// check arguments
assert_eq!(&*my_args[1], arg);
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(static_assert)]
+
#[static_assert]
static b: bool = true;
}
pub fn main() {
- assert!(MAX_LEN <= std::usize::BITS);
+ assert!(MAX_LEN <= std::usize::BITS as usize);
// len can't go above 64.
for len in 2..MAX_LEN {
for _ in 0..REPEATS {