Skip to content

Instantly share code, notes, and snippets.

@trimoq
trimoq / dyn.rs
Last active November 24, 2019 15:57
df:di_bench_dyn
use std::env;
use std::time::SystemTime;
trait Backend{
fn compute(&self,number: i64) -> i64;
}
struct PositiveBackend;
struct NegativeBackend;
@trimoq
trimoq / df_di_bench_inline.rs
Last active December 3, 2019 12:45
First benchmark for a baseline
use std::time::SystemTime;
struct PositiveBackend;
impl PositiveBackend{
fn compute(&self, number: u64) -> u64{
number+1
}
}
impl<'a, 'r> FromRequest<'a, 'r> for AuthUser {
type Error = ApiError;
fn from_request(request: &'a Request<'r>) -> request::Outcome<AuthUser, Self::Error> {
let con = request.guard::<DbConn>().unwrap();
request.cookies()
.get_private("user_id")
.and_then(|cookie| cookie.value().parse().ok())
.and_then(|id| ApiUserDAO::get_by_slug_enabled(&con,id))
.or_else( || {
request.headers().get_one("x-api-key")
pub fn insert(con: &DbCon, new_stay: NewStay) -> Result<Stay, Error> {
diesel::insert_into(stay::table)
.values(&new_stay)
.get_result(&**conn)
}
pub fn get_all_for_user(con: &DbCon, user: ApiUser) -> Vec<Stay> {
Stay::belonging_to(&user)
.load::<Stay>(&**conn)
.unwrap() // this is quite bad but let's ignore it for the example
@trimoq
trimoq / schema.rs
Last active October 21, 2019 10:52
table! {
drive (id) {
id -> Int4,
user_id -> Int4,
travel_date -> Date,
start_loc -> Varchar,
end_loc -> Varchar,
distance -> Int4,
}
}
CREATE TABLE drive (
id SERIAL PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES apiuser(id) ON DELETE CASCADE,
travel_date DATE NOT NULL,
start_loc VARCHAR NOT NULL,
end_loc VARCHAR NOT NULL,
distance INTEGER NOT NULL,
UNIQUE(user_id,travel_date)
);
@trimoq
trimoq / AuthUserFromRequestTiny.rs
Created October 21, 2019 09:18
Get the username from the cookie
impl<'a, 'r> FromRequest<'a, 'r> for AuthUser {
type Error = ApiError;
fn from_request(request: &'a Request<'r>) -> request::Outcome<AuthUser, Self::Error> {
request.cookies()
.get_private("user_id")
.and_then(|cookie| cookie.value().parse().ok())
.into_outcome((Status::Unauthorized,ApiError::unauthorized("Unauthorized or no cookie")))
.map(|user| AuthUser(user))
}
}
@trimoq
trimoq / stay_update.rs
Created October 21, 2019 09:07
posting a Stay object
#[put("/stay/<id>", format = "json", data = "<new_stay>")]
fn stay_update(id: i32, new_stay: Json<Stay> ) -> Result<...> {
// ...
}
@trimoq
trimoq / Behemoth.rs
Created October 21, 2019 08:59
Expanded sample behemoth
#![feature(prelude_import)]
#![no_std]
#![feature(proc_macro_hygiene, decl_macro)]
#[prelude_import]
use ::std::prelude::v1::*;
#[macro_use]
extern crate std as std;
#[macro_use]
extern crate rocket;
fn hello(name: String) -> String {
@trimoq
trimoq / tiny_hello.rs
Created October 21, 2019 08:55
Tiny hello world code
#[macro_use]
extern crate rocket;
#[get("/hello/<name>")]
fn hello(name: String) -> String {
format!("hello {}", name)
}
fn main() {
rocket::ignite()