Skip to content

AdithyaDamarla/Rust-Udacity

Repository files navigation

Rust-Udacity Learning Repository

A comprehensive collection of Rust programming projects from the Udacity course, demonstrating core language concepts, advanced features, concurrency patterns, and game development with FFI integration.


Table of Contents

  1. Overview
  2. Repository Structure
  3. Getting Started
  4. Projects Overview
  5. Prerequisites
  6. Building and Running
  7. Key Concepts

Overview

This repository contains hands-on implementations of Rust programming concepts taught in the Udacity course. Projects progress from foundational concepts like ownership and borrowing to advanced topics including:

  • Package management and modular code organization
  • Generics and trait systems
  • Concurrency patterns (async/await, threading)
  • Procedural macros and FFI (Foreign Function Interface)
  • Game development with OpenGL integration

Repository Structure

Rust-Udacity/
├── Cargo and modules/                    # Package management and module organization
│   ├── hello-world-binary/               # Basic binary project
│   ├── shape_calculator/                 # Library with modules, benching, and testing
│   └── string_search_benchmark/          # Performance benchmarking example
│
├── Introduction to Rust/                 # Core language fundamentals
│   └── OwnershipBorrowLifetime.rs       # Ownership, borrowing, and lifetime concepts
│
├── Generics and Traits, Error Handling, and Control Flow, Enums, and Pattern Matching/
│   └── Exercise.rs                       # Generic functions, error handling, pattern matching
│
├── Concurrency/                          # Concurrent programming patterns
│   ├── Asynchronous/                     # Async/await with tokio and reqwest
│   └── Job_Scheduler/                    # Thread-based job scheduling with crossbeam
│
├── Macros_and_FFI/                       # Declarative macros and C interoperability
│   ├── Macros/                           # Custom declarative macro examples
│   ├── ffi_string_reverse/               # FFI with C string manipulation
│   └── procedural_macros/                # Procedural macro definitions
│
└── intro-to-rust-starter/                # Comprehensive game engine project
    ├── starter/
    │   ├── game_pong/                    # Pong game implementation
    │   ├── rust_test_game/               # Complete game framework with rendering
    │   ├── my_rust_lib/                  # Rust game engine library with FFI
    │   ├── opengl_wrapper_lib/           # C OpenGL wrapper
    │   ├── c_test_game/                  # Reference C implementation
    │   └── Makefile                      # Build automation
    ├── Report.md                         # Detailed implementation guide
    └── results/                          # Generated output and screenshots

Getting Started

Prerequisites

  • Rust toolchain: Install from rustup.rs
  • Cargo: Comes with Rust installation
  • C compiler: GCC or Clang
  • Development libraries (Linux):
    sudo apt-get install libglfw3-dev libgl1-mesa-dev
  • Python (optional): For some build scripts

Installation

  1. Clone the repository:

    git clone https://github.com/AdithyaDamarla/Rust-Udacity.git
    cd Rust-Udacity
  2. Verify Rust installation:

    rustc --version
    cargo --version

Projects Overview

Cargo and Modules

Location: Cargo and modules/

This section covers Rust's package management system and module organization patterns.

hello-world-binary

Basic binary Rust project demonstrating the simplest Cargo setup.

cd "Cargo and modules/hello-world-binary"
cargo run

shape_calculator

A library project that demonstrates:

  • Module organization: Separate modules for Circle, Rectangle, and Square
  • Code organization: Traits and implementations
  • Benchmarking: Performance benchmarks using Criterion
  • Testing: Integration tests and unit tests

Directory structure:

shape_calculator/
├── benches/
│   └── area_bench.rs        # Benchmark comparisons
├── src/
│   ├── lib.rs               # Library root with module definitions
│   ├── circle.rs            # Circle shape implementation
│   ├── rectangle.rs         # Rectangle shape implementation
│   ├── square.rs            # Square shape implementation
│   └── intrgration_test.rs  # Integration tests
└── Cargo.toml

Run tests and benchmarks:

cd "Cargo and modules/shape_calculator"
cargo test           # Run all tests
cargo bench          # Run benchmarks

string_search_benchmark

Demonstrates performance benchmarking for string search algorithms.

cd "Cargo and modules/string_search_benchmark"
cargo bench

Introduction to Rust

Location: Introduction to Rust/

OwnershipBorrowLifetime.rs

Explores fundamental Rust concepts:

  • Ownership: Understanding Rust's memory management model
  • Borrowing: References and mutability
  • Lifetimes: Specifying relationships between references

This file demonstrates:

  • Creating owned String values
  • Borrowing with references (&T)
  • Using lifetime annotations ('a) to link references across structs
  • Functions that borrow data without taking ownership

Key concepts:

struct Book<'a> {
    title: String,      // Owned value
    author: &'a str,    // Borrowed reference with lifetime
}

Generics, Traits, Error Handling, and Pattern Matching

Location: Generics and Traits, Error Handling, and Control Flow, Enums, and Pattern Matching/

