Commit a754dcb1 authored by Mateusz Mikuła's avatar Mateusz Mikuła
Browse files

Cargo fmt

parent 6b59fa4b
......@@ -3,79 +3,103 @@ extern crate rustc_version;
use std::env;
use std::fs::File;
use std::io::Write;
use std::ops::{Neg, Sub};
use std::path::PathBuf;
use std::ops::{Neg,Sub};
/*
* Let me explain this hack. For the sync shell script it's easiest if every
* line in mapping.rs looks exactly the same. This means that specifying an
* array literal is not possible. include!() can only expand to expressions, so
* Let me explain this hack. For the sync shell script it's easiest if every
* line in mapping.rs looks exactly the same. This means that specifying an
* array literal is not possible. include!() can only expand to expressions, so
* just specifying the contents of an array is also not possible.
*
* This leaves us with trying to find an expression in which every line looks
* the same. This can be done using the `-` operator. This can be a unary
* operator (first thing on the first line), or a binary operator (later
* lines). That is exactly what's going on here, and Neg and Sub simply build a
* This leaves us with trying to find an expression in which every line looks
* the same. This can be done using the `-` operator. This can be a unary
* operator (first thing on the first line), or a binary operator (later
* lines). That is exactly what's going on here, and Neg and Sub simply build a
* vector of the operangs.
*/
struct Mapping(&'static str,&'static str);
struct Mapping(&'static str, &'static str);
impl Neg for Mapping {
type Output = Vec<Mapping>;
type Output = Vec<Mapping>;
fn neg(self) -> Vec<Mapping> {
vec![self.into()]
}
vec![self.into()]
}
}
impl Sub<Mapping> for Vec<Mapping> {
type Output=Vec<Mapping>;
type Output = Vec<Mapping>;
fn sub(mut self, rhs: Mapping) -> Vec<Mapping> {
self.push(rhs.into());
self
}
self.push(rhs.into());
self
}
}
fn main() {
let ver=rustc_version::version_meta();
let ver = rustc_version::version_meta();
let io_commit="b9adc3327ec7d2820ab2db8bb3cc2a0196a8375d";
/*
let io_commit=match env::var("CORE_IO_COMMIT") {
Ok(c) => c,
Err(env::VarError::NotUnicode(_)) => panic!("Invalid commit specified in CORE_IO_COMMIT"),
Err(env::VarError::NotPresent) => {
let mappings=include!("mapping.rs");
let compiler=ver.commit_hash.expect("Couldn't determine compiler version");
mappings.iter().find(|&&Mapping(elem,_)|elem==compiler).expect("Unknown compiler version, upgrade core_io?").1.to_owned()
}
};
*/
let io_commit = "b9adc3327ec7d2820ab2db8bb3cc2a0196a8375d";
/*
let io_commit=match env::var("CORE_IO_COMMIT") {
Ok(c) => c,
Err(env::VarError::NotUnicode(_)) => panic!("Invalid commit specified in CORE_IO_COMMIT"),
Err(env::VarError::NotPresent) => {
let mappings=include!("mapping.rs");
if ver.commit_date.as_ref().map_or(true,|d| &**d>="2018-01-01") {
println!("cargo:rustc-cfg=core_memchr");
}
let compiler=ver.commit_hash.expect("Couldn't determine compiler version");
mappings.iter().find(|&&Mapping(elem,_)|elem==compiler).expect("Unknown compiler version, upgrade core_io?").1.to_owned()
}
};
*/
if ver.commit_date.as_ref().map_or(true,|d| &**d>="2017-06-15") {
println!("cargo:rustc-cfg=no_collections");
}
if ver
.commit_date
.as_ref()
.map_or(true, |d| &**d >= "2018-01-01")
{
println!("cargo:rustc-cfg=core_memchr");
}
if ver.commit_date.as_ref().map_or(false,|d| &**d<"2016-12-15") {
println!("cargo:rustc-cfg=rustc_unicode");
} else if ver.commit_date.as_ref().map_or(false,|d| &**d<"2017-03-03") {
println!("cargo:rustc-cfg=std_unicode");
}
if ver
.commit_date
.as_ref()
.map_or(true, |d| &**d >= "2017-06-15")
{
println!("cargo:rustc-cfg=no_collections");
}
let mut dest_path=PathBuf::from(env::var_os("OUT_DIR").unwrap());
dest_path.push("io.rs");
let mut f=File::create(&dest_path).unwrap();
let mut target_path=PathBuf::from(env::var_os("CARGO_MANIFEST_DIR").unwrap());
target_path.push("src");
target_path.push(io_commit);
target_path.push("mod.rs");
if ver
.commit_date
.as_ref()
.map_or(false, |d| &**d < "2016-12-15")
{
println!("cargo:rustc-cfg=rustc_unicode");
} else if ver
.commit_date
.as_ref()
.map_or(false, |d| &**d < "2017-03-03")
{
println!("cargo:rustc-cfg=std_unicode");
}
f.write_all(br#"#[path=""#).unwrap();
f.write_all(target_path.into_os_string().into_string().unwrap().replace("\\", "\\\\").as_bytes()).unwrap();
f.write_all(br#""] mod io;"#).unwrap();
let mut dest_path = PathBuf::from(env::var_os("OUT_DIR").unwrap());
dest_path.push("io.rs");
let mut f = File::create(&dest_path).unwrap();
let mut target_path = PathBuf::from(env::var_os("CARGO_MANIFEST_DIR").unwrap());
target_path.push("src");
target_path.push(io_commit);
target_path.push("mod.rs");
f.write_all(br#"#[path=""#).unwrap();
f.write_all(
target_path
.into_os_string()
.into_string()
.unwrap()
.replace("\\", "\\\\")
.as_bytes(),
)
.unwrap();
f.write_all(br#""] mod io;"#).unwrap();
}
......@@ -15,9 +15,9 @@ use io::prelude::*;
use core::cmp;
use core::fmt;
use io::{self, Initializer, DEFAULT_BUF_SIZE, Error, ErrorKind, SeekFrom};
use io::memchr;
use io::memchr;
use io::{self, Error, ErrorKind, Initializer, SeekFrom, DEFAULT_BUF_SIZE};
/// The `BufReader` struct adds buffering to any reader.
///
/// It can be excessively inefficient to work directly with a [`Read`] instance.
......@@ -127,7 +127,9 @@ impl<R: Read> BufReader<R> {
/// Ok(())
/// }
/// ```
pub fn get_ref(&self) -> &R { &self.inner }
pub fn get_ref(&self) -> &R {
&self.inner
}
/// Gets a mutable reference to the underlying reader.
///
......@@ -147,7 +149,9 @@ impl<R: Read> BufReader<R> {
/// Ok(())
/// }
/// ```
pub fn get_mut(&mut self) -> &mut R { &mut self.inner }
pub fn get_mut(&mut self) -> &mut R {
&mut self.inner
}
/// Returns a reference to the internally buffered data.
///
......@@ -193,7 +197,9 @@ impl<R: Read> BufReader<R> {
/// Ok(())
/// }
/// ```
pub fn into_inner(self) -> R { self.inner }
pub fn into_inner(self) -> R {
self.inner
}
}
impl<R: Seek> BufReader<R> {
......@@ -259,11 +265,17 @@ impl<R: Read> BufRead for BufReader<R> {
}
}
impl<R> fmt::Debug for BufReader<R> where R: fmt::Debug {
impl<R> fmt::Debug for BufReader<R>
where
R: fmt::Debug,
{
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.debug_struct("BufReader")
.field("reader", &self.inner)
.field("buffer", &format_args!("{}/{}", self.cap - self.pos, self.buf.len()))
.field(
"buffer",
&format_args!("{}/{}", self.cap - self.pos, self.buf.len()),
)
.finish()
}
}
......@@ -457,14 +469,18 @@ impl<W: Write> BufWriter<W> {
match r {
Ok(0) => {
ret = Err(Error::new(ErrorKind::WriteZero,
"failed to write the buffered data"));
ret = Err(Error::new(
ErrorKind::WriteZero,
"failed to write the buffered data",
));
break;
}
Ok(n) => written += n,
Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}
Err(e) => { ret = Err(e); break }
Err(e) => {
ret = Err(e);
break;
}
}
}
if written > 0 {
......@@ -486,7 +502,9 @@ impl<W: Write> BufWriter<W> {
/// // we can use reference just like buffer
/// let reference = buffer.get_ref();
/// ```
pub fn get_ref(&self) -> &W { self.inner.as_ref().unwrap() }
pub fn get_ref(&self) -> &W {
self.inner.as_ref().unwrap()
}
/// Gets a mutable reference to the underlying writer.
///
......@@ -503,7 +521,9 @@ impl<W: Write> BufWriter<W> {
/// // we can use reference just like buffer
/// let reference = buffer.get_mut();
/// ```
pub fn get_mut(&mut self) -> &mut W { self.inner.as_mut().unwrap() }
pub fn get_mut(&mut self) -> &mut W {
self.inner.as_mut().unwrap()
}
/// Unwraps this `BufWriter`, returning the underlying writer.
///
......@@ -527,7 +547,7 @@ impl<W: Write> BufWriter<W> {
pub fn into_inner(mut self) -> Result<W, IntoInnerError<BufWriter<W>>> {
match self.flush_buf() {
Err(e) => Err(IntoInnerError(self, e)),
Ok(()) => Ok(self.inner.take().unwrap())
Ok(()) => Ok(self.inner.take().unwrap()),
}
}
}
......@@ -551,11 +571,17 @@ impl<W: Write> Write for BufWriter<W> {
}
}
impl<W: Write> fmt::Debug for BufWriter<W> where W: fmt::Debug {
impl<W: Write> fmt::Debug for BufWriter<W>
where
W: fmt::Debug,
{
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.debug_struct("BufWriter")
.field("writer", &self.inner.as_ref().unwrap())
.field("buffer", &format_args!("{}/{}", self.buf.len(), self.buf.capacity()))
.field(
"buffer",
&format_args!("{}/{}", self.buf.len(), self.buf.capacity()),
)
.finish()
}
}
......@@ -607,7 +633,9 @@ impl<W> IntoInnerError<W> {
/// }
/// };
/// ```
pub fn error(&self) -> &Error { &self.1 }
pub fn error(&self) -> &Error {
&self.1
}
/// Returns the buffered writer instance which generated the error.
///
......@@ -639,11 +667,15 @@ impl<W> IntoInnerError<W> {
/// }
/// };
/// ```
pub fn into_inner(self) -> W { self.0 }
pub fn into_inner(self) -> W {
self.0
}
}
impl<W> From<IntoInnerError<W>> for Error {
fn from(iie: IntoInnerError<W>) -> Error { iie.1 }
fn from(iie: IntoInnerError<W>) -> Error {
iie.1
}
}
impl<W> fmt::Display for IntoInnerError<W> {
......@@ -779,7 +811,9 @@ impl<W: Write> LineWriter<W> {
/// Ok(())
/// }
/// ```
pub fn get_ref(&self) -> &W { self.inner.get_ref() }
pub fn get_ref(&self) -> &W {
self.inner.get_ref()
}
/// Gets a mutable reference to the underlying writer.
///
......@@ -801,7 +835,9 @@ impl<W: Write> LineWriter<W> {
/// Ok(())
/// }
/// ```
pub fn get_mut(&mut self) -> &mut W { self.inner.get_mut() }
pub fn get_mut(&mut self) -> &mut W {
self.inner.get_mut()
}
/// Unwraps this `LineWriter`, returning the underlying writer.
///
......@@ -828,10 +864,13 @@ impl<W: Write> LineWriter<W> {
/// ```
pub fn into_inner(self) -> Result<W, IntoInnerError<LineWriter<W>>> {
self.inner.into_inner().map_err(|IntoInnerError(buf, e)| {
IntoInnerError(LineWriter {
inner: buf,
need_flush: false,
}, e)
IntoInnerError(
LineWriter {
inner: buf,
need_flush: false,
},
e,
)
})
}
}
......@@ -859,7 +898,7 @@ impl<W: Write> Write for LineWriter<W> {
let n = self.inner.write(&buf[..=i])?;
self.need_flush = true;
if self.flush().is_err() || n != i + 1 {
return Ok(n)
return Ok(n);
}
// At this point we successfully wrote `i + 1` bytes and flushed it out,
......@@ -880,12 +919,17 @@ impl<W: Write> Write for LineWriter<W> {
}
}
impl<W: Write> fmt::Debug for LineWriter<W> where W: fmt::Debug {
impl<W: Write> fmt::Debug for LineWriter<W>
where
W: fmt::Debug,
{
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.debug_struct("LineWriter")
.field("writer", &self.inner.inner)
.field("buffer",
&format_args!("{}/{}", self.inner.buf.len(), self.inner.buf.capacity()))
.field(
"buffer",
&format_args!("{}/{}", self.inner.buf.len(), self.inner.buf.capacity()),
)
.finish()
}
}
......@@ -895,9 +939,9 @@ mod tests {
use io::prelude::*;
use io::{self, BufReader, BufWriter, LineWriter, SeekFrom};
use sync::atomic::{AtomicUsize, Ordering};
use thread;
use test;
use test;
use thread;
/// A dummy reader intended at testing short-reads propagation.
pub struct ShortReader {
lengths: Vec<usize>,
......@@ -986,7 +1030,7 @@ mod tests {
fn test_buffered_reader_seek_underflow() {
// gimmick reader that yields its position modulo 256 for each byte
struct PositionReader {
pos: u64
pos: u64,
}
impl Read for PositionReader {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
......@@ -1017,11 +1061,17 @@ mod tests {
let mut reader = BufReader::with_capacity(5, PositionReader { pos: 0 });
assert_eq!(reader.fill_buf().ok(), Some(&[0, 1, 2, 3, 4][..]));
assert_eq!(reader.seek(SeekFrom::End(-5)).ok(), Some(u64::max_value()-5));
assert_eq!(
reader.seek(SeekFrom::End(-5)).ok(),
Some(u64::max_value() - 5)
);
assert_eq!(reader.fill_buf().ok().map(|s| s.len()), Some(5));
// the following seek will require two underlying seeks
let expected = 9223372036854775802;
assert_eq!(reader.seek(SeekFrom::Current(i64::min_value())).ok(), Some(expected));
assert_eq!(
reader.seek(SeekFrom::Current(i64::min_value())).ok(),
Some(expected)
);
assert_eq!(reader.fill_buf().ok().map(|s| s.len()), Some(5));
// seeking to 0 should empty the buffer.
assert_eq!(reader.seek(SeekFrom::Current(0)).ok(), Some(expected));
......@@ -1080,7 +1130,10 @@ mod tests {
assert_eq!(&w.get_ref().get_ref()[..], &[0, 1, 2, 3, 4, 5, 6, 7][..]);
assert_eq!(w.seek(SeekFrom::Start(2)).ok(), Some(2));
w.write_all(&[8, 9]).unwrap();
assert_eq!(&w.into_inner().unwrap().into_inner()[..], &[0, 1, 8, 9, 4, 5, 6, 7]);
assert_eq!(
&w.into_inner().unwrap().into_inner()[..],
&[0, 1, 8, 9, 4, 5, 6, 7]
);
}
#[test]
......@@ -1180,7 +1233,9 @@ mod tests {
#[test]
fn test_short_reads() {
let inner = ShortReader{lengths: vec![0, 1, 2, 0, 1, 0]};
let inner = ShortReader {
lengths: vec![0, 1, 2, 0, 1, 0],
};
let mut reader = BufReader::new(inner);
let mut buf = [0, 0];
assert_eq!(reader.read(&mut buf).unwrap(), 0);
......@@ -1198,7 +1253,9 @@ mod tests {
struct FailFlushWriter;
impl Write for FailFlushWriter {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> { Ok(buf.len()) }
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
Err(io::Error::last_os_error())
}
......@@ -1224,30 +1281,30 @@ mod tests {
WRITES.fetch_add(1, Ordering::SeqCst);
panic!();
}
fn flush(&mut self) -> io::Result<()> { Ok(()) }
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
thread::spawn(|| {
let mut writer = BufWriter::new(PanicWriter);
let _ = writer.write(b"hello world");
let _ = writer.flush();
}).join().unwrap_err();
})
.join()
.unwrap_err();
assert_eq!(WRITES.load(Ordering::SeqCst), 1);
}
#[bench]
fn bench_buffered_reader(b: &mut test::Bencher) {
b.iter(|| {
BufReader::new(io::empty())
});
b.iter(|| BufReader::new(io::empty()));
}
#[bench]
fn bench_buffered_writer(b: &mut test::Bencher) {
b.iter(|| {
BufWriter::new(io::sink())
});
b.iter(|| BufWriter::new(io::sink()));
}
struct AcceptOneThenFail {
......
......@@ -2,48 +2,61 @@
//! This is just a listing of the functionality available in this crate. See
//! the [std documentation](https://doc.rust-lang.org/nightly/std/io/index.html)
//! for a full description of the functionality.
#![allow(stable_features,unused_features)]
#![feature(question_mark,const_fn,copy_from_slice,
try_from,str_internals,align_offset,doc_spotlight,slice_internals)]
#![cfg_attr(feature="alloc",feature(alloc))]
#![allow(stable_features, unused_features)]
#![feature(
question_mark,
const_fn,
copy_from_slice,
try_from,
str_internals,
align_offset,
doc_spotlight,
slice_internals
)]
#![cfg_attr(feature = "alloc", feature(alloc))]
#![no_std]
#[cfg_attr(feature="collections",macro_use)]
#[cfg(all(feature="collections",not(no_collections)))] extern crate collections;
#[cfg_attr(feature="collections",allow(unused_imports))]
#[cfg_attr(feature="collections",macro_use)]
#[cfg(all(feature="collections",no_collections))] extern crate alloc as collections;
#[cfg(feature="alloc")] extern crate alloc;
#[cfg(feature = "alloc")]
extern crate alloc;
#[cfg_attr(feature = "collections", allow(unused_imports))]
#[cfg_attr(feature = "collections", macro_use)]
#[cfg(all(feature = "collections", no_collections))]
extern crate alloc as collections;
#[cfg_attr(feature = "collections", macro_use)]
#[cfg(all(feature = "collections", not(no_collections)))]
extern crate collections;
#[cfg(rustc_unicode)]
extern crate rustc_unicode;
#[cfg(std_unicode)]
extern crate std_unicode;
#[cfg(not(feature="collections"))]
#[cfg(not(feature = "collections"))]
pub type ErrorString = &'static str;
// Provide Box::new wrapper
#[cfg(not(feature="alloc"))]
#[cfg(not(feature = "alloc"))]
struct FakeBox<T>(core::marker::PhantomData<T>);
#[cfg(not(feature="alloc"))]
#[cfg(not(feature = "alloc"))]
impl<T> FakeBox<T> {
fn new(val: T) -> T {
val
}
fn new(val: T) -> T {
val
}
}
// Needed for older compilers, to ignore vec!/format! macros in tests
#[cfg(not(feature="collections"))]
#[cfg(not(feature = "collections"))]
#[allow(unused)]
macro_rules! vec (
( $ elem : expr ; $ n : expr ) => { () };
( $ ( $ x : expr ) , * ) => { () };
( $ ( $ x : expr , ) * ) => { () };
);
#[cfg(not(feature="collections"))]
#[cfg(not(feature = "collections"))]
#[allow(unused)]
macro_rules! format {
( $ ( $ arg : tt ) * ) => { () };
( $ ( $ arg : tt ) * ) => {
()
};
}
include!(concat!(env!("OUT_DIR"), "/io.rs"));
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment