Rust, getting values from HashMap with enum - rust

I'm trying make one HashMap with different types. I don't want to make two different HashMaps for specific data types.
My code is bellow:
use std::collections::HashMap;
#[derive(Debug)]
enum DataTypes {
String(String),
Bool(bool),
}
fn get_hashmap() -> Result<HashMap<String, DataTypes>, ()>{
let data = HashMap::from([
("password".to_string(), DataTypes::String("password".to_string())),
("username".to_string(), DataTypes::String("Fun username".to_string())),
("is_blocked".to_string(), DataTypes::Bool(true)),
("is_confirmed".to_string(), DataTypes::Bool(false)),
]);
Ok(data)
}
fn main() {
let data = get_hashmap().unwrap();
let keys = data.keys();
println!("Keys: {:?}", &keys);
for key in keys {
let result: Option<T> = match data.get(key).unwrap() {
DataTypes::Bool(value) => Some(value),
DataTypes::String(value) => Some(value),
_ => panic!("Error!"),
};
println!("Result of matching: {:?}", &result);
}
}
Like you can see I'm trying to maching Enums to getting their values. But i have some problem of data types.
My solution for this is wrap result of matching to Some struct. But still main problem is not resolved.
So I want to make result of matching in Option class to make available unwrap().
But I don't know how i can do that correctly...
I have two question:
Can i do this better?
How can I wrap let result: Option to working state?

Some feedback:
Don't include a _ default match case if you already handle all the options. It will hide future errors.
Don't name a variable DataTypes if every member is only a single datatype. Name it DataType.
result has to be a specific type. The whole point of the enum is that you can handle the different values separately, so combining them in a result type is pointless. Although you of course can keep result a DataType object and implement Debug/Display for it, which is how I will do it in my reworked code.
While you can query the key first and then again query the value in the loop, this is quite slow. You can iterate over key-value pairs right away. That way you avoid a lot of unwrap()s, which makes your code a lot less error-prone.
use std::collections::HashMap;
#[derive(Debug)]
enum DataType {
String(String),
Bool(bool),
}
fn get_hashmap() -> Result<HashMap<String, DataType>, ()> {
let data = HashMap::from([
(
"password".to_string(),
DataType::String("password".to_string()),
),
(
"username".to_string(),
DataType::String("Fun username".to_string()),
),
("is_blocked".to_string(), DataType::Bool(true)),
("is_confirmed".to_string(), DataType::Bool(false)),
]);
Ok(data)
}
fn main() {
let data = get_hashmap().unwrap();
for (key, value) in data {
println!("{}: {:?}", key, value);
match value {
DataType::Bool(value) => {
println!("\tValue was a bool: {}", value);
// do something if the value is a bool
}
DataType::String(value) => {
println!("\tValue was a string: {}", value);
// do something if the value is a string,
} /*
* Don't include a default case. That way the compiler
* will remind you to handle additional enum entries if
* you add them in the future.
* Adding a default case is only a good practice in languages
* where matching is not exhaustive.
*/
};
}
}
username: String("Fun username")
Value was a string: Fun username
is_confirmed: Bool(false)
Value was a bool: false
is_blocked: Bool(true)
Value was a bool: true
password: String("password")
Value was a string: password
Don't worry though, you don't need to use match everywhere you use this enum, otherwise you wouldn't win much compared to two separate hashmaps. You can, instead, define shared functionality for all enum entries, and hide the match inside of it. Like this:
use std::collections::HashMap;
#[derive(Debug)]
enum DataType {
String(String),
Bool(bool),
}
impl DataType {
fn do_something(&self) {
match self {
DataType::Bool(value) => {
println!("\tDo something with boolean '{}'!", value);
}
DataType::String(value) => {
println!("\tDo something with string {:?}!", value);
}
};
}
}
fn get_hashmap() -> Result<HashMap<String, DataType>, ()> {
let data = HashMap::from([
(
"password".to_string(),
DataType::String("password".to_string()),
),
(
"username".to_string(),
DataType::String("Fun username".to_string()),
),
("is_blocked".to_string(), DataType::Bool(true)),
("is_confirmed".to_string(), DataType::Bool(false)),
]);
Ok(data)
}
fn main() {
let data = get_hashmap().unwrap();
for (key, value) in data {
println!("{}: {:?}", key, value);
value.do_something();
}
}
is_confirmed: Bool(false)
Do something with boolean 'false'!
password: String("password")
Do something with string "password"!
is_blocked: Bool(true)
Do something with boolean 'true'!
username: String("Fun username")
Do something with string "Fun username"!
If your goal is to add serialization/deserialization to your struct (as you seem to implement manually here), let me hint you towards serde, which already takes care of the majority of serialization for free.
Like in this example (which may or may not be how your struct looks like) that serializes your struct to and from JSON:
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
struct User {
username: String,
password: String,
is_blocked: bool,
is_confirmed: bool,
}
fn main() {
let user = User {
username: "Fun username".to_string(),
password: "password".to_string(),
is_blocked: true,
is_confirmed: false,
};
let user_serialized = serde_json::to_string(&user).unwrap();
println!("Serialized: {}", user_serialized);
let user_deserialized: User = serde_json::from_str(&user_serialized).unwrap();
println!("Name: {}", user_deserialized.username);
}
Serialized: {"username":"Fun username","password":"password","is_blocked":true,"is_confirmed":false}
Name: Fun username

Related

Derive macro generation

I'm making my own Serializable trait, in the context of a client / server system.
My idea was that the messages sent by the system is an enum made by the user of this system, so it can be customize as needed.
Too ease implementing the trait on the enum, I would like to use the #[derive(Serializable)] method, as implementing it is always the same thing.
Here is the trait :
pub trait NetworkSerializable {
fn id(&self) -> usize;
fn size(&self) -> usize;
fn serialize(self) -> Vec<u8>;
fn deserialize(id: usize, data: Vec<u8>) -> Self;
}
Now, I've tried to look at the book (this one too) and this example to try to wrap my head around derive macros, but I'm really struggling to understand them and how to implement them. I've read about token streams and abstract trees, and I think I understand the basics.
Let's take the example of the id() method : it should gives a unique id for each variant of the enum, to allow headers of messages to tell which message is incoming.
let's say I have this enum as a message system :
enum NetworkMessages {
ErrorMessage,
SpawnPlayer(usize, bool, Transform), // player id, is_mine, position
MovePlayer(usize, Transform), // player id, new_position
DestroyPlayer(usize) // player_id
}
Then, the id() function should look like this :
fn id(&self) -> usize {
match &self {
&ErrorMessage => 0,
&SpawnPlayer => 1,
&MovePlayer => 2,
&DestroyPlayer => 3,
}
}
Here was my go with writting this using a derive macro :
#[proc_macro_derive(NetworkSerializable)]
pub fn network_serializable_derive(input: TokenStream) -> TokenStream {
// Construct a representation of Rust code as a syntax tree
// that we can manipulate
let ast = syn::parse(input).unwrap();
// Build the trait implementation
impl_network_serializable_macro(&ast)
}
fn impl_network_serializable_macro(ast: &syn::DeriveInput) -> TokenStream {
// get enum name
let ref name = ast.ident;
let ref data = ast.data;
let (id_func, size_func, serialize_func, deserialize_func) = match data {
// Only if data is an enum, we do parsing
Data::Enum(data_enum) => {
// Iterate over enum variants
let mut id_func_internal = TokenStream2::new();
let mut variant_id: usize = 0;
for variant in &data_enum.variants {
// add the branch for the variant
id_func_internal.extend(quote_spanned!{
variant.span() => &variant_id,
});
variant_id += 1;
}
(id_func_internal, (), (), ())
}
_ => {(TokenStream2::new(), (), (), ())},
};
let expanded = quote! {
impl NetworkSerializable for #name {
// variant_checker_functions gets replaced by all the functions
// that were constructed above
fn size(&self) -> usize {
match &self {
#id_func
}
}
/*
#size_func
#serialize_func
#deserialize_func
*/
}
};
expanded.into()
}
So this is generating quite a lot of errors, with the "proc macro NetworkSerializable not expanded: no proc macro dylib present" being first. So I'm guessing there a lot of misunderstaning from my part in here.

How to access nested enums without full match syntax

I am using the Serde crate to deserialise a JSON file, which has a nested structure like this:
struct Nested {
a: Vec<Foo>,
b: u8,
}
struct Foo {
c: Bar,
d: Vec<f32>,
}
Struct Bar {
e: u32,
f: String,
}
Part of the applications purpose is to check for missing parameters (or incorrect types in parameters), and then display a nicely printed list of errors found in the file, so I need to handle the structure missing parameters or wrongly typed.
I came across this great post that helped solved my issue, by wrapping each parameter in an enum result that contains the value if it passed, the value if it failed, or a final enum if it was missing (since the nested structures might also be missing I wrapped them in the same enum):
pub enum TryParse<T> {
Parsed(T),
Unparsed(Value),
NotPresent
}
struct Nested {
a: TryParse<Vec<Foo>>,
b: TryParse<u8>,
}
struct Foo {
c: TryParse<Bar>,
d: TryParse<Vec<f32>>,
}
Struct Bar {
e: TryParse<u32>,
f: TryParse<String>,
}
However, I'm not sure how to access them now without unpacking every step into a match statement. For example, I can access B very easily:
match file.b {
Parsed(val) => {println!("Got parameter of {}", val)},
Unparsed(val) => {println!("Invalid type: {:?}", val)}
NotPresent => {println!("b not found")},
};
However, I'm not sure how to access the nested ones (C D E and F). I can't use Unwrap or expect since this isn't technically a 'Result', so how do I unpack these?:
if file.a.c.e.Parsed() && file.a.c.e == 32 {... //invalid
if file.a.d && file.a.d.len() == 6... //invalid
I know in a way this flies against rust's 'handle every outcome' philosophy, and I want to handle them, but I want to know if there is a nicer way than 400 nested match statements (the above example is very simplified, the files I am using have up to 6 nested layers, each parameter in the top node has at least 3 layers, some are vectors as well)…
Perhaps I need to implement a function similar to unwrap() on my 'TryParse'? or would it be better to wrap each parameter in a 'Result', extend that with the deserialise trait, and then somehow store the error in the Err option that says if it was a type error or missing parameter?
EDIT
I tried adding the following, some of which works and some of which does not:
impl <T> TryParse<T> {
pub fn is_ok(self) -> bool { //works
match self {
Self::Parsed(_t) => true,
_ => false,
}
}
pub fn is_absent(self) -> bool { //works
match self {
Self::NotPresent => true,
_ => false,
}
}
pub fn is_invalid(self) -> bool { //works
match self {
Self::Unparsed(_) => true,
_ => false,
}
}
pub fn get(self) -> Result<T, dyn Error> { //doesnt work
match self {
Self::Parsed(t) => Ok(t),
Self::Unparsed(e) => Err(e),
Self::NotPresent => Err("Invalid")
}
}
}
I can't believe it is this hard just to get the result, should I just avoid nested enums or get rid of the TryParse enums/ functions all together and wrap everything in a result, so the user simply knows if it worked or didn't work (but no explanation why it failed)
Implementing unwrap() is one possibility. Using Result is another, with a custom error type. You can deserialize directly into result with #[serde(deserialize_with = "...")], or using a newtype wrapper.
However, a not-enough-used power of pattern matching is nested patterns. For example, instead of if file.a.c.e.Parsed() && file.a.c.e == 32 you can write:
if let TryParse::Parsed(a) = &file.a {
// Unfortunately we cannot combine this `if let` with the surrounding `if let`,
// because `Vec` doesn't support pattern matching (currently).
if let TryParsed::Parsed(
[Foo {
c:
TryParse::Parsed(Bar {
e: TryParse::Parsed(32),
..
}),
..
}, ..],
) = a.as_slice()
{
// ...
}
}
May not be the most Rust-y way of doing it, but for those like me moving from another language like C/Python/C++, this is the way I have done it that still allows me to quickly validate if I have an error and use the match syntax to handle it. Thanks to #Chayim Friedman for assisting with this, his way is probably better but this made the most sense for me:
#[derive(Debug)]
pub enum TryParse<T> {
Parsed(T),
Unparsed(Value),
NotPresent
}
impl<'de, T: DeserializeOwned> Deserialize<'de> for TryParse<T> {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
match Option::<Value>::deserialize(deserializer)? {
None => Ok(TryParse::NotPresent),
Some(value) => match T::deserialize(&value) {
Ok(t) => Ok(TryParse::Parsed(t)),
Err(_) => Ok(TryParse::Unparsed(value)),
},
}
}
}
impl <T> TryParse<T> {
//pub fn is_ok(self) -> bool { ---> Use get().is_ok(), built into result
// match self {
// Self::Parsed(_t) => true,
// _ => false,
// }
//}
pub fn is_absent(self) -> bool {
match self {
Self::NotPresent => true,
_ => false,
}
}
pub fn is_invalid(self) -> bool {
match self {
Self::Unparsed(_) => true,
_ => false,
}
}
pub fn get(&self) -> Result<&T, String> {
match self {
Self::Parsed(t) => Ok(t),
Self::Unparsed(v) => Err(format!("Unable to Parse {:?}", v)),
Self::NotPresent => Err("Parameter not Present".to_string())
}
}
// pub fn get_direct(&self) -> &T {
// match self {
// Self::Parsed(t) => t,
// _ => panic!("Can't get this value!"),
// }
// }
}
match &nested.a.get().unwrap()[1].c.get.expect("Missing C Parameter").e{
Parsed(val) => {println!("Got value of E: {}", val)},
Unparsed(val) => {println!("Invalid Type: {:?}", val)}
NotPresent => {println!("Param E Not Found")},
};
//Note the use of '&' at the beginning because we need to borrow a reference to it
I know I need to change my mindset to use the rust way of thinking, and I am completely open to other suggestions if they can demonstrate some working code.

