Skip to content

Commit

Permalink
feat: add a new directory
Browse files Browse the repository at this point in the history
  • Loading branch information
Shieber authored and Shieber committed May 15, 2022
1 parent 0abed85 commit a9164d7
Show file tree
Hide file tree
Showing 239 changed files with 14,420 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ All demo codes are saved by chapter under `code/`.
![star](https://starchart.cc/QMHTMY/RustBook.svg)

### Changelog
* 2022-05-15 add a new directory `publication`
* 2022-02-27 change the book cover
* 2022-02-15 add stargazer chart
* 2022-02-12 add code statistics
Expand Down
1 change: 1 addition & 0 deletions README_CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
![star](https://starchart.cc/QMHTMY/RustBook.svg)

### 更新日志
* 2022-05-15 添加新目录 `publication`
* 2022-02-27 更换书籍封面
* 2022-02-15 添加收藏数变化图
* 2022-02-12 添加代码统计信息
Expand Down
1 change: 1 addition & 0 deletions README_JP.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
![star](https://starchart.cc/QMHTMY/RustBook.svg)

### 変更ログ
* 2022-05-15 新しいディレクトリ `publication` を追加する
* 2022-02-27 本の表紙を変更する
* 2022-02-15 人気チャートを追加する
* 2022-02-12 コード統計を追加する
Expand Down
1 change: 1 addition & 0 deletions README_TW.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
![star](https://starchart.cc/QMHTMY/RustBook.svg)

### 更新日誌
* 2022-05-15 添加新目錄 `publication`
* 2022-02-27 更換書籍封面
* 2022-02-15 添加收藏數變化圖
* 2022-02-12 添加代碼統計信息
Expand Down
5 changes: 5 additions & 0 deletions publication/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
### Description [[](./README_CN.md)[](./README_TW.md)[](./README_JP.md)]

The published book consists of ten chapters and all demo codes are here.

![code_statistics](./code_statistics.png)
5 changes: 5 additions & 0 deletions publication/README_CN.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
### 简介 [[En](./README.md)[](./README_TW.md)[](./README_JP.md)]

本书打算出版了,共十章内容,代码如下。

![code_statistics](./code_statistics.png)
4 changes: 4 additions & 0 deletions publication/README_JP.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
### 説明 [[En](./README.md)[](./README_CN.md)[](./README_TW.md)]
その本は10章で出版される予定である。すべてのコードは、章ごとに `code/` に保存されました。

![code_statistics](./code_statistics.png)
5 changes: 5 additions & 0 deletions publication/README_TW.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
### 簡介 [[En](./README.md)[](./README_CN.md)[](./README_JP.md)]

本書打算出版了,共十章內容,所有代碼按照章節保存在 `code/`

![code_statistics](./code_statistics.png)
7 changes: 7 additions & 0 deletions publication/code/chapter01/PasswdGenerator/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[workspace]

members = [
"hash",
"encryptor",
"main",
]
12 changes: 12 additions & 0 deletions publication/code/chapter01/PasswdGenerator/encryptor/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
[package]
name = "encryptor"
authors = ["shieber"]
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
anyhow = "1.0.56"
base64 = "0.13.0"
hash = { path = "../hash" }
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub mod password;
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
use anyhow::{bail, Error, Result};
use base64::encode;
use hash::merhash::mersenne_hash;

/// 密码子 (长度 100),可随意交换次序,增减字符,实现个性化定制
const CRYPTO: &str = "!pqHr$*+STKU1%Vst_uv:w{WSX&YZ-/01_2.34<ABECo|x#yDE^FG?HEI[]JK>LM#NOBWPQ:Ra@}cde56R7=8l9f/9gIhi,jkzmn";

/// 哈希密码函数,利用哈希值高次方值来选择密码子中字符
///
/// #Example
/// ```
/// use encryptor::password::generate_password;
/// let seed = "jdwnp";
/// let length = 16;
/// let passwd = generate_password(seed, length);
/// match passwd {
/// Ok(val) => println!("{:#?}", val),
/// Err(err) => println!("{:#?}", err),
/// }
/// ```
pub fn generate_password(seed: &str, length: usize) -> Result<String, Error> {
// 判断密码长度,不能太短
if length < 6 {
bail!("length must >= 6");
}

// 计算 mer_hash
let p = match length {
6..=10 => 1,
11..=15 => 2,
16..=20 => 3,
_ => 3,
};
let mut mer_hash = mersenne_hash(seed).pow(p);

// 由 mer_hash 计算 passwd
let mut passwd = String::new();
let crypto_len = CRYPTO.len();
while mer_hash > 9 {
let loc = mer_hash % crypto_len;
let nthc = CRYPTO.chars().nth(loc).expect("Error while getting char!");
passwd.push(nthc);
mer_hash /= crypto_len;
}

// 将 seed 中字符逐个加入 passwd
let interval = passwd.clone();
for c in seed.chars() {
passwd.push(c);
passwd += &interval;
}

// 将 passwd 编码为 base64
passwd = encode(passwd);
passwd = passwd.replace("+", "*").replace("/", "*");

// 长度不够,interval 来凑
let interval = passwd.clone();
while passwd.len() < length {
passwd += &interval;
}

// 返回前 length 个字符作为密码
Ok(format!("{}: {}", seed, &passwd[..length]))
}
9 changes: 9 additions & 0 deletions publication/code/chapter01/PasswdGenerator/hash/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
[package]
name = "hash"
authors = ["shieber"]
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
13 changes: 13 additions & 0 deletions publication/code/chapter01/PasswdGenerator/hash/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
pub mod merhash;

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

#[test]
fn mersenne_hash_works() {
let seed = String::from("jdxjp");
let hash = mersenne_hash(&seed);
assert_eq!(2000375, hash);
}
}
21 changes: 21 additions & 0 deletions publication/code/chapter01/PasswdGenerator/hash/src/merhash.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
//! 梅森哈希
//!
/// 用梅森素数 127 计算哈希值
///
/// # Example
/// ```
/// use hash::merhash::mersenne_hash;
///
/// let seed = "jdxjp";
/// let hash = mersenne_hash(&seed);
/// assert_eq!(2000375, hash);
/// ```
pub fn mersenne_hash(seed: &str) -> usize {
let mut hash: usize = 0;

for (i, c) in seed.chars().enumerate() {
hash += (i + 1) * (c as usize);
}

(hash % 127).pow(3) - 1
}
12 changes: 12 additions & 0 deletions publication/code/chapter01/PasswdGenerator/main/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
[package]
name = "PasswdGenerator"
authors = ["shieber"]
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
anyhow = "1.0.56"
clap = { version = "3.1.6", features = ["derive"] }
encryptor = { path = "../encryptor"}
32 changes: 32 additions & 0 deletions publication/code/chapter01/PasswdGenerator/main/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
use anyhow::{bail, Result};
use clap::Parser;
use encryptor::password::generate_password;

/// A simple password generator for any account
#[derive(Parser, Debug)]
#[clap(version, about, long_about = None)]
struct Args {
/// Seed to generate password
#[clap(short, long)]
seed: String,

/// Length of password
#[clap(short, long, default_value_t = 16)]
length: usize,
}

fn main() -> Result<()> {
let args = Args::parse();
if args.seed.len() < 4 {
bail!("seed {} length must >= 4", &args.seed);
}

let (seed, length) = (args.seed, args.length);
let passwd = generate_password(&seed[..], length);
match passwd {
Ok(val) => println!("{}", val),
Err(err) => println!("{}", err),
}

Ok(())
}
16 changes: 16 additions & 0 deletions publication/code/chapter01/adapter_consumer.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// adapter_consumer.rs

fn main() {
let nums = vec![1,2,3,4,5,6];
let nums_iter = nums.iter();
let total = nums_iter.sum::<i32>(); // 消费者

let new_nums: Vec<i32> = (0..100).filter(|&n| 0 == n % 2)
.collect(); // 适配器
println!("{:?}", new_nums);

// 求小于1000的能被3或5整除的所有整数之和
let sum = (1..1000).filter(|n| n % 3 == 0 || n % 5 == 0)
.sum::<u32>(); // 结合适配器和消费者
println!("{sum}");
}
46 changes: 46 additions & 0 deletions publication/code/chapter01/code_style.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// 枚举
enum Result<T, E> {
Ok(T),
Err(E),
}

// 特性,trait
pub trait From<T> {
fn from<T> -> Self;
}

// 结构体
struct Rectangle {
height: i32,
width: i32,
}
impl Rectangle {
// 构造函数
fn new(height: i32, width: i32) -> Self {
Self {
height,
width,
}
}

// 函数
fn calc_area(&self) -> i32 {
self.height * self.width
}
}

// 静态变量和常量
static NAME: &str = "kew";
const AGE: i32 = 25;

// 宏定义
macro_rules! add {
($a:expr, $b:expr) => {
{
$a + $b
}
}
}

// 变量及宏使用
let sum_of_nums = add!(1, 2);
13 changes: 13 additions & 0 deletions publication/code/chapter01/install_rust.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
#!/bin/bash

# Linux 下安装 Rust

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

echo " " >> ~/.bashrc
echo "# Rust 语言环境变量" >> ~/.bashrc
echo "export RUSTPATH=$HOME/.cargo/bin" >> ~/.bashrc
echo "export PATH=$PATH:$RUSTPATH" >> ~/.bashrc
echo " " >> ~/.bashrc

source ~/.bashrc
23 changes: 23 additions & 0 deletions publication/code/chapter01/integer_to_complex.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// integer_to_complex.rs

#[derive(Debug)]
struct Complex {
real: i32, // 实部
imag: i32 // 虚部
}

// 为 i32 实现到复数的转换功能,i32 转换为实部,虚部置 0
impl From<i32> for Complex {
fn from(real: i32) -> Self {
Complex {
real,
imag: 0
}
}
}

fn main() {
let c1: Complex = Complex::from(2_i32);
let c2: Complex = 2_i32.into(); // 默认实现了 Into
println!("c1: {:?}, c2: {:?}", c1, c2);
}
10 changes: 10 additions & 0 deletions publication/code/chapter01/keywords.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
Self enum match super
as extern mod trait
async false move true
await fn mut type
break for pub union
const if ref unsafe
continue impl return use
crate in self where
dyn let static while
else loop struct
34 changes: 34 additions & 0 deletions publication/code/chapter01/more_cow_usage.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// more_cow_usage.rs

use std::borrow::Cow;

fn abs_all(input: &mut Cow<[i32]>) {
for i in 0..input.len() {
let v = input[i];
if v < 0 {
input.to_mut()[i] = -v;
}
}
}

fn main() {
// 只读,不写,没有发生复制操作
let a = [0, 1, 2];
let mut input = Cow::from(&a[..]);
abs_all(&mut input);
assert_eq!(input, Cow::Borrowed(a.as_ref()));

// 写时复制, 在读到-1的时候发生复制
let b = [0, -1, -2];
let mut input = Cow::from(&b[..]);
abs_all(&mut input);
assert_eq!(input, Cow::Owned(vec![0,1,2]) as Cow<[i32]>);

// 没有写时复制,因为已经拥有所有权
let mut input = Cow::from(vec![0, -1, -2]);
abs_all(&mut input);
assert_eq!(input, Cow::Owned(vec![0,1,2]) as Cow<[i32]>);

let v = input.into_owned();
assert_eq!(v, [0, 1, 2]);
}
Loading

0 comments on commit a9164d7

Please sign in to comment.