-
-
Save jpastuszek/6ab7fafb0042ea56dabfcd75e33a1ea2 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::marker::PhantomData; | |
use std::convert::TryFrom; | |
use std::convert::TryInto; | |
#[derive(Debug)] | |
struct ConversionError; | |
struct ResultSet<T> { | |
column_names: Vec<String>, | |
rows: Vec<Vec<i32>>, | |
t: PhantomData<T>, | |
} | |
impl<T> ResultSet<T> { | |
fn pop<'rs>(&'rs mut self) -> Option<RowWithSchema<'rs>> { | |
let column_names = self.column_names.as_slice(); | |
self.rows.pop().map(|columns| RowWithSchema { | |
column_names, | |
columns, | |
}) | |
} | |
} | |
struct RowWithSchema<'rs> { | |
column_names: &'rs[String], | |
columns: Vec<i32>, | |
} | |
#[derive(Debug)] | |
struct Row(Vec<i32>); | |
impl<T> Iterator for ResultSet<T> where T: for<'rs> TryFrom<RowWithSchema<'rs>, Error = ConversionError> { | |
type Item = Result<T, ConversionError>; | |
fn next(&mut self) -> Option<Result<T, ConversionError>> { | |
self.pop().map(|r| r.try_into()) | |
} | |
} | |
impl<'rs> TryFrom<RowWithSchema<'rs>> for Row { | |
type Error = ConversionError; | |
fn try_from(r: RowWithSchema<'rs>) -> Result<Row, ConversionError> { | |
Ok(Row(r.columns)) | |
} | |
} | |
fn main() { | |
let rs: ResultSet<Row> = ResultSet { | |
column_names: vec!["foo".to_owned(), "bar".to_owned()], | |
rows: vec![ | |
vec![1, 2], | |
vec![3, 4], | |
], | |
t: PhantomData, | |
}; | |
for row in rs { | |
println!("{:?}", row); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment