Skip to content

Instantly share code, notes, and snippets.

View cfoster's full-sized avatar

Charles Foster cfoster

  • Warwick, United Kingdom
View GitHub Profile
@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 {
@fancellu
fancellu / hex_colours.rs
Created February 8, 2024 15:26
Rust conversion of hex rgb strings to their components
use crate::RGBError::WrongLength;
use std::num::ParseIntError;
use std::str::FromStr;
#[derive(Debug)]
struct RGB {
red: u8,
green: u8,
blue: u8,
}
@fancellu
fancellu / isbn.rs
Last active February 15, 2024 11:20
Rust check digit calculation for ISBN-13
use crate::InvalidIsbn::{BadChecksum, TooLong, TooShort};
use std::str::FromStr;
// check digit calculation for ISBN-13
#[derive(Debug)]
struct Isbn {
raw: String,
}
@fancellu
fancellu / sum_missing.rs
Created February 6, 2024 19:14
Sum up a vector of optional numbers
use std::iter::Sum;
fn sum_with_missing<T: Sum + Copy>(vec: &Vec<Option<T>>) -> T {
vec.into_iter().filter_map(|x| *x).sum()
}
fn main() {
let mut v = vec![Some(1), Some(2), Some(3), None, Some(5)];
println!("{}", sum_with_missing(&v));