126 lines
3.0 KiB
Rust
126 lines
3.0 KiB
Rust
// Workspace: more_fields
|
|
// File: more_fields/src/lib.rs
|
|
//! Get all the fields as a Vec<("attribute", "type")>
|
|
//! Note that this map is implemented without self, allowing us to use it only as a generic,
|
|
//! however this limitation is completely artificial
|
|
|
|
pub use more_fields_macro::FieldsAsSlice;
|
|
pub use more_fields_macro::InstanceAsArray;
|
|
|
|
pub trait FieldsAsSlice {
|
|
fn attributes_slice() -> &'static [(&'static str, &'static str)];
|
|
}
|
|
|
|
/// Converts an instance into a homogeneous array.
|
|
///
|
|
/// The array length is determined by the derive macro.
|
|
pub trait InstanceAsArray {
|
|
/// Element type of the generated array.
|
|
type Item;
|
|
|
|
// /// Concrete array type, e.g. `[Value; 5]`.
|
|
// type Array: AsRef<Vec<Self::Item>>;
|
|
|
|
fn instance_as_array(&self) -> Vec<Self::Item>;
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod test {
|
|
use crate::FieldsAsSlice;
|
|
use pretty_assertions::assert_eq;
|
|
|
|
#[allow(dead_code)]
|
|
#[derive(FieldsAsSlice, Default)]
|
|
struct Bob {
|
|
#[TEXT]
|
|
field_ouane: u16,
|
|
#[INTEGER]
|
|
field_2: u16,
|
|
#[BLOB]
|
|
field_3: u16,
|
|
#[NULL]
|
|
field_4: u16,
|
|
#[REAL]
|
|
field_5: u16,
|
|
field_6: u16,
|
|
}
|
|
#[test]
|
|
fn test_derive_impl() {
|
|
println!("{:?}", Bob::attributes_slice());
|
|
// assert!(
|
|
let b_hash = vec![
|
|
("field_ouane", "TEXT"),
|
|
("field_2", "INTEGER"),
|
|
("field_3", "BLOB"),
|
|
("field_4", "NULL"),
|
|
("field_5", "REAL"),
|
|
("field_6", "TEXT"),
|
|
];
|
|
|
|
assert_eq!(Bob::attributes_slice(), b_hash);
|
|
}
|
|
use crate::InstanceAsArray;
|
|
|
|
#[allow(dead_code)]
|
|
#[derive(Debug, PartialEq)]
|
|
enum Value {
|
|
Integer(i64),
|
|
Text(String),
|
|
}
|
|
|
|
impl From<i32> for Value {
|
|
fn from(v: i32) -> Self {
|
|
Value::Integer(v as i64)
|
|
}
|
|
}
|
|
|
|
impl From<String> for Value {
|
|
fn from(v: String) -> Self {
|
|
Value::Text(v)
|
|
}
|
|
}
|
|
|
|
#[derive(FieldsAsSlice, InstanceAsArray)]
|
|
#[InstanceAsArray(Type = String)]
|
|
struct Person {
|
|
#[INTEGER]
|
|
id: String,
|
|
|
|
#[TEXT]
|
|
name: String,
|
|
|
|
#[SKIP]
|
|
cached: String,
|
|
}
|
|
|
|
#[test]
|
|
fn instance_as_array_works() {
|
|
let person = Person {
|
|
id: "Alice".into(),
|
|
name: "Alice".into(),
|
|
cached: "Alice".into(),
|
|
};
|
|
assert!(person.cached == "Alice",);
|
|
let array = person.instance_as_array();
|
|
let slice = array.as_ref();
|
|
|
|
assert_eq!(slice, &["Alice".to_string(), "Alice".to_string(),]);
|
|
}
|
|
|
|
// #[test]
|
|
// fn attributes_slice_matches_instance_array() {
|
|
// let attrs = Person::attributes_slice();
|
|
|
|
// assert_eq!(attrs, &[("id", "INTEGER"), ("name", "TEXT"),]);
|
|
|
|
// let values = Person {
|
|
// id: 1,
|
|
// name: "Bob".into(),
|
|
// cached: false,
|
|
// }
|
|
// .instance_as_array();
|
|
|
|
// assert_eq!(attrs.len(), values.as_ref().len());
|
|
// }
|
|
}
|