docs/rust/cpp_to_rust_cheat_sheet.md
This document provides a "translation" of C++ concepts and APIs into their Rust equivalents.
The document focuses on things that seem relevant and helpful to Chromium engineers. If you are looking for a more generic C++ to Rust mapping, then try the following resources:
CHECK, DCHECK, DCHECK_EQ, DCHECK_IS_ONCHECK(condition) << "msg" from C++ is spelled
assert!(condition, msg) in Rust - see also
the official documentation of
the assert macro.
There are also
assert_eq
and
assert_ne
macros, but no equivalents of CHECK_GT, CHECK_LE, etc.
DCHECK(condition) << "msg" from C++ is spelled
debug_assert!(condition, msg) in Rust - see also
the official documentation of
the debug_assert macro.
There are also
debug_assert_eq
and
debug_assert_ne
macros, but no equivalents of DCHECK_GT, DCHECK_LE, etc.
#if DCHECK_IS_ON() is spelled as #[cfg(debug_assertions)] - see also
the official documentation of
the cfg attribute.
Note that build/config/BUILD.gn
consistently applies
dcheck_always_on both to C++ and Rust, which means that
debug_assert! is active exactly when DCHECK is active
and should in general behave in a similar way.
NOTREACHED() << "Foo is " << foo from C++ is spelled as panic!("Foo is {foo}") in Rust. Rust panics (triggered via panic!, assert!,
debug_assert!, etc.) are translated into LOG(FATAL) calls and therefore
should result in the same behaviour wrt printing a task trace, crash keys,
communicating the crash to the test harness, etc.
TODO(https://crbug.com/343218479): Static linking of Rust standard library
means that Chromium's custom panic hook is only active in //base component
and not in other binaries.
#if, BUILDFLAG#if BUILDFLAG(IS_MAC) from C++ is spelled
#[cfg(target_os = "macos")] in Rust - see also
the official documentation of
the cfg attribute
and of
the conditions natively understood by the Rust compiler.
Chromium-specific build settings are typically exposed to C++ and Rust
via //build/buildflag_header.gni
which has
documentation comments
that describe how to 1) depend on the
appropriate Rust-specific build config and 2) how to check the build
configuration from an .rs file. For example,
#if BUILDFLAG(CHROMIUM_BRANDING) from C++ is spelled
#[cfg(CHROMIUM_BRANDING)] in Rust.
Note that Rust integration in //build/buildflag_header.gni only supports
boolean configuration values. TODO: Can this be done by
setting (undocumented...) rustenv attribute in rust_static_library and
reading the value using
the env! macro?
LOG(ERROR) << ...LOG(ERROR) << "Foo is " << foo from C++ is spelled as
log::error!("Foo is {foo}") in Rust.
This Rust code depends on
the log crate
which can be used with the following .gn snippet:
deps = [ "//third_party/rust/log/v0_4:lib" ].