Skip to content

Commit 7aeec79

Browse files
authored
Add GitHub Copilot instructions for Rust (#365)
Add scoped Copilot instruction file that automatically applies Rust coding conventions and best practices when working with .rs files. Based on github/awesome-copilot community instructions covering error handling, API design, ownership patterns, testing, and code style. Fixes: VECTOR-541.
2 parents 9563764 + d4204ed commit 7aeec79

File tree

3 files changed

+149
-0
lines changed

3 files changed

+149
-0
lines changed
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
---
2+
description: 'Rust coding conventions and contribution guidelines for Vector Store'
3+
applyTo: '**/*.rs'
4+
---
5+
6+
When working on Rust code, follow the guidelines defined in:
7+
8+
- [docs/rust_instructions.md](../../docs/rust_instructions.md) — Rust coding conventions and best practices
9+
- [CONTRIBUTING.md](../../CONTRIBUTING.md) — contribution workflow, PR requirements, static checks, and testing

CONTRIBUTING.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,10 @@ After submitting a compliant PR, it will be reviewed by one or more maintainers.
2323
**Current maintainers:**
2424
- Paweł Pery (@ewienik)
2525

26+
## Rust Coding Conventions
27+
28+
For detailed Rust coding conventions and best practices used in this project, see [docs/rust_instructions.md](docs/rust_instructions.md).
29+
2630
## Static Checks
2731

2832
To ensure code quality, we use several static analysis tools. All static checks must pass before merging.

docs/rust_instructions.md

Lines changed: 136 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
1+
# Rust Coding Conventions and Best Practices
2+
3+
Follow idiomatic Rust practices and community standards when writing Rust code.
4+
5+
These instructions are based on [The Rust Book](https://doc.rust-lang.org/book/), [Rust API Guidelines](https://rust-lang.github.io/api-guidelines/), [RFC 430 naming conventions](https://github.com/rust-lang/rfcs/blob/master/text/0430-finalizing-naming-conventions.md), and the broader Rust community at [users.rust-lang.org](https://users.rust-lang.org/).
6+
7+
## General Instructions
8+
9+
- Always prioritize readability, safety, and maintainability.
10+
- Use strong typing and leverage Rust's ownership system for memory safety.
11+
- Break down complex functions into smaller, more manageable functions.
12+
- For algorithm-related code, include explanations of the approach used.
13+
- Write code with good maintainability practices, including comments on why certain design decisions were made.
14+
- Handle errors gracefully using `Result<T, E>` and provide meaningful error messages.
15+
- For external dependencies, mention their usage and purpose in documentation.
16+
- Use consistent naming conventions following [RFC 430](https://github.com/rust-lang/rfcs/blob/master/text/0430-finalizing-naming-conventions.md).
17+
- Write idiomatic, safe, and efficient Rust code that follows the borrow checker's rules.
18+
- Ensure code compiles without warnings.
19+
20+
## Patterns to Follow
21+
22+
- Use modules (`mod`) and public interfaces (`pub`) to encapsulate logic.
23+
- Handle errors properly using `?`, `match`, or `if let`.
24+
- Use `serde` for serialization and `thiserror` or `anyhow` for custom errors.
25+
- Implement traits to abstract services or external dependencies.
26+
- Structure async code using `async/await` and `tokio` or `async-std`.
27+
- Prefer enums over flags and states for type safety.
28+
- Use builders for complex object creation.
29+
- Split binary and library code (`main.rs` vs `lib.rs`) for testability and reuse.
30+
- Use `rayon` for data parallelism and CPU-bound tasks.
31+
- Use iterators instead of index-based loops as they're often faster and safer.
32+
- Use `&str` instead of `String` for function parameters when you don't need ownership.
33+
- Prefer borrowing and zero-copy operations to avoid unnecessary allocations.
34+
35+
### Ownership, Borrowing, and Lifetimes
36+
37+
- Prefer borrowing (`&T`) over cloning unless ownership transfer is necessary.
38+
- Use `&mut T` when you need to modify borrowed data.
39+
- Explicitly annotate lifetimes when the compiler cannot infer them.
40+
- Use `Rc<T>` for single-threaded reference counting and `Arc<T>` for thread-safe reference counting.
41+
- Use `RefCell<T>` for interior mutability in single-threaded contexts and `Mutex<T>` or `RwLock<T>` for multi-threaded contexts.
42+
43+
## Patterns to Avoid
44+
45+
- Don't use `unwrap()` or `expect()` unless absolutely necessary—prefer proper error handling.
46+
- Avoid panics in library code—return `Result` instead.
47+
- Don't rely on global mutable state—use dependency injection or thread-safe containers.
48+
- Avoid deeply nested logic—refactor with functions or combinators.
49+
- Don't ignore warnings—treat them as errors during CI.
50+
- Avoid `unsafe` unless required and fully documented.
51+
- Don't overuse `clone()`, use borrowing instead of cloning unless ownership transfer is needed.
52+
- Avoid premature `collect()`, keep iterators lazy until you actually need the collection.
53+
- Avoid unnecessary allocations—prefer borrowing and zero-copy operations.
54+
55+
## Code Style and Formatting
56+
57+
- Follow the Rust Style Guide and use `rustfmt` for automatic formatting.
58+
- Keep lines under 100 characters when possible.
59+
- Place function and struct documentation immediately before the item using `///`.
60+
- Use `cargo clippy` to catch common mistakes and enforce best practices.
61+
62+
## Error Handling
63+
64+
- Use `Result<T, E>` for recoverable errors and `panic!` only for unrecoverable errors.
65+
- Prefer `?` operator over `unwrap()` or `expect()` for error propagation.
66+
- Create custom error types using `thiserror` or implement `std::error::Error`.
67+
- Use `Option<T>` for values that may or may not exist.
68+
- Provide meaningful error messages and context.
69+
- Error types should be meaningful and well-behaved (implement standard traits).
70+
- Validate function arguments and return appropriate errors for invalid input.
71+
72+
## API Design Guidelines
73+
74+
### Common Traits Implementation
75+
76+
Eagerly implement common traits where appropriate:
77+
78+
- `Copy`, `Clone`, `Eq`, `PartialEq`, `Ord`, `PartialOrd`, `Hash`, `Debug`, `Display`, `Default`
79+
- Use standard conversion traits: `From`, `AsRef`, `AsMut`
80+
- Collections should implement `FromIterator` and `Extend`
81+
- Note: `Send` and `Sync` are auto-implemented by the compiler when safe; avoid manual implementation unless using `unsafe` code
82+
83+
### Type Safety and Predictability
84+
85+
- Use newtypes to provide static distinctions
86+
- Arguments should convey meaning through types; prefer specific types over generic `bool` parameters
87+
- Use `Option<T>` appropriately for truly optional values
88+
- Functions with a clear receiver should be methods
89+
- Only smart pointers should implement `Deref` and `DerefMut`
90+
91+
### Future Proofing
92+
93+
- Use sealed traits to protect against downstream implementations
94+
- Structs should have private fields
95+
- Functions should validate their arguments
96+
- All public types must implement `Debug`
97+
98+
## Testing and Documentation
99+
100+
- Write comprehensive unit tests using `#[cfg(test)]` modules and `#[test]` annotations.
101+
- Use test modules alongside the code they test (`mod tests { ... }`).
102+
- Write integration tests in `tests/` directory with descriptive filenames.
103+
- Write clear and concise comments for each function, struct, enum, and complex logic.
104+
- Ensure functions have descriptive names and include comprehensive documentation.
105+
- Document all public APIs with rustdoc (`///` comments) following the [API Guidelines](https://rust-lang.github.io/api-guidelines/).
106+
- Use `#[doc(hidden)]` to hide implementation details from public documentation.
107+
- Document error conditions, panic scenarios, and safety considerations.
108+
- Examples should use `?` operator, not `unwrap()` or deprecated `try!` macro.
109+
110+
## Project Organization
111+
112+
- Use semantic versioning in `Cargo.toml`.
113+
- Include comprehensive metadata: `description`, `license`, `repository`, `keywords`, `categories`.
114+
- Use feature flags for optional functionality.
115+
- Organize code into modules using `mod.rs` or named files.
116+
- Keep `main.rs` or `lib.rs` minimal - move logic to modules.
117+
118+
## Quality Checklist
119+
120+
Before publishing or reviewing Rust code, ensure:
121+
122+
### Core Requirements
123+
124+
- [ ] **Naming**: Follows RFC 430 naming conventions
125+
- [ ] **Traits**: Implements `Debug`, `Clone`, `PartialEq` where appropriate
126+
- [ ] **Error Handling**: Uses `Result<T, E>` and provides meaningful error types
127+
- [ ] **Documentation**: All public items have rustdoc comments with examples
128+
- [ ] **Testing**: Comprehensive test coverage including edge cases
129+
130+
### Safety and Quality
131+
132+
- [ ] **Safety**: No unnecessary `unsafe` code, proper error handling
133+
- [ ] **Performance**: Efficient use of iterators, minimal allocations
134+
- [ ] **API Design**: Functions are predictable, flexible, and type-safe
135+
- [ ] **Future Proofing**: Private fields in structs, sealed traits where appropriate
136+
- [ ] **Tooling**: Code passes `cargo fmt`, `cargo clippy`, and `cargo test`

0 commit comments

Comments
 (0)