rust extend built-in enum Result?

tl;dr Is it possible to extend std::result::Result to add my own variant that signals "things are Okay but also..." and keep impl Result methods like is_ok()?
I want to extend Result to signal additional states that a function caller can use for special cases.
use std::result::Result
use std::io::Error;
/// Extend Result to also signal "things are okay but check on things"
enum ResultExt<T, E> {
Result<T, E>,
OkButCheckThings(T),
}
pub fn do_stuff() -> ResultExt<u64, Error> {
// ...
}
pub fn main() -> {
let var = match do_stuff() {
Ok(val) => { val },
Err(err) => { 0 },
OkButCheckThings(val) => { check_things(); val },
}
dbg!(var);
}
It's possible to plainly extend an Enum. But I would also like to use the underlying Result<T, E> functions like is_ok.
let var2 = do_stuff();
if var2.is_ok() {
println!("It is totally Ok, nothing to check!");
}
I created a rust playground example that successfully extends Result<T, E> but the extended enum cannot use functions like is_ok().
The real-world use-case is a function that calls std::io::Read may need to "modify" the returned Result to signal additional states beyond Ok and Err. But I want these various "meta states" to be captured by one enum, as opposed to returning various other bool flags (I want to avoid return signature with (Result<T>, bool, bool). This would allow one clean match statement of all possible states; Ok, Err, "Okay but...", "Err but ...", etc..
There is no current way of "extending" and enum perse.
But it could be simply solved by embedding your own enum type into the result itself.
Simple example, similar to yours:
use std::fmt::Display;
enum StuffToCheck<T> {
Ok(T),
CheckThis(T),
}
impl<T> StuffToCheck<T>
where
T: Display + Copy,
{
pub fn check_things(&self) -> T {
match self {
Self::Ok(val) => {
*val
}
Self::CheckThis(val) => {
println!("Checking stuff for {}", val);
*val
}
}
}
}
fn do_stuff() -> ResultExt<u64> {
Ok(StuffToCheck::CheckThis(10))
}
type ResultExt<T> = Result<StuffToCheck<T>, std::io::Error>;
fn main() {
let var = match do_stuff() {
Ok(result) => result.check_things(),
Err(_err) => 0,
};
dbg!(var);
}
Playground
You could even use nested pattern matching:
...
match do_stuff() {
Err(e) => {//handle error}
Ok(StuffToCheck::Ok(value)) => { value },
Ok(StuffToCheck::CheckThis(value)) => {
check_things(value);
value
}
}
...
I think this is an instance of the X-Y problem. You can use the built-in result, you just need a different error type, that returns an option: Some(partial_result) or None.
For example you have function parse, that can attempt to adjust for a malformed input, but report the error.
pub fn parse(b: &str) -> Result<&str, CustomParseError> {
// Do something that might fail,
if failed(){
return CustomParseError::new(None)
} else if partially_failed() {
return CustomParseError::new(Some(partial_result))
} else {
return completeResult
}
}
This way you have a clean code path where nothing failed, and all of your assumptions are correct, and if it's not => instead of unwrapping, you match and check which case you have. This is vastly superior, because the error often contains enough information for you to reconstruct both what went wrong, and what could be done to fix it.

Validate enum with associated values in a vec for uniqueness

Below there is code in which I have defined a method with an input type of Vec<Food>. This method should validate if an arm, without checking the associated value, must be unique. It means it should contain at most 1 pizza, 1 cake and 1 subway. Note: it is not needed that all arms are in the Vec. I wrote some tests in the code below also, they still need to pass.
I have much more enum arms in my 'real' code, and my current way doesn't scale very well, so I was hoping there is a easier way.
fn main() {
}
enum Food {
Cake(String),
Pizza(i32),
Subway(u64)
}
struct CustomError;
fn validate(foods: Vec<Food>) -> Result<(), CustomError> {
let mut cake = false;
let mut pizza = false;
let mut subway = false;
for f in foods.iter() {
match f {
Food::Cake(_) => {
if cake {
return Err(CustomError)
}
cake = true;
},
Food::Pizza(_) => {
if pizza {
return Err(CustomError)
}
pizza = true;
},
Food::Subway(_) => {
if subway {
return Err(CustomError)
}
subway = true;
},
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test() {
assert!(validate(vec![Food::Pizza(1)]).is_ok());
assert!(validate(vec![Food::Pizza(1), Food::Cake("Apple".to_owned())]).is_ok());
assert!(validate(vec![]).is_ok());
assert!(validate(vec![Food::Pizza(1), Food::Pizza(1)]).is_err());
assert!(validate(vec![Food::Pizza(1), Food::Pizza(2)]).is_err());
}
}
To compare enum variants without caring about any associated data, the function std::mem::discriminant is very useful. Given a value of an enum type, std::mem::discriminant returns a value of type std::mem::Discriminant which tells which variant the value is. std::mem::Discriminant implements Hash, so we can keep all the variants we've seen so far in a HashSet to check if there are any duplicates.
Just a small trick: HashSet::insert returns a boolean which is true when the inserted element isn't already in the set. That means we can combine the steps of checking if a discriminant has been seen and inserting a new discriminant.
use std::collections::HashSet;
use std::mem::discriminant;
enum Food {
Cake(String),
Pizza(i32),
Subway(u64),
}
struct CustomError;
fn validate(foods: Vec<Food>) -> Result<(), CustomError> {
let mut discriminants = HashSet::new();
for food in foods {
if !discriminants.insert(discriminant(&food)) {
return Err(CustomError);
}
}
Ok(())
}
(playground)
Rust doesn't have much by way of reflection capabilities, so I suspect the best you can do is write something like a procedural macro to generate a function containing the match statement which you described not wanting to write by hand.

Implement AsExpression and FromSqlRow for a custom type [duplicate]

I have an SQL table that I want to work with through Diesel:
CREATE TABLE records (
id BIGSERIAL PRIMARY KEY,
record_type SMALLINT NOT NULL,
value DECIMAL(10, 10) NOT NULL
)
This table generates the following schema:
table! {
records (id) {
id -> Int8,
record_type -> Int2,
value -> Numeric,
}
}
Diesel exports decimals as bigdecimal::BigDecimal, but I'd like to work with decimal::d128 instead. I also want to map record_type to an enum, so I declare my model like this:
use decimal::d128;
pub enum RecordType {
A,
B,
}
pub struct Record {
pub id: i64,
pub record_type: RecordType,
pub value: d128,
}
I can't use #derive(Queryable, Insertable) because of non-standard type mapping, so I try to implement these traits myself:
impl Queryable<records::SqlType, Pg> for Record {
type Row = (i64, i16, BigDecimal);
fn build(row: Self::Row) -> Self {
Record {
id: row.0,
record_type: match row.1 {
1 => RecordType::A,
2 => RecordType::B,
_ => panic!("Wrong record type"),
},
value: d128!(format!("{}", row.2)),
}
}
}
I can't figure out how to implement Insertable. What is the Values associated type? Diesel's documentation is not very clear on this.
Maybe there's a better way to achieve what I'm trying to do?
Cargo.toml:
[dependencies]
bigdecimal = "0.0.10"
decimal = "2.0.4"
diesel = { version = "1.1.1", features = ["postgres", "bigdecimal", "num-bigint", "num-integer", "num-traits"] }
dotenv = "0.9.0"
I find it more convenient to create newtype wrappers that implement ToSql and FromSql. You can then build with these basic blocks to create larger types that can derive Queryable / Insertable.
This example only shows how to perform the mapping of the enum to and from a SmallInt, but the case for the decimal would be the same. The only difference would be in how you perform the transformations:
#[macro_use]
extern crate diesel;
mod types {
use diesel::sql_types::*;
use diesel::backend::Backend;
use diesel::deserialize::{self, FromSql};
use diesel::serialize::{self, ToSql, Output};
use std::io;
table! {
records (id) {
id -> BigInt,
record_type -> SmallInt,
}
}
#[derive(Debug, Copy, Clone, AsExpression, FromSqlRow)]
#[sql_type = "SmallInt"]
pub enum RecordType {
A,
B,
}
impl<DB: Backend> ToSql<SmallInt, DB> for RecordType
where
i16: ToSql<SmallInt, DB>,
{
fn to_sql<W>(&self, out: &mut Output<W, DB>) -> serialize::Result
where
W: io::Write,
{
let v = match *self {
RecordType::A => 1,
RecordType::B => 2,
};
v.to_sql(out)
}
}
impl<DB: Backend> FromSql<SmallInt, DB> for RecordType
where
i16: FromSql<SmallInt, DB>,
{
fn from_sql(bytes: Option<&DB::RawValue>) -> deserialize::Result<Self> {
let v = i16::from_sql(bytes)?;
Ok(match v {
1 => RecordType::A,
2 => RecordType::B,
_ => return Err("replace me with a real error".into()),
})
}
}
#[derive(Insertable, Queryable, Debug)]
#[table_name = "records"]
pub struct Record {
pub id: i64,
pub record_type: RecordType,
}
}
There's a draft guide describing all the derives and their annotations, but it doesn't yet mention #[sql_type] for an entire type. This lets Diesel know what kind of underlying storage is needed inside of the database.
See also the Diesel tests for custom types.
Sometimes, the easiest way to understand what a macro does (derives are just a different form of macros) is to ask the compiler for the expanded code. With a nightly compiler, you can do this using this command:
cargo rustc -- -Z unstable-options --pretty expanded > expanded.rs
This will output the expanded code in expanded.rs.
We can now look at this file to see what #[derive(Insertable)] expands to. Naturally, I first changed the definition of Record to match the types that Diesel. After some cleaning up, this is the generated code:
impl<'insert> diesel::insertable::Insertable<records::table> for &'insert Record {
type Values = <(
Option<diesel::dsl::Eq<records::id, &'insert i64>>,
Option<diesel::dsl::Eq<records::record_type, &'insert i16>>,
Option<diesel::dsl::Eq<records::value, &'insert BigDecimal>>
) as diesel::insertable::Insertable<records::table>>::Values;
#[allow(non_shorthand_field_patterns)]
fn values(self) -> Self::Values {
let Record {
id: ref id,
record_type: ref record_type,
value: ref value,
} = *self;
diesel::insertable::Insertable::values((
Some(::ExpressionMethods::eq(records::id, id)),
Some(::ExpressionMethods::eq(records::record_type, record_type)),
Some(::ExpressionMethods::eq(records::value, value))))
}
}
impl diesel::query_builder::UndecoratedInsertRecord<records::table> for Record {
}
We can now adapt the Insertable implementation for our custom types. Notice that I've changed the Values associated type to return values directly rather than references to the values, because for two of them, the value is created in the values method, so we couldn't return a reference, and for the other one, returning a reference doesn't gain much in terms of performance.
impl<'insert> diesel::insertable::Insertable<records::table> for &'insert Record {
type Values = <(
Option<diesel::dsl::Eq<records::id, i64>>,
Option<diesel::dsl::Eq<records::record_type, i16>>,
Option<diesel::dsl::Eq<records::value, BigDecimal>>
) as diesel::insertable::Insertable<records::table>>::Values;
#[allow(non_shorthand_field_patterns)]
fn values(self) -> Self::Values {
let Record {
id: ref id,
record_type: ref record_type,
value: ref value,
} = *self;
let record_type = match *record_type {
RecordType::A => 1,
RecordType::B => 2,
};
let value: BigDecimal = value.to_string().parse().unwrap();
diesel::insertable::Insertable::values((
Some(::ExpressionMethods::eq(records::id, *id)),
Some(::ExpressionMethods::eq(records::record_type, record_type)),
Some(::ExpressionMethods::eq(records::value, value))))
}
}

Resources