Exercise.rs

Comprehensive example implementing:

  • Generics: Type-safe abstractions over multiple types
  • Traits: Defining shared behavior across types
  • Error Handling: Using Result<T, E> for error propagation
  • Pattern Matching: Conditional logic with pattern matching
  • Enums: Sum types for representing alternatives

Key features:

  • Generic calculate<T> function supporting multiple arithmetic operations
  • Operation enum for compile-time safety
  • Division-by-zero error handling
  • Generic trait bounds for arithmetic operations

Example:

enum Operation { Add, Subtract, Multiply, Divide }

fn calculate<T>(a: T, b: T, op: Operation) -> Result<T, &'static str>
where T: Add<Output=T> + Sub<Output=T> + ... { ... }

Concurrency

Location: Concurrency/

Demonstrates modern concurrent programming patterns in Rust.

Asynchronous

Path: Concurrency/Asynchronous/src/main.rs

Implements async/await patterns using Tokio runtime:

  • Async HTTP requests: Using reqwest for non-blocking web requests
  • Task spawning: Creating concurrent tasks with tokio::spawn
  • Task coordination: Waiting for all tasks to complete
  • Error handling: Graceful error management in async code

Key components:

struct WebRequestProcessor {
    urls: VecDeque<String>,
}

// Async function for downloading web content
async fn download(url: &str) -> Result<String, Error> {
    let response = reqwest::get(url).await?;
    response.text().await
}

// Concurrent processing of multiple URLs
async fn start_requests(&self) { ... }

Run:

cd Concurrency/Asynchronous
cargo run

Job Scheduler

Path: Concurrency/Job_Scheduler/src/main.rs

Implements thread-based job scheduling:

  • Thread management: Creating and managing worker threads
  • Synchronization: Using Arc<Mutex<T>> for safe shared state
  • Channel communication: Using crossbeam_channel for thread coordination
  • Job abstraction: Boxing closures as jobs

Key concepts:

type Job = Box<dyn FnOnce() -> String + Send + 'static>;

struct JobScheduler {
    jobs: Arc<Mutex<Vec<Job>>>,
}

Run:

cd Concurrency/Job_Scheduler
cargo run

Macros and FFI

Location: Macros_and_FFI/

Explores advanced Rust features: declarative macros and Foreign Function Interface.

Macros

Path: Macros_and_FFI/Macros/src/main.rs

Demonstrates declarative macros (macro_rules!):

  • Custom debug formatting: Implementing Debug trait via macros
  • Code generation: Macro patterns and replacements
  • Metaprogramming: Writing code that generates code

Example macro:

macro_rules! custom_debug {
    ($struct_name:ident { $( $field:ident : $type:ty ),* }) => {
        impl Debug for $struct_name { ... }
    }
}

Run:

cd Macros_and_FFI/Macros
cargo run

FFI String Reverse

Path: Macros_and_FFI/ffi_string_reverse/src/main.rs

Demonstrates Foreign Function Interface (FFI) with C:

  • C interoperability: Calling C functions from Rust
  • Memory safety: Proper memory management across FFI boundaries
  • Type conversion: Converting between Rust and C types
  • Unsafe code: Using unsafe blocks for FFI calls

Key features:

unsafe extern "C" {
    fn reverse_string(s: *mut c_char, len: usize) -> *mut c_char;
}

// Safely calling C functions
unsafe { reverse_string(c_ptr, length); }

Build and run:

cd Macros_and_FFI/ffi_string_reverse
cargo build
cargo run

Procedural Macros

Path: Macros_and_FFI/procedural_macros/

Advanced macro system for compile-time code generation:

  • Custom derives
  • Attribute-like macros
  • Function-like procedural macros

Intro to Rust Starter (Game Engine Project)

Location: intro-to-rust-starter/

This is the flagship project, demonstrating a complete game engine with:

  • C/Rust interoperability via FFI
  • OpenGL rendering
  • Game physics and collision detection
  • Input handling and UI systems
  • Build automation

For detailed implementation guide, see: Report.md

Project Structure

