0% found this document useful (0 votes)
38 views23 pages

Rust Programming .Null

Rust is a modern programming language emphasizing performance, reliability, and productivity, with features like memory safety, zero-cost abstractions, and a rich type system. It is particularly suited for backend development, offering frameworks like Actix Web and Rocket, as well as database connectivity through ORMs like Diesel and SQLx. Additionally, Rust's ecosystem supports machine learning with libraries such as ndarray and linfa, making it a compelling choice for performance-critical applications.

Uploaded by

jack
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views23 pages

Rust Programming .Null

Rust is a modern programming language emphasizing performance, reliability, and productivity, with features like memory safety, zero-cost abstractions, and a rich type system. It is particularly suited for backend development, offering frameworks like Actix Web and Rocket, as well as database connectivity through ORMs like Diesel and SQLx. Additionally, Rust's ecosystem supports machine learning with libraries such as ndarray and linfa, making it a compelling choice for performance-critical applications.

Uploaded by

jack
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

# Rust Programming

Rust is a modern systems programming language that focuses on performance,


reliability, and productivity. It provides memory safety without garbage collection and
enables concurrency without data races.

## Key Features of Rust

- **Memory safety** without garbage collection


- **Zero-cost abstractions**
- **Fearless concurrency**
- **Rich type system** with pattern matching
- **Ownership model** for memory management
- **Cargo** - built-in package manager and build system

## Basic Rust Syntax

```rust
// Hello World
fn main() {
println!("Hello, world!");
}

// Variables (immutable by default)


let x = 5;
let mut y = 10; // mutable variable

// Functions
fn add(a: i32, b: i32) -> i32 {
a + b // no semicolon means return
}

// Structs
struct Point {
x: f64,
y: f64,
}

// Enums
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
}

// Pattern matching
match some_value {
1 => println!("one"),
2 => println!("two"),
_ => println!("something else"),
}
```

## Ownership System

Rust's ownership model is its most distinctive feature:

1. **Ownership Rules**:
- Each value has an owner
- Only one owner at a time
- When the owner goes out of scope, the value is dropped

2. **Borrowing**:
- Immutable references (`&T`)
- Mutable references (`&mut T`)
- No dangling references

## Getting Started

