Skip to content

Instantly share code, notes, and snippets.

View fancellu's full-sized avatar

Dino Fancellu fancellu

View GitHub Profile
@fancellu
fancellu / tokio_mutex.rs
Created February 23, 2024 19:25
Rust example of Tokio Mutex usage between threads
use std::sync::Arc;
use tokio::sync::Mutex;
// async tokio function to increment i32 behind arc mutex
async fn increment(remote: Arc<Mutex<i32>>) {
println!("trying to lock");
let mut tvc = remote.lock().await;
println!("incremented");
*tvc += 1;
}
@fancellu
fancellu / tokio_spawn.rs
Last active February 24, 2024 02:56
Rust example of tokio::spawn and JoinHandle processing
async fn hello(name: &str) -> String {
// pretend to be doing some work
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
format!("Hello {}", name)
}
fn blocking() -> String {
println!("Blocking");
@fancellu
fancellu / csv_demo.rs
Last active February 24, 2024 02:56
Rust simple CSV processing from a CV file, using csv crate
use std::{error::Error, process};
fn cities() -> Result<(), Box<dyn Error>> {
let mut csv_rdr = csv::Reader::from_path("data/cities.csv")?;
for result in csv_rdr.records() {
let record = result?;
println!("{:?}", record);
println!("{}",record.get(0).unwrap());
}
Ok(())
@fancellu
fancellu / reqwest_demo.rs
Created February 19, 2024 20:02
Rust reqwest http client async json demo with serde
use serde::Deserialize;
use std::time::Duration;
#[derive(Deserialize, Debug)]
struct Product {
id: i32,
title: String,
description: String,
price: f64,
#[serde(rename = "discountPercentage")]
@fancellu
fancellu / DiningPhilosophersIOApp.scala
Created February 16, 2024 14:23
Dining Philosophers with Cats Effect
import cats.effect.std.Semaphore
import cats.effect._
import cats.implicits._
import scala.concurrent.duration._
object DiningPhilosophersIOApp extends IOApp {
case class Fork(id: Int, lock: Semaphore[IO])
@fancellu
fancellu / DiningPhilosophers.scala
Last active February 16, 2024 12:17
Scala implementation of dining philosophers, after doing it in Rust
import java.util.concurrent.Executors
import java.util.concurrent.locks.{Lock, ReentrantLock}
import scala.concurrent.{Await, ExecutionContext, Future}
import scala.concurrent.duration.*
import scala.concurrent.ExecutionContext.Implicits.global
case class Fork(id: Int, lock: Lock)
case class Philosopher(name: String, left: Fork, right: Fork)
@fancellu
fancellu / dining_philosophers.rs
Last active February 23, 2024 20:43
Rust dining philosophers problem, to eat, each must grab 2 forks, but we have same number of forks as philosophers
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
struct Fork {
id: usize,
mutex: Mutex<()>,
}
impl Fork {
@fancellu
fancellu / rascii_demo.rs
Created February 12, 2024 19:23
Rust demo of rasciigraph, which plots simple ascii graphs, quite nice
use rand::Rng;
use rasciigraph::{plot, Config};
fn main() {
let vec = (0..70)
.map(|_| rand::thread_rng().gen::<f64>() * 13.0 - 3.0)
.collect::<Vec<_>>();
let plot = plot(
vec,
@fancellu
fancellu / flexi_data_parse.rs
Created February 9, 2024 22:31
Rust code to parse dates flexibly with several formats
use chrono::prelude::*;
fn flexi_data_parse(text: &str) -> Option<NaiveDate> {
let text = text.replace(['.', '/'], "-");
let fmts = ["%Y-%m-%d", "%Y-%b-%d", "%d-%b-%Y", "%b-%d-%Y", "%d-%m-%Y"];
for fmt in fmts {
let parser = NaiveDate::parse_from_str(text.as_str(), fmt);
if parser.is_ok() {
return parser.ok();
@fancellu
fancellu / run_length_encoding.rs
Created February 8, 2024 22:24
Rust run length encoding
use std::fmt::Display;
use std::str::FromStr;
#[derive(Debug)]
struct Rle {
data: Vec<u8>,
}
impl Rle {
fn decode(&self) -> String {