Chapter 1 · Level 0

⚡ Unsafe Mastery

Harnessing the Power and Responsibility of Unsafe Rust

Introduction to Unsafe Rust

Rust's safety guarantees are one of its strongest features, but sometimes you need to break these rules to achieve low-level control, interface with hardware, or optimize critical code paths. The unsafe keyword gives you this power, but with great power comes great responsibility.

⚠️ Warning: Unsafe code can lead to undefined behavior, memory corruption, and security vulnerabilities if used incorrectly. Always minimize unsafe code and encapsulate it behind safe abstractions.

1. Understanding Raw Pointers

Raw pointers are Rust's equivalent to C pointers. Unlike references, they:

📝 Example: Creating Raw Pointers
fn main() {
    let mut num = 42;

    // Immutable raw pointer (*const T)
    let r1 = &num as *const i32;

    // Mutable raw pointer (*mut T)
    let r2 = &mut num as *mut i32;

    // Creating from arbitrary memory address (dangerous!)
    let address = 0x012345usize;
    let r3 = address as *const i32;

    println!("Pointers created: {:p}, {:p}, {:p}", r1, r2, r3);
}
ℹ️ Note: Creating raw pointers is safe. It's dereferencing them that requires unsafe code!

Dereferencing Raw Pointers

📝 Example: Dereferencing Safely
fn main() {
    let mut num = 42;

    let r1 = &num as *const i32;
    let r2 = &mut num as *mut i32;

    unsafe {
        // Reading through immutable pointer
        println!("r1 points to: {}", *r1);

        // Writing through mutable pointer
        *r2 = 100;
        println!("r2 changed value to: {}", *r2);
    }

    println!("Final value: {}", num); // 100
}

2. Unsafe Functions and Blocks

Unsafe functions must be called from within unsafe blocks or other unsafe functions. This creates a clear boundary showing where unsafe operations occur.

📝 Example: Unsafe Function
unsafe fn dangerous() {
    println!("Doing something dangerous!");
}

fn main() {
    // This won't compile without unsafe block
    // dangerous();

    unsafe {
        dangerous();
    }
}

// Unsafe function that manipulates raw pointers
unsafe fn write_at_offset(ptr: *mut i32, offset: isize, value: i32) {
    *ptr.offset(offset) = value;
}

fn main_example() {
    let mut arr = [1, 2, 3, 4, 5];
    let ptr = arr.as_mut_ptr();

    unsafe {
        // Write 100 at index 2
        write_at_offset(ptr, 2, 100);
    }

    println!("Array: {:?}", arr); // [1, 2, 100, 4, 5]
}

Creating Safe Abstractions

The best practice is to wrap unsafe code in safe functions that maintain Rust's invariants:

📝 Example: Safe Wrapper Around Unsafe Code
use std::slice;

// Safe function using unsafe internally
fn split_at_mut_custom(slice: &mut [T], mid: usize) -> (&mut [T], &mut [T]) {
    let len = slice.len();
    let ptr = slice.as_mut_ptr();

    // Validate preconditions
    assert!(mid <= len);

    unsafe {
        (
            slice::from_raw_parts_mut(ptr, mid),
            slice::from_raw_parts_mut(ptr.add(mid), len - mid),
        )
    }
}

fn main() {
    let mut v = vec![1, 2, 3, 4, 5, 6];

    let (left, right) = split_at_mut_custom(&mut v, 3);

    left[0] = 10;
    right[0] = 20;

    println!("{:?}", v); // [10, 2, 3, 20, 5, 6]
}

3. Calling External C Functions (FFI Preview)

One of the most common uses of unsafe is calling C functions through FFI:

📝 Example: Calling C Standard Library
extern "C" {
    fn abs(input: i32) -> i32;
}

fn main() {
    unsafe {
        println!("Absolute value of -3 according to C: {}", abs(-3));
    }
}

// More complex example: malloc and free
use std::alloc::{alloc, dealloc, Layout};

fn manual_allocation() {
    unsafe {
        // Allocate memory for i32
        let layout = Layout::new::();
        let ptr = alloc(layout) as *mut i32;

        if ptr.is_null() {
            panic!("Allocation failed!");
        }

        // Use the memory
        *ptr = 42;
        println!("Value: {}", *ptr);

        // Must manually free!
        dealloc(ptr as *mut u8, layout);
    }
}

4. Implementing Unsafe Traits

Some traits are marked as unsafe because implementers must uphold certain invariants:

📝 Example: Unsafe Trait Implementation
// Send trait indicates type can be transferred between threads
// Sync trait indicates type can be shared between threads

struct MyType {
    data: *mut i32,
}

// We must guarantee this type is safe to send between threads
unsafe impl Send for MyType {}

// For mutable statics, we use unsafe
static mut COUNTER: u32 = 0;

fn increment_counter() {
    unsafe {
        COUNTER += 1;
    }
}

// Better alternative: use std::sync::atomic
use std::sync::atomic::{AtomicU32, Ordering};

static ATOMIC_COUNTER: AtomicU32 = AtomicU32::new(0);

fn increment_atomic() {
    ATOMIC_COUNTER.fetch_add(1, Ordering::SeqCst);
}

5. Practical Example: Ring Buffer

Let's build a lock-free ring buffer using unsafe code for performance:

📝 Example: Lock-Free Ring Buffer
use std::sync::atomic::{AtomicUsize, Ordering};
use std::alloc::{alloc, dealloc, Layout};
use std::ptr;

pub struct RingBuffer {
    buffer: *mut T,
    capacity: usize,
    head: AtomicUsize,
    tail: AtomicUsize,
}

impl RingBuffer {
    pub fn new(capacity: usize) -> Self {
        assert!(capacity > 0 && capacity.is_power_of_two());

        let layout = Layout::array::(capacity).unwrap();

        let buffer = unsafe {
            alloc(layout) as *mut T
        };

        if buffer.is_null() {
            panic!("Allocation failed");
        }

        RingBuffer {
            buffer,
            capacity,
            head: AtomicUsize::new(0),
            tail: AtomicUsize::new(0),
        }
    }

    pub fn push(&self, value: T) -> Result<(), T> {
        let head = self.head.load(Ordering::Acquire);
        let tail = self.tail.load(Ordering::Acquire);

        let next_tail = (tail + 1) & (self.capacity - 1);

        if next_tail == head {
            return Err(value); // Buffer full
        }

        unsafe {
            ptr::write(self.buffer.add(tail), value);
        }

        self.tail.store(next_tail, Ordering::Release);
        Ok(())
    }

    pub fn pop(&self) -> Option {
        let head = self.head.load(Ordering::Acquire);
        let tail = self.tail.load(Ordering::Acquire);

        if head == tail {
            return None; // Buffer empty
        }

        let value = unsafe {
            ptr::read(self.buffer.add(head))
        };

        let next_head = (head + 1) & (self.capacity - 1);
        self.head.store(next_head, Ordering::Release);

        Some(value)
    }
}

unsafe impl Send for RingBuffer {}
unsafe impl Sync for RingBuffer {}

impl Drop for RingBuffer {
    fn drop(&mut self) {
        // Drop all remaining elements
        while self.pop().is_some() {}

        // Deallocate buffer
        let layout = Layout::array::(self.capacity).unwrap();
        unsafe {
            dealloc(self.buffer as *mut u8, layout);
        }
    }
}

fn main() {
    let buffer = RingBuffer::new(8);

    buffer.push(1).unwrap();
    buffer.push(2).unwrap();
    buffer.push(3).unwrap();

    println!("{:?}", buffer.pop()); // Some(1)
    println!("{:?}", buffer.pop()); // Some(2)

    buffer.push(4).unwrap();

    println!("{:?}", buffer.pop()); // Some(3)
    println!("{:?}", buffer.pop()); // Some(4)
    println!("{:?}", buffer.pop()); // None
}

6. Best Practices

🔑 Key Principles for Safe Unsafe Code

  1. Minimize Unsafe Code: Use unsafe only when absolutely necessary
  2. Encapsulate: Wrap unsafe code in safe abstractions
  3. Document Invariants: Clearly state what invariants must be maintained
  4. Validate Inputs: Check preconditions before unsafe operations
  5. Test Thoroughly: Use tools like Miri and extensive testing
  6. Review Carefully: Have unsafe code reviewed by experienced developers
📝 Example: Documented Unsafe Function
/// Splits a mutable slice into two at the given index.
///
/// # Safety
///
/// Caller must ensure that `mid <= slice.len()`.
/// Violating this invariant leads to undefined behavior.
///
/// # Panics
///
/// Panics if `mid > slice.len()`.
pub fn split_at_mut_unsafe(
    slice: &mut [T],
    mid: usize
) -> (&mut [T], &mut [T]) {
    let len = slice.len();
    let ptr = slice.as_mut_ptr();

    assert!(mid <= len, "mid must be <= len");

    unsafe {
        (
            std::slice::from_raw_parts_mut(ptr, mid),
            std::slice::from_raw_parts_mut(ptr.add(mid), len - mid),
        )
    }
}

7. Common Pitfalls

Pitfall Description Solution
Null Pointer Dereference Dereferencing a null pointer Always check is_null() before dereferencing
Use After Free Using memory after it's been deallocated Track ownership carefully, use RAII patterns
Data Races Concurrent access without synchronization Use atomic operations or locks
Buffer Overflow Writing past allocated memory Validate bounds before pointer arithmetic
Alignment Issues Accessing unaligned memory Use std::ptr::read_unaligned

Summary

✅ You've learned:

  • How to create and use raw pointers safely
  • When and how to use unsafe blocks and functions
  • How to build safe abstractions around unsafe code
  • Common patterns and pitfalls in unsafe Rust
  • Best practices for writing maintainable unsafe code

Unsafe Rust is a powerful tool that enables low-level programming and performance optimization. By understanding its principles and following best practices, you can harness this power while maintaining code safety and correctness.

Korea Standardization Infrastructure Mapping

Korea operates a comprehensive standards governance system through inter-ministerial cooperation. National Standards Council (under Prime Minister's Office, per Framework Act on National Standards Article 5) coordinates KATS (Korean Agency for Technology and Standards), MFDS (Ministry of Food and Drug Safety), MOTIE (Ministry of Trade, Industry and Energy), MSIT (Ministry of Science and ICT), MOIS (Ministry of the Interior and Safety), MOE (Ministry of Environment), MOHW (Ministry of Health and Welfare), MND (Ministry of National Defense), MCST (Ministry of Culture, Sports and Tourism), MOFA (Ministry of Foreign Affairs), MOJ (Ministry of Justice), and FSC (Financial Services Commission). Accreditation and Testing: KOLAS (Korea Laboratory Accreditation Scheme) accredits 800+ testing laboratories. KAS (Korea Accreditation System) accredits 50+ certification bodies. KTC (Korea Testing Certification), KTR (Korea Testing & Research Institute), KTL (Korea Testing Laboratory), and KCL (Korea Conformity Laboratories) provide conformance testing. Telecom and Cyber: KCC (Korea Communications Commission), KCA (Korea Communications Agency), TTA (Telecommunications Technology Association), IITP (Institute for Information & Communications Technology Planning & Evaluation), NIPA (National IT Industry Promotion Agency), KISA (Korea Internet & Security Agency), KCMVP (Korea Cryptographic Module Validation Program), NIS (National Intelligence Service), NSR (National Security Research Institute), and NCSC (National Cyber Security Center). National R&D Centers: KIST, ETRI, KAIST, Seoul National University, Yonsei University, Korea University, POSTECH, UNIST, GIST, DGIST, KISTI, KIER, KIMM, KRICT, KFRI, KRIBB. International Standards Cooperation: ISO TC/SC Korean secretariats, IEC TC/SC Korean secretariats, ITU-T Study Group Korean chairs, 3GPP RAN/SA Korean chairs, IEEE 802 Korean chairs, W3C Korea office, OASIS Korea office, IETF Korea cooperation, OECD CSTP, UN ESCAP, APEC SCSC Korean cooperation. Korean Industrial Standards (KS) Catalog: KS X (Information) 25,000+, KS A (Basic) 15,000+, KS B (Machinery) 25,000+, KS C (Electrical) 18,000+, KS D (Metallurgy) 12,000+, KS E (Mining) 5,000+, KS F (Construction) 18,000+, KS H (Food) 8,000+, KS I (Environment) 5,000+, KS J (Biology) 3,000+, KS K (Textile) 15,000+, KS L (Ceramics) 7,000+, KS M (Chemistry) 12,000+, KS P (Medical) 5,000+, KS Q (Quality Mgmt) 4,000+, KS R (Transport) 12,000+, KS S (Service) 3,000+, KS T (Packaging) 4,000+, KS V (Shipbuilding) 5,000+, KS W (Aerospace) 3,000+ — totaling 220,000+ Korean Industrial Standards. Key Acts: Personal Information Protection Act (Act 19234, effective Sept 15, 2024), Electronic Government Act, Electronic Signature Act, Act on Promotion of Information and Communications Network Utilization and Information Protection, Information and Communications Infrastructure Protection Act, Data Industry Act, Public Data Act, AI Framework Act (Act 20212, effective July 2026), Industrial Technology Innovation Promotion Act, Framework Act on Science and Technology — 70+ Korean standardization-related laws.

Korea Digital Transformation Detailed Mapping

Korea operates digital transformation through a comprehensive governance system. Digital Government: Digital Platform Government Committee (established September 2022, under the President)·Ministry of the Interior and Safety Digital Government Bureau·e-Government Support Center·Gov.kr·National Citizen Service·KDIS (Korea Digital Information Society)·NIA (National Information Society Agency)·MOIS (Ministry of the Interior and Safety). K-DNS Infrastructure: Korea Internet & Security Agency (KISA) Korea Internet Center·KISA DNS Root Server·KRNIC (Korea Network Information Center)·BGP Korea·National Cyber Security Center (NCSC)·KCC (Korea Communications Commission)·MSIT (Ministry of Science and ICT)·NIA·NIPA. Korean Cloud Infrastructure: KT Cloud·NAVER Cloud (NCloud)·Samsung SDS Cloud·LG U+ Cloud·NHN Cloud·Kakao Enterprise Cloud·SK Telecom Cloud·KISA Cloud Security Assurance Program (CSAP)·KCMVP-validated cloud·ISMS-P (Information Security & Personal Information Management System). Korean Security Certifications: KISA ISMS-P certification·KCMVP (Korean Cryptographic Module Validation Program)·NIS (National Intelligence Service) "National Cryptographic Technology Operation Standards"·NCSC "National Cyber Security Strategy 2024-2028"·CC (Common Criteria) Korean evaluation bodies·EAL4·EAL5·KS X ISO/IEC 15408·19790·24759 Korean Profile. Korean Data Standards: NIA AI Hub·National Data Standardization Committee·Statistics Korea (KOSTAT)·MyData 4 Designated Combination Specialists (Samsung SDS, KICI, KOSTAT, KFTC)·National Institute of Korean Language·National Law Information Center·National Spatial Information Platform·National Spatial Data Center·Korean Spatial Information Standards. Finance and Fintech Standards: FSC (Financial Services Commission)·FSS (Financial Supervisory Service)·FIU (Financial Intelligence Unit)·BOK (Bank of Korea)·FSEC (Financial Security Institute)·KFTC (Korea Financial Telecommunications)·KSD (Korea Securities Depository)·KRX (Korea Exchange) 8-agency cooperation. 5G/6G Communications Infrastructure: 5G subscribers 35 million (2024)·5G base stations 350,000·6G commercialization target 2028·5G dedicated networks 16 operators·6G Acceleration Council (MSIT, 2024). K-Content: KOCCA (Korea Creative Content Agency)·MCST (Ministry of Culture, Sports and Tourism)·KCA (Korea Communications Agency)·Korea Culture Information Service Agency·Korean Film Archive·Korea Publishing Industry Promotion Agency. Data 3 Acts (Personal Information Protection Act·Credit Information Act·Telecommunications Network Act, 2020 enforcement)·Data Industry Act (2021)·Public Data Act (2013)·AI Framework Act (2026)·Digital Platform Government Framework Act (2024 proposed) — Korea digital transformation core legislation.

Korea Industrial, Research, Education Infrastructure Mapping

Korea operates its industrial ecosystem and standardization system through the following core infrastructure. Korea Top 5 Groups: Samsung, Hyundai Motor, LG, SK, Lotte. Each group operates standardization committees and ISO/IEC TC Korean secretariats. Samsung Electronics (semiconductors, displays, home appliances, telecom)·Hyundai Motor (automobiles, mobility)·LG Electronics (home appliances, displays, OLED)·SK hynix (memory)·LG Energy Solution·Samsung SDI (batteries)·POSCO Future M (materials)·Hyundai Mobis (parts). Korean IT Big Tech: NAVER (search, cloud, AI HyperCLOVA)·Kakao (messenger, payment, mobility, banking)·Coupang (e-commerce, logistics)·Karrot Market·Toss·Woowa Brothers. Korea Telcos: SK Telecom·KT·LG U+. 5G·5G dedicated networks·B2B cloud·AI businesses operating. Korea Top 7 Research Universities: Seoul National University·KAIST·POSTECH·Yonsei University·Korea University·UNIST·DGIST·GIST. All serve as standardization R&D bases and ISO/IEC/IEEE Korean chairs. Korea Government-affiliated National Research Institutes (26): KIST, KAERI, KIMM, KIER, KFRI, KRICT, KRIBB, KARI, KASI, KIGAM, KICT, KISTI, KETI, ETRI, NIMS, KIMS, KISDI, KOTRA, STEPI, KOEN, KICCE, KIET, KIPF, KIHASA, KICJ, KLRI. Korea Industrial Complexes / Tech Valleys: Pangyo Techno Valley·Dongtan·Gwanggyo·Songdo IBD·Yeouido·Gangnam·Sihwa·Banwol·Gumi·Ulsan·Changwon·Geoje·Yeosu·Onsan·Cheongju·Iksan·Gwangyang·POSCO Gwangyang Steel Mill·Asan Bay·Seosan·Songdo·Incheon Airport·Sejong·Cheongna·Geomdan. Korea Trade and Finance Infrastructure: Korea International Trade Association (KITA)·Korea Trade-Investment Promotion Agency (KOTRA)·Export-Import Bank of Korea (KEXIM)·Bank of Korea·Kookmin Bank·Shinhan·Hana·Woori·NH Nonghyup·IBK Industrial Bank·SC First Bank·Citi Bank Korea·HSBC Korea·DBS Korea — 14 Korean major banks and foreign banks. Korea K-POP / K-Content: HYBE·SM·YG·JYP 4 major entertainment companies·CJ ENM·tvN·MBC·KBS·SBS·EBS·YTN·Yonhap News TV·JTBC Korean broadcasting·NETFLIX Korea·Disney Plus·TVING·Wavve·Watcha·Coupang Play. Korea Gaming Industry: Nexon·NCsoft·Krafton·Netmarble·Kakao Games·Pearl Abyss·Com2uS·Gamevil·NHN·Smilegate·Webzen. Korea Automotive / Battery: Hyundai Motor·Kia·Genesis·LG Energy Solution·Samsung SDI·SK On·POSCO Future M·EcoPro·L&F battery cathode material suppliers. Korea Semiconductor: Samsung Electronics (HBM3E·HBM4)·SK hynix (HBM3E 12-Hi)·DB HiTek·SK siltron·SK Enpulse·Dongjin Semichem·Seoul Semiconductor·Simmtech·Samsung Display·LG Display.