Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Rust <-> Android Bridge

Rust <-> Android Bridge

Discover the benefits of using Rust for Android development. We’ll cover the basics of the language, compare it to C++, and show you how to set up a Rust development environment for Android. You’ll also see some real-world examples of Rust & Android together in action!

This slides were presented during on 30th May 2023 in Warsaw, Poland on plDroid conference.

Jacek Ryś

June 13, 2023
Tweet

Other Decks in Programming

Transcript

  1. Hello Jacek Ryś Senior Android Engineer @ MYO Solutions Branches

    Automotive eCommerce Finance Security IoT Logistics
  2. Agenda • • • • • What is Rust? Basic

    Concepts in Rust What about C++? Rust in Android projects Summary
  3. Rust’s greatest ambition is to eliminate the trade-offs that programmers

    have accepted for decades by providing safety and productivity, speed and ergonomics. – Steve Klabnik and Carol Nichols, "The Rust Programming Book" “
  4. What is Rust? • • • • • • •

    • • • • • • • Systems programming language Focus on safety, performance, and concurrency Memory safety without garbage collection Ownership and borrowing system Strong, static type system Supports many platforms x86, ARM, WebAssembly Linux, Mac, Windows Used for wide range of devices firmware and boot loaders smart displays mobile phones desktops servers
  5. From personal project to systems programming revolution Conception and Development

    • • • Graydon Hoare starts personal project Goal: "Create a language that combines C and C++ performance with modern language features" Support from Mozilla Official Release • After several years version 1.0 is released in May 2015 Continuous Improvement • • • Improvements and updates Growth of community Focus on stability, backward compatibility and involvement of the community Growing Popularity and Adoption • • • Increased adoption in various domains Rust used in Polkadot, Mozilla, Dropbox, Discord, Claudflare, Microsoft Developers looking for security, performance and secure concurency find Rust as a solution Rust history 📝 🚀 🔄 📈
  6. Developers seem to love Rust Let's check out the results

    from StackOverflow Surveys from last couple of years
  7. 2015 StackOverflow Developer Survey Most loved languages Most wanted languages

    % of devs who are developing with the language or tech that have expressed interest in continuing to develop with it. % of devs who are not developing with the language or tech but have expressed interest in developing with it. Rust 2015 Edition: estabished with Rust 1.0 in May 2015
  8. Basic concepts • • • • crate trait mod unsafe

    Keywords • • • • • • • • mut: Indicates that a binding or reference is mutable, meaning its value can be changed. dyn: Used to indicate a dynamic (trait object) type. A trait object is a runtime instance of a type implementing a specific trait. mpl: Used for implementing a trait for a specific type or defining inherent methods on a type. move: A keyword used in closures to take ownership of captured variables. pub: Specifies that an item (e.g., function, module, struct, or enum) should be publicly accessible from outside the current module. ref: Used in pattern matching to create a reference to the matched value. Self (capitalized): Refers to the type implementing a trait within the trait definition or implementation block. use: Used to import items (functions, structs, traits, etc.) from other modules or crates into the current scope.
  9. Main tools used for programming in Rust • • •

    • • • rustc - The Compiler cargo - The Package Manager - crates.io rustup - The Installer rust-analyzer - The Code Analyzer Clippy - The Linter rustfmt - The Formatter
  10. Compiler Guarantees • • • • • • • No

    uninitialized variables No accidental memory leaks (leaks on purpose are still possible with use of Box::leak or std::mem:forget) No double-frees No use-after-free No NULL pointers 🎉 No forgotten locked mutexes No data races between threads
  11. Rust vs C++ C++ Rust • use after free" errors

    are still possible despite of smart pointers introduced in C++ 11 • • C++ and C are the "unsafe" languages as they let programmers have full control over howe they manage an app's memory pointers with no restrictions or warnings on basic memory management errors C++ compilers do not provide automatic checks for data races, so bugs may go unnoticed until runtime, potentially leading to production issues or security vulnerabilities. • • • borrow checker ensures that references do not outlive data which they refer to. Such problems are detected at compile time each reference has a lifetime where you can set the scope for which that reference is valid Rust gives you a choice of writing Safe on Unsafe Rust code (the unsafe keyword) • Rust provides compile-time guarantees to prevent data races. "In C, you publish your API if it's possible to use it correctly (open world). In Rust, you publish a safe API if it's impossible to use incorrectly (closed world).” @dtolnay/cxx library is a tool and library for seamless interoperability between Rust and C++. It enables developers to write Rust code that can directly call C++ code and vice versa, without the need for manually writing complex and error-prone FFI (Foreign Function Interface) bindings
  12. Why Rust in Android development? • • • • •

    • Improved memory safety and security Better performance Integration with Existing Java/Kotlin Codebase Interoperability with existing C/C++ code Growing community and ecosystem and more… “In Rust, the compiler plays a gatekeeper role by refusing to compile code with these elusive bugs, including concurrency bugs. By working alongside the compiler, the team can spend their time focusing on the program’s logic rather than chasing down bugs.” – Steve Klabnik and Carol Nichols, "The Rust Programming Book"
  13. Rust - Android project 101 1. 2. 3. 4. 5.

    6. 7. 8. Create Android Project​ Create Rust library Binary crate is a executable project, here we need library to put list of components used elsewhere in the project. Download Android NDK​ Define rust library type in Cargo.toml​ The cdylib crate type will produce a dynamic system library that's suitable for use via FFI from another programming language, in our case - JNI. Define linkers for all android targets You need to do it To tell Rust build system to use Android NDK linkers when building for Android platform. Add Rust code Use Rust based library in Android project Profit
  14. Pros of Rust in Android development • • • •

    • • • • Memory safety guarantees reduce crashes and security vulnerabilities Concurrency support improves performance in multi-core systems Modern syntax and error messages enhance developer experience Growing ecosystem and community Lack of garbage collector predictable performance - no unpredictable pauses that can occur when the GC decides to reclaim memory no overhead of GC - A garbage collector continuously uses CPU cycles to track and deallocate unused memory. avoidance of common GC issues - no memory leaks. In Rust, it's prevented by design
  15. Cons of Rust in Android development • • • •

    Learning curve for developers new to Rust It may be annoying to work with the compiler at first time Smaller ecosystem compared to C++ Knowledge of C++ is not mandadatory but would make it easier to dive into Rust
  16. How to get started with Rust in Android 1. 2.

    3. 4. 5. 6. Learn Rust fundamentals (resources: The Rust Programming Language book, Rust by Example, Rustlings) Set up Rust development environment (Rust toolchain, Cargo) Integrate Rust libraries with JNI/NDK for seamless interoperability Use the 'cargo-ndk' tool for building Rust libraries for Android Explore existing libraries and projects (Android-Rust-NDK, Rust-Android-Gradle) https://google.github.io/comprehensive-rust/
  17. Conclusion Change perspective • • • • • • broadening

    skillset performance improvement memory safety interoperability professional growth community and support