Skip to content

Instantly share code, notes, and snippets.

View first_lifetime_fix.rs
struct SomeCollection<'a> {
strings: Vec<&'a str>
}
impl<'a> SomeCollection<'a> {
pub fn new() -> Self {
SomeCollection { strings: Vec::new() }
}
pub fn insert(&mut self, s: &'a str) {
View two_examples.rb
# first version
my_collection = SomeCollection.new
(1..10).each do |item|
value = "value number #{item + 1}"
my_collection.insert(value)
end
# second version
my_collection = SomeCollection.new
values = []
View second_lifetime_fix.rs
struct SomeCollection {
strings: Vec<String>
}
impl SomeCollection {
pub fn new() -> Self {
SomeCollection { strings: Vec::new() }
}
pub fn insert(&mut self, s: String) {
View borrow_checker_error.rs
struct SomeCollection<'a> {
strings: Vec<&'a str>
}
impl<'a> SomeCollection<'a> {
pub fn new() -> Self {
SomeCollection { strings: Vec::new() }
}
pub fn insert(&mut self, s: &'a str) {
View or_reducer.rs
pub fn reduce_or(stack: &mut Vec<Token>) -> Result<Token, RuntimeError> {
// would return Err if the vector were not entirely
// made of Token::Operand(Type::Bool), since we can't reduce with `or`
// other values
let bool_result = unwrap_boolean_tokens(stack);
if let Ok(bool_vec) = bool_result {
Ok(Token::Operand(Type::Bool(
bool_vec.iter().any(|b| *b) // and reducer has "all" here
)))
} else {
View subtract_and_divide_reduce.rs
fn reduce_subtraction(stack: &mut Vec<Token>) -> Result<Token, RuntimeError> {
let operands = unwrap_operand_tokens(stack);
match operands {
Ok(mut operand_vec) =>{
let initial_positive_option = operand_vec.pop();
if let Some(initial_positive) = initial_positive_option {
Ok(Token::Operand(
operand_vec
.iter()
.fold(initial_positive, |sum, value| sum - value)))
View add_and_mult_reduce.rs
fn reduce_addition(stack: &mut Vec<Token>) -> Result<Token, RuntimeError> {
let operands = unwrap_operand_tokens(stack);
match operands {
Ok(operand_vec) => Ok(Token::Operand(
operand_vec
.iter()
.fold(0, |sum, value| sum + value))),
Err(_) => Err(RuntimeError{})
}
}
View simple_parser.rs
pub fn parse(bytes: &[u8]) -> Result<Vec<Token>, TokenizationError> {
let parse_result = tokens(bytes).to_result();
match parse_result {
Ok(token_vec) => Ok(token_vec),
Err(_) => Err(TokenizationError {})
}
}
View nom_combinators.rs
named!(single_token<&[u8], Token>,
alt!(
left_paren |
right_paren |
addition_sign |
subtraction_sign |
multiplication_sign |
division_sign |
operand
)
View nom_tokenizer.rs
named!(left_paren<&[u8], Token>,
do_parse!(tag!("(") >> (Token::LeftParen))
);
named!(right_paren<&[u8], Token>,
do_parse!(tag!(")") >> (Token::RightParen))
);
named!(addition_sign<&[u8], Token>,
do_parse!(tag!("+") >> (Token::Operator(Opcode::Add)))