test_name 0.1.8

Just some Rust learning test cases
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
//! Rust Learning Test Cases Crate
//!
//! Type here to add documentation comments
//!
//! Support markdown syntax
//!
//! <div>title</div>
//!
//! | col1     | col2   | col3 |
//! |:-------:|:-------:|:-------:|
//! | cell1   | cell2   | cell3   |
//! | cell4   | cell5   | cell6   |
//!
use rand::Rng;
use std::cmp::Ordering;
use std::io;

mod front_of_house;
pub use crate::front_of_house::hosting;

pub fn add_one(x: i32) -> i32 {
    x + 1
}

pub fn add(left: usize, right: usize) -> usize {
    left + right
}

#[allow(warnings)]
fn guess_num_game() {
    let secret_number = rand::thread_rng().gen_range(0..=100);
    println!("guess a num😛");
    println!("num is : {}", secret_number);
    loop {
        let mut guess = String::new();
        io::stdin()
            .read_line(&mut guess)
            .expect("Unable to read row!");
        let guess: u32 = match guess.trim().parse() {
            Ok(num) => num,
            Err(_) => continue,
        };
        println!("guess num is : {}", secret_number);
        match guess.cmp(&secret_number) {
            Ordering::Less => println!("Smaller!"),
            Ordering::Greater => println!("Bigger!"),
            Ordering::Equal => {
                println!("Guess right!");
                break;
            }
        }
    }
}

//////////////////////////////////////////
///
//////////////////////////////////////////
#[allow(warnings)]
mod back_of_house {
    pub struct Breakfast {
        pub toast: String,
        seassonal_fruil: String,
    }

    impl Breakfast {
        pub fn summer(toast: &str) -> Breakfast {
            Breakfast {
                toast: String::from(toast),
                seassonal_fruil: String::from("peaches"),
            }
        }
    }

    fn fix_incorrect_order() {
        cook_order();
        super::serve_order();
        crate::serve_order();
    }

    fn cook_order() {}
}

fn serve_order() {}

//////////////////////////////////////////
/// # Examples
/// ```
/// let arg = 5;
/// let answer = test_name::add_one(arg);
/// assert_eq!(6,answer);
/// ```
/// ```
/// println!("666");
/// ```
/// # Panics
/// # Errors
/// # Safety
///
//////////////////////////////////////////
pub fn eat_at_restaurant() {
    let mut meal = back_of_house::Breakfast::summer("Rye");
    meal.toast = String::from("Wheat");
    println!("{}", meal.toast);
}

//////////////////////////////////////////
///
//////////////////////////////////////////
pub trait Summary {
    fn summarize(&self) -> String {
        format!("(Read more from {}...)\n", self.summarize_author())
    }
    fn summarize_author(&self) -> String;
}

pub struct NewsArticle {
    pub headline: String,
    pub location: String,
    pub author: String,
    pub content: String,
}

impl Summary for NewsArticle {
    fn summarize(&self) -> String {
        format!("{}, by {} ({})", self.headline, self.author, self.location)
    }
    fn summarize_author(&self) -> String {
        format!("@{}", self.author)
    }
}

pub struct Tweet {
    pub username: String,
    pub content: String,
    pub reply: bool,
    pub retweet: bool,
}

impl Summary for Tweet {
    fn summarize(&self) -> String {
        format!("{}: {}", self.username, self.content)
    }
    fn summarize_author(&self) -> String {
        format!("@{}", self.username)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::cmp::PartialOrd;
    use std::collections::HashMap;
    use std::fs::File;
    use std::io::{self, ErrorKind, Read};
    use std::net::IpAddr;
    use std::process::Command;

    #[test]
    fn string_slice() {
        let s = String::from("Hello world");
        let word_index = first_world(&s[..]);
        let hello = &s[..=4];
        let world = &s[6..];
        println!("{} {} {}", word_index, hello, world);
        let a = [1, 2, 3, 4, 5];
        let slice = &a[1..3];
        for i in slice {
            println!("{}", i);
        }
        println!("{}", slice[0]);
        println!("{}", slice[1]);
    }

    fn first_world(s: &str) -> &str {
        let bytes = s.as_bytes();
        for (i, &item) in bytes.iter().enumerate() {
            if item == b' ' {
                return &s[..i];
            }
        }
        &s[..]
    }

    //////////////////////////////////////////
    /// `struct` can define in `mod tests`
    //////////////////////////////////////////
    struct User {
        username: String,
        email: String,
        sign_in_count: u64,
        active: bool,
    }

    #[test]
    fn test_struct() {
        let user1 = User {
            email: String::from("someone@example.com"),
            username: String::from("someone"),
            active: true,
            sign_in_count: 1,
        };
        let user2 = User {
            email: user1.email,
            username: String::from("user2"),
            ..user1
        };
        println!(
            "{} {} {} {}",
            user2.username, user2.email, user2.sign_in_count, user2.active
        );
    }

    ////////////////////////////////////////
    /// `struct` and `impl` can define in `fn`
    ////////////////////////////////////////
    #[test]
    fn test_rectangele() {
        #[derive(Debug)]
        struct Rectangle {
            width: u32,
            length: u32,
        }

        impl Rectangle {
            fn area(&self) -> u32 {
                self.width * self.length
            }
            fn can_hold(&self, other: &Rectangle) -> bool {
                self.width > other.width && self.length > other.length
            }
            fn square(size: u32) -> Rectangle {
                Rectangle {
                    width: size,
                    length: size,
                }
            }
        }

        let s = Rectangle::square(20);
        println!("{:#?}", s);
        let rect1 = Rectangle {
            width: 30,
            length: 50,
        };
        let rect2 = Rectangle {
            width: 10,
            length: 40,
        };
        let rect3 = Rectangle {
            width: 35,
            length: 55,
        };
        println!("{}", rect1.can_hold(&rect2));
        println!("{}", rect1.can_hold(&rect3));
        println!("{}", rect1.area());
        println!("{:#?}", rect1);
    }

    ////////////////////////////////////////
    /// also, `enum` and `fn` can define in `fn`
    ////////////////////////////////////////
    #[test]
    #[allow(warnings)]
    fn test_enum() {
        enum IpAddrKind {
            V4(u8, u8, u8, u8),
            V6(String),
            Move { x: i32, y: i32 },
        }
        let home = IpAddrKind::V4(127, 0, 0, 1);
        let loopback = IpAddrKind::V6(String::from("::1"));
        route(home);
        route(loopback);
        fn route(ip_kind: IpAddrKind) {}
    }

    ////////////////////////////////////////
    /// `enum` can use `enum` type to define member
    ////////////////////////////////////////
    #[derive(Debug)]
    #[allow(warnings)]
    enum UsState {
        Alabama,
        Alaska,
    }

    #[derive(Debug)]
    #[allow(warnings)]
    enum Coin {
        Penny,
        Nickel,
        Dime,
        Quarter(UsState),
    }

    #[test]
    fn test_enum_match() {
        let c = Coin::Quarter(UsState::Alaska);
        println!("{}", value_in_cents(c));
    }

    fn value_in_cents(coin: Coin) -> u8 {
        match coin {
            Coin::Penny => 1,
            Coin::Nickel => 5,
            Coin::Dime => 10,
            Coin::Quarter(state) => {
                println!("{:#?}", state);
                25
            }
        }
    }

    ////////////////////////////////////////
    /// use `Option` type and `if let`
    ////////////////////////////////////////
    #[test]
    fn test_if_let() {
        let five = Some(5);
        let six = plus_one(five);
        assert_eq!(Some(6), six);

        let none = plus_one(None);
        assert_eq!(None, none);

        let v = Some(3u8);
        // let v: Option<i32> = None;
        if let Some(a) = v {
            println!("{}", a);
        } else {
            println!("others");
        }
    }

    fn plus_one(x: Option<i32>) -> Option<i32> {
        match x {
            None => None,
            Some(i) => Some(i + 1),
        }
    }

    #[test]
    fn test_vec() {
        let mut v: Vec<i32> = Vec::new();
        for number in 1..=4 {
            v.push(number);
            println!("{}", number);
        }
        match v.get(20) {
            Some(third) => println!("{}", third),
            None => println!("NONE"),
        }
        let first = &v[0];
        println!("{}", first);
    }

    #[test]
    fn test_string() {
        let s1 = "😀ni好";
        let s2 = ",world".to_string();
        let s = format!("{}{}", s1, s2);
        for b in s1.bytes() {
            println!("{}", b);
        }
        for b in s1.chars() {
            println!("{}", b);
        }
        let s3 = &s[..9];
        println!("{}", s3);
    }

    #[test]
    fn test_hashmap() {
        let mut scores = HashMap::new();
        scores.insert("Blue".to_string(), 10);
        let teams = vec!["Blue".to_string(), "Yellow".to_string()];
        let intial_scores = vec![10, 50];
        let scores: HashMap<_, _> = teams.iter().zip(intial_scores.iter()).collect();

        let team_name = "Blue".to_string();
        let score = scores.get(&team_name);

        match score {
            Some(s) => println!("{}", s),
            None => println!("team not exist"),
        }

        let text = "hello world wonderful world";
        let mut map = HashMap::new();
        for word in text.split_whitespace() {
            let count = map.entry(word).or_insert(0);
            *count += 1;
        }
        println!("{:#?}", map);
    }

    #[test]
    #[should_panic]
    fn test_panic() {
        // panic!("crash and burn");
        let v = vec![1, 2, 3];
        v[99];
        println!("finish");
    }

    #[test]
    fn test_error() {
        test_read_file();
        let s = read_username_from_file();
        match s {
            Ok(file) => println!("{}", file),
            Err(error) => println!("{}", error),
        }
        let home: IpAddr = "127.0.0.1".parse().unwrap();
        println!("{}", home);
    }

    fn test_read_file() -> File {
        let f = File::open("hello.txt");
        let f = match f {
            Ok(file) => file,
            Err(error) => match error.kind() {
                ErrorKind::NotFound => match File::create("hello.txt") {
                    Ok(fc) => fc,
                    Err(e) => panic!("Error creating file: {:?}", e),
                },
                oe => panic!("Error opening file {:?}", oe),
            },
        };
        f
    }

    fn read_username_from_file() -> Result<String, io::Error> {
        let mut s = String::new();
        File::open("hello.txt")?.read_to_string(&mut s)?;
        Ok(s)
    }

    #[test]
    fn use_guess() {
        pub struct Guess {
            value: i32,
        }
        impl Guess {
            pub fn new(value: i32) -> Guess {
                if value < 1 || value > 100 {
                    panic!("Guess btn 1 and 100, got {}", value);
                }
                Guess { value }
            }
            pub fn value(&self) -> i32 {
                self.value
            }
        }
        let guess = Guess::new(30);
        println!("{}", guess.value);
        println!("{}", guess.value());
    }

    #[test]
    fn test_largest() {
        let mut number_list = [1, 4, 2, 3];

        increase(&mut number_list);
        show(&number_list);

        let result = largest(&number_list);
        println!("{}", result);
        for item in number_list.iter() {
            print!("{} ", &item);
        }
        println!();

        let char_list = vec!["da", "da", "ads", "easd", "bsa"];
        let result = largest(&char_list);
        println!("{}", result);
    }

    fn largest<T: PartialOrd + Clone>(list: &[T]) -> &T {
        let mut largest = &list[0];
        for item in list.iter() {
            if item > largest {
                largest = item;
            }
        }
        largest
    }

    fn increase(list: &mut [i32]) {
        for item in list.iter_mut() {
            *item += 1;
        }
    }

    fn show(list: &[i32]) {
        for &item in list.iter() {
            print!("{} ", item);
        }
    }

    //////////////////////////////
    /// need `use super::*;`
    //////////////////////////////
    #[test]
    fn test_trait() {
        let tweet = Tweet {
            username: "horse_ebooks".to_string(),
            content: "of course, shuodedaoli".to_string(),
            reply: false,
            retweet: false,
        };
        println!("{}", tweet.summarize());

        let article = NewsArticle {
            headline: "ASDAasdasd".to_string(),
            content: "asdsadadsadsadasdasdas".to_string(),
            author: "xin".to_string(),
            location: "jiangsu".to_string(),
        };
        print!("{}", article.summarize());
    }

    #[allow(warnings)]
    struct ImportantExcerpt<'a> {
        part: &'a str,
    }