1. Install Rust using [rustup](https://rustup.rs/):


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

2. Create a new project:


```bash
cargo new my_project
cd my_project
```

3. Build and run:


```bash
cargo build
cargo run
```

## Learning Resources

- [The Rust Book](https://doc.rust-lang.org/book/)


- [Rust by Example](https://doc.rust-lang.org/rust-by-example/)
- [Rustlings](https://github.com/rust-lang/rustlings) (small exercises)
- [Rust Standard Library Docs](https://doc.rust-lang.org/std/)
Would you like me to focus on any particular aspect of Rust programming?

# Rust for Backend Development

Rust is an excellent choice for backend development, offering performance


comparable to C/C++ with much stronger safety guarantees. Here's what you need to
know about building backend services with Rust:

## Popular Rust Backend Frameworks

### 1. **Actix Web** (Most popular)


```rust
use actix_web::{get, web, App, HttpServer, Responder};

#[get("/{id}/{name}/index.html")]
async fn index(info: web::Path<(u32, String)>) -> impl Responder {
format!("Hello {}! id:{}", info.1, info.0)
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| App::new().service(index))
.bind(("127.0.0.1", 8080))?
.run()
.await
}
```

### 2. **Rocket** (More beginner-friendly)


```rust
#[macro_use] extern crate rocket;

#[get("/hello/<name>/<age>")]
fn hello(name: &str, age: u8) -> String {
format!("Hello, {} year old named {}!", age, name)
}

#[launch]
fn rocket() -> _ {
rocket::build().mount("/", routes![hello])
}
```

### 3. **Axum** (Built on tokio)


```rust
use axum::{Router, routing::get, extract::Path};

async fn hello(Path((id, name)): Path<(u32, String)>) -> String {


format!("Hello {}! id:{}", name, id)
}

#[tokio::main]
async fn main() {
let app = Router::new()
.route("/:id/:name", get(hello));
axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
.serve(app.into_make_service())
.await
.unwrap();
}
```

## Database Connectivity

### Popular ORMs and Query Builders

1. **Diesel** (Most mature ORM)


```rust
// Schema
table! {
users (id) {
id -> Integer,
name -> Text,
email -> Text,
}
}

// Model
#[derive(Queryable)]
pub struct User {
pub id: i32,
pub name: String,
pub email: String,
}

// Usage
let users = users::table
.filter(name.eq("John"))
.load::<User>(&conn)?;
```

2. **SQLx** (Async, compile-time checked SQL)


```rust
let row = sqlx::query!("SELECT id, name FROM users WHERE email = ?", email)
.fetch_one(&pool)
.await?;
```

## Async Programming

Rust's async/await is perfect for backend services:

```rust
use tokio::time::{sleep, Duration};
async fn fetch_data() -> String {
sleep(Duration::from_secs(1)).await;
"Data fetched".to_string()
}

#[tokio::main]
async fn main() {
let result = fetch_data().await;
println!("{}", result);
}
```

## Deployment Considerations

1. **Docker Example**:
```dockerfile
FROM rust:latest as builder
WORKDIR /app
COPY . .
RUN cargo build --release

FROM debian:buster-slim
COPY --from=builder /app/target/release/myapp /usr/local/bin
CMD ["myapp"]
```

2. **Performance Tips**:
- Use `jemalloc` for memory allocation
- Consider `mimalloc` for alternative allocator
- Enable LTO in release builds

## Ecosystem Highlights

- **gRPC**: tonic (https://github.com/hyperium/tonic)


- **WebSockets**: tokio-tungstenite
- **Authentication**: OAuth2, JWT crates
- **Configuration**: dotenv, config-rs
- **Logging**: tracing, log, env_logger

## When to Choose Rust for Backend

- Need high performance/low latency


- Require strong safety guarantees
- Building long-running services (reduced memory leaks)
- Want to minimize runtime overhead
- Need easy interoperability with other languages

## Learning Path for Backend Rust

1. Learn Rust fundamentals (ownership, traits, error handling)


2. Pick a web framework (Actix Web recommended)
3. Learn async Rust (Futures, tokio runtime)
4. Add database connectivity
5. Explore middleware (logging, auth, etc.)
6. Learn deployment strategies

Would you like me to dive deeper into any specific aspect of Rust backend
development?

# Building a Complete Website with Rust

Here's a comprehensive guide to building a full-stack website using Rust, covering


both backend and frontend options.

## Option 1: Traditional Backend with Rust + Frontend Framework

### Backend (Actix Web Example)

**Directory Structure:**
```
my-website/
├── Cargo.toml
├── src/
│ ├── main.rs
│ ├── routes/
│ │ ├── mod.rs
│ │ ├── auth.rs
│ │ └── api.rs
│ └── models/
│ └── user.rs
├── templates/ # For server-side rendering
│ └── index.html.tera
└── static/ # For CSS/JS/images
```

**Cargo.toml:**
```toml
[package]
name = "my-website"
version = "0.1.0"

[dependencies]
actix-web = "4"
serde = { version = "1.0", features = ["derive"] }
tera = "1" # Templating engine
diesel = { version = "2.0", features = ["postgres"] } # ORM
dotenv = "0.15" # For environment variables
```
**Main Application (src/main.rs):**
```rust
use actix_web::{web, App, HttpServer};
use routes::{auth, api};

mod routes;
mod models;

#[actix_web::main]
async fn main() -> std::io::Result<()> {
// Database setup would go here

HttpServer::new(|| {
App::new()
.service(
web::scope("/api")
.configure(api::config)
)
.service(
web::scope("/auth")
.configure(auth::config)
)
// Serve static files
.service(actix_files::Files::new("/static", "static"))
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}
```

### Frontend Options

1. **Traditional HTML/CSS/JS** - Served from Rust backend


2. **HTMX** - Lightweight frontend interactions
3. **React/Vue/Svelte** - With Rust API backend

## Option 2: Full-Stack Rust with Leptos (WASM Frontend)

For a truly Rust-fullstack approach:

**Directory Structure:**
```
leptos-site/
├── Cargo.toml
├── src/
│ ├── main.rs
│ └── app.rs
└── index.html
```

**Cargo.toml:**
```toml
[package]
name = "leptos-site"
version = "0.1.0"

[dependencies]
leptos = "0.5"
leptos_actix = "0.5" # Actix integration
serde = { version = "1.0", features = ["derive"] }

[features]
hydrate = ["leptos/hydrate"]
ssr = ["leptos/ssr"]
```

**Main Application (src/main.rs):**


```rust
use actix_web::*;
use leptos::*;
use leptos_actix::{generate_route_list, LeptosRoutes};
use my_app::App;

#[actix_web::main]
async fn main() -> std::io::Result<()> {
let conf = get_configuration(None).await.unwrap();
let addr = conf.leptos_options.site_addr;
let routes = generate_route_list(App);

HttpServer::new(move || {
let leptos_options = &conf.leptos_options;
let site_root = &leptos_options.site_root;

App::new()
.route("/api/{tail:.*}", leptos_actix::handle_server_fns())
.leptos_routes(
leptos_options.to_owned(),
routes.to_owned(),
App
)
.service(fs::Files::new("/", site_root))
})
.bind(&addr)?
.run()
.await
}
```
**Frontend Component (src/app.rs):**
```rust
use leptos::*;

#[component]
pub fn App() -> impl IntoView {
let (count, set_count) = create_signal(0);

view! {
<h1>"Welcome to my Rust website!"</h1>
<button
on:click=move |_| set_count.update(|n| *n += 1)
>
"Click me: " {count}
</button>
}
}
```

## Key Components for a Complete Website

### 1. Database Integration

**Using SQLx (async):**


```rust
use sqlx::postgres::PgPoolOptions;

async fn get_db_pool() -> Result<PgPool, sqlx::Error> {


PgPoolOptions::new()
.max_connections(5)
.connect(&std::env::var("DATABASE_URL")?)
.await
}
```

### 2. Authentication

**Example with JWT:**


```rust
use jsonwebtoken::{encode, decode, Header, Validation, EncodingKey,
DecodingKey};

#[derive(Debug, Serialize, Deserialize)]


struct Claims {
sub: String,
exp: usize,
}

fn create_token(user_id: &str) -> String {


let claims = Claims {
sub: user_id.to_owned(),
exp: (chrono::Utc::now() + chrono::Duration::hours(24)).timestamp() as usize,
};

encode(&Header::default(), &claims,
&EncodingKey::from_secret("secret".as_ref()))
.unwrap()
}
```

### 3. API Routes

**Example CRUD endpoint:**


```rust
#[derive(Deserialize)]
struct CreateUser {
name: String,
email: String,
}

#[post("/users")]
async fn create_user(
data: web::Json<CreateUser>,
pool: web::Data<PgPool>
) -> Result<HttpResponse, Error> {
let user = sqlx::query!(
r#"INSERT INTO users (name, email) VALUES ($1, $2) RETURNING id"#,
data.name,
data.email
)
.fetch_one(&**pool)
.await?;

Ok(HttpResponse::Created().json(user.id))
}
```

### 4. Frontend Interaction

**Using Leptos (React-like syntax):**


```rust
#[component]
pub fn Counter() -> impl IntoView {
let (count, set_count) = create_signal(0);

let increment = move |_| set_count.update(|n| *n += 1);

view! {
<div>
<button on:click=increment>
"Count is: " {count}
</button>
</div>
}
}
```

## Deployment

### 1. Docker Setup

```dockerfile
# Build stage
FROM rust:latest as builder
WORKDIR /app
COPY . .
RUN cargo build --release

# Runtime stage
FROM debian:buster-slim
RUN apt-get update && apt-get install -y \
openssl \
ca-certificates

COPY --from=builder /app/target/release/my-website /usr/local/bin


COPY --from=builder /app/static /static
COPY --from=builder /app/templates /templates

ENV RUST_LOG=info
EXPOSE 8080

CMD ["my-website"]
```

### 2. Systemd Service (for VPS)

```ini
[Unit]
Description=My Rust Website
After=network.target

[Service]
User=www-data
WorkingDirectory=/var/www/my-website
ExecStart=/usr/local/bin/my-website
Restart=always

[Install]
WantedBy=multi-user.target
```
## Complete Example Repositories

1. [Actix Web Fullstack Example](https://github.com/actix/examples)


2. [Leptos Fullstack Starter](https://github.com/leptos-rs/start)
3. [Rust Web Boilerplate](https://github.com/emreyalvac/rust-web-boilerplate)

Would you like me to elaborate on any specific part of building a website with Rust?

# Machine Learning in Rust

Rust is emerging as a compelling choice for machine learning due to its performance,
safety guarantees, and growing ecosystem. While not as mature as Python's ML stack,
Rust offers unique advantages for production systems and performance-critical
applications.

## Rust ML Ecosystem Overview

### Core Libraries

1. **Tensor Operations**
- [`ndarray`](https://github.com/rust-ndarray/ndarray): N-dimensional array library
(similar to NumPy)
- [`tch-rs`](https://github.com/LaurentMazare/tch-rs): Rust bindings for PyTorch
- [`candle`](https://github.com/huggingface/candle): Hugging Face's lightweight
tensor library

2. **Machine Learning Frameworks**


- [`linfa`](https://github.com/rust-ml/linfa): Rust equivalent to scikit-learn
- [`smartcore`](https://github.com/smartcorelib/smartcore): Another scikit-learn-like
library

3. **Deep Learning**
- [`dfdx`](https://github.com/coreylowman/dfdx): Shape-checked deep learning
- [`burn`](https://github.com/burn-rs/burn): Flexible deep learning framework

## Practical Examples

### 1. Linear Regression with Linfa

```rust
use linfa::traits::Fit;
use linfa_linear::LinearRegression;
use ndarray::{array, Array2};

fn main() {
// Sample data (house size vs price)
let x: Array2<f64> = array![
[1.0], [2.0], [3.0], [4.0], [5.0]
];
let y = array![1.0, 3.0, 5.0, 7.0, 9.0];

// Create dataset
let dataset = linfa::Dataset::new(x, y);

// Fit model
let model = LinearRegression::default()
.fit(&dataset)
.unwrap();

// Predict
let new_x = array![[6.0]];
let pred = model.predict(&new_x);
println!("Prediction for 6: {:?}", pred);
}
```

### 2. Neural Network with tch-rs (PyTorch bindings)

```rust
use tch::{nn, nn::Module, nn::OptimizerConfig, Device, Tensor};

fn main() {
let vs = nn::VarStore::new(Device::Cpu);
let net = nn::seq()
.add(nn::linear(&vs.root(), 8, 16, Default::default()))
.add_fn(|x| x.relu())
.add(nn::linear(&vs.root(), 16, 1, Default::default()));

let mut opt = nn::Adam::default().build(&vs, 1e-3).unwrap();

// Training loop example


for _ in 0..100 {
let input = Tensor::randn(&[32, 8], (tch::Kind::Float, Device::Cpu));
let target = Tensor::randn(&[32, 1], (tch::Kind::Float, Device::Cpu));

let loss = net.forward(&input).mse_loss(&target, tch::Reduction::Mean);


opt.backward_step(&loss);
}
}
```

### 3. Image Classification with Candle

```rust
use candle_core::{DType, Device, Tensor};
use candle_nn::{loss, ops, Linear, Module, Optimizer, VarBuilder, VarMap};
struct Model {
linear1: Linear,
linear2: Linear,
}

impl Model {
fn new(vs: VarBuilder) -> Result<Self> {
let linear1 = Linear::new(vs.pp("linear1"), 784, 128)?;
let linear2 = Linear::new(vs.pp("linear2"), 128, 10)?;
Ok(Self { linear1, linear2 })
}

fn forward(&self, x: &Tensor) -> Result<Tensor> {


let x = self.linear1.forward(x)?.relu()?;
self.linear2.forward(&x)
}
}

fn main() -> Result<()> {


let device = Device::Cpu;
let varmap = VarMap::new();
let vs = VarBuilder::from_varmap(&varmap, DType::F32, &device);
let model = Model::new(vs.clone())?;

// Example training step


let dummy_input = Tensor::rand(0f32, 1f32, &[1, 784], &device)?;
let dummy_target = Tensor::zeros(&[1, 10], DType::F32, &device)?;

let logits = model.forward(&dummy_input)?;


let loss = loss::cross_entropy(&logits, &dummy_target)?;

println!("Loss: {}", loss.to_scalar::<f32>()?);


Ok(())
}
```

## Performance Considerations

1. **BLAS/LAPACK Integration**:
- Use `ndarray` with `blas` feature for optimized linear algebra
- Consider `intel-mkl-tool` for Intel Math Kernel Library

2. **GPU Acceleration**:
- `tch-rs` supports CUDA via PyTorch's backend
- `candle` supports CUDA and Metal

3. **Parallel Processing**:
- Use `rayon` for data parallelism
- `ndarray-parallel` for parallel array operations
## Data Processing Pipeline

```rust
use polars::prelude::*;
use ndarray_stats::QuantileExt;

fn process_data() -> Result<()> {


// Load data with Polars (Rust's pandas alternative)
let df = CsvReader::from_path("data.csv")?
.finish()?;

// Normalize numeric columns


let mut df = df
.lazy()
.with_columns([
(col("age") - col("age").mean()).alias("age_norm"),
(col("income") - col("income").mean()).alias("income_norm")
])
.collect()?;

// Convert to ndarray
let features = df
.select_series(&["age_norm", "income_norm"])?
.iter()
.map(|s| s.f64()?.to_ndarray())
.collect::<Result<Vec<_>>>()?;

let combined = ndarray::stack(Axis(1), &features)?;


Ok(())
}
```

## When to Use Rust for ML

1. **Production Deployment**:
- Need for small binaries with no Python dependency
- Memory safety requirements
- WebAssembly deployment

2. **Performance-Critical Components**:
- High-frequency model inference
- Custom ops/kernels
- Real-time processing

3. **Embedded/Edge ML**:
- Microcontrollers with Rust support
- Mobile applications

## Learning Resources
1. [Rust ML Working Group](https://github.com/rust-ml)
2. [Practical Deep Learning in Rust](https://github.com/sotrh/learn-wgpu)
3. [Rust for Data Science Book](https://rustfordata.science/)

## Current Limitations

1. **Ecosystem Maturity**:
- Fewer pre-trained models
- Less documentation compared to Python
- Some algorithms not yet implemented

2. **Development Speed**:
- More verbose than Python
- Compile times for complex models

3. **Visualization**:
- Limited plotting libraries (plotters is main option)

Would you like me to focus on any specific aspect of Rust for machine learning, such
as deploying models, specific algorithms, or performance optimization techniques?

# Common Algorithms Implemented in Rust

Rust's performance and safety features make it an excellent choice for implementing
algorithms. Here are several fundamental algorithms implemented in Rust:

## 1. Sorting Algorithms

### QuickSort
```rust
pub fn quicksort<T: Ord>(arr: &mut [T]) {
if arr.len() <= 1 {
return;
}
let pivot = partition(arr);
quicksort(&mut arr[..pivot]);
quicksort(&mut arr[pivot + 1..]);
}

fn partition<T: Ord>(arr: &mut [T]) -> usize {


let pivot = arr.len() - 1;
let mut i = 0;
for j in 0..pivot {
if arr[j] <= arr[pivot] {
arr.swap(i, j);
i += 1;
}
}
arr.swap(i, pivot);
i
}
```

### MergeSort
```rust
pub fn mergesort<T: Ord + Clone>(arr: &mut [T]) {
if arr.len() <= 1 {
return;
}
let mid = arr.len() / 2;
mergesort(&mut arr[..mid]);
mergesort(&mut arr[mid..]);
merge(arr, mid);
}

fn merge<T: Ord + Clone>(arr: &mut [T], mid: usize) {


let left = arr[..mid].to_vec();
let right = arr[mid..].to_vec();
let mut i = 0;
let mut j = 0;
let mut k = 0;

while i < left.len() && j < right.len() {


if left[i] <= right[j] {
arr[k] = left[i].clone();
i += 1;
} else {
arr[k] = right[j].clone();
j += 1;
}
k += 1;
}

while i < left.len() {


arr[k] = left[i].clone();
i += 1;
k += 1;
}

while j < right.len() {


arr[k] = right[j].clone();
j += 1;
k += 1;
}
}
```

## 2. Search Algorithms
### Binary Search
```rust
pub fn binary_search<T: Ord>(arr: &[T], target: &T) -> Option<usize> {
let mut left = 0;
let mut right = arr.len();

while left < right {


let mid = left + (right - left) / 2;
match arr[mid].cmp(target) {
std::cmp::Ordering::Equal => return Some(mid),
std::cmp::Ordering::Less => left = mid + 1,
std::cmp::Ordering::Greater => right = mid,
}
}
None
}
```

## 3. Graph Algorithms

### Dijkstra's Shortest Path


```rust
use std::collections::{BinaryHeap, HashMap};
use std::cmp::Ordering;

#[derive(Eq, PartialEq)]
struct State {
node: usize,
cost: usize,
}

impl Ord for State {


fn cmp(&self, other: &Self) -> Ordering {
other.cost.cmp(&self.cost)
}
}

impl PartialOrd for State {


fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}

pub fn dijkstra(adj_list: &[Vec<(usize, usize)>], start: usize) -> Vec<usize> {


let mut dist: Vec<_> = (0..adj_list.len()).map(|_| usize::MAX).collect();
let mut heap = BinaryHeap::new();

dist[start] = 0;
heap.push(State { node: start, cost: 0 });
while let Some(State { node, cost }) = heap.pop() {
if cost > dist[node] {
continue;
}

for &(neighbor, weight) in &adj_list[node] {


let next = State { node: neighbor, cost: cost + weight };
if next.cost < dist[neighbor] {
dist[neighbor] = next.cost;
heap.push(next);
}
}
}
dist
}
```

## 4. Dynamic Programming

### Fibonacci (Memoization)


```rust
use std::collections::HashMap;

pub fn fibonacci(n: u64, memo: &mut HashMap<u64, u64>) -> u64 {


if let Some(&val) = memo.get(&n) {
return val;
}
if n <= 1 {
return n;
}
let res = fibonacci(n - 1, memo) + fibonacci(n - 2, memo);
memo.insert(n, res);
res
}

// Usage:
// let mut memo = HashMap::new();
// fibonacci(10, &mut memo);
```

### Knapsack Problem


```rust
pub fn knapsack(weights: &[usize], values: &[usize], capacity: usize) -> usize {
let n = weights.len();
let mut dp = vec![vec![0; capacity + 1]; n + 1];

for i in 1..=n {
for w in 1..=capacity {
if weights[i - 1] <= w {
dp[i][w] = std::cmp::max(
values[i - 1] + dp[i - 1][w - weights[i - 1]],
dp[i - 1][w]
);
} else {
dp[i][w] = dp[i - 1][w];
}
}
}
dp[n][capacity]
}
```

## 5. Tree Algorithms

### Binary Search Tree


```rust
type Link<T> = Option<Box<Node<T>>>;

struct Node<T: Ord> {


value: T,
left: Link<T>,
right: Link<T>,
}

impl<T: Ord> Node<T> {


fn new(value: T) -> Self {
Node {
value,
left: None,
right: None,
}
}

fn insert(&mut self, value: T) {


if value < self.value {
if let Some(left) = &mut self.left {
left.insert(value);
} else {
self.left = Some(Box::new(Node::new(value)));
}
} else if value > self.value {
if let Some(right) = &mut self.right {
right.insert(value);
} else {
self.right = Some(Box::new(Node::new(value)));
}
}
}
fn search(&self, value: &T) -> bool {
if value == &self.value {
true
} else if value < &self.value {
self.left.as_ref().map_or(false, |left| left.search(value))
} else {
self.right.as_ref().map_or(false, |right| right.search(value))
}
}
}
```

## 6. String Algorithms

### KMP Pattern Matching


```rust
pub fn kmp_search(text: &str, pattern: &str) -> Vec<usize> {
let pattern = pattern.as_bytes();
let text = text.as_bytes();
let lps = compute_lps(pattern);
let mut i = 0;
let mut j = 0;
let mut result = Vec::new();

while i < text.len() {


if pattern[j] == text[i] {
i += 1;
j += 1;

if j == pattern.len() {
result.push(i - j);
j = lps[j - 1];
}
} else if j > 0 {
j = lps[j - 1];
} else {
i += 1;
}
}
result
}

fn compute_lps(pattern: &[u8]) -> Vec<usize> {


let mut lps = vec![0; pattern.len()];
let mut len = 0;
let mut i = 1;

while i < pattern.len() {


if pattern[i] == pattern[len] {
len += 1;
lps[i] = len;
i += 1;
} else if len > 0 {
len = lps[len - 1];
} else {
lps[i] = 0;
i += 1;
}
}
lps
}
```

## 7. Numerical Algorithms

### Fast Power (Exponentiation by Squaring)


```rust
pub fn fast_power(mut base: u64, mut power: u64) -> u64 {
let mut result = 1;
while power > 0 {
if power % 2 == 1 {
result *= base;
}
base *= base;
power /= 2;
}
result
}
```

### Sieve of Eratosthenes (Prime Numbers)


```rust
pub fn sieve_of_eratosthenes(n: usize) -> Vec<bool> {
let mut sieve = vec![true; n + 1];
sieve[0] = false;
sieve[1] = false;

for i in 2..=(n as f64).sqrt() as usize {


if sieve[i] {
for j in (i * i..=n).step_by(i) {
sieve[j] = false;
}
}
}
sieve
}
```

## Key Advantages of Implementing Algorithms in Rust


1. **Performance**: Comparable to C/C++ implementations
2. **Memory Safety**: No segfaults or buffer overflows
3. **Concurrency**: Safe parallel implementations with ownership system
4. **Generics**: Type-safe implementations that work with many data types
5. **Error Handling**: Explicit error handling with Result/Option

Would you like me to elaborate on any specific algorithm or show more advanced
implementations?

You might also like