diff --git a/tp1/.vscode/settings.json b/tp1/.vscode/settings.json new file mode 100644 index 0000000000000000000000000000000000000000..51fd3bd546abd136028d3a3ccd42a629d75bb8ac --- /dev/null +++ b/tp1/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "rust-analyzer.checkOnSave": true +} \ No newline at end of file diff --git a/tp1/src/Elided1.rs b/tp1/src/Elided1.rs new file mode 100644 index 0000000000000000000000000000000000000000..8a46f035b58933bf705c37d6835152119726799f --- /dev/null +++ b/tp1/src/Elided1.rs @@ -0,0 +1,7 @@ +fn total_len<'l>(a: &'l str, b: &'l str) -> usize { + a.len() + b.len() +} +fn main() { + let len = total_len("Hello", "World"); + println!("{len}"); +} diff --git a/tp1/src/Elided2.rs b/tp1/src/Elided2.rs new file mode 100644 index 0000000000000000000000000000000000000000..49e92929ff3c825fb23f9723a28e62fa7738ef92 --- /dev/null +++ b/tp1/src/Elided2.rs @@ -0,0 +1,11 @@ +fn half_end<'l>(input: &'l str) -> &'l str { + if input.len() < 2 { + &input + } else { + &input[input.len()/2..] + } +} +fn main() { + let half = half_end("Hello rust world"); + println!("{half}"); +} diff --git a/tp1/src/Elided3.rs b/tp1/src/Elided3.rs new file mode 100644 index 0000000000000000000000000000000000000000..63d499673a779576b2fdb2841b45c702ad298af9 --- /dev/null +++ b/tp1/src/Elided3.rs @@ -0,0 +1,27 @@ +struct Foo { + one: u32, + two: u32, + default: u32, +} + +impl Foo { + fn new() -> Self { + Self { one: 1, two: 2, default: 12 } + } + fn value<'a, 'b>(&'a self, which: &'b str) -> &'a u32 { + if which == "one" { + &self.one + } else if which == "two" { + &self.two + } else { + &self.default + } + } +} + +fn main() { + let f = Foo::new(); + println!("{}", f.value("one")); + println!("{}", f.value("two")); + println!("{}", f.value("who cares")); +} diff --git a/tp1/src/Explicit1.rs b/tp1/src/Explicit1.rs new file mode 100644 index 0000000000000000000000000000000000000000..73f9e56af59338d860733f7e68ff6e586af7d0c9 --- /dev/null +++ b/tp1/src/Explicit1.rs @@ -0,0 +1,14 @@ +enum Message { + Hello, + World +} +fn message(m: Message) -> &'static str { + match m { + Message::Hello => "Hello", + Message::World => "World", + } +} + +fn main() { + println!("{}", message(Message::Hello)); +} diff --git a/tp1/src/Explicit2.rs b/tp1/src/Explicit2.rs new file mode 100644 index 0000000000000000000000000000000000000000..6f32aee81e97449504cb9b7f387114fffacf6955 --- /dev/null +++ b/tp1/src/Explicit2.rs @@ -0,0 +1,14 @@ +fn longuest<'l>(a: &'l str, b: &'l str) -> &'l str { + if a.len() > b.len() { + a + } else { + b + } +} + +fn main() { + let a = String::from("Hello"); + let b = "Rust World"; + + println!("longuest: {}", longuest(&a, b)); +} diff --git a/tp1/src/main.rs b/tp1/src/main.rs index 7d5b0c85de3969f1c8cb0b211bb345bf2d992100..0e0cd03bd27ea4c964d9304c1fee9c45229f01ec 100644 --- a/tp1/src/main.rs +++ b/tp1/src/main.rs @@ -1,178 +1,14 @@ -use std::{io, net::IpAddr}; -use std::net::{TcpStream, SocketAddr}; -use std::time::Duration; - -pub enum PasswordError { - Empty, - Wrong, -} - -/// A type that can be used to check if a given input is a valid password -pub struct PasswordChecker { - secret: String, -} - -impl PasswordChecker { - fn new(pass: &str) -> Self { - Self {secret : pass.to_string() } - } - - pub fn check(&self, input: &str) -> Result<(), PasswordError> { - if input.trim() == self.secret { - Ok(()) - }else { - if input.trim().is_empty() { - Err(PasswordError::Empty) - }else { - Err(PasswordError::Wrong) - } - } - } -} - -fn main() -> Result<(), io::Error>{ - println!("Hello, world!"); - - // let x: i8 = 42; - // println!("{x}"); - // eprintln!("{x:#08x}"); - - // let mut y = 1; - // while y < 11 { - // println!("{y}"); - // y += 1; - // } - - // check_password(); - - // println!("Enter password: "); - // let mut input = String::new(); - // let _ = io::stdin().read_line(&mut input); - // let checker = PasswordChecker::new("Rust"); - - // // Call the check function on the checker. - // // This function should have the same return type as - // // the check_password function of the previous exercise - // match checker.check(&input) { - // Ok(()) => println!("ok"), - // Err(PasswordError::Empty) => println!("Empty Password"), - // Err(PasswordError::Wrong) => println!("Wrong password"), - // } - - let ports = vec![20, 80, 443]; - println!("Parsing ips file"); - match get_addrs("ips.txt") { - Ok(ips) => { - for ip in &ips { - println!("Connecting to {} ....", *ip); - for port in &ports { - let _ = try_connect(*ip, *port); - } - } - } - Err(e) => eprintln!("Erreur lors de la lecture du fichier : {}", e), - } - - Ok(()) +fn insert<'l>(vec: &mut Vec<&'l str>, s: &'l str) { + vec.push(s); } -/// Reads a file that contains an address per line and returns a Vector with all well-formed -/// addresses and prints a warning on the standard error output for every malformed lines. -/// -/// Addresses should be ipv4 or ipv6 addresses. -fn get_addrs(path: &str) -> Result<Vec<IpAddr>, std::io::Error> { - let content = std::fs::read_to_string(path)?; - let mut addresses = Vec::new(); - - for line in content.lines() { - let line = line.trim(); // Supprimer les espaces inutiles - if line.is_empty() { - continue; // Ignorer les lignes vides - } - - match line.parse::<IpAddr>() { - Ok(addr) => addresses.push(addr), // Ajouter l'adresse seulement si elle est valide - Err(_) => eprintln!("'{}' : is not a correct IP address invalid IP address syntax", line), - } - } +fn main() { + let message = String::from("Hello rust world"); + let message2 = String::from("lifetimes are great"); + let mut v = Vec::new(); - Ok(addresses) // Retourner uniquement les adresses valides + insert(&mut v, &message); + insert(&mut v, &message2); + + println!("{v:?}"); } - - -/// Tries to connect to a given host with a TCP Connection with a one second timeout. -/// -/// Returns Ok(()) or a corresponding error if connection fails. -/// -fn try_connect(addr: IpAddr, port: u16) -> Result<(), std::io::Error> { - let socket = SocketAddr::new(addr, port); - let timeout = Duration::from_secs(1); - match TcpStream::connect_timeout(&socket, timeout) { - Ok(_) => { - println!(" port {port}: alive"); - Ok(()) - } - Err(e) => { - eprintln!(" port {port}: down (Connection refused ({e}))"); - Err(e) - } - } -} - - - - - - - - - - - - - - - - - - - -// fn check_password() { -// println!("Enter password: "); - -// let mut input = String::new(); -// let _ = io::stdin().read_line(&mut input); - -// match check_password3(&input) { -// Ok(()) => println!("ok"), -// Err(PasswordError::Empty) => println!("Empty Password"), -// Err(PasswordError::Wrong) => println!("Wrong password"), -// } -// } - -// Check an input for a predetermined secret password -// Returns `Ok(())` if the input matches the password or `Err(())` otherwise. -// pub fn check_password2(input: &str) -> Result<(), ()> { -// let predefined_password = "Rust"; -// if input.trim() == predefined_password { -// // println!("Good"); -// Ok(()) -// } else { -// // println!("Wrong"); -// Err(()) -// } -// } - -// pub fn check_password3(input: &str) -> Result<(), PasswordError> { -// let predefined_password = "Rust"; -// if input.trim() == predefined_password { -// Ok(()) -// } else { -// if input.trim().is_empty() { -// Err(PasswordError::Empty) -// }else { -// Err(PasswordError::Wrong) -// } -// } -// } - diff --git a/tp1/src/main1.rs b/tp1/src/main1.rs new file mode 100644 index 0000000000000000000000000000000000000000..7d5b0c85de3969f1c8cb0b211bb345bf2d992100 --- /dev/null +++ b/tp1/src/main1.rs @@ -0,0 +1,178 @@ +use std::{io, net::IpAddr}; +use std::net::{TcpStream, SocketAddr}; +use std::time::Duration; + +pub enum PasswordError { + Empty, + Wrong, +} + +/// A type that can be used to check if a given input is a valid password +pub struct PasswordChecker { + secret: String, +} + +impl PasswordChecker { + fn new(pass: &str) -> Self { + Self {secret : pass.to_string() } + } + + pub fn check(&self, input: &str) -> Result<(), PasswordError> { + if input.trim() == self.secret { + Ok(()) + }else { + if input.trim().is_empty() { + Err(PasswordError::Empty) + }else { + Err(PasswordError::Wrong) + } + } + } +} + +fn main() -> Result<(), io::Error>{ + println!("Hello, world!"); + + // let x: i8 = 42; + // println!("{x}"); + // eprintln!("{x:#08x}"); + + // let mut y = 1; + // while y < 11 { + // println!("{y}"); + // y += 1; + // } + + // check_password(); + + // println!("Enter password: "); + // let mut input = String::new(); + // let _ = io::stdin().read_line(&mut input); + // let checker = PasswordChecker::new("Rust"); + + // // Call the check function on the checker. + // // This function should have the same return type as + // // the check_password function of the previous exercise + // match checker.check(&input) { + // Ok(()) => println!("ok"), + // Err(PasswordError::Empty) => println!("Empty Password"), + // Err(PasswordError::Wrong) => println!("Wrong password"), + // } + + let ports = vec![20, 80, 443]; + println!("Parsing ips file"); + match get_addrs("ips.txt") { + Ok(ips) => { + for ip in &ips { + println!("Connecting to {} ....", *ip); + for port in &ports { + let _ = try_connect(*ip, *port); + } + } + } + Err(e) => eprintln!("Erreur lors de la lecture du fichier : {}", e), + } + + Ok(()) +} + +/// Reads a file that contains an address per line and returns a Vector with all well-formed +/// addresses and prints a warning on the standard error output for every malformed lines. +/// +/// Addresses should be ipv4 or ipv6 addresses. +fn get_addrs(path: &str) -> Result<Vec<IpAddr>, std::io::Error> { + let content = std::fs::read_to_string(path)?; + let mut addresses = Vec::new(); + + for line in content.lines() { + let line = line.trim(); // Supprimer les espaces inutiles + if line.is_empty() { + continue; // Ignorer les lignes vides + } + + match line.parse::<IpAddr>() { + Ok(addr) => addresses.push(addr), // Ajouter l'adresse seulement si elle est valide + Err(_) => eprintln!("'{}' : is not a correct IP address invalid IP address syntax", line), + } + } + + Ok(addresses) // Retourner uniquement les adresses valides +} + + +/// Tries to connect to a given host with a TCP Connection with a one second timeout. +/// +/// Returns Ok(()) or a corresponding error if connection fails. +/// +fn try_connect(addr: IpAddr, port: u16) -> Result<(), std::io::Error> { + let socket = SocketAddr::new(addr, port); + let timeout = Duration::from_secs(1); + match TcpStream::connect_timeout(&socket, timeout) { + Ok(_) => { + println!(" port {port}: alive"); + Ok(()) + } + Err(e) => { + eprintln!(" port {port}: down (Connection refused ({e}))"); + Err(e) + } + } +} + + + + + + + + + + + + + + + + + + + +// fn check_password() { +// println!("Enter password: "); + +// let mut input = String::new(); +// let _ = io::stdin().read_line(&mut input); + +// match check_password3(&input) { +// Ok(()) => println!("ok"), +// Err(PasswordError::Empty) => println!("Empty Password"), +// Err(PasswordError::Wrong) => println!("Wrong password"), +// } +// } + +// Check an input for a predetermined secret password +// Returns `Ok(())` if the input matches the password or `Err(())` otherwise. +// pub fn check_password2(input: &str) -> Result<(), ()> { +// let predefined_password = "Rust"; +// if input.trim() == predefined_password { +// // println!("Good"); +// Ok(()) +// } else { +// // println!("Wrong"); +// Err(()) +// } +// } + +// pub fn check_password3(input: &str) -> Result<(), PasswordError> { +// let predefined_password = "Rust"; +// if input.trim() == predefined_password { +// Ok(()) +// } else { +// if input.trim().is_empty() { +// Err(PasswordError::Empty) +// }else { +// Err(PasswordError::Wrong) +// } +// } +// } + diff --git a/tp1/src/problem1.rs b/tp1/src/problem1.rs new file mode 100644 index 0000000000000000000000000000000000000000..af1687c682eeb07728d837aa18dac46f18532137 --- /dev/null +++ b/tp1/src/problem1.rs @@ -0,0 +1,13 @@ +struct Foo { + value: u8 +} + +fn print_foo(foo: &Foo) { + println!("I am foo: {}", foo.value); +} + +fn main() { + let f = Foo { value: 4 }; + print_foo(&f); + print_foo(&f); +} diff --git a/tp1/src/problem2.rs b/tp1/src/problem2.rs new file mode 100644 index 0000000000000000000000000000000000000000..7a01ec7f74a2bc9d266500725dddba5df67de00a --- /dev/null +++ b/tp1/src/problem2.rs @@ -0,0 +1,34 @@ +struct Foo { + value: u8 +} + +fn change_foo(foo: &mut Foo) { + foo.value += 13; + // solution 2 + // return foo; +} + +fn solution1() { + let mut f= Foo { value: 4 }; + change_foo(&mut f); + println!("foo is now {}", f.value); +} + +fn solution2() { + let mut f= Foo { value: 4 }; + change_foo(&mut f); + println!("foo is now {}", f.value); +} + + +fn main() { + // solution 1 + let mut f= Foo { value: 4 }; + change_foo(&mut f); + println!("foo is now {}", f.value); + + //solution 2 + let mut f= Foo { value: 4 }; + change_foo(f); + println!("foo is now {}", f.value); +} \ No newline at end of file diff --git a/tp1/src/problem3.rs b/tp1/src/problem3.rs new file mode 100644 index 0000000000000000000000000000000000000000..6f8dd3fc7b6d466aba46838791ee0eeefd058e7b --- /dev/null +++ b/tp1/src/problem3.rs @@ -0,0 +1,21 @@ +struct Foo { + value: u8 +} + +impl Foo { + fn new() -> Self { + Self {value: 0} + } + fn change(&mut self) { + self.value += 13; + } + fn print(&self) { + println!("Foo: {}", self.value); + } +} + +fn main() { + let mut f = Foo::new(); + f.change(); + f.print(); +} diff --git a/tp1/src/problem4.rs b/tp1/src/problem4.rs new file mode 100644 index 0000000000000000000000000000000000000000..746f78e12c584940e7dcd43fd44be54dbe278658 --- /dev/null +++ b/tp1/src/problem4.rs @@ -0,0 +1,20 @@ +struct Foo { + value: u8 +} + +fn get_nth_item(values: &[Foo; 4], idx: usize) -> &Foo { + let val = values.get(idx).unwrap(); + // Foo {value: val.value} + val +} + +fn main() { + + let values = [ + Foo { value: 0}, + Foo { value: 1}, + Foo { value: 2}, + Foo { value: 3}, + ]; + println!("The second value is {}", get_nth_item(&values, 1).value); +} diff --git a/tp1/src/problem5.rs b/tp1/src/problem5.rs new file mode 100644 index 0000000000000000000000000000000000000000..3ee4f8e39cdaee050bf22fb5c245a47a80119532 --- /dev/null +++ b/tp1/src/problem5.rs @@ -0,0 +1,31 @@ +/// Returns a Vec of random values +fn get_rand_values(seed: &mut u32, count: usize) -> Vec<u32> { + let mut v = Vec::new(); + for _ in 0..count { + *seed ^= *seed << 13; + *seed ^= *seed >> 17; + *seed ^= *seed << 5; + v.push(*seed); + } + v +} + +fn main() { + + let mut best = None; + let mut best_sum = 0; + let mut seed = 123; + for _ in 0..10 { + let rand_values = get_rand_values(&mut seed, 10); + let mut sum: u32 = 0; + for val in &rand_values { + // prevent panic in debug mode when sum wraps + sum = sum.wrapping_add(*val); + } + if sum > best_sum { + best = Some(rand_values); + best_sum = sum; + } + } + println!("{best_sum:#?}"); +}