Skip to content

Instantly share code, notes, and snippets.

Created October 11, 2017 16:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/765d46640b29d8deb6863f4b895bd085 to your computer and use it in GitHub Desktop.
Save anonymous/765d46640b29d8deb6863f4b895bd085 to your computer and use it in GitHub Desktop.
Rust code shared from the playground
extern crate csv;
#[macro_use]
extern crate serde_derive;
use std::io::Cursor;
use std::io::Write;
const DATA_LABELS: &[&'static str] = &[
"latitude",
"longitude",
"altitude",
"course",
"heading",
"speed",
"year",
"month",
"day",
"hour",
"minute",
"second",
"temperature",
"humidity",
"pitch",
"roll",
"object_distance_front",
"object_distance_back",
];
#[derive(Debug, Deserialize, PartialEq)]
pub struct Data {
latitude: f64,
longitude: f64,
altitude: f64,
course: f32,
heading: f32,
speed: f32,
year: u16,
month: u8,
day: u8,
hour: u8,
minute: u8,
second: u8,
temperature: f32,
humidity: f32,
pitch: f32,
roll: f32,
object_distance_front: u16,
object_distance_back: f32,
}
fn main() {
let data = "-100.00 100.00 100.00 77.39 195.9 1.111 2017 9 29 13 14 48 0 0 2.1 -1.3 82 67.3\n";
/* Set up reader */
let mut csv_reader = csv::ReaderBuilder::new()
.delimiter(' ' as u8)
.terminator(csv::Terminator::Any('\n' as u8))
.from_reader(Cursor::new(Vec::new()));
// Add the headers
let mut headers: String = DATA_LABELS
.iter()
.map(|it| it.to_string())
.collect::<Vec<_>>()
.join(' '.encode_utf8(&mut [0u8; 2]));
eprintln!("Headers: {}", headers);
headers.push('\n');
// Write headers to csv reader
let mut position = csv_reader.position().clone();
position.set_byte(0);
{
let cursor = csv_reader.get_mut();
cursor.set_position(position.byte());
cursor.write_all(headers.as_bytes()).unwrap();
eprintln!("Cursor contents: {:?}", cursor.get_ref());
}
csv_reader
.seek_raw(std::io::SeekFrom::Start(position.byte()), position.clone())
.unwrap();
// TODO cleanup all these get_mut's
csv_reader.get_mut().set_position(position.byte());
csv_reader.get_mut().write_all(headers.as_bytes()).expect(
"Error writing into Vec, meaning it's full (shouldn't be) -- this is a bug!",
);
csv_reader.get_mut().set_position(0);
// Read headers
csv_reader.records().next();
// Clear cursor of headers
csv_reader.get_mut().get_mut().clear();
/* Feed data */
let mut position = csv_reader.position().clone();
position.set_byte(0);
{
let cursor = csv_reader.get_mut();
cursor.set_position(position.byte());
cursor.write_all(data.as_bytes()).unwrap();
eprintln!("Cursor contents: {:?}", cursor.get_ref());
}
{
let reader = &mut csv_reader;
reader
.seek_raw(std::io::SeekFrom::Start(position.byte()), position.clone())
.unwrap();
reader.get_mut().set_position(position.byte());
}
/* Parse */
println!("{:?}", csv_reader.deserialize::<Data>().next().unwrap().unwrap());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment