提交 58450c04 编写于 作者: B bors 提交者: GitHub

Auto merge of #36446 - GuillaumeGomez:rollup, r=GuillaumeGomez

Rollup of 5 pull requests

- Successful merges: #36357, #36380, #36389, #36397, #36402
- Failed merges:
......@@ -152,7 +152,7 @@ the thing `y` points at. You’ll notice that `x` had to be marked `mut` as well
If it wasn’t, we couldn’t take a mutable borrow to an immutable value.
You'll also notice we added an asterisk (`*`) in front of `y`, making it `*y`,
this is because `y` is a `&mut` reference. You'll need to use astrisks to
this is because `y` is a `&mut` reference. You'll need to use asterisks to
access the contents of a reference as well.
Otherwise, `&mut` references are like references. There _is_ a large
......
......@@ -262,22 +262,25 @@
/// Moves a value out of scope without running drop glue.
pub fn forget<T>(_: T) -> ();
/// Reinterprets the bits of a value of one type as another type; both types
/// must have the same size. Neither the original, nor the result, may be an
/// [invalid value] (../../nomicon/meet-safe-and-unsafe.html).
/// Reinterprets the bits of a value of one type as another type.
///
/// Both types must have the same size. Neither the original, nor the result,
/// may be an [invalid value](../../nomicon/meet-safe-and-unsafe.html).
///
/// `transmute` is semantically equivalent to a bitwise move of one type
/// into another. It copies the bits from the destination type into the
/// source type, then forgets the original. It's equivalent to C's `memcpy`
/// under the hood, just like `transmute_copy`.
/// into another. It copies the bits from the source value into the
/// destination value, then forgets the original. It's equivalent to C's
/// `memcpy` under the hood, just like `transmute_copy`.
///
/// `transmute` is incredibly unsafe. There are a vast number of ways to
/// cause undefined behavior with this function. `transmute` should be
/// `transmute` is **incredibly** unsafe. There are a vast number of ways to
/// cause [undefined behavior][ub] with this function. `transmute` should be
/// the absolute last resort.
///
/// The [nomicon](../../nomicon/transmutes.html) has additional
/// documentation.
///
/// [ub]: ../../reference.html#behavior-considered-undefined
///
/// # Examples
///
/// There are a few things that `transmute` is really useful for.
......@@ -292,7 +295,8 @@
/// assert_eq!(bitpattern, 0x3F800000);
/// ```
///
/// Turning a pointer into a function pointer:
/// Turning a pointer into a function pointer. This is *not* portable to
/// machines where function pointers and data pointers have different sizes.
///
/// ```
/// fn foo() -> i32 {
......@@ -305,8 +309,8 @@
/// assert_eq!(function(), 0);
/// ```
///
/// Extending a lifetime, or shortening an invariant lifetime; this is
/// advanced, very unsafe rust:
/// Extending a lifetime, or shortening an invariant lifetime. This is
/// advanced, very unsafe Rust!
///
/// ```
/// struct R<'a>(&'a i32);
......@@ -322,11 +326,9 @@
///
/// # Alternatives
///
/// However, many uses of `transmute` can be achieved through other means.
/// `transmute` can transform any type into any other, with just the caveat
/// that they're the same size, and often interesting results occur. Below
/// are common applications of `transmute` which can be replaced with safe
/// applications of `as`:
/// Don't despair: many uses of `transmute` can be achieved through other means.
/// Below are common applications of `transmute` which can be replaced with safer
/// constructs.
///
/// Turning a pointer into a `usize`:
///
......@@ -335,6 +337,7 @@
/// let ptr_num_transmute = unsafe {
/// std::mem::transmute::<&i32, usize>(ptr)
/// };
///
/// // Use an `as` cast instead
/// let ptr_num_cast = ptr as *const i32 as usize;
/// ```
......@@ -346,6 +349,7 @@
/// let ref_transmuted = unsafe {
/// std::mem::transmute::<*mut i32, &mut i32>(ptr)
/// };
///
/// // Use a reborrow instead
/// let ref_casted = unsafe { &mut *ptr };
/// ```
......@@ -357,6 +361,7 @@
/// let val_transmuted = unsafe {
/// std::mem::transmute::<&mut i32, &mut u32>(ptr)
/// };
///
/// // Now, put together `as` and reborrowing - note the chaining of `as`
/// // `as` is not transitive
/// let val_casts = unsafe { &mut *(ptr as *mut i32 as *mut u32) };
......@@ -368,9 +373,11 @@
/// // this is not a good way to do this.
/// let slice = unsafe { std::mem::transmute::<&str, &[u8]>("Rust") };
/// assert_eq!(slice, &[82, 117, 115, 116]);
///
/// // You could use `str::as_bytes`
/// let slice = "Rust".as_bytes();
/// assert_eq!(slice, &[82, 117, 115, 116]);
///
/// // Or, just use a byte string, if you have control over the string
/// // literal
/// assert_eq!(b"Rust", &[82, 117, 115, 116]);
......@@ -381,18 +388,21 @@
/// ```
/// let store = [0, 1, 2, 3];
/// let mut v_orig = store.iter().collect::<Vec<&i32>>();
///
/// // Using transmute: this is Undefined Behavior, and a bad idea.
/// // However, it is no-copy.
/// let v_transmuted = unsafe {
/// std::mem::transmute::<Vec<&i32>, Vec<Option<&i32>>>(
/// v_orig.clone())
/// };
///
/// // This is the suggested, safe way.
/// // It does copy the entire Vector, though, into a new array.
/// // It does copy the entire vector, though, into a new array.
/// let v_collected = v_orig.clone()
/// .into_iter()
/// .map(|r| Some(r))
/// .collect::<Vec<Option<&i32>>>();
///
/// // The no-copy, unsafe way, still using transmute, but not UB.
/// // This is equivalent to the original, but safer, and reuses the
/// // same Vec internals. Therefore the new inner type must have the
......@@ -412,6 +422,7 @@
///
/// ```
/// use std::{slice, mem};
///
/// // There are multiple ways to do this; and there are multiple problems
/// // with the following, transmute, way.
/// fn split_at_mut_transmute<T>(slice: &mut [T], mid: usize)
......@@ -426,6 +437,7 @@
/// (&mut slice[0..mid], &mut slice2[mid..len])
/// }
/// }
///
/// // This gets rid of the typesafety problems; `&mut *` will *only* give
/// // you an `&mut T` from an `&mut T` or `*mut T`.
/// fn split_at_mut_casts<T>(slice: &mut [T], mid: usize)
......@@ -439,6 +451,7 @@
/// (&mut slice[0..mid], &mut slice2[mid..len])
/// }
/// }
///
/// // This is how the standard library does it. This is the best method, if
/// // you need to do something like this
/// fn split_at_stdlib<T>(slice: &mut [T], mid: usize)
......
......@@ -21,54 +21,39 @@
#[stable(feature = "rust1", since = "1.0.0")]
pub use intrinsics::transmute;
/// Leaks a value into the void, consuming ownership and never running its
/// destructor.
/// Leaks a value: takes ownership and "forgets" about the value **without running
/// its destructor**.
///
/// This function will take ownership of its argument, but is distinct from the
/// `mem::drop` function in that it **does not run the destructor**, leaking the
/// value and any resources that it owns.
/// Any resources the value manages, such as heap memory or a file handle, will linger
/// forever in an unreachable state.
///
/// There's only a few reasons to use this function. They mainly come
/// up in unsafe code or FFI code.
///
/// * You have an uninitialized value, perhaps for performance reasons, and
/// need to prevent the destructor from running on it.
/// * You have two copies of a value (like when writing something like
/// [`mem::swap`][swap]), but need the destructor to only run once to
/// prevent a double `free`.
/// * Transferring resources across [FFI][ffi] boundaries.
///
/// [swap]: fn.swap.html
/// [ffi]: ../../book/ffi.html
/// If you want to dispose of a value properly, running its destructor, see
/// [`mem::drop`][drop].
///
/// # Safety
///
/// This function is not marked as `unsafe` as Rust does not guarantee that the
/// `Drop` implementation for a value will always run. Note, however, that
/// leaking resources such as memory or I/O objects is likely not desired, so
/// this function is only recommended for specialized use cases.
///
/// The safety of this function implies that when writing `unsafe` code
/// yourself care must be taken when leveraging a destructor that is required to
/// run to preserve memory safety. There are known situations where the
/// destructor may not run (such as if ownership of the object with the
/// destructor is returned) which must be taken into account.
/// `forget` is not marked as `unsafe`, because Rust's safety guarantees
/// do not include a guarantee that destructors will always run. For example,
/// a program can create a reference cycle using [`Rc`][rc], or call
/// [`process:exit`][exit] to exit without running destructors. Thus, allowing
/// `mem::forget` from safe code does not fundamentally change Rust's safety
/// guarantees.
///
/// # Other forms of Leakage
/// That said, leaking resources such as memory or I/O objects is usually undesirable,
/// so `forget` is only recommended for specialized use cases like those shown below.
///
/// It's important to point out that this function is not the only method by
/// which a value can be leaked in safe Rust code. Other known sources of
/// leakage are:
/// Because forgetting a value is allowed, any `unsafe` code you write must
/// allow for this possibility. You cannot return a value and expect that the
/// caller will necessarily run the value's destructor.
///
/// * `Rc` and `Arc` cycles
/// * `mpsc::{Sender, Receiver}` cycles (they use `Arc` internally)
/// * Panicking destructors are likely to leak local resources
/// [rc]: ../../std/rc/struct.Rc.html
/// [exit]: ../../std/process/fn.exit.html
///
/// # Example
/// # Examples
///
/// Leak some heap memory by never deallocating it:
///
/// ```rust
/// ```
/// use std::mem;
///
/// let heap_memory = Box::new(3);
......@@ -77,7 +62,7 @@
///
/// Leak an I/O object, never closing the file:
///
/// ```rust,no_run
/// ```no_run
/// use std::mem;
/// use std::fs::File;
///
......@@ -85,9 +70,43 @@
/// mem::forget(file);
/// ```
///
/// The `mem::swap` function uses `mem::forget` to good effect:
/// The practical use cases for `forget` are rather specialized and mainly come
/// up in unsafe or FFI code.
///
/// ## Use case 1
///
/// You have created an uninitialized value using [`mem::uninitialized`][uninit].
/// You must either initialize or `forget` it on every computation path before
/// Rust drops it automatically, like at the end of a scope or after a panic.
/// Running the destructor on an uninitialized value would be [undefined behavior][ub].
///
/// ```
/// use std::mem;
/// use std::ptr;
///
/// # let some_condition = false;
/// unsafe {
/// let mut uninit_vec: Vec<u32> = mem::uninitialized();
///
/// if some_condition {
/// // Initialize the variable.
/// ptr::write(&mut uninit_vec, Vec::new());
/// } else {
/// // Forget the uninitialized value so its destructor doesn't run.
/// mem::forget(uninit_vec);
/// }
/// }
/// ```
///
/// ## Use case 2
///
/// You have duplicated the bytes making up a value, without doing a proper
/// [`Clone`][clone]. You need the value's destructor to run only once,
/// because a double `free` is undefined behavior.
///
/// ```rust
/// An example is the definition of [`mem::swap`][swap] in this module:
///
/// ```
/// use std::mem;
/// use std::ptr;
///
......@@ -109,6 +128,41 @@
/// }
/// }
/// ```
///
/// ## Use case 3
///
/// You are transferring ownership across a [FFI] boundary to code written in
/// another language. You need to `forget` the value on the Rust side because Rust
/// code is no longer responsible for it.
///
/// ```no_run
/// use std::mem;
///
/// extern "C" {
/// fn my_c_function(x: *const u32);
/// }
///
/// let x: Box<u32> = Box::new(3);
///
/// // Transfer ownership into C code.
/// unsafe {
/// my_c_function(&*x);
/// }
/// mem::forget(x);
/// ```
///
/// In this case, C code must call back into Rust to free the object. Calling C's `free`
/// function on a [`Box`][box] is *not* safe! Also, `Box` provides an [`into_raw`][into_raw]
/// method which is the preferred way to do this in practice.
///
/// [drop]: fn.drop.html
/// [uninit]: fn.uninitialized.html
/// [clone]: ../clone/trait.Clone.html
/// [swap]: fn.swap.html
/// [FFI]: ../../book/ffi.html
/// [box]: ../../std/boxed/struct.Box.html
/// [into_raw]: ../../std/boxed/struct.Box.html#method.into_raw
/// [ub]: ../../reference.html#behavior-considered-undefined
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn forget<T>(t: T) {
......@@ -133,7 +187,14 @@ pub fn size_of<T>() -> usize {
unsafe { intrinsics::size_of::<T>() }
}
/// Returns the size of the given value in bytes.
/// Returns the size of the pointed-to value in bytes.
///
/// This is usually the same as `size_of::<T>()`. However, when `T` *has* no
/// statically known size, e.g. a slice [`[T]`][slice] or a [trait object],
/// then `size_of_val` can be used to get the dynamically-known size.
///
/// [slice]: ../../std/primitive.slice.html
/// [trait object]: ../../book/trait-objects.html
///
/// # Examples
///
......@@ -141,6 +202,10 @@ pub fn size_of<T>() -> usize {
/// use std::mem;
///
/// assert_eq!(4, mem::size_of_val(&5i32));
///
/// let x: [u8; 13] = [0; 13];
/// let y: &[u8] = &x;
/// assert_eq!(13, mem::size_of_val(y));
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
......@@ -148,10 +213,14 @@ pub fn size_of_val<T: ?Sized>(val: &T) -> usize {
unsafe { intrinsics::size_of_val(val) }
}
/// Returns the ABI-required minimum alignment of a type
/// Returns the [ABI]-required minimum alignment of a type.
///
/// Every valid address of a value of the type `T` must be a multiple of this number.
///
/// This is the alignment used for struct fields. It may be smaller than the preferred alignment.
///
/// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
///
/// # Examples
///
/// ```
......@@ -167,7 +236,11 @@ pub fn min_align_of<T>() -> usize {
unsafe { intrinsics::min_align_of::<T>() }
}
/// Returns the ABI-required minimum alignment of the type of the value that `val` points to
/// Returns the [ABI]-required minimum alignment of the type of the value that `val` points to.
///
/// Every valid address of a value of the type `T` must be a multiple of this number.
///
/// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
///
/// # Examples
///
......@@ -184,10 +257,14 @@ pub fn min_align_of_val<T: ?Sized>(val: &T) -> usize {
unsafe { intrinsics::min_align_of_val(val) }
}
/// Returns the alignment in memory for a type.
/// Returns the [ABI]-required minimum alignment of a type.
///
/// Every valid address of a value of the type `T` must be a multiple of this number.
///
/// This is the alignment used for struct fields. It may be smaller than the preferred alignment.
///
/// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
///
/// # Examples
///
/// ```
......@@ -201,7 +278,11 @@ pub fn align_of<T>() -> usize {
unsafe { intrinsics::min_align_of::<T>() }
}
/// Returns the ABI-required minimum alignment of the type of the value that `val` points to
/// Returns the [ABI]-required minimum alignment of the type of the value that `val` points to.
///
/// Every valid address of a value of the type `T` must be a multiple of this number.
///
/// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface
///
/// # Examples
///
......@@ -216,16 +297,23 @@ pub fn align_of_val<T: ?Sized>(val: &T) -> usize {
unsafe { intrinsics::min_align_of_val(val) }
}
/// Creates a value initialized to zero.
/// Creates a value whose bytes are all zero.
///
/// This has the same effect as allocating space with
/// [`mem::uninitialized`][uninit] and then zeroing it out. It is useful for
/// [FFI] sometimes, but should generally be avoided.
///
/// This function is similar to allocating space for a local variable and zeroing it out (an unsafe
/// operation).
/// There is no guarantee that an all-zero byte-pattern represents a valid value of
/// some type `T`. If `T` has a destructor and the value is destroyed (due to
/// a panic or the end of a scope) before being initialized, then the destructor
/// will run on zeroed data, likely leading to [undefined behavior][ub].
///
/// Care must be taken when using this function, if the type `T` has a destructor and the value
/// falls out of scope (due to unwinding or returning) before being initialized, then the
/// destructor will run on zeroed data, likely leading to crashes.
/// See also the documentation for [`mem::uninitialized`][uninit], which has
/// many of the same caveats.
///
/// This is useful for FFI functions sometimes, but should generally be avoided.
/// [uninit]: fn.uninitialized.html
/// [FFI]: ../../book/ffi.html
/// [ub]: ../../reference.html#behavior-considered-undefined
///
/// # Examples
///
......@@ -233,6 +321,7 @@ pub fn align_of_val<T: ?Sized>(val: &T) -> usize {
/// use std::mem;
///
/// let x: i32 = unsafe { mem::zeroed() };
/// assert_eq!(0, x);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
......@@ -241,32 +330,38 @@ pub unsafe fn zeroed<T>() -> T {
}
/// Bypasses Rust's normal memory-initialization checks by pretending to
/// produce a value of type T, while doing nothing at all.
/// produce a value of type `T`, while doing nothing at all.
///
/// **This is incredibly dangerous, and should not be done lightly. Deeply
/// consider initializing your memory with a default value instead.**
///
/// This is useful for FFI functions and initializing arrays sometimes,
/// This is useful for [FFI] functions and initializing arrays sometimes,
/// but should generally be avoided.
///
/// # Undefined Behavior
/// [FFI]: ../../book/ffi.html
///
/// It is Undefined Behavior to read uninitialized memory. Even just an
/// # Undefined behavior
///
/// It is [undefined behavior][ub] to read uninitialized memory, even just an
/// uninitialized boolean. For instance, if you branch on the value of such
/// a boolean your program may take one, both, or neither of the branches.
/// a boolean, your program may take one, both, or neither of the branches.
///
/// Note that this often also includes *writing* to the uninitialized value.
/// Rust believes the value is initialized, and will therefore try to Drop
/// the uninitialized value and its fields if you try to overwrite the memory
/// in a normal manner. The only way to safely initialize an arbitrary
/// uninitialized value is with one of the `ptr` functions: `write`, `copy`, or
/// `copy_nonoverlapping`. This isn't necessary if `T` is a primitive
/// or otherwise only contains types that don't implement Drop.
/// Writing to the uninitialized value is similarly dangerous. Rust believes the
/// value is initialized, and will therefore try to [`Drop`][drop] the uninitialized
/// value and its fields if you try to overwrite it in a normal manner. The only way
/// to safely initialize an uninitialized value is with [`ptr::write`][write],
/// [`ptr::copy`][copy], or [`ptr::copy_nonoverlapping`][copy_no].
///
/// If this value *does* need some kind of Drop, it must be initialized before
/// If the value does implement `Drop`, it must be initialized before
/// it goes out of scope (and therefore would be dropped). Note that this
/// includes a `panic` occurring and unwinding the stack suddenly.
///
/// [ub]: ../../reference.html#behavior-considered-undefined
/// [write]: ../ptr/fn.write.html
/// [copy]: ../intrinsics/fn.copy.html
/// [copy_no]: ../intrinsics/fn.copy_nonoverlapping.html
/// [drop]: ../ops/trait.Drop.html
///
/// # Examples
///
/// Here's how to safely initialize an array of `Vec`s.
......@@ -309,8 +404,8 @@ pub unsafe fn zeroed<T>() -> T {
/// println!("{:?}", &data[0]);
/// ```
///
/// This example emphasizes exactly how delicate and dangerous doing this is.
/// Note that the `vec!` macro *does* let you initialize every element with a
/// This example emphasizes exactly how delicate and dangerous using `mem::uninitialized`
/// can be. Note that the `vec!` macro *does* let you initialize every element with a
/// value that is only `Clone`, so the following is semantically equivalent and
/// vastly less dangerous, as long as you can live with an extra heap
/// allocation:
......@@ -325,21 +420,20 @@ pub unsafe fn uninitialized<T>() -> T {
intrinsics::uninit()
}
/// Swap the values at two mutable locations of the same type, without deinitializing or copying
/// either one.
/// Swaps the values at two mutable locations, without deinitializing either one.
///
/// # Examples
///
/// ```
/// use std::mem;
///
/// let x = &mut 5;
/// let y = &mut 42;
/// let mut x = 5;
/// let mut y = 42;
///
/// mem::swap(x, y);
/// mem::swap(&mut x, &mut y);
///
/// assert_eq!(42, *x);
/// assert_eq!(5, *y);
/// assert_eq!(42, x);
/// assert_eq!(5, y);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
......@@ -361,10 +455,7 @@ pub fn swap<T>(x: &mut T, y: &mut T) {
}
/// Replaces the value at a mutable location with a new one, returning the old value, without
/// deinitializing or copying either one.
///
/// This is primarily used for transferring and swapping ownership of a value in a mutable
/// location.
/// deinitializing either one.
///
/// # Examples
///
......@@ -373,15 +464,17 @@ pub fn swap<T>(x: &mut T, y: &mut T) {
/// ```
/// use std::mem;
///
/// let mut v: Vec<i32> = Vec::new();
/// let mut v: Vec<i32> = vec![1, 2];
///
/// mem::replace(&mut v, Vec::new());
/// let old_v = mem::replace(&mut v, vec![3, 4, 5]);
/// assert_eq!(2, old_v.len());
/// assert_eq!(3, v.len());
/// ```
///
/// This function allows consumption of one field of a struct by replacing it with another value.
/// The normal approach doesn't always work:
/// `replace` allows consumption of a struct field by replacing it with another value.
/// Without `replace` you can run into issues like these:
///
/// ```rust,ignore
/// ```ignore
/// struct Buffer<T> { buf: Vec<T> }
///
/// impl<T> Buffer<T> {
......@@ -401,6 +494,7 @@ pub fn swap<T>(x: &mut T, y: &mut T) {
/// ```
/// # #![allow(dead_code)]
/// use std::mem;
///
/// # struct Buffer<T> { buf: Vec<T> }
/// impl<T> Buffer<T> {
/// fn get_and_reset(&mut self) -> Vec<T> {
......@@ -417,14 +511,25 @@ pub fn replace<T>(dest: &mut T, mut src: T) -> T {
/// Disposes of a value.
///
/// While this does call the argument's implementation of `Drop`, it will not
/// release any borrows, as borrows are based on lexical scope.
/// While this does call the argument's implementation of [`Drop`][drop],
/// it will not release any borrows, as borrows are based on lexical scope.
///
/// This effectively does nothing for
/// [types which implement `Copy`](../../book/ownership.html#copy-types),
/// e.g. integers. Such values are copied and _then_ moved into the function,
/// so the value persists after this function call.
///
/// This function is not magic; it is literally defined as
///
/// ```
/// pub fn drop<T>(_x: T) { }
/// ```
///
/// Because `_x` is moved into the function, it is automatically dropped before
/// the function returns.
///
/// [drop]: ../ops/trait.Drop.html
///
/// # Examples
///
/// Basic usage:
......@@ -461,8 +566,8 @@ pub fn replace<T>(dest: &mut T, mut src: T) -> T {
/// v.push(4); // no problems
/// ```
///
/// Since `RefCell` enforces the borrow rules at runtime, `drop()` can
/// seemingly release a borrow of one:
/// Since `RefCell` enforces the borrow rules at runtime, `drop` can
/// release a `RefCell` borrow:
///
/// ```
/// use std::cell::RefCell;
......@@ -478,7 +583,7 @@ pub fn replace<T>(dest: &mut T, mut src: T) -> T {
/// println!("{}", *borrow);
/// ```
///
/// Integers and other types implementing `Copy` are unaffected by `drop()`
/// Integers and other types implementing `Copy` are unaffected by `drop`.
///
/// ```
/// #[derive(Copy, Clone)]
......@@ -496,19 +601,22 @@ pub fn replace<T>(dest: &mut T, mut src: T) -> T {
#[stable(feature = "rust1", since = "1.0.0")]
pub fn drop<T>(_x: T) { }
/// Interprets `src` as `&U`, and then reads `src` without moving the contained
/// value.
/// Interprets `src` as having type `&U`, and then reads `src` without moving
/// the contained value.
///
/// This function will unsafely assume the pointer `src` is valid for
/// `sizeof(U)` bytes by transmuting `&T` to `&U` and then reading the `&U`. It
/// will also unsafely create a copy of the contained value instead of moving
/// out of `src`.
/// [`size_of::<U>()`][size_of] bytes by transmuting `&T` to `&U` and then reading
/// the `&U`. It will also unsafely create a copy of the contained value instead of
/// moving out of `src`.
///
/// It is not a compile-time error if `T` and `U` have different sizes, but it
/// is highly encouraged to only invoke this function where `T` and `U` have the
/// same size. This function triggers undefined behavior if `U` is larger than
/// same size. This function triggers [undefined behavior][ub] if `U` is larger than
/// `T`.
///
/// [ub]: ../../reference.html#behavior-considered-undefined
/// [size_of]: fn.size_of.html
///
/// # Examples
///
/// ```
......
......@@ -410,10 +410,13 @@ fn check_exhaustive<'a, 'tcx>(cx: &MatchCheckCtxt<'a, 'tcx>,
},
_ => bug!(),
};
span_err!(cx.tcx.sess, sp, E0297,
let pattern_string = pat_to_string(witness);
struct_span_err!(cx.tcx.sess, sp, E0297,
"refutable pattern in `for` loop binding: \
`{}` not covered",
pat_to_string(witness));
pattern_string)
.span_label(sp, &format!("pattern `{}` not covered", pattern_string))
.emit();
},
_ => {
let pattern_strings: Vec<_> = witnesses.iter().map(|w| {
......
......@@ -468,8 +468,7 @@ fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.panicked = false;
r
} else {
let amt = cmp::min(buf.len(), self.buf.capacity());
Write::write(&mut self.buf, &buf[..amt])
Write::write(&mut self.buf, buf)
}
}
fn flush(&mut self) -> io::Result<()> {
......
......@@ -249,37 +249,58 @@ mod prim_pointer { }
#[doc(primitive = "array")]
//
/// A fixed-size array, denoted `[T; N]`, for the element type, `T`, and the
/// non-negative compile time constant size, `N`.
/// non-negative compile-time constant size, `N`.
///
/// Arrays values are created either with an explicit expression that lists
/// each element: `[x, y, z]` or a repeat expression: `[x; N]`. The repeat
/// expression requires that the element type is `Copy`.
/// There are two syntactic forms for creating an array:
///
/// The type `[T; N]` is `Copy` if `T: Copy`.
/// * A list with each element, i.e. `[x, y, z]`.
/// * A repeat expression `[x; N]`, which produces an array with `N` copies of `x`.
/// The type of `x` must be [`Copy`][copy].
///
/// Arrays of sizes from 0 to 32 (inclusive) implement the following traits if
/// the element type allows it:
///
/// - `Clone` (only if `T: Copy`)
/// - `Debug`
/// - `IntoIterator` (implemented for `&[T; N]` and `&mut [T; N]`)
/// - `PartialEq`, `PartialOrd`, `Ord`, `Eq`
/// - `Hash`
/// - `AsRef`, `AsMut`
/// - `Borrow`, `BorrowMut`
/// - `Default`
///
/// This limitation to `N in 0..33` exists because Rust does not yet support
/// generics over the size of an array type. `[Foo; 3]` and `[Bar; 3]` are
/// instances of same generic type `[T; 3]`, but `[Foo; 3]` and `[Foo; 5]` are
/// - [`Clone`][clone] (only if `T: Copy`)
/// - [`Debug`][debug]
/// - [`IntoIterator`][intoiterator] (implemented for `&[T; N]` and `&mut [T; N]`)
/// - [`PartialEq`][partialeq], [`PartialOrd`][partialord], [`Eq`][eq], [`Ord`][ord]
/// - [`Hash`][hash]
/// - [`AsRef`][asref], [`AsMut`][asmut]
/// - [`Borrow`][borrow], [`BorrowMut`][borrowmut]
/// - [`Default`][default]
///
/// This limitation on the size `N` exists because Rust does not yet support
/// code that is generic over the size of an array type. `[Foo; 3]` and `[Bar; 3]`
/// are instances of same generic type `[T; 3]`, but `[Foo; 3]` and `[Foo; 5]` are
/// entirely different types. As a stopgap, trait implementations are
/// statically generated for `N in 0..33`.
/// statically generated up to size 32.
///
/// Arrays coerce to [slices (`[T]`)][slice], so their methods can be called on
/// arrays. Slices are dynamic and do not coerce to arrays; consequently more
/// methods are defined on `slice` where they support both types.
/// Arrays of *any* size are [`Copy`][copy] if the element type is `Copy`. This
/// works because the `Copy` trait is specially known to the compiler.
///
/// Arrays coerce to [slices (`[T]`)][slice], so a slice method may be called on
/// an array. Indeed, this provides most of the API for working with arrays.
/// Slices have a dynamic size and do not coerce to arrays.
///
/// There is no way to move elements out of an array. See [`mem::replace`][replace]
/// for an alternative.
///
/// [slice]: primitive.slice.html
/// [copy]: marker/trait.Copy.html
/// [clone]: clone/trait.Clone.html
/// [debug]: fmt/trait.Debug.html
/// [intoiterator]: iter/trait.IntoIterator.html
/// [partialeq]: cmp/trait.PartialEq.html
/// [partialord]: cmp/trait.PartialOrd.html
/// [eq]: cmp/trait.Eq.html
/// [ord]: cmp/trait.Ord.html
/// [hash]: hash/trait.Hash.html
/// [asref]: convert/trait.AsRef.html
/// [asmut]: convert/trait.AsMut.html
/// [borrow]: borrow/trait.Borrow.html
/// [borrowmut]: borrow/trait.BorrowMut.html
/// [default]: default/trait.Default.html
/// [replace]: mem/fn.replace.html
///
/// # Examples
///
......@@ -295,7 +316,30 @@ mod prim_pointer { }
/// for x in &array {
/// print!("{} ", x);
/// }
/// ```
///
/// An array itself is not iterable:
///
/// ```ignore
/// let array: [i32; 3] = [0; 3];
///
/// for x in array { }
/// // error: the trait bound `[i32; 3]: std::iter::Iterator` is not satisfied
/// ```
///
/// The solution is to coerce the array to a slice by calling a slice method:
///
/// ```
/// # let array: [i32; 3] = [0; 3];
/// for x in array.iter() { }
/// ```
///
/// If the array has 32 or fewer elements (see above), you can also use the
/// array reference's `IntoIterator` implementation:
///
/// ```
/// # let array: [i32; 3] = [0; 3];
/// for x in &array { }
/// ```
///
mod prim_array { }
......
......@@ -11,5 +11,7 @@
fn main() {
let xs : Vec<Option<i32>> = vec!(Some(1), None);
for Some(x) in xs {} //~ ERROR E0297
for Some(x) in xs {}
//~^ ERROR E0297
//~| NOTE pattern `None` not covered
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册