Skip to content

Commit

Permalink
Rustup.
Browse files Browse the repository at this point in the history
This required a couple breaking changes.

Firstly, we've moved to using `rustc_serialize` instead of `serialize`,
since the latter has been deprecated. This requires you to change:

    extern crate serialize;

to

    extern crate "rustc-serialize" as rustc_serialize;

And all instances of `deriving(Decodable)` and `deriving(Encodable)`
to `deriving(RustcDecodable)` and `deriving(RustcEncodable)`,
respectively.

The second breaking change is that several public methods used to
accept `S: StrAllocating`, which allowed you to pass a `String` or
a `&str`. Now that `StrAllocating` has been removed, this has been
switched to `Sized? S: ToOwned<String>`. This requires that `S` is
passed by reference. So change code like this:

    let s: String = String::from_str("hi");
    let mut rdr = csv::Reader::from_string(s);

to this

    let mut rdr = csv::Reader::from_string(&s);

[breaking-change]
  • Loading branch information
BurntSushi committed Dec 24, 2014
1 parent 0b9ecfa commit ea505ae
Show file tree
Hide file tree
Showing 12 changed files with 66 additions and 51 deletions.
3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ license = "Unlicense"
[lib]
name = "csv"

[dependencies]
rustc-serialize = "*"

[profile.bench]
opt-level = 3
lto = true # this doesn't seem to work... why?
4 changes: 2 additions & 2 deletions examples/nfl_plays.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
extern crate csv;
extern crate serialize;
extern crate "rustc-serialize" as rustc_serialize;

use std::path::Path;

