Libraries

Articles in Section

  • itertools

    Itertools library

  • rand

    Random numbers library

  • serde

    Serialization / Deserialization Library

Library Unit-tests

Примеры:

pub fn greet_user(name: &str) -> String {
    format!("Hello {name}")
}

pub fn login(username: &str, password: &str) -> bool {
    username == "admin" && password == "P@ssw0rd"
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_greet_user() {
        assert_eq!("Hello Alex", greet_user("Alex"));
    }

    #[test]
    fn test_login() {
        assert!(login("admin", "P@ssw0rd"));
    }
}

Запуск тестов - командой cargo test

Subsections of Libraries

itertools

External link: https://docs.rs/itertools/latest/itertools/

Working with iterators

Sorting() a string of letters (with rev() - reverse order)

use itertools::Itertools;

let text = "Hello world";
let text_sorted = text.chars().sorted().rev().collect::<String>();
// rev() - Iterate the iterable in reverse
   
println!("Text: {}, Sorted Text: {}", text, text_sorted); 
// Text: Hello world, Sorted Text: wroollledH 

Counts() подсчёт количества одинаковых элементов в Array

use itertools::Itertools;

let number_list = [1,12,3,1,5,2,7,8,7,8,2,3,12,7,7];
let mode = number_list.iter().counts(); // Itertools::counts() 
// возвращает Hashmap, где ключи взяты из массива, значения - частота
for (key, value) in &mode {  
    println!("Число {key} встречается {value} раз");  
 } 

rand

Generating random numbers

External links:

Using rand lib example:

use rand::Rng;

fn main() {
let secret_of_type = rand::thread_rng().gen::<u32>();
let secret = rand::thread_rng().gen_range(1..=100);

println!("Random nuber of type u32: {secret_of_type}");
println!("Random nuber from 1 to 100: {}", secret); }

serde

Installing

Add serde framework with Derive feature to use it in structures and functions. Also add a separate serde_json lib for converting into specifically JSON:

cargo add serde -F derive
cargo add serde_json

Usage

Add serde, then mark the structures with Serialise, Deserialise traits and use serde_json for serialising:

use serde::{Deserialize, Serialize};

#[derive(PartialEq, Debug, Clone, Serialize, Deserialize)]
pub enum LoginRole {
    Admin,
    User,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct User {
    pub username: String,
    pub password: String,
    pub role: LoginRole,
}

pub fn get_default_users() -> HashMap<String, User> {
    let mut users = HashMap::new();
    users.insert(
        "admin".to_string(),
        User::new("admin", "password", LoginRole::Admin),
    );
    users.insert(
        "bob".to_string(),
        User::new("bob", "password", LoginRole::User),
    );
    users
}

pub fn get_users() -> HashMap<String, User> {
    let users_path = Path::new("users.json");
    if users_path.exists() {
        // Load the file!
        let users_json = std::fs::read_to_string(users_path).unwrap();
        let users: HashMap<String, User> = serde_json::from_str(&users_json).unwrap();
        users
    } else {
        // Create a file and return it
        let users = get_default_users();
        let users_json = serde_json::to_string(&users).unwrap();
        std::fs::write(users_path, users_json).unwrap();
        users
    }