starter/
├── opengl_wrapper_lib/           # C library wrapping OpenGL
│   ├── opengl_wrapper_lib.c
│   └── opengl_wrapper_lib.h
│
├── c_test_game/                  # Reference C implementation
│   └── test_game.c
│
├── c_output/                     # Compiled C binaries
│   └── test_game_exe
│
├── my_rust_lib/                  # Rust game engine library
│   ├── build.rs                  # Build script for C compilation
│   ├── Cargo.toml
│   └── src/
│       ├── lib.rs                # Library root
│       ├── ffi.rs                # FFI bindings to C
│       ├── macros.rs             # Declarative macros
│       └── macro.rs
│
├── game_pong/                    # Pong game using engine
│   ├── Cargo.toml
│   └── src/
│       ├── main.rs               # Entry point
│       ├── game.rs               # Game logic
│       ├── inputs.rs             # Input handling
│       ├── logger.rs             # Logging utilities
│       ├── movement_collision.rs # Physics
│       ├── program_player.rs     # AI implementation
│       ├── render.rs             # Rendering
│       ├── sprite.rs             # Sprite system
│       ├── ui.rs                 # UI elements
│       └── world.rs              # World management
│
├── rust_test_game/               # Test game framework
│   ├── Cargo.toml
│   └── src/
│       ├── main.rs               # Entry point
│       ├── game.rs               # Game logic
│       ├── gameobject.rs         # Entity system
│       ├── gameobjectdata.rs     # Component data
│       ├── gameworld.rs          # World state
│       ├── inputs.rs             # Input processing
│       ├── logger.rs             # Logging
│       ├── objectcreator.rs      # Factory patterns
│       ├── render.rs             # Rendering system
│       └── networking.rs         # Networking support
│
├── Makefile                      # Build automation
└── README.md                     # Project documentation

Key Components

1. C OpenGL Wrapper (opengl_wrapper_lib)

Safe C wrapper around OpenGL for basic rendering:

  • Window management with GLFW
  • 2D rectangle rendering
  • Color management
  • Frame buffer operations
2. Rust Game Engine (my_rust_lib)

Safe Rust bindings and utilities:

  • FFI Module (ffi.rs): Safe wrappers around C functions
  • Macros (macros.rs): start_window_and_game_loop! for game initialization
  • Build Script (build.rs): Compiles C code and links libraries

Key macro:

start_window_and_game_loop!(
    "Window Title",
    1024,   // width
    768,    // height
    {
        // Initialization
    },
    {
        // Main game loop
    },
    {
        // Cleanup
    }
);
3. Game Projects

game_pong: Complete Pong game with AI player rust_test_game: Test framework for game engine features

Running the Game Projects

Verify C compilation:

cd intro-to-rust-starter/starter
make run-c  # Runs the C reference implementation

Run Pong game:

cd intro-to-rust-starter/starter/game_pong
cargo run

Run test game:

cd intro-to-rust-starter/starter/rust_test_game
cargo run

Building Everything

cd intro-to-rust-starter/starter
make build-all     # Build all projects
make clean         # Clean build artifacts

Building and Running

Build All Projects

# From repository root
cargo build --all

# Or build individual projects
cd "path/to/project"
cargo build

Run Projects

# Binary projects
cargo run

# Library tests
cargo test

# Benchmarks
cargo bench

# With output
cargo run -- --verbose

Running Tests

# All tests in workspace
cargo test --all

# Specific test
cargo test test_name

# With output
cargo test -- --nocapture

Performance Benchmarking

# Benchmark shape calculations
cd "Cargo and modules/shape_calculator"
cargo bench

# String search benchmarks
cd "Cargo and modules/string_search_benchmark"
cargo bench

Key Concepts

1. Ownership and Borrowing

Rust's memory management without garbage collection:

  • Ownership: Each value has one owner
  • Borrowing: References allow temporary access without ownership transfer
  • Lifetimes: Ensure references don't outlive their data

2. Type System

  • Generics: Writing code that works with multiple types
  • Traits: Defining shared behavior (similar to interfaces)
  • Pattern Matching: Safe, exhaustive conditional logic
  • Enums: Sum types for representing choices

3. Error Handling

  • Result<T, E>: Returning success or failure
  • Option: Representing presence or absence of values
  • ? operator: Ergonomic error propagation

4. Concurrency

Two main paradigms:

  • Async/Await: Lightweight, cooperative concurrency for I/O
  • Threading: Preemptive, OS-level parallelism for CPU-bound work

5. Macros

  • Declarative Macros (macro_rules!): Pattern-based code generation
  • Procedural Macros: Compiler plugins for custom derives

6. FFI (Foreign Function Interface)

  • Calling C functions from Rust
  • Memory safety across language boundaries
  • Proper type conversions and ownership management

7. Game Development Patterns

  • Entity Component System: Separating data from behavior
  • Game Loop: Initialization, update, render cycle
  • Collision Detection: Physics and spatial partitioning
  • Input Handling: Event processing and state management

Learning Resources


Project Reports

For detailed implementation guides and technical documentation, see:


Quick Reference Commands

Project Navigation

# Navigate to specific projects
cd "Cargo and modules/shape_calculator"
cd "Concurrency/Asynchronous"
cd "intro-to-rust-starter/starter/game_pong"

Common Operations

# Build and run
cargo build
cargo run

# Testing
cargo test
cargo test -- --nocapture
cargo test test_name

# Benchmarking
cargo bench

# Formatting
cargo fmt

# Linting
cargo clippy

# Documentation
cargo doc --open

Game Engine (starter/)

# Build C reference
make build-c
make run-c

# Build all projects
make build-all

# Clean
make clean

Last Updated: November 2025 Status: Complete with all projects documented

About

Rust programming exercises and projects demonstrating core language concepts, concurrency patterns, and game engine development.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors