skills: add rust_best_practices and bluetooth Migrated from fuchsia, for use in the independent development here. Change-Id: I57eb50f438e5508bacdda467289050806a6a6964 Reviewed-on: https://bluetooth-review.googlesource.com/c/bluetooth/+/4280
diff --git a/.agents/skills/bluetooth/SKILL.md b/.agents/skills/bluetooth/SKILL.md new file mode 100644 index 0000000..a32b4ab --- /dev/null +++ b/.agents/skills/bluetooth/SKILL.md
@@ -0,0 +1,9 @@ +--- +name: Bluetooth +description: Instructions for working with the Bluetooth Core Specification. +--- + +# Bluetooth Core Specification + +Read @resources/bluetooth_core_specification.md for instructions on how to read +the Bluetooth Core Specification.
diff --git a/.agents/skills/bluetooth/resources/bluetooth_core_specification.md b/.agents/skills/bluetooth/resources/bluetooth_core_specification.md new file mode 100644 index 0000000..b0543b0 --- /dev/null +++ b/.agents/skills/bluetooth/resources/bluetooth_core_specification.md
@@ -0,0 +1,76 @@ +# Bluetooth Core Specification Management + +This resource explains how to access, search, and cite the Bluetooth Core +Specification effectively using the dedicated local cache and management tools. + +## The Local Cache Strategy + +Since the official Bluetooth specification is massive and fragmented, we use a +local cache of the seven most critical "Core" chapters. This allows for instant, +reliable searching even for complex data like packet formats and section +numbers. + +### **The Three-File System** + +For every chapter in the core specification, the shared cache contains three +versions: + +1. **`<name>.md` (The Search Index):** Our primary search target. It features + **Markdown tables** and **stitched headers** (e.g., "3.5.1. Pairing + Request") on single lines for perfect `grep_search` results. +2. **`<name>_pretty.html` (The Context View):** A formatted HTML file used for + `view_file`. Use this to see original tables, lists, and diagram references + once you've found the correct section in the `.md` file. +3. **`<name>.html` (The Source):** The raw, minified official HTML from + bluetooth.com. + +### **Section Index** + +We maintain a global **`index.md`** in the specifications directory. + +* **Use this first:** To find which file contains a specific section number or + topic, run `grep_search` on `index.md`. The `index.md` output will contain + the file name and the exact line number (e.g., + `logical-link-control-and-adaptation-protocol-specification.md:1057`), + allowing you to use `view_file` to jump directly to the correct line in the + corresponding `.md` file. + +-------------------------------------------------------------------------------- + +## Management Tooling + +### **Synchronizing the Cache** + +To refresh all core specifications or initialize the cache, run the downloader +directly with Python: +`python3 .agents/skills/bluetooth/scripts/bluetooth_specification_downloader.py` + +*Note: The generated Markdown files, HTML copies, and global `index.md` will be +placed in the source folder at: `.agents/skills/bluetooth/specifications/`* + +This tool automatically: + +* Downloads the latest HTML from official URLs. +* Converts HTML tables into readable Markdown tables. +* Stitches fragmented section numbers into searchable headers. +* Re-generates the `index.md`. + +-------------------------------------------------------------------------------- + +## How to Research and Search + +1. **Start with the Core Specs:** + * Use `grep_search` on `.agents/skills/bluetooth/specifications/index.md` + to find the correct file and line number. + * **Use Case Insensitivity:** The Bluetooth specification uses + inconsistent capitalization. Always use `CaseInsensitive: true` when + searching. + * Once you have the target file name and line number from `index.md`, use + `view_file` to read the exact section in the corresponding `.md` file. +2. **When the topic is outside the Core Specs:** + * Use the `search_web` tool with + `site:bluetooth.com/wp-content/uploads/Files/Specification/HTML/Core-62 + "term"`. +3. **Citing the Specification:** + * Always provide the Volume, Part, and Section (e.g., "Vol 3, Part H, + Section 3.5.1").
diff --git a/.agents/skills/bluetooth/scripts/bluetooth_specification_downloader.py b/.agents/skills/bluetooth/scripts/bluetooth_specification_downloader.py new file mode 100755 index 0000000..d9b0254 --- /dev/null +++ b/.agents/skills/bluetooth/scripts/bluetooth_specification_downloader.py
@@ -0,0 +1,278 @@ +# Copyright 2026 The Pigweed Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may not +# use this file except in compliance with the License. You may obtain a copy of +# the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations under +# the License. + +"""Downloads and formats Bluetooth core specification documents.""" + +import os +import re +import sys +from typing import Optional +from urllib.request import urlopen, Request +from urllib.error import URLError +from urllib.parse import urlparse +from bs4 import BeautifulSoup, Tag + +# Root project directory for specification cache +SPEC_DIR = os.path.join( + os.path.dirname(os.path.dirname(os.path.abspath(__file__))), + "specifications", +) + +# Hardcoded list of official Bluetooth Core Specification URLs +CORE_SPEC_URLS = [ + ( + "https://www.bluetooth.com/wp-content/uploads/Files/Specification/" + "HTML/Core-62/out/en/host-controller-interface/" + "host-controller-interface-functional-specification.html" + ), + ( + "https://www.bluetooth.com/wp-content/uploads/Files/Specification/" + "HTML/Core-62/out/en/host/" + "logical-link-control-and-adaptation-protocol-specification.html" + ), + ( + "https://www.bluetooth.com/wp-content/uploads/Files/Specification/" + "HTML/Core-62/out/en/host/attribute-protocol--att-.html" + ), + ( + "https://www.bluetooth.com/wp-content/uploads/Files/Specification/" + "HTML/Core-62/out/en/host/generic-access-profile.html" + ), + ( + "https://www.bluetooth.com/wp-content/uploads/Files/Specification/" + "HTML/Core-62/out/en/host/generic-attribute-profile--gatt-.html" + ), + ( + "https://www.bluetooth.com/wp-content/uploads/Files/Specification/" + "HTML/Core-62/out/en/host/security-manager-specification.html" + ), + ( + "https://www.bluetooth.com/wp-content/uploads/Files/Specification/" + "HTML/Core-62/out/en/br-edr-controller/" + "link-manager-protocol-specification.html" + ), + ( + "https://www.bluetooth.com/wp-content/uploads/Files/Specification/" + "HTML/Core-62/out/en/low-energy-controller/" + "link-layer-specification.html" + ), +] + + +def fetch_html(url: str) -> Optional[str]: + """Downloads HTML content from the given URL.""" + print(f"Downloading: {url}...") + headers = {'User-Agent': 'Mozilla/5.0'} + try: + req = Request(url, headers=headers) + with urlopen(req, timeout=30) as response: + return response.read().decode('utf-8') + except URLError as e: + print(f"Error downloading {url}: {e}") + return None + + +def extract_metadata_header(soup: BeautifulSoup, url: str) -> str: + """Extracts the document title and formats an initial metadata header.""" + meta_header = f"Source URL: {url}\n" + title_div = soup.find('div', class_='titlepage') + + if title_div: + title_element = title_div.find(class_='title') + raw_title_source = title_element if title_element else title_div + raw_title = raw_title_source.get_text(separator=' ', strip=True) + # Remove internal SIG codenames/revisions like 'vAtlanta r00' + clean_title = re.sub(r'\bv[A-Za-z]+\s+r\d{2,}\b', '', raw_title) + # Clean up any double spaces left behind + clean_title = re.sub(r'\s{2,}', ' ', clean_title).strip() + + meta_header += clean_title + "\n" + meta_header += "=" * max(10, len(clean_title)) + "\n\n" + + return meta_header + + +def stitch_headers(content_root: Tag) -> None: + """Combines section numbers and titles into single Markdown headers.""" + for header in content_root.find_all(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']): + num = header.find("span", class_="formal-number") + title = header.find("span", class_="formal-title") + + if num and title: + # Prefix with Markdown header hashes based on heading level + level = int(header.name[1]) + hashes = "#" * level + stitched = ( + f"{hashes} {num.get_text().strip()}. {title.get_text().strip()}" + ) + header.clear() + header.append(stitched) + + +def convert_table_to_markdown(table: Tag) -> str: + """Converts a BeautifulSoup table element into a Markdown table string.""" + rows = [] + max_cols = 0 + for tr in table.find_all('tr'): + cells = [] + for cell in tr.find_all(['th', 'td']): + # Clean up cell text: remove extra newlines/spaces and escape pipes + text = ( + cell.get_text(separator=' ', strip=True) + .replace('|', '\\|') + .replace('\n', ' ') + ) + cells.append(text) + + max_cols = max(max_cols, len(cells)) + if cells: + rows.append(f"| {' | '.join(cells)} |") + + if not rows: + return "" + + # Create the separator row + if max_cols > 0: + separator = f"|{'---|' * max_cols}" + # Insert after header if possible + if len(rows) > 1: + rows.insert(1, separator) + else: + rows.append(separator) + + return '\n\n' + '\n'.join(rows) + '\n\n' + + +def replace_tables_with_markdown( + content_root: Tag, soup: BeautifulSoup +) -> None: + """Finds all tables in the HTML and replaces them with Markdown text.""" + for table in content_root.find_all('table'): + md_table = convert_table_to_markdown(table) + table.replace_with(soup.new_string(md_table)) + + +def extract_clean_text(meta_header: str, content_root: Tag) -> str: + """Extracts text content and cleans up excessive newlines.""" + text_content = content_root.get_text(separator='\n', strip=True) + # Remove internal SIG codenames/revisions like 'vAtlanta r00' + # (on its own line) + text_content = re.sub(r'(?im)^v[a-z]+\s+r\d{2,}$\n?', '', text_content) + full_text = meta_header + text_content + return re.sub(r'\n{3,}', '\n\n', full_text) + + +def process_spec(url: str) -> None: + """ + Coordinates the process of downloading, parsing, and saving a specification. + """ + sys.setrecursionlimit(10000) + + # Determine filenames + parsed_url = urlparse(url) + page_name = os.path.basename(parsed_url.path).replace('.html', '') + raw_path = os.path.join(SPEC_DIR, f"{page_name}.html") + pretty_path = os.path.join(SPEC_DIR, f"{page_name}_pretty.html") + md_path = os.path.join(SPEC_DIR, f"{page_name}.md") + + # Ensure output directory exists + os.makedirs(SPEC_DIR, exist_ok=True) + + if ( + os.path.exists(md_path) + and os.path.exists(raw_path) + and os.path.exists(pretty_path) + ): + print(f"Skipping cached spec: {page_name}") + return + + html_content = fetch_html(url) + if not html_content: + return + # Save raw HTML + with open(raw_path, 'w', encoding='utf-8') as f: + f.write(html_content) + + soup = BeautifulSoup(html_content, 'html.parser') + + # Save prettified HTML + with open(pretty_path, 'w', encoding='utf-8') as f: + f.write(soup.prettify()) + + meta_header = extract_metadata_header(soup, url) + + main_article = soup.find('article', class_='topic') + content_root = main_article if main_article else soup + + stitch_headers(content_root) + replace_tables_with_markdown(content_root, soup) + text_content = extract_clean_text(meta_header, content_root) + + # Save Markdown + with open(md_path, 'w', encoding='utf-8') as f: + f.write(text_content) + print(f"Generated enhanced Markdown: {md_path}") + + +def generate_index() -> None: + """Scans all .md files and generates a global index.md.""" + print("\nGenerating Section Index...") + index_entries = [] + + # Regex to find lines starting with section numbers (prefixed with hashes) + section_pattern = re.compile(r'^(#+)\s+(\d+(\.\d+)*\.)\s+(.+)$') + + for filename in sorted(os.listdir(SPEC_DIR)): + if filename.endswith(".md") and filename != "index.md": + filepath = os.path.join(SPEC_DIR, filename) + spec_name = "" + + with open(filepath, 'r', encoding='utf-8') as f: + for line_num, line in enumerate(f, 1): + stripped = line.strip() + # The second line is the spec title + if line_num == 2 and not spec_name: + spec_name = stripped + + match = section_pattern.match(stripped) + if match: + section_num = match.group(2) + title = match.group(4) + index_entries.append( + f"| {section_num} | {title} | {spec_name} | " + f"{filename}:{line_num} |" + ) + + index_path = os.path.join(SPEC_DIR, "index.md") + with open(index_path, 'w', encoding='utf-8') as f: + f.write("# Bluetooth Core Specification Index\n\n") + f.write("| Section | Title | Specification | File:Line |\n") + f.write("|---|---|---|---|\n") + + # Remove duplicates while keeping order + seen = set() + for entry in index_entries: + if entry not in seen: + f.write(entry + "\n") + seen.add(entry) + + print(f"Index created: {index_path}") + + +if __name__ == '__main__': + for spec_url in CORE_SPEC_URLS: + process_spec(spec_url) + + generate_index() + print("\nAll core specifications synchronized and indexed successfully.")
diff --git a/.agents/skills/rust_best_practices/SKILL.md b/.agents/skills/rust_best_practices/SKILL.md new file mode 100644 index 0000000..b58f4fd --- /dev/null +++ b/.agents/skills/rust_best_practices/SKILL.md
@@ -0,0 +1,415 @@ +--- +name: rust-best-practices +description: > + Generic best practices, patterns, and style guidelines for writing Rust code + in Fuchsia, incorporating the official Fuchsia Rust Rubric. +--- + +# Rust Best Practices in Fuchsia + +This guide outlines generic best practices, style conventions, and API design +rules for writing Rust code in Fuchsia. It incorporates the official **Fuchsia +Rust Rubric** (from `docs/development/api/rust.md`). For driver-specific +practices, refer to the `rust_driver_best_practices` skill. + +## 1. Naming and Style Conventions + +* **Casing Conforms to Rust Idioms**: Follow standard Rust naming casing. For + example, `CamelCase` for types, `snake_case` for functions and variables, + and `SCREAMING_SNAKE_CASE` for constants. See [C-CASE]. +* **Getter Names Avoid `get_`**: Do not use the `get_` prefix for getter + methods. Use direct field names (e.g., `rect.width()` instead of + `rect.get_width()`). See [C-GETTER]. +* **Ad-Hoc Conversions**: Ad-hoc conversions follow standard prefix/suffix + naming conventions: + * `as_`: Cheap, reference-to-reference conversion (e.g., `as_bytes()`). + * `to_`: Expensive, reference-to-value/owned conversion (e.g., + `to_str()`). + * `into_`: Consuming value-to-value conversion (e.g., `into_vec()`). + * See [C-CONV]. +* **Iterator Methods & Type Names**: Methods on collections that produce + iterators should follow `iter`, `iter_mut`, `into_iter`. Iterator type names + should match the methods that produce them (e.g., `Iter`, `IterMut`, + `IntoIter`). See [C-ITER] and [C-ITER-TY]. +* **Consistent Word Order**: Keep word ordering consistent across APIs (e.g. + `new_connection` and `open_connection`, rather than mixing prefixes and + suffixes). See [C-WORD-ORDER]. +* **Use Statements at Top**: All `use` statements must be grouped together at + the top of the file. Do not place `use` statements inline within functions + or modules. This makes file dependencies clear and easy to find. +* **Avoid Long Namespaces**: Use `use` statements to import symbols so that + you can avoid long namespaced structs or methods in the code. This improves + readability. +* **Descriptive Naming**: Do not use shorthand or abbreviated names for + variables, structs, or functions. Use complete, descriptive words. +* **Avoid `allow_unused`**: Do not leave `#[allow(unused)]` or + `#[allow(dead_code)]` in the final implementation. If a field is + intentionally unused but must be held by a struct (like an async scope to + keep it alive), prefix its name with an underscore (e.g., `_scope`). +* **Clean up AI-Targeted Comments**: Analyze all comments before finalizing + the code. Remove any comments that are targeted at the AI agent itself. +* **Associated vs. Free (Top-Level) Functions**: + * Keep a function as an associated function in the `impl` block if the + type is important to the function's purpose (e.g., constructors + returning `Self` or a `Result`/`Option` of `Self`). + * Prefer associated functions when a free function's name would otherwise + feel redundant by including the type name (e.g., favor + `Thing::does_what()` over a free function named `thing_does_what()`). + * Avoid overly strong preferences for free functions, as too many free + functions create namespace noise. + * Note that in Rust, the privacy boundary is the module (`mod`), not the + type itself. Free functions inside the same module can access private + fields of a struct just as easily as associated functions. +* **Use Constants, Not Magic Values**: Avoid scattering hardcoded numeric + literals throughout the code. Use descriptive `const` definitions at the top + of the file or module for loop counts, timeout limits, array sizes, and + configuration values. + +## 2. Interoperability and Traits + +* **Eagerly Implement Common Traits**: Implement common standard library + traits when appropriate. These include `Copy`, `Clone`, `Eq`, `PartialEq`, + `Ord`, `PartialOrd`, `Hash`, `Debug`, `Display`, and `Default`. See + [C-COMMON-TRAITS]. +* **Standard Conversion Traits**: Prefer using standard conversion traits like + `From`, `AsRef`, and `AsMut` rather than custom methods where possible. + Implementing `From<A> for B` automatically gives you `Into<B> for A`. See + [C-CONV-TRAITS]. +* **Collections and Iterators**: Custom collections should implement + `FromIterator` and `Extend` to interact naturally with standard Rust + iterators and `.collect()`. See [C-COLLECT]. +* **Data Serialization**: Data structures representing external interfaces or + configurations should implement Serde's `Serialize` and `Deserialize` + traits. See [C-SERDE]. +* **Concurrency Safety**: Types should be `Send` and `Sync` where possible. + Ensure your design doesn't inadvertently block these traits unless thread + unsafety is intended. See [C-SEND-SYNC]. +* **Meaningful Error Types**: Error types should be meaningful, well-behaved, + and implement `std::error::Error`. Avoid returning raw strings or generic + error types unless prototyping. See [C-GOOD-ERR]. +* **Binary Number Formatting**: If representing custom binary numbers or bit + flags, provide formatting implementations for `Hex`, `Octal`, and `Binary`. + See [C-NUM-FMT]. +* **Generic I/O Signatures**: Generic reader/writer functions should take + `R: Read` and `W: Write` by value, not by reference, to allow callers to + pass owned readers/writers or standard wrappers. See [C-RW-VALUE]. + +## 3. API and Type Design + +* **Smart Pointers**: Avoid adding inherent methods to smart pointers. All + methods on a smart pointer should be accessed via trait implementations or + associated functions to avoid shadowing methods on the inner type. See + [C-SMART-PTR]. +* **Conversion Location**: Conversions live on the most specific type + involved. See [C-CONV-SPECIFIC]. +* **Clear Receivers**: Functions with a clear primary receiver should be + designed as methods taking `self`, `&self`, or `&mut self`. See [C-METHOD]. +* **No Out-Parameters**: Functions should return their results directly (as + single values, tuples, or structs) rather than using mutable out-parameters. + See [C-NO-OUT]. +* **Unsurprising Operator Overloads**: Overload operators only when the + behavior is completely expected and matches standard conventions (e.g., + overriding `Add` for a custom complex number type). See [C-OVERLOAD]. +* **`Deref` & `DerefMut`**: Implement `Deref` and `DerefMut` ONLY for smart + pointers. Do not use them for inheritance or code reuse. See [C-DEREF]. +* **Constructors**: Constructors should be static, inherent methods (typically + called `new` or `with_...`). See [C-CTOR]. +* **Flexibility and Performance**: + * **Expose Intermediate Results**: Expose intermediate results in your API + where they can prevent duplicate work for callers. See [C-INTERMEDIATE]. + * **Caller Decides Allocation**: Let the caller decide where to copy and + place data (e.g., pass owned arguments or `Cow` rather than cloning + internally). See [C-CALLER-CONTROL]. + * **Generic Parameters**: Minimize assumptions about parameters by using + generics (e.g., `impl AsRef<str>` instead of `&str` if appropriate). See + [C-GENERIC]. + * **Object Safety**: Design traits to be object-safe if they may be useful + as a trait object. See [C-OBJECT]. +* **Type Safety and Encapsulation**: + * **Newtypes for Static Distinction**: Use the newtype pattern to provide + static type distinctions (e.g., `struct UserId(u64)` rather than a plain + `u64`). See [C-NEWTYPE]. + * **Arguments Convey Meaning**: Use custom types or enums for arguments to + convey precise meaning, instead of using boolean flag parameters or + nested `Option` types. See [C-CUSTOM-TYPE]. + * **Sets of Flags**: Use the `bitflags` crate to represent a set of flags, + not enums or raw integers. See [C-BITFLAG]. + * **Builders for Complex Values**: Use the builder pattern to construct + complex values where there are many optional parameters. See + [C-BUILDER]. + * **Sealed Traits**: Use sealed traits if you want to define a trait but + prevent downstream crates from implementing it. See [C-SEALED]. + * **Private Fields**: Struct fields should be private by default to + encapsulate implementation details. See [C-STRUCT-PRIVATE]. + * **Encapsulation**: Use newtypes to encapsulate internal implementation + details of complex types. See [C-NEWTYPE-HIDE]. + * **Derived Bounds**: Do not duplicate derived trait bounds on struct + definitions; place them on the `impl` blocks instead. See + [C-STRUCT-BOUNDS]. + +## 4. Concurrency and Async Patterns + +* **`spawn` vs `spawn_local`**: + * Use `scope.spawn()` as the default when the task implements `Send`. + * Use `scope.spawn_local()` when the task does not implement `Send` (e.g., + it holds non-thread-safe types like `Rc` or `RefCell`). +* **Do Not Detach Tasks**: Never use + `fuchsia_async::Task::spawn(...).detach();`. Detaching tasks is considered + bad style and can lead to resource leaks or silent task failures. Use + `scope.spawn(...);` instead. +* **Mutex Preference**: When a mutex is strictly necessary, prefer using + `fuchsia_sync::Mutex` over `std::sync::Mutex`. + +## 5. Macros + +* **Evocative Input**: The input syntax of a macro should be evocative of the + output it produces. See [C-EVOCATIVE]. +* **Attribute Composition**: Macros should compose well with attributes, + ensuring that doc-comments and other attributes can be attached directly to + generated items. See [C-MACRO-ATTR]. +* **Item Scope**: Item macros should work anywhere that items are allowed + (e.g., in modules, functions). See [C-ANYWHERE]. +* **Visibility**: Item macros should support standard visibility specifiers + (like `pub`, `pub(crate)`). See [C-MACRO-VIS]. +* **Type Flexibility**: Macro type fragments should be flexible and allow for + standard Rust types and lifetime bounds. See [C-MACRO-TY]. + +## 6. Documentation & Rustdoc Guidelines + +* **Crate-Level Docs**: Crate-level documentation must be thorough and include + examples of how to use the crate. See [C-CRATE-DOC]. +* **Item Examples**: All public items should have a rustdoc example + illustrating their usage. See [C-EXAMPLE]. + + > [!NOTE] This guideline is not strictly enforced for targets building on + > Fuchsia until doctests are supported on Fuchsia targets. +* **Ergonomic Examples**: Examples should use the `?` operator, not `try!`, + and not call `unwrap` or `expect`. See [C-QUESTION-MARK]. +* **Function Failure and Safety**: Function docs must clearly document: + + * Error conditions under which the function returns `Err`. + * Panic conditions (under what inputs or states the function will panic). + * Safety considerations (preconditions required for `unsafe` functions). + See [C-FAILURE]. +* **Prose Hyperlinks**: Include hyperlinks to relevant types, methods, and + concepts in rustdoc prose. See [C-LINK]. +* **Hide Implementation Details**: Rustdoc should not show unhelpful internal + implementation details. See [C-HIDDEN]. + +## 7. Safety and Unsafe Code Rules + +* **Error Handling**: Avoid `unwrap()` and `expect()` which can panic the + process. Use `ok_or_else()` or handle errors explicitly. If an error is + truly unrecoverable, provide a context string explaining why it is safe to + panic. +* **Arithmetic**: Always use checked math operations (e.g., `checked_add()`, + `checked_mul()`) on external or untrusted input to prevent overflows. +* **Fuchsia Unsafe Guidelines**: + + > [!IMPORTANT] **Every `unsafe` block must have an accompanying + > justification.** Safety justifications should begin with `// SAFETY: ` and + > explain why the unsafe block is sound. + + * **Format Requirements**: + * Must use `// SAFETY: <why this unsafe operation is sound>` + * Do **NOT** use other formats like `// Safety:`, `// [SAFETY]`, or + lazy placeholders like `// SAFETY: Trust me.` + * **Soundness Explanation**: Explain why the unsafe block is necessary and + why the code inside is sound. If there are safe alternatives that appear + suitable but cannot be used, document why they are not viable (e.g., + performance). + + **Do:** + + ```rust + // SAFETY: The `bytes` returned from our string builder are guaranteed to be + // valid UTF-8. We used to call `from_utf8`, but this caused performance issues + // with large inputs. + let s = unsafe { String::from_utf8_unchecked(bytes) }; + ``` + + **Don't:** + + ```rust + // SAFETY: We shouldn't have to validate `bytes`, and the safe version is slow. + let s = unsafe { String::from_utf8_unchecked(bytes) }; + ``` + + * **Unsafe Traits & Impls**: + + * Unsafe traits must document safety considerations. + * Unsafe trait implementations must be justified using the + `// SAFETY: ` comment pattern. + + * **Always use `unsafe` Blocks in `unsafe` Functions**: + + * `unsafe` functions are not considered unsafe contexts in Fuchsia. + Unsafe operations must always be located inside an explicit `unsafe` + block, even if they are in an `unsafe` function body. + + **Do:** + + ```rust + unsafe fn clear_slice(ptr: *mut i32, len: usize) { + assert!(len.checked_mul(mem::size_of::<i32>()).unwrap() < isize::MAX); + + // SAFETY: + // - The caller has guaranteed that `ptr` points to `len` consecutive, valid + // i32s and that the data behind `ptr` is not simultaneously accessed. + // - We asserted that the total size of the slice is less than isize::MAX. + let slice = unsafe { slice::from_raw_parts_mut(ptr, len) }; + for x in slice.iter_mut() { + *x = 0; + } + } + ``` + +## 8. Dependability and Debuggability + +* **Argument Validation**: Functions validate their arguments and return early + with an error or panic on invalid inputs before corrupting state. See + [C-VALIDATE]. +* **Destructors Never Fail**: Destructors (`Drop` implementations) should + never fail or panic. See [C-DTOR-FAIL]. +* **Non-blocking Destructors**: Destructors that may block the thread must + have non-blocking alternatives. See [C-DTOR-BLOCK]. +* **Public Types Debuggability**: All public types must implement `Debug`. See + [C-DEBUG]. +* **Non-empty Debug Representation**: The `Debug` representation should never + be empty. See [C-DEBUG-NONEMPTY]. + +## 9. Testing Idioms + +* **Test Macro**: Use `#[fuchsia::test]` instead of `#[test]`. It natively + supports async tests and logging out of the box. +* **Ergonomic Testing**: Utilize the `assert_matches` crate for pattern + assertions and `pretty_assertions` for colored diffs on failure. +* **GN Configuration**: Add `with_unit_tests = true` to your `rustc_binary` or + `rustc_library` templates to generate test targets. + +## 10. Framework and Build Rules + +* **Target Edition**: Set `edition = "2024"` for new `BUILD.gn` Rust targets. +* **Deprecated Crates**: Do not use the `fuchsia_zircon` crate. Use the + standard `zx` bindings or relevant crates. +* **Handle Methods**: Do not include `zx::AsHandleRef` to call methods on + handles. It is no longer needed. +* **Lazy Initialization**: Do not use the `lazy_static!` macro. Use + `std::sync::LazyLock` from the standard library instead. + +## 11. Reviewing Changes + +Upon finishing authoring a change to Rust code, you MUST use this skill to +review the change. Verify that: + +- [ ] All `use` statements are grouped at the top of the file. +- [ ] No shorthand or abbreviated names are used for variables or structs. +- [ ] No `#[allow(unused)]` or `#[allow(dead_code)]` attributes remain in the + final code. +- [ ] Comments are targeted at human maintainers, not the AI agent. +- [ ] Constants are used instead of magic values. +- [ ] `spawn` vs `spawn_local` is correctly chosen based on `Send` + requirements. +- [ ] `fuchsia_sync::Mutex` is preferred if a mutex is strictly necessary. +- [ ] `#[fuchsia::test]` is used for tests. +- [ ] `unwrap()` and `expect()` are avoided where possible. +- [ ] **Every `unsafe` block has a `// SAFETY: ` comment** that details + exactly why it is sound and necessary. +- [ ] Unsafe operations within `unsafe` functions are wrapped in an explicit + `unsafe` block. +- [ ] Public types implement `Debug` and getter methods avoid `get_`. +- [ ] Checked math is used on external or untrusted input. + +-------------------------------------------------------------------------------- + +### References to Upstream Rust API Guidelines + +[C-CASE]: https://rust-lang.github.io/api-guidelines/naming.html#c-case +[C-CONV]: https://rust-lang.github.io/api-guidelines/naming.html#c-conv +[C-GETTER]: https://rust-lang.github.io/api-guidelines/naming.html#c-getter +[C-ITER]: https://rust-lang.github.io/api-guidelines/naming.html#c-iter +[C-ITER-TY]: https://rust-lang.github.io/api-guidelines/naming.html#c-iter-ty +[C-WORD-ORDER]: +https://rust-lang.github.io/api-guidelines/naming.html#c-word-order +[C-COMMON-TRAITS]: +https://rust-lang.github.io/api-guidelines/interoperability.html#c-common-traits +[C-CONV-TRAITS]: +https://rust-lang.github.io/api-guidelines/interoperability.html#c-conv-traits +[C-COLLECT]: +https://rust-lang.github.io/api-guidelines/interoperability.html#c-collect +[C-SERDE]: +https://rust-lang.github.io/api-guidelines/interoperability.html#c-serde +[C-SEND-SYNC]: +https://rust-lang.github.io/api-guidelines/interoperability.html#c-send-sync +[C-GOOD-ERR]: +https://rust-lang.github.io/api-guidelines/interoperability.html#c-good-err +[C-NUM-FMT]: +https://rust-lang.github.io/api-guidelines/interoperability.html#c-num-fmt +[C-RW-VALUE]: +https://rust-lang.github.io/api-guidelines/interoperability.html#c-rw-value +[C-SMART-PTR]: +https://rust-lang.github.io/api-guidelines/predictability.html#c-smart-ptr +[C-CONV-SPECIFIC]: +https://rust-lang.github.io/api-guidelines/predictability.html#c-conv-specific +[C-METHOD]: +https://rust-lang.github.io/api-guidelines/predictability.html#c-method +[C-NO-OUT]: +https://rust-lang.github.io/api-guidelines/predictability.html#c-no-out +[C-OVERLOAD]: +https://rust-lang.github.io/api-guidelines/predictability.html#c-overload +[C-DEREF]: +https://rust-lang.github.io/api-guidelines/predictability.html#c-deref +[C-CTOR]: +https://rust-lang.github.io/api-guidelines/predictability.html#c-ctor +[C-INTERMEDIATE]: +https://rust-lang.github.io/api-guidelines/flexibility.html#c-intermediate +[C-CALLER-CONTROL]: +https://rust-lang.github.io/api-guidelines/flexibility.html#c-caller-control +[C-GENERIC]: +https://rust-lang.github.io/api-guidelines/flexibility.html#c-generic +[C-OBJECT]: https://rust-lang.github.io/api-guidelines/flexibility.html#c-object +[C-NEWTYPE]: +https://rust-lang.github.io/api-guidelines/type-safety.html#c-newtype +[C-CUSTOM-TYPE]: +https://rust-lang.github.io/api-guidelines/type-safety.html#c-custom-type +[C-BITFLAG]: +https://rust-lang.github.io/api-guidelines/type-safety.html#c-bitflag +[C-BUILDER]: +https://rust-lang.github.io/api-guidelines/type-safety.html#c-builder +[C-VALIDATE]: +https://rust-lang.github.io/api-guidelines/dependability.html#c-validate +[C-DTOR-FAIL]: +https://rust-lang.github.io/api-guidelines/dependability.html#c-dtor-fail +[C-DTOR-BLOCK]: +https://rust-lang.github.io/api-guidelines/dependability.html#c-dtor-block +[C-DEBUG]: https://rust-lang.github.io/api-guidelines/debuggability.html#c-debug +[C-DEBUG-NONEMPTY]: +https://rust-lang.github.io/api-guidelines/debuggability.html#c-debug-nonempty +[C-SEALED]: +https://rust-lang.github.io/api-guidelines/future-proofing.html#c-sealed +[C-STRUCT-PRIVATE]: +https://rust-lang.github.io/api-guidelines/future-proofing.html#c-struct-private +[C-NEWTYPE-HIDE]: +https://rust-lang.github.io/api-guidelines/future-proofing.html#c-newtype-hide +[C-STRUCT-BOUNDS]: +https://rust-lang.github.io/api-guidelines/future-proofing.html#c-struct-bounds +[C-EVOCATIVE]: +https://rust-lang.github.io/api-guidelines/macros.html#c-evocative +[C-MACRO-ATTR]: +https://rust-lang.github.io/api-guidelines/macros.html#c-macro-attr +[C-ANYWHERE]: https://rust-lang.github.io/api-guidelines/macros.html#c-anywhere +[C-MACRO-VIS]: +https://rust-lang.github.io/api-guidelines/macros.html#c-macro-vis +[C-MACRO-TY]: +https://rust-lang.github.io/api-guidelines/macros.html#c-macro-ty +[C-CRATE-DOC]: +https://rust-lang.github.io/api-guidelines/documentation.html#c-crate-doc +[C-EXAMPLE]: +https://rust-lang.github.io/api-guidelines/documentation.html#c-example +[C-QUESTION-MARK]: +https://rust-lang.github.io/api-guidelines/documentation.html#c-question-mark +[C-FAILURE]: +https://rust-lang.github.io/api-guidelines/documentation.html#c-failure +[C-LINK]: https://rust-lang.github.io/api-guidelines/documentation.html#c-link +[C-HIDDEN]: +https://rust-lang.github.io/api-guidelines/documentation.html#c-hidden