    #[allow(warnings)]
    impl<'a> ImportantExcerpt<'a> {
        fn level(&self) -> i32 {
            3
        }
    }

    #[allow(warnings)]
    struct ImportantExcerpt2 {
        part: &'static str,
    }

    #[allow(warnings)]
    impl ImportantExcerpt2 {
        fn level(&self) -> i32 {
            3
        }
    }

    #[allow(warnings)]
    fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
        if x.len() > y.len() {
            x
        } else {
            y
        }
    }

    #[test]
    fn iterator_demonstration() {
        let v1 = vec![1, 2, 3];
        let mut v1_iter = v1.iter();
        assert_eq!(v1_iter.next(), Some(&1));
        assert_eq!(v1_iter.next(), Some(&2));
        assert_eq!(v1_iter.next(), Some(&3));
    }

    // P74
    #[test]
    fn test_iterator_sum() {
        let v1 = vec![1, 2, 3];
        let v2: Vec<_> = v1.iter().map(|x| x + 1).collect();
        println!("{:#?}", v2);
    }

    #[test]
    fn using_other_iterator_trait_methods() {
        let sum: u32 = Counter::new()
            .zip(Counter::new().skip(1))
            .map(|(a, b)| a * b)
            .filter(|x| x % 3 == 0)
            .sum();
        println!("{}", sum);
    }

    #[test]
    fn calling_next_directly() {
        let mut counter = Counter::new();
        println!("{:?}", counter);
        for i in 0..7 {
            let n = counter.next();
            println!("i{}: {:?}", i, n);
        }
    }

    #[derive(Debug)]
    struct Counter {
        count: u32,
    }
    impl Counter {
        fn new() -> Counter {
            Counter { count: 0 }
        }
    }
    impl Iterator for Counter {
        type Item = u32;

        fn next(&mut self) -> Option<Self::Item> {
            if self.count < 5 {
                self.count += 1;
                Some(self.count)
            } else {
                None
            }
        }
    }

    //////////////////////////////////////////
    /// run in linux
    //////////////////////////////////////////
    #[test]
    #[allow(warnings)]
    fn cmd() {
        let output = Command::new("ls")
            .output()
            .expect("failed to execute command");

        if output.status.success() {
            let stdout = String::from_utf8_lossy(&output.stdout);
            println!("Command executed successfully. Output:\n{}", stdout);
        } else {
            let stderr = String::from_utf8_lossy(&output.stderr);
            println!("Command failed. Error:\n{}", stderr);
        }
    }
}