use std::process::{Command, Output, Stdio};
// A helper function to execute a shell command from a Rust script
fn execute_command(command: &str) -> Result<(), std::io::Error> {
let status = Command::new("bash")
.arg("-c")
.arg(command)
.stderr(Stdio::inherit())
.status()?;
if status.success() {
Ok(())
} else {
Err(std::io::Error::from_raw_os_error(status.code().unwrap_or(1)))
}
}
let command = "echo 'your-password' | sudo -S ./chapter-1/1-null-pointer-dereference/c/null_pointer";
if let Err(err) = execute_command(command) {
eprintln!("Error executing command: {}", err);
}
// Replace 'your-password', and you should see something like:
// [sudo] password for username: bash: line 1: 64243 Done echo 'your-password'
// 64943 Segmentation fault | sudo -S ./chapter-1/1-null-pointer-dereference/c/null_pointer
// Error executing command: Unknown error 139 (os error 139)
[sudo] password for mahmoud: Sorry, try again. [sudo] password for mahmoud: sudo: no password was provided sudo: 1 incorrect password attempt Error executing command: Operation not permitted (os error 1)
()
let ptr: *const i32 = std::ptr::null();
let value = unsafe { *ptr };
println!("Value: {}", value);
// Sometimes, this code may result in a segmentation fault.
Value: 21891
Let's execute a bash command.
let command = "echo 'your-password' | sudo -S ./chapter-1/1-null-pointer-dereference/rust/null_pointer";
if let Err(err) = execute_command(command) {
eprintln!("Error executing command: {}", err);
}
// Replace 'your-password', and you should see something like:
// [sudo] password for username: bash: line 1: 64243 Done echo 'your-password'
// 64579 Segmentation fault | sudo -S ./chapter-1/1-null-pointer-dereference/rust/null_pointer
// Error executing command: Unknown error 139 (os error 139)
[sudo] password for mahmoud: Sorry, try again. [sudo] password for mahmoud: sudo: no password was provided sudo: 1 incorrect password attempt Error executing command: Operation not permitted (os error 1)
()
let mut vec = vec![1, 2, 3];
// let mut vec: Vec<i32> = vec![];
let item = vec.pop();
match item {
Some(val) => println!("Popped value: {}", val),
None => println!("Vector is empty"),
}
Popped value: 3
()
// Or
let command = "rustc ./chapter-1/1-null-pointer-dereference/rust/null_pointer_safe.rs && ./chapter-1/1-null-pointer-dereference/rust/null_pointer_safe";
if let Err(err) = execute_command(command) {
eprintln!("Error executing command: {}", err);
}
Popped value: 3
()
let command = "echo 'your-password' | sudo -S ./chapter-1/2-buffer-overflow/c/buffer_overflow";
if let Err(err) = execute_command(command) {
eprintln!("Error executing command: {}", err);
}
// Replace 'your-password', and you should see:
// [sudo] password for username: bash: line 1: 64243 Done echo 'your-password'
// 64244 Segmentation fault | sudo -S ./chapter-1/2-buffer-overflow/c/buffer_overflow
// Error executing command: Unknown error 139 (os error 139)
[sudo] password for mahmoud: Sorry, try again. [sudo] password for mahmoud: sudo: no password was provided sudo: 1 incorrect password attempt Error executing command: Operation not permitted (os error 1)
()
// Replace 'your-password'
let command = "echo 'your-password' | sudo -S ./chapter-1/2-buffer-overflow/rust/buffer_ovreflow";
if let Err(err) = execute_command(command) {
eprintln!("Error executing command: {}", err);
}
[sudo] password for mahmoud: thread 'main' panicked at 'range end index 20 out of range for slice of length 5', buffer_ovreflow.rs:4:5 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace Error executing command: Network is unreachable (os error 101)
()
let command = "echo 'your-password' | sudo -S ./chapter-1/3-garbage-collector/c++/gc";
if let Err(err) = execute_command(command) {
eprintln!("Error executing command: {}", err);
}
()
struct Resource {
data: Vec<u8>,
}
let resource = Resource {
data: vec![1, 2, 3, 4, 5],
};
use std::thread;
let data = vec![1, 2, 3, 4, 5];
let mut handles = vec![];
for &item in &data {
handles.push(thread::spawn(move || {
println!("Processed: {}", item * 2);
}));
}
for handle in handles {
handle.join().unwrap();
}
Processed: 2 Processed: 4 Processed: 6 Processed: 8 Processed: 10
()
use std::sync::{Arc, Mutex};
use std::thread;
let data = Arc::new(Mutex::new(0));
let handles: Vec<_> = (0..10)
.map(|_| {
let data = data.clone();
thread::spawn(move || {
let mut data = data.lock().unwrap();
*data += 1;
})
})
.collect();
for handle in handles {
handle.join().unwrap();
}
println!("Final data value: {:?}", *data.lock().unwrap());
Final data value: 10
let command = "echo 'your-password' | sudo -S ./chapter-1/4-the-era-of-multithreading-and-parallelism/c++/thread";
if let Err(err) = execute_command(command) {
eprintln!("Error executing command: {}", err);
}
Processed: 2Processed: 4Processed: Processed: 8 Processed: 10 6
()
enum Shape {
Circle(f64),
Rectangle(f64, f64),
Triangle(f64, f64, f64),
}
fn area(shape: Shape) -> f64 {
match shape {
Shape::Circle(radius) => std::f64::consts::PI * radius * radius,
Shape::Rectangle(width, height) => width * height,
Shape::Triangle(a, b, c) => {
let s = (a + b + c) / 2.0;
(s * (s - a) * (s - b) * (s - c)).sqrt()
}
}
}
area(Shape::Circle(32.0))
3216.990877275948
fn longest_common_prefix<'a>(x: &'a str, y: &'a str) -> &'a str {
let min_length = std::cmp::min(x.len(), y.len());
let bytes_x = x.as_bytes();
let bytes_y = y.as_bytes();
for i in 0..min_length {
if bytes_x[i] != bytes_y[i] {
return &x[..i];
}
}
&x[..min_length]
}
let string1 = "abc";
let result;
{
let string2 = "abdef";
result = longest_common_prefix(string1, string2);
}
println!("The longest common prefix is: {}", result);
The longest common prefix is: ab
use std::thread;
let data = vec![1, 2, 3, 4, 5];
let shared_data = std::sync::Arc::new(data);
let handles: Vec<_> = (0..5).map(|i| {
let shared_data = shared_data.clone();
thread::spawn(move || {
let local_sum: i32 = shared_data.iter().sum();
println!("Thread {} Sum: {}", i, local_sum);
})
}).collect();
for handle in handles {
handle.join().unwrap();
}
Thread 0 Sum: 15 Thread 1 Sum: 15 Thread 2 Sum: 15 Thread 3 Sum: 15 Thread 4 Sum: 15
()
extern "C" {
fn process_data(data: *mut u8, length: usize);
}
fn main() {
let mut data: Vec<u8> = vec![1, 2, 3, 4, 5];
unsafe {
process_data(data.as_mut_ptr(), data.len());
}
}
// gcc -c external_lib.c -o external_lib.o
// ar rcs libexternal_lib.a external_lib.o
// rustc -L . -o main main.rs -l external_lib
let command = "./chapter-1/8-foreign-function-interface/rust/main";
if let Err(err) = execute_command(command) {
eprintln!("Error executing command: {}", err);
}
1 2 3 4 5
()
use std::fs::File;
use std::io::{Read, Error};
fn read_file_contents(filename: &str) -> Result<String, Error> {
let mut file = File::open(filename)?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
Ok(contents)
}
let filename = "./chapter-1/9-robust-error-handling-with-result-and-option/rust/content.txt";
match read_file_contents(filename) {
Ok(contents) => {
println!("File contents:\n{}", contents);
}
Err(err) => {
eprintln!("Error reading file: {}", err);
}
}
File contents: line 1 line 2 line 3
()
let mut data = [1, 2, 3, 4, 5];
let data_ptr = data.as_mut_ptr();
unsafe {
*data_ptr.offset(2) = 10;
}
println!("Modified data: {:?}", data);
Modified data: [1, 2, 10, 4, 5]