Code Snippets Rust

Short texts Rust 🧑‍💻 Code snippets Rust ✍️ Reading lists Rust 👀

tungstenite-stack-test.rs

use std::net::TcpListener; use std::sync::mpsc::{channel, Sender}; use std::thread; use std::time::Duration; use futures_util::{SinkExt, StreamExt}; use tungstenite::accept; use tungstenite::Message; fn block_client() { tokio::runtime::Runtime::new().unwrap().block_on(tokio_client()); } async fn async_client() { let (ws, _) = async_tungstenite::tokio::connect_async(“ws://127.0.0.1:9001”).await.unwrap(); let mut counter = 0; let (mut tx, mut rx) = ws.split(); tokio::spawn(async move { loop { tx.send(Message::Text(format!(“hello {}”, counter))).await.unwrap(); counter += 1; tokio::time::sleep(Duration::from_secs(1)).await; } […]

main.rs

use crossterm::style::*; // add import impl Output { … fn draw_rows(&mut self) { let screen_rows = self.win_size.1; let screen_columns = self.win_size.0; for i in 0..screen_rows { let file_row = i + self.cursor_controller.row_offset; if file_row >= self.editor_rows.number_of_rows() { if self.editor_rows.number_of_rows() == 0 && i == screen_rows / 3 { let mut welcome = format!(“Pound Editor — […]

Simple Rust Phone Number Validator

use regex::Regex; use std::io; fn main() { let re = Regex::new(r”^((?:\+\d{1,3})?\(?\d{3}\)?\-?\d{3}\-?\d{4})\r?\n$”).unwrap(); println!(“Enter Phone Number:”); let mut number = String::new(); io::stdin().read_line(&mut number).expect(“yikes”); let caps = re.captures(&number); if !caps.is_none() { println!(“Great job! Your phone number is: {}”, caps.unwrap().get(1).unwrap().as_str()); } else { println!(“Feel bad about yourself, that was a terrible phone number. Jesus.”) } }

Custom Text based Diesel type for an enum

#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] #[serde(rename_all=”snake_case”)] pub enum State { Pending, Sending, Sent, Failed, } impl fmt::Display for State { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, “{}”, match *self { State::Pending => “pending”, State::Sending => “sending”, State::Sent => “sent”, State::Failed => “failed”, }) } } impl FromSqlRow for State { fn build_from_row(row: […]