Snippets Collections
# method 1
import * as wasm from 'wasm/pkg'

ngOnInit()
  wasm.greet()


#method 2
import { greet } from 'wasm/pkg/wasm_bg.wasm'; #|| from 'wasm/pkg'
  ngOnInit()
    greet()

# method 3
ngOnInit() {
  const rust = import('../../wasm/pkg');
  rust.then(m => m.greet()).catch(console.error);

  rust.then(m => console.log(m.add(2, 2), 'added'));
}

# Terminal command to build lib.rs 
wasm-pack build
use std::collections::BTreeMap;

use bencode::{Bencode, Encoder};
use bencode::util::ByteString;

#[derive(Default, Debug)]
pub struct Torrent {
    announce: String,
    announce_list: Vec<String>,
    name: String,
    comment: String,
    multi_file: bool,
    piece_length: i32,
    length: i64,
    creation_date: String,
    total_size: i32,
}


impl Torrent {
    pub fn new() -> Self {
        return Torrent {
            ..Default::default()
        };
    }
    pub fn populate_from_bencode(&mut self, b: Bencode) -> Bencode {
        if let Bencode::Dict(dict) = b {
            dict.into_iter().for_each(|(s, b)| {
                if s.as_slice() == b"announce" {
                    self.announce = extract_string(b).unwrap_or_else(|| panic!("unable to extract announce"));
                } else if s.as_slice() == b"name" {
                    self.name = extract_string(b).unwrap_or_else(|| panic!("unable to extract name"));
                } else if s.as_slice() == b"pieces" {} else if s.as_slice() == b"comment" {
                    self.comment = extract_string(b).unwrap_or_else(|| panic!("unable to extract comment"));
                } else if s.as_slice() == b"creation-date" {
                    self.creation_date = extract_string(b).unwrap_or_else(|| panic!("unable to extract creation-date"));
                } else if s.as_slice() == b"info" {
                    self.populate_from_bencode(b);
                } else if s.as_slice() == b"length" {
                    if let Bencode::Number(length) = self.populate_from_bencode(b) {
                        self.length = length;
                    }
                } else if s.as_slice() == b"announce-list" {
                    if let Bencode::List(x) = self.populate_from_bencode(b) {
                        self.announce_list = x.into_iter()
                            .map(|x| extract_list(x).unwrap_or_else(|| panic!("list")))
                            .flatten()
                            .map(|x| extract_string(x).unwrap_or_else(|| panic!("unable to extract string")))
                            .collect();
                    }
                }
            });

            return Bencode::Empty;
        } else {
            return b;
        }
    }
}

fn extract_list(b: Bencode) -> Option<Vec<Bencode>> {
    if let Bencode::List(s) = b {
        return Some(s);
    }
    return None;
}

fn extract_pieces(b: Bencode) -> Option<Vec<u8>> {
    if let Bencode::ByteString(x) = b {
        return Some(x);
    }
    return None;
}


fn extract_string(b: Bencode) -> Option<String> {
    if let Bencode::ByteString(s) = b {
        return Some(String::from_utf8_lossy(&s).to_string());
    }
    return None;
}


//decoder.rs

use std::fs::File;
use std::io::Read;

use bencode::Bencode;

use crate::torrent;
use crate::torrent::Torrent;


pub fn decode_file_into_torrent(path: &'static str) -> Result<Torrent, Box<dyn std::error::Error>> {
    let mut file = File::open(path)?;
    let v = file.bytes().map(|x| x.unwrap()).collect::<Vec<u8>>();
    let bencode = bencode::from_vec(v).unwrap();
    let mut t = Torrent::new();
    t.populate_from_bencode(bencode);
    Ok(t)
}







#[cfg(test)]
mod tests {
    use crate::decoder;

    use super::*;

    #[test]
    fn test_parser() {
        let t = decoder::decode_file_into_torrent("src/test.torrent");
        assert!(t.is_ok());
    }
}
use std::fs::File;
use std::io::Read;

fn main() {
    let path = "/home/aaryaman/projects/rusty/oxibit/Hawkeye.torrent";
    let mut torrent = File::open(path).unwrap();

    let mut buf = vec![];
    torrent.read_to_end(&mut buf);
    let contents = String::from_utf8_lossy(&buf);
    println!("{}", contents);
}
const root = document.body;

const createElement = (el, parent, prepend = false) => {
  const { nodeName = 'div', ...attrs } = el;
  const element = document.createElement(nodeName);
  Object.entries(attrs).forEach(([attr, value]) => {
    element[attr] = value;
  });
  if (prepend) parent.prepend(element);
  else parent.append(element);
};