#[allow(dead_code)]
#[deriving(Decodable)]
#[deriving(RustcDecodable)]
struct Play {
gameid: String,
qtr: uint,
Expand Down
4 changes: 2 additions & 2 deletions examples/simple_missing.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
extern crate csv;
extern crate serialize;
extern crate "rustc-serialize" as rustc_serialize;

use std::path::Path;

#[deriving(Decodable)]
#[deriving(RustcDecodable)]
struct Record {
s1: String,
s2: String,
Expand Down
4 changes: 2 additions & 2 deletions examples/simple_struct.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
extern crate csv;
extern crate serialize;
extern crate "rustc-serialize" as rustc_serialize;

use std::path::Path;

#[deriving(Decodable)]
#[deriving(RustcDecodable)]
struct Record {
s1: String,
s2: String,
Expand Down
2 changes: 1 addition & 1 deletion src/bench.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ fn string_records(b: &mut Bencher) {
}

#[allow(dead_code)]
#[deriving(Decodable)]
#[deriving(RustcDecodable)]
struct Play {
gameid: String,
qtr: int,
Expand Down
6 changes: 4 additions & 2 deletions src/bytestr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ impl IntoVector<u8> for ByteString {
}

impl<'a> IntoVector<u8> for &'a str {
fn into_vec(self) -> Vec<u8> { self.into_string().into_bytes() }
fn into_vec(self) -> Vec<u8> { self.to_owned().into_bytes() }
}

impl<'a> IntoVector<u8> for String {
Expand Down Expand Up @@ -114,7 +114,9 @@ impl ByteString {
/// Consumes the byte string and decodes it into a Unicode string. If the
/// decoding fails, then the original ByteString is returned.
pub fn into_utf8_string(self) -> Result<String, ByteString> {
String::from_utf8(self.into_bytes()).map_err(ByteString)
// FIXME: Figure out how to return an error here.
String::from_utf8(self.into_bytes())
.map_err(|(bytes, _)| ByteString(bytes))
}

/// Return the number of bytes in the string.
Expand Down
22 changes: 12 additions & 10 deletions src/decoder.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
use std::borrow::ToOwned;
use std::default::Default;
use std::str::FromStr;

use serialize;
use rustc_serialize as serialize;

use {ByteString, CsvResult, Error};

Expand Down Expand Up @@ -33,7 +34,7 @@ impl Decoded {
fn pop(&mut self) -> CsvResult<ByteString> {
self.popped += 1;
match self.stack.pop() {
None => self.err(format!(
None => self.err(&format!(
"Expected a record with length at least {}, \
but got a record with length {}.",
self.popped, self.popped - 1)),
Expand All @@ -53,7 +54,7 @@ impl Decoded {
let s = s.as_slice().trim();
match FromStr::from_str(s) {
Some(t) => Ok(t),
None => self.err(format!("Failed converting '{}' from str.", s)),
None => self.err(&format!("Failed converting '{}' from str.", s)),
}
}

Expand All @@ -65,14 +66,15 @@ impl Decoded {
self.push(ByteString::from_bytes(s.into_bytes()));
}

fn err<T, S: StrAllocating>(&self, msg: S) -> CsvResult<T> {
Err(Error::Decode(msg.into_string()))
fn err<T, Sized? S>(&self, msg: &S) -> CsvResult<T>
where S: ToOwned<String> {
Err(Error::Decode(msg.to_owned()))
}
}

impl serialize::Decoder<Error> for Decoded {
fn error(&mut self, err: &str) -> Error {
Error::Decode(err.into_string())
Error::Decode(err.to_owned())
}
fn read_nil(&mut self) -> CsvResult<()> { unimplemented!() }
fn read_uint(&mut self) -> CsvResult<uint> { self.pop_from_str() }
Expand All @@ -92,7 +94,7 @@ impl serialize::Decoder<Error> for Decoded {
let s = try!(self.pop_string());
let chars: Vec<char> = s.as_slice().chars().collect();
if chars.len() != 1 {
return self.err(format!(
return self.err(&format!(
"Expected single character but got '{}'.", s))
}
Ok(chars[0])
Expand All @@ -115,7 +117,7 @@ impl serialize::Decoder<Error> for Decoded {
Err(_) => { self.push_string(cur); }
}
}
self.err(format!(
self.err(&format!(
"Could not load value into any variant in {}", names))
}
fn read_enum_variant_arg<T, F>(&mut self, _: uint, f: F) -> CsvResult<T>
Expand All @@ -138,8 +140,8 @@ impl serialize::Decoder<Error> for Decoded {
where F: FnOnce(&mut Decoded) -> CsvResult<T> {
if self.len() < len {
return self.err(
format!("Struct '{}' has {} fields but current record \
has {} fields.", s_name, len, self.len()));
&format!("Struct '{}' has {} fields but current record \
has {} fields.", s_name, len, self.len()));
}
f(self)
}
Expand Down
17 changes: 9 additions & 8 deletions src/encoder.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::fmt;
use std::borrow::ToOwned;

use serialize;
use rustc_serialize as serialize;

use {ByteString, CsvResult, Error, IntoVector};

Expand Down Expand Up @@ -29,12 +29,13 @@ impl Encoded {
Ok(())
}

fn push_string<S: StrAllocating>(&mut self, s: S) -> CsvResult<()> {
self.push_bytes(s.into_string().into_bytes())
fn push_string<Sized? S>(&mut self, s: &S) -> CsvResult<()>
where S: ToOwned<String> {
self.push_bytes(s.to_owned().into_bytes())
}

fn push_to_string<T: fmt::Show>(&mut self, t: T) -> CsvResult<()> {
self.push_string(t.to_string())
fn push_to_string<T: ToString>(&mut self, t: T) -> CsvResult<()> {
self.push_string(&t.to_string())
}
}

Expand All @@ -56,10 +57,10 @@ impl serialize::Encoder<Error> for Encoded {
self.push_to_string(v)
}
fn emit_f64(&mut self, v: f64) -> CsvResult<()> {
self.push_string(::std::f64::to_str_digits(v, 10))
self.push_string(&::std::f64::to_str_digits(v, 10))
}
fn emit_f32(&mut self, v: f32) -> CsvResult<()> {
self.push_string(::std::f32::to_str_digits(v, 10))
self.push_string(&::std::f32::to_str_digits(v, 10))
}
fn emit_char(&mut self, v: char) -> CsvResult<()> {
let mut bytes = [0u8, ..4];
Expand Down
3 changes: 2 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -182,9 +182,10 @@
//! while providing an outlet to use byte strings.

extern crate rand;
extern crate serialize;
extern crate "test" as stdtest;

extern crate "rustc-serialize" as rustc_serialize;

use std::error::Error as StdError;
use std::error::FromError;
use std::fmt;
Expand Down
29 changes: 16 additions & 13 deletions src/reader.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::borrow::ToOwned;
use std::io::{mod, MemReader};

use serialize::Decodable;
use rustc_serialize::Decodable;

use buffered::BufferedReader;
use {
Expand Down Expand Up @@ -168,8 +169,9 @@ impl Reader<io::IoResult<io::File>> {

impl Reader<MemReader> {
/// Creates a CSV reader for an in memory string buffer.
pub fn from_string<S: StrAllocating>(s: S) -> Reader<MemReader> {
Reader::from_bytes(s.into_string().into_bytes())
pub fn from_string<Sized? S>(s: &S) -> Reader<MemReader>
where S: ToOwned<String> {
Reader::from_bytes(s.to_owned().into_bytes())
}

/// Creates a CSV reader for an in memory buffer of bytes.
Expand Down Expand Up @@ -198,11 +200,11 @@ impl<R: io::Reader> Reader<R> {
/// currently, the *names* of the struct members are irrelevant.)
///
/// ```rust
/// extern crate serialize;
/// extern crate "rustc-serialize" as rustc_serialize;
/// # extern crate csv;
/// # fn main() {
///
/// #[deriving(Decodable)]
/// #[deriving(RustcDecodable)]
/// struct Pair {
/// name1: String,
/// name2: String,
Expand All @@ -224,17 +226,17 @@ impl<R: io::Reader> Reader<R> {
/// valid data in every record (whether it be empty or malformed).
///
/// ```rust
/// extern crate serialize;
/// extern crate "rustc-serialize" as rustc_serialize;
/// # extern crate csv;
/// # fn main() {
///
/// #[deriving(Decodable, PartialEq, Show)]
/// #[deriving(RustcDecodable, PartialEq, Show)]
/// struct MyUint(uint);
///
/// #[deriving(Decodable, PartialEq, Show)]
/// #[deriving(RustcDecodable, PartialEq, Show)]
/// enum Number { Integer(i64), Float(f64) }
///
/// #[deriving(Decodable)]
/// #[deriving(RustcDecodable)]
/// struct Row {
/// name1: String,
/// name2: String,
Expand All @@ -257,11 +259,11 @@ impl<R: io::Reader> Reader<R> {
/// "tail" of another tuple/struct/`Vec` to capture all remaining fields:
///
/// ```rust
/// extern crate serialize;
/// extern crate "rustc-serialize" as rustc_serialize;
/// # extern crate csv;
/// # fn main() {
///
/// #[deriving(Decodable)]
/// #[deriving(RustcDecodable)]
/// struct Pair {
/// name1: String,
/// name2: String,
Expand Down Expand Up @@ -1092,9 +1094,10 @@ impl<'a, R: io::Reader> Iterator<CsvResult<Vec<ByteString>>>

fn byte_record_to_utf8(record: Vec<ByteString>) -> CsvResult<Vec<String>> {
for bytes in record.iter() {
if !::std::str::is_utf8(bytes[]) {
if let Err(err) = ::std::str::from_utf8(bytes[]) {
return Err(Error::Decode(format!(
"Could not decode the following bytes as UTF-8: {}", bytes)));
"Could not decode the following bytes as UTF-8 because {}: {}",
err.to_string(), bytes)));
}
}
Ok(unsafe { ::std::mem::transmute(record) })
Expand Down
7 changes: 4 additions & 3 deletions src/test.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use std::borrow::ToOwned;
use std::io::ByRefReader;
use std::io::Reader as IoReader;
use std::io::Writer as IoWriter;
Expand Down Expand Up @@ -234,14 +235,14 @@ parses_to!(flexible_rows2, "a,b\nx", vec![vec!["a", "b"], vec!["x"]],
fail_parses_to!(nonflexible, "a\nx,y", vec![]);
fail_parses_to!(nonflexible2, "a,b\nx", vec![]);

#[deriving(Decodable, Encodable, Show, PartialEq, Eq)]
#[deriving(RustcDecodable, RustcEncodable, Show, PartialEq, Eq)]
enum Val { Unsigned(uint), Signed(int), Bool(bool) }

decodes_to!(decode_int, "1", (uint,), vec![(1u,)]);
decodes_to!(decode_many_int, "1,2", (uint, i16), vec![(1u,2i16)]);
decodes_to!(decode_float, "1,1.0,1.5", (f64, f64, f64), vec![(1f64, 1.0, 1.5)]);
decodes_to!(decode_char, "a", (char,), vec![('a',)]);
decodes_to!(decode_str, "abc", (String,), vec![("abc".into_string(),)]);
decodes_to!(decode_str, "abc", (String,), vec![("abc".to_owned(),)]);

decodes_to!(decode_opt_int, "a", (Option<uint>,), vec![(None,)]);
decodes_to!(decode_opt_float, "a", (Option<f64>,), vec![(None,)]);
Expand All @@ -253,7 +254,7 @@ decodes_to!(decode_val, "false,-5,5", (Val, Val, Val),
decodes_to!(decode_opt_val, "1.0", (Option<Val>,), vec![(None,)]);

decodes_to!(decode_tail, "abc,1,2,3,4", (String, Vec<uint>),
vec![("abc".into_string(), vec![1u, 2, 3, 4])]);
vec![("abc".to_owned(), vec![1u, 2, 3, 4])]);

writes_as!(wtr_one_record_one_field, vec![vec!["a"]], "a\n");
writes_as!(wtr_one_record_many_field, vec![vec!["a", "b"]], "a,b\n");
Expand Down
16 changes: 9 additions & 7 deletions src/writer.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
use std::borrow::ToOwned;
use std::error::FromError;
use std::io;
use std::str;

use serialize::Encodable;
use rustc_serialize::Encodable;

use {BorrowBytes, ByteString, CsvResult, Encoded, Error, RecordTerminator};

Expand Down Expand Up @@ -158,11 +159,11 @@ impl<W: io::Writer> Writer<W> {
/// edit distances computed.
///
/// ```rust
/// extern crate serialize;
/// extern crate "rustc-serialize" as rustc_serialize;
/// # extern crate csv;
/// # fn main() {
///
/// #[deriving(Encodable)]
/// #[deriving(RustcEncodable)]
/// struct Distance {
/// name1: &'static str,
/// name2: &'static str,
Expand Down Expand Up @@ -350,8 +351,9 @@ impl<W: io::Writer> Writer<W> {
}

impl<W: io::Writer> Writer<W> {
fn err<S: StrAllocating, T>(&self, msg: S) -> CsvResult<T> {
Err(Error::Encode(msg.into_string()))
fn err<Sized? S, T>(&self, msg: &S) -> CsvResult<T>
where S: ToOwned<String> {
Err(Error::Encode(msg.to_owned()))
}

fn w_bytes(&mut self, s: &[u8]) -> CsvResult<()> {
Expand Down Expand Up @@ -382,7 +384,7 @@ impl<W: io::Writer> Writer<W> {
if self.first_len == 0 {
self.first_len = cur_len;
} else if self.first_len != cur_len {
return self.err(format!(
return self.err(&format!(
"Record has length {} but other records have length {}",
cur_len, self.first_len))
}
Expand All @@ -399,7 +401,7 @@ impl<W: io::Writer> Writer<W> {
if !needs() {
Ok(false)
} else {
self.err(format!(
self.err(&format!(
"Field requires quotes, but quote style \
is 'Never': '{}'",
String::from_utf8_lossy(field)))
Expand Down

0 comments on commit ea505ae

Please sign in to comment.