Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feedback #1

Open
wants to merge 5 commits into
base: feedback
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@
fn main() {
let s0 = String::from("Hello");

let mut s1 = append_to_string(s0);

// Don't change the following line!
println!("{} == `{}`", stringify!(s0), s0);

let mut s1 = append_to_string(s0);

s1.push('!');

println!("{} == `{}`", stringify!(s1), s1);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ fn main() {
println!("{} == `{}`", stringify!(s1), s1);
}

fn append_to_string(s: String) -> String {
fn append_to_string(mut s: String) -> String {
s.push_str("Hello World");

s
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
//! function.

fn main() {
let s0 = String::new();
//let s0 = String::new();

let mut s1 = create_string(s0);
let mut s1 = create_string();

println!("{} == `{}`", stringify!(s1), s1);

Expand All @@ -16,7 +16,7 @@ fn main() {

///`create_string()` no longer takes `s: String` as argument
fn create_string() -> String {
let mut s = s;
let s = String::from("Hello");

s
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
fn main() {
let mut x = 100;
let y = &mut x;
let z = &mut x;
*y += 100;
let z = &mut x;
*z += 1000;
assert_eq!(x, 1200);
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,19 @@
fn main() {
let data = "Rust is great!".to_string();

get_char(data);
get_char(&data);

string_uppercase(&data);
string_uppercase(data);
}

// Should not take ownership
fn get_char(data: String) -> char {
fn get_char(data: &String) -> char {
data.chars().last().unwrap()
}

// Should take ownership
fn string_uppercase(mut data: &String) {
data = &data.to_uppercase();
fn string_uppercase(mut data: String) {
data = data.to_uppercase();

println!("{}", data);
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,33 +18,60 @@ use std::fs::File;
use std::io::{self, BufRead, BufReader, Lines};

//change this into:
//fn read_lines(filename: &str) -> Result<Lines<BufReader<File>>, io::Error> {
fn read_lines(filename: &str) -> Lines<BufReader<File>> {
let file = File::open(filename).unwrap(); // this can easily fail
BufReader::new(file).lines()
fn read_lines(filename: &str) -> Result<Lines<BufReader<File>>, io::Error> {
//fn read_lines(filename: &str) -> Lines<BufReader<File>> {
let file = File::open(filename); // this can easily fail
match file {
Err(e) => return Err(e),
Ok(f) => {
return Ok(BufReader::new(f).lines());
}
}
}

//change this into:
//fn count_bytes_and_lines(filename: &str) -> Result<(usize, usize, usize), io::Error> {
fn count_bytes_and_lines(filename: &str) -> (usize, usize, usize) {
fn count_bytes_and_lines(filename: &str) -> Result<(usize, usize, usize), io::Error> {
//fn count_bytes_and_lines(filename: &str) -> (usize, usize, usize) {
let lines = read_lines(filename);
let mut line_count = 0;
let mut word_count = 0;
let mut byte_count = 0;
for line in lines {
let text = line.unwrap(); // this will usually not fail
line_count += 1;
word_count += text.split_whitespace().count();
byte_count += text.len();
}
match lines {
Err(e) => {
return Err(e);
}
Ok(l) => {
let mut line_count = 0;
let mut word_count = 0;
let mut byte_count = 0;
for line in l {
let text = line;
match text {
Err(e) => {
return Err(e);
}
Ok(t) => {
line_count += 1;
word_count += t.split_whitespace().count();
byte_count += t.len();
}
}
}

(line_count, word_count, byte_count)
Ok((line_count, word_count, byte_count))
}
}

}

fn main() {
let args: Vec<String> = env::args().collect();
let filename = &args[1];

let (lines, words, bytes) = count_bytes_and_lines(filename);
println!("{filename}: {lines} lines, {words} words, {bytes} bytes");
let result = count_bytes_and_lines(filename);
match result {
Err(e) => {
eprintln!("Error counting bytes and lines: {}", e);
return;
}
Ok((lines, words, bytes)) => {
println!("{filename}: {lines} lines, {words} words, {bytes} bytes");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,31 +24,55 @@
use std::io::{BufRead, self, Write};

#[derive(Debug)]
enum MyError{ InvalidName,IOError( io::Error),
enum MyError{
InvalidName,
IOError( io::Error),
}

fn get_username( )
-> String
{
fn get_username() -> Result<String, MyError> {
print!("Username: ");
io::stdout().flush();
if let Err(e) = io::stdout().flush() {
return Err(MyError::IOError(e));
}

let mut input=String::new();
io::stdin().lock().read_line(&mut input); input=input.trim().to_string();
match io::stdin().lock().read_line(&mut input) {
Err(e) => return Err(MyError::IOError(e)),
_ => {
input = input.trim().to_string();

for c in input.chars()
{
if !char::is_alphabetic(c) { panic!("that's not a valid name, try again"); }
for c in input.chars() {
if !char::is_alphabetic(c) {
return Err(MyError::InvalidName);
}
}

if input.is_empty() {
return Err(MyError::InvalidName);
}

Ok(input)
},
}

if input.is_empty() {
panic!("that's not a valid name, try again");
}

input

}

fn main() {
let name=get_username();
let mut name = get_username();
while let Err(e) = name {
match e {
MyError::InvalidName => {
println!("Invalid name, please try again.");
name = get_username();
},
MyError::IOError(e) => {
eprintln!("IOError: {}", e);
return;
},
}
}

let name = name.unwrap();

println!("Hello {name}!")
}
31 changes: 17 additions & 14 deletions 2-foundations-of-rust/3-advanced-syntax/3-slices/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@
fn merge(a: &[i32], b: &[i32]) -> Vec<i32> {
let mut dest = Vec::new();

let a_idx = 0;
let b_idx = 0;
let mut a_idx = 0;
let mut b_idx = 0;

while a_idx < a.len() && b_idx < b.len() {
if a[a_idx] <= b[b_idx] {
Expand All @@ -23,11 +23,11 @@ fn merge(a: &[i32], b: &[i32]) -> Vec<i32> {
}
}

for elem in a[a_idx..] {
dest.push(elem)
for elem in &a[a_idx..] {
dest.push(*elem)
}
for elem in b[b_idx..] {
dest.push(elem)
for elem in &b[b_idx..] {
dest.push(*elem)
}

dest
Expand All @@ -36,8 +36,10 @@ fn merge(a: &[i32], b: &[i32]) -> Vec<i32> {
/// Take an array slice, and sort into a freshly constructed vector using the above function
fn merge_sort(data: &[i32]) -> Vec<i32> {
if data.len() > 1 {
// implement this
todo!()
let mid = data.len() / 2;
let left = merge_sort(&data[..mid]);
let right = merge_sort(&data[mid..]);
merge(&left, &right)
} else {
data.to_vec()
}
Expand All @@ -49,8 +51,9 @@ fn read_numbers() -> Vec<i32> {
let mut result = Vec::new();
for line in io::stdin().lines().flatten() {
for word in line.split_whitespace() {
result.push(word.parse().unwrap())
result.push(word.parse().unwrap());
}
break;
}

result
Expand All @@ -73,10 +76,10 @@ mod test {

#[test]
fn test_sort() {
assert_eq!(merge_sort(&[]), vec![]);
assert_eq!(merge_sort(&[5]), vec![5]);
assert_eq!(merge_sort(&[1,2,3]), vec![1,2,3]);
assert_eq!(merge_sort(&[47,42,5,1]), vec![1,5,42,47]);
assert_eq!(merge_sort(&[6,47,42,5,1,123]), vec![1,5,6,42,47,123]);
assert_eq!(merge_sort(&[]), vec![]);
assert_eq!(merge_sort(&[5]), vec![5]);
assert_eq!(merge_sort(&[1,2,3]), vec![1,2,3]);
assert_eq!(merge_sort(&[47,42,5,1]), vec![1,5,42,47]);
assert_eq!(merge_sort(&[6,47,42,5,1,123]), vec![1,5,6,42,47,123]);
}
}
37 changes: 31 additions & 6 deletions 2-foundations-of-rust/3-advanced-syntax/4-ring-buffer/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,22 +12,22 @@

// 3) change the method 'new()' into 'new(size: usize)' that initializes a ring buffer of the given size (instead of a fixed size of 16); use the 'make_box' function.

// 4) in a queue that has size N, how many elements can be stored at one time? (test your answer experimentally)
// 4) in a queue that has size N, how many elements can be stored at one time? (test your answer experimentally) / R: N - 1

// 5) EXTRA EXERCISES:
// - add a method "has_room" so that "queue.has_room()" is true if and only if writing to the queue will succeed
// - add a method "peek" so that "queue.peek()" returns the same thing as "queue.read()", but leaves the element in the queue

struct RingBuffer {
data: [u8; 16],
data: Box<[u8]>,
start: usize,
end: usize,
}

impl RingBuffer {
fn new() -> RingBuffer {
fn new(size: usize) -> RingBuffer {
RingBuffer {
data: [0; 16],
data: make_box(size),
start: 0,
end: 0,
}
Expand All @@ -37,7 +37,13 @@ impl RingBuffer {
/// it returns None if the queue was empty

fn read(&mut self) -> Option<u8> {
todo!()
if self.start == self.end {
None
} else {
let value = self.data[self.start];
self.start = (self.start + 1) % self.data.len();
Some(value)
}
}

/// This function tries to put `value` on the queue; and returns true if this succeeds
Expand All @@ -55,6 +61,18 @@ impl RingBuffer {
true
}
}

fn has_room(&self) -> bool {
(self.end + 1) % self.data.len() != self.start
}

fn peek(&self) -> Option<u8> {
if self.start == self.end {
None
} else {
Some(self.data[self.start])
}
}
}

/// This function creates an "owned slice" a user-selectable size by allocating it as a vector (filled with zeros) using vec![], and then turning it
Expand All @@ -75,12 +93,19 @@ impl Iterator for RingBuffer {
}

fn main() {
let mut queue = RingBuffer::new();
let mut queue = RingBuffer::new(12);
assert!(queue.write(1));
assert!(queue.write(2));
assert!(queue.write(3));
assert!(queue.write(4));
assert!(queue.write(5));
assert!(queue.write(1));
assert!(queue.write(2));
assert!(queue.write(3));
assert!(queue.write(4));
assert!(queue.write(5));
assert!(queue.peek() == Some(1));
assert!(queue.has_room());
for elem in queue {
println!("{elem}");
}
Expand Down
Loading