createElement(
  {
    nodeName: 'div',
    textContent: 'Hello world',
  },
  root
);

createElement(
  {
    nodeName: 'p',
    textContent: 'Hi',
  },
  root,
  true
);
use std::fs;

fn main() {
	let dir = "/home/aaryaman/projects/rusty/music";
	let paths = fs::read_dir(&dir).unwrap();
	let names = 
	paths.map(|entry| {
		// entry is a Result<DirEntry, std::io::Error>
		let entry = entry.unwrap();
		// entry is a DirEntry
		
		let entry_path = entry.path();
		// entry_path is a PathBuf
		
		let file_name = entry_path.file_name().unwrap();
		// file_name is OsStr

		let file_name_as_str = file_name.to_str().unwrap();
		let file_name_as_string = String::from(file_name_as_str);

		file_name_as_string

	}).collect::<Vec<String>>();

	println!("{:?}", names);
}
use std::fs;

fn main() {
    let paths = fs::read_dir("./").unwrap();

    for path in paths {
        println!("Name: {}", path.unwrap().path().display())
    }
}
#!/usr/bin/env bash

# install cargo
sudo apt-get update -y
sudo apt-get install -y cargo

echo '\n# Add .cargo to $PATH\nexport PATH="~/.cargo/bin:$PATH"\n' >> ~/.zshrc

cargo install cargo-update
let hello = warp::path!("hello" / String)
        .and(warp::any().map(move || validator.clone()))
        .and(warp::addr::remote())
        .and_then(response);

warp::serve(hello).run(([127, 0, 0, 1], 3030)).await;
async fn response(
    name: String,
    validator: Validator,
    remote: Option<SocketAddr>,
) -> Result<impl warp::Reply, warp::Rejection> {
    if let Some(addr) = remote {
        let ip_string = addr.ip().to_string();
        if validator.is_valid(ip_string.clone()).await {
            Ok(format!("Hello, {} from {}!", name, &ip_string))
        } else {
            Ok(format!("No key for {}!", &ip_string))
        }
    } else {
        Ok("No remote address!".to_string())
    }
}
let validator = Validator::new();
let path = std::path::Path::new(".env");
dotenv::from_path(path).ok();

if std::env::var("RUST_LOG").is_err() {
  std::env::set_var("RUST_LOG", "info");
}
env_logger::init();
star

Mon Jul 11 2022 18:59:17 GMT+0000 (Coordinated Universal Time) https://rustwasm.github.io/docs/book/game-of-life/hello-world.html

#rust #wasm #wasm-pack #angular
star

Thu Jul 07 2022 10:05:59 GMT+0000 (Coordinated Universal Time) https://codereview.stackexchange.com/questions/227694/rust-torrent-parser

#rust
star

Thu Jul 07 2022 09:46:08 GMT+0000 (Coordinated Universal Time)

#rust
star

Mon Jun 20 2022 16:40:48 GMT+0000 (Coordinated Universal Time)

#rust
star

Wed Jun 15 2022 11:40:18 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/a/31226040

#rust
star

Tue Jun 14 2022 20:20:32 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/a/26084812

#rust
star

Wed Feb 02 2022 22:07:52 GMT+0000 (Coordinated Universal Time) https://github.com/jimbrig/dotfiles-wsl/blob/main/scripts/dev/scripts/install-cargo.sh

#installation #linux #bash #wsl #cargo #rust
star

Tue Aug 17 2021 16:37:54 GMT+0000 (Coordinated Universal Time) https://rust-unofficial.github.io/patterns/intro.html

#rust #design #patterns
star

Tue Aug 17 2021 16:32:31 GMT+0000 (Coordinated Universal Time) https://rust-lang.github.io/api-guidelines/

#rust #api
star

Thu Jul 29 2021 16:13:09 GMT+0000 (Coordinated Universal Time) https://nnethercote.github.io/perf-book/title-page.html

#rust #performance
star

Fri Jun 04 2021 05:28:37 GMT+0000 (Coordinated Universal Time)

#rust
star

Fri Jun 04 2021 05:27:18 GMT+0000 (Coordinated Universal Time)

#rust
star

Fri Jun 04 2021 05:26:25 GMT+0000 (Coordinated Universal Time)

#rust
star

Fri Jun 04 2021 05:25:20 GMT+0000 (Coordinated Universal Time)

#rust

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension