api_guidelines/lib.rs
1//! # API Guidelines
2//!
3//! A comprehensive Rust library providing structured enums and utilities for implementing and referencing the official Rust API Guidelines.
4//!
5//! This crate systematically organizes the [Rust API Guidelines](https://rust-lang.github.io/api-guidelines/) into structured enums, making it easier to:
6//! - Reference specific guidelines in code documentation
7//! - Build linting tools and static analyzers
8//! - Document API design decisions with precise guideline references
9//! - Ensure code quality and consistency across Rust projects
10//! - Generate guideline compliance reports
11//!
12//! ## Author
13//!
14//! This crate is developed and maintained by [slightmeta](https://github.com/slightmeta).
15//!
16//! ## Categories
17//!
18//! The guidelines are organized into the following categories:
19//! - **Naming**: Conventions for naming types, methods, and conversions
20//! - **Interoperability**: Traits, conversions, and standard library integration
21//! - **Predictability**: Consistent behavior and intuitive APIs
22//! - **Flexibility**: Generic programming and trait design
23//! - **Type Safety**: Strong typing and compile-time guarantees
24//! - **Dependability**: Error handling and reliability
25//! - **Debuggability**: Debug implementations and diagnostics
26//! - **Future Proofing**: API evolution and compatibility
27//! - **Necessities**: Licensing and stability requirements
28//! - **Documentation**: Documentation standards and examples
29//! - **Macros**: Macro design and implementation guidelines
30//!
31//! ## Usage
32//!
33//! ```rust
34//! use api_guidelines::{Naming, Interoperability, Predictability};
35//!
36//! // Reference naming conventions
37//! let naming_convention = Naming::C_CASE;
38//! let conversion_guideline = Naming::C_CONV;
39//!
40//! // Reference interoperability guidelines
41//! let common_traits = Interoperability::C_COMMON_TRAITS;
42//! let conversion_traits = Interoperability::C_CONV_TRAITS;
43//!
44//! // Reference predictability guidelines
45//! let smart_ptr_guideline = Predictability::C_SMART_PTR;
46//! let constructor_guideline = Predictability::C_CTOR;
47//! ```
48//!
49//! ## Features
50//!
51//! - **Comprehensive Coverage**: All official Rust API Guidelines are represented
52//! - **Structured Organization**: Guidelines are logically grouped by category
53//! - **Rich Documentation**: Each enum variant includes detailed documentation with examples
54//! - **Easy Integration**: Simple enum-based API for easy reference in code
55//! - **Tooling Support**: Designed to support linting tools and static analysis
56//!
57//! ## Example Use Cases
58//!
59//! - **Linting Tools**: Build custom lints that reference specific guidelines
60//! - **Code Review**: Reference guidelines in code review comments
61//! - **Documentation**: Link to specific guidelines in API documentation
62//! - **Learning**: Study Rust API design patterns systematically
63//!
64//! This crate is based on the official [Rust API Guidelines](https://rust-lang.github.io/api-guidelines/).
65
66#![allow(non_camel_case_types)]
67
68/// Naming conventions and guidelines for Rust APIs
69#[derive(Debug)]
70pub enum Naming {
71 /// In general, Rust tends to use UpperCamelCase for "type-level" constructs (types and traits) and snake_case for "value-level" constructs.
72 ///
73 /// <table>
74 /// <thead>
75 /// <tr>
76 /// <th>Item</th>
77 /// <th>Convention</th>
78 /// </tr>
79 /// </thead>
80 /// <tbody>
81 /// <tr>
82 /// <td><code>Crates</code></td>
83 /// <td><a href="https://github.com/rust-lang/api-guidelines/issues/101">unclear</a></td>
84 /// </tr>
85 /// <tr>
86 /// <td><code>Modules</code></td>
87 /// <td>snake_case</td>
88 /// </tr>
89 /// <tr>
90 /// <td><code>Crates</code></td>
91 /// <td><code>unclear</code></td>
92 /// </tr>
93 /// <tr>
94 /// <td><code>Types</code></td>
95 /// <td><code>UpperCamelCase</code></td>
96 /// </tr>
97 /// <tr>
98 /// <td><code>Traits</code></td>
99 /// <td><code>UpperCamelCase</code></td>
100 /// </tr>
101 /// <tr>
102 /// <td><code>Enum variants</code></td>
103 /// <td><code>UpperCamelCase</code></td>
104 /// </tr>
105 /// <tr>
106 /// <td><code>Functions</code></td>
107 /// <td><code>snake_case</code></td>
108 /// </tr>
109 /// <tr>
110 /// <td><code>Methods</code></td>
111 /// <td><code>snake_case</code></td>
112 /// </tr>
113 /// <tr>
114 /// <td><code>General constructors</code></td>
115 /// <td><code>new or with_more_details</code></td>
116 /// </tr>
117 /// <tr>
118 /// <td><code>Conversion constructors</code></td>
119 /// <td><code>from_some_other_type</code></td>
120 /// </tr>
121 /// <tr>
122 /// <td><code>Macros</code></td>
123 /// <td><code>snake_case!</code></td>
124 /// </tr>
125 /// <tr>
126 /// <td><code>Local variables</code></td>
127 /// <td><code>snake_case</code></td>
128 /// </tr>
129 /// <tr>
130 /// <td><code>Statics</code></td>
131 /// <td><code>SCREAMING_SNAKE_CASE</code></td>
132 /// </tr>
133 /// <tr>
134 /// <td><code>Constants</code></td>
135 /// <td><code>SCREAMING_SNAKE_CASE</code></td>
136 /// </tr>
137 /// <tr>
138 /// <td><code>Type parameters</code></td>
139 /// <td><code>concise UpperCamelCase, usually single uppercase letter: T</code></td>
140 /// </tr>
141 /// <tr>
142 /// <td><code>Lifetimes</code></td>
143 /// <td><code>short lowercase, usually a single letter: 'a, 'de, 'src</code></td>
144 /// </tr>
145 /// <tr>
146 /// <td><code>Features</code></td>
147 /// <td><code><a href="https://github.com/rust-lang/api-guidelines/issues/101">unclear</a> but see <a href="https://rust-lang.github.io/api-guidelines/naming.html#c-feature">C-FEATURE</a></code></td>
148 /// </tr>
149 /// </tbody>
150 /// </table>
151 /// In UpperCamelCase, acronyms and contractions of compound words count as one word: use Uuid rather than UUID, Usize rather than USize or Stdin rather than StdIn. In snake_case, acronyms and contractions are lower-cased: is_xid_start.
152 ///
153 /// In snake_case or SCREAMING_SNAKE_CASE, a "word" should never consist of a single letter unless it is the last "word". So, we have btree_map rather than b_tree_map, but PI_2 rather than PI2.
154 ///
155 /// Crate names should not use -rs or -rust as a suffix or prefix. Every crate is Rust! It serves no purpose to remind users of this constantly.
156 ///
157 /// [ Casing conforms to RFC 430 ](https://rust-lang.github.io/api-guidelines/naming.html)
158 C_CASE,
159 /// Conversions should be provided as methods, with names prefixed as follows:
160 /// <table>
161 /// <thead>
162 /// <tr>
163 /// <th>Prefix</th>
164 /// <th>Cost</th>
165 /// <th>Ownership</th>
166 /// </tr>
167 /// </thead>
168 /// <tbody>
169 /// <tr>
170 /// <td><code>as_</code></td>
171 /// <td><code>Free</code></td>
172 /// <td><code>borrowed -> borrowed</code></td>
173 /// </tr>
174 /// <tr>
175 /// <td><code>to_</code></td>
176 /// <td><code>Expensive</code></td>
177 /// <td><code>borrowed -> borrowed borrowed -> owned (non-Copy types) owned -> owned (Copy types)</code></td>
178 /// </tr>
179 /// <tr>
180 /// <td><code>into_</code></td>
181 /// <td><code>Variable</code></td>
182 /// <td><code>owned -> owned (non-Copy types)</code></td>
183 /// </tr>
184 /// </tbody>
185 /// </table>
186 ///
187 /// For example:
188 ///
189 /// [str::as_bytes()](https://doc.rust-lang.org/std/primitive.str.html#method.as_bytes) gives a view of a str as a slice of UTF-8 bytes, which is free. The input is a borrowed &str and the output is a borrowed &[u8].
190 ///
191 /// [Path::to_str](https://doc.rust-lang.org/std/path/struct.Path.html#method.to_str) performs an expensive UTF-8 check on the bytes of an operating system path. The input and output are both borrowed. It would not be correct to call this as_str because this method has nontrivial cost at runtime.
192 ///
193 /// [str::to_lowercase()](https://doc.rust-lang.org/std/primitive.str.html#method.to_lowercase) produces the Unicode-correct lowercase equivalent of a str, which involves iterating through characters of the string and may require memory allocation. The input is a borrowed &str and the output is an owned String.
194 ///
195 /// [f64::to_radians()](https://doc.rust-lang.org/std/primitive.f64.html#method.to_radians) converts a floating point quantity from degrees to radians. The input is f64. Passing a reference &f64 is not warranted because f64 is cheap to copy. Calling the function into_radians would be misleading because the input is not consumed.
196 ///
197 /// [String::into_bytes()](https://doc.rust-lang.org/std/string/struct.String.html#method.into_bytes) extracts the underlying Vec<u8> of a String, which is free. It takes ownership of a String and returns an owned Vec<u8>.
198 ///
199 /// [BufReader::into_inner()](https://doc.rust-lang.org/std/io/struct.BufReader.html#method.into_inner) takes ownership of a buffered reader and extracts out the underlying reader, which is free. Data in the buffer is discarded.
200 ///
201 /// [BufWriter::into_inner()](https://doc.rust-lang.org/std/io/struct.BufWriter.html#method.into_inner) takes ownership of a buffered writer and extracts out the underlying writer, which requires a potentially expensive flush of any buffered data.
202 ///
203 /// Conversions prefixed as_ and into_ typically decrease abstraction, either exposing a view into the underlying representation (as) or deconstructing data into its underlying representation (into). Conversions prefixed to_, on the other hand, typically stay at the same level of abstraction but do some work to change from one representation to another.
204 ///
205 /// When a type wraps a single value to associate it with higher-level semantics, access to the wrapped value should be provided by an into_inner() method. This applies to wrappers that provide buffering like [ BufReader ](https://doc.rust-lang.org/std/io/struct.BufReader.html#method.into_inner), encoding or decoding like [ GzDecoder ](https://docs.rs/flate2/0.2.19/flate2/read/struct.GzDecoder.html#method.into_inner), atomic access like [ AtomicBool ](https://doc.rust-lang.org/std/sync/atomic/struct.AtomicBool.html#method.into_inner), or any similar semantics.
206 ///
207 /// If the mut qualifier in the name of a conversion method constitutes part of the return type, it should appear as it would appear in the type. For example [Vec::as_mut_slice](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.as_mut_slice) returns a mut slice; it does what it says. This name is preferred over as_slice_mut.
208 /// ```
209 /// // Return type is a mut slice.
210 /// fn as_mut_slice(&mut self) -> &mut [T];
211 /// ```
212 /// More examples from the standard library
213 ///
214 /// + [Result::as_ref](https://doc.rust-lang.org/std/result/enum.Result.html#method.as_ref)
215 /// + [RefCell::as_ptr](https://doc.rust-lang.org/std/cell/struct.RefCell.html#method.as_ptr)
216 /// + [slice::to_vec](https://doc.rust-lang.org/std/primitive.slice.html#method.to_vec)
217 /// + [Option::into_iter](https://doc.rust-lang.org/std/option/enum.Option.html#method.into_iter)
218 ///
219 /// [Ad-hoc conversions follow as_, to_, into_ conventions](https://rust-lang.github.io/api-guidelines/naming.html#ad-hoc-conversions-follow-as_-to_-into_-conventions-c-conv)
220 C_CONV,
221 /// With a few exceptions, the get_ prefix is not used for getters in Rust code.
222 ///
223 /// The get naming is used only when there is a single and obvious thing that could reasonably be gotten by a getter. For example [Cell::get](https://doc.rust-lang.org/std/cell/struct.Cell.html#method.get) accesses the content of a Cell.
224 ///
225 /// For getters that do runtime validation such as bounds checking, consider adding unsafe _unchecked variants. Typically those will have the following signatures.
226 /// ```
227 /// fn get(&self, index: K) -> Option<&V>;
228 /// fn get_mut(&mut self, index: K) -> Option<&mut V>;
229 /// unsafe fn get_unchecked(&self, index: K) -> &V;
230 /// unsafe fn get_unchecked_mut(&mut self, index: K) -> &mut V;
231 /// ```
232 /// The difference between getters and conversions ([C-CONV](https://rust-lang.github.io/api-guidelines/naming.html#c-conv)) can be subtle and is not always clear-cut. For example [TempDir::path](https://docs.rs/tempdir/0.3.5/tempdir/struct.TempDir.html#method.path) can be understood as a getter for the filesystem path of the temporary directory, while [TempDir::into_path](https://docs.rs/tempdir/0.3.5/tempdir/struct.TempDir.html#method.into_path) is a conversion that transfers responsibility for deleting the temporary directory to the caller. Since path is a getter, it would not be correct to call it get_path or as_path.
233 ///
234 /// Examples from the standard library
235 ///
236 /// + [std::io::Cursor::get_mut](https://doc.rust-lang.org/std/io/struct.Cursor.html#method.get_mut)
237 /// + [std::pin::Pin::get_mut](https://doc.rust-lang.org/std/pin/struct.Pin.html#method.get_mut)
238 /// + [std::sync::PoisonError::get_mut](https://doc.rust-lang.org/std/sync/struct.PoisonError.html#method.get_mut)
239 /// + [std::sync::atomic::AtomicBool::get_mut](https://doc.rust-lang.org/std/sync/atomic/struct.AtomicBool.html#method.get_mut)
240 /// + [std::collections::hash_map::OccupiedEntry::get_mut](https://doc.rust-lang.org/std/collections/hash_map/struct.OccupiedEntry.html#method.get_mut)
241 /// + [<\[T\]>::get_unchecked](https://doc.rust-lang.org/std/primitive.slice.html#method.get_unchecked)
242 ///
243 /// [Getter names follow Rust convention (C-GETTER)](https://rust-lang.github.io/api-guidelines/naming.html#getter-names-follow-rust-convention-c-getter)
244 C_GETTER,
245 /// Per [RFC 199](https://github.com/rust-lang/rfcs/blob/master/text/0199-ownership-variants.md).
246 ///
247 /// For a container with elements of type U, iterator methods should be named:
248 /// ```
249 /// fn iter(&self) -> Iter // Iter implements Iterator<Item = &U>
250 /// fn iter_mut(&mut self) -> IterMut // IterMut implements Iterator<Item = &mut U>
251 /// fn into_iter(self) -> IntoIter // IntoIter implements Iterator<Item = U>
252 /// ```
253 /// This guideline applies to data structures that are conceptually homogeneous collections. As a counterexample, the str type is slice of bytes that are guaranteed to be valid UTF-8. This is conceptually more nuanced than a homogeneous collection so rather than providing the iter/iter_mut/into_iter group of iterator methods, it provides [str::bytes](https://doc.rust-lang.org/std/primitive.str.html#method.bytes) to iterate as bytes and [str::chars](https://doc.rust-lang.org/std/primitive.str.html#method.chars) to iterate as chars.
254 ///
255 /// This guideline applies to methods only, not functions. For example [percent_encode](https://docs.rs/url/1.4.0/url/percent_encoding/fn.percent_encode.html) from the url crate returns an iterator over percent-encoded string fragments. There would be no clarity to be had by using an iter/iter_mut/into_iter convention.
256 ///
257 /// Examples from the standard library
258 /// + [Vec::iter](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.iter)
259 /// + [Vec::iter_mut](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.iter_mut)
260 /// + [Vec::into_iter](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.into_iter)
261 /// + [BTreeMap::iter](https://doc.rust-lang.org/std/collections/struct.BTreeMap.html#method.iter)
262 /// + [BTreeMap::iter_mut](https://doc.rust-lang.org/std/collections/struct.BTreeMap.html#method.iter_mut)
263 ///
264 /// [Methods on collections that produce iterators follow iter, iter_mut, into_iter (C-ITER)](https://rust-lang.github.io/api-guidelines/naming.html#methods-on-collections-that-produce-iterators-follow-iter-iter_mut-into_iter-c-iter)
265 C_ITER,
266 /// A method called into_iter() should return a type called IntoIter and similarly for all other methods that return iterators.
267 ///
268 /// This guideline applies chiefly to methods, but often makes sense for functions as well. For example the [percent_encode](https://docs.rs/url/1.4.0/url/percent_encoding/fn.percent_encode.html) function from the url crate returns an iterator type called PercentEncode.
269 ///
270 /// These type names make the most sense when prefixed with their owning module, for example [vec::IntoIter](https://doc.rust-lang.org/std/vec/struct.IntoIter.html).
271 ///
272 /// [Iterator type names match the methods that produce them ](https://rust-lang.github.io/api-guidelines/naming.html#iterator-type-names-match-the-methods-that-produce-them-c-iter-ty)
273 C_ITER_TY,
274 /// Do not include words in the name of a [Cargo feature](http://doc.crates.io/manifest.html#the-features-section) that convey zero meaning, as in use-abc or with-abc. Name the feature abc directly.
275 ///
276 /// [Feature names are free of placeholder words (C-FEATURE)](https://rust-lang.github.io/api-guidelines/naming.html#feature-names-are-free-of-placeholder-words-c-feature)
277 ///
278 C_FEATURE,
279 /// All of these use verb-object-error word order. If we were adding an error to represent an address failing to parse, for consistency we would want to name it in verb-object-error order like ParseAddrError rather than AddrParseError.
280 ///
281 /// The particular choice of word order is not important, but pay attention to consistency within the crate and consistency with similar functionality in the standard library.
282 ///
283 /// [Names use a consistent word order (C-WORD-ORDER)](https://rust-lang.github.io/api-guidelines/naming.html#names-use-a-consistent-word-order-c-word-order)
284 C_WORD_ORDER,
285}
286#[derive(Debug)]
287pub enum Interoperability {
288 /// Rust's trait system does not allow orphans: roughly, every impl must live either in the crate that defines the trait or the implementing type. Consequently, crates that define new types should eagerly implement all applicable, common traits.
289 ///
290 /// [Types eagerly implement common traits (C-COMMON-TRAITS)](https://rust-lang.github.io/api-guidelines/interoperability.html#types-eagerly-implement-common-traits-c-common-traits)
291 C_COMMON_TRAITS,
292 /// The following conversion traits should be implemented where it makes sense: [From](https://doc.rust-lang.org/std/convert/trait.From.html) [TryFrom](https://doc.rust-lang.org/std/convert/trait.TryFrom.html) [AsRef](https://doc.rust-lang.org/std/convert/trait.AsRef.html) [AsMut](https://doc.rust-lang.org/std/convert/trait.AsMut.html)
293 ///
294 /// The following conversion traits should never be implemented: [Into](https://doc.rust-lang.org/std/convert/trait.Into.html) [TryInto](https://doc.rust-lang.org/std/convert/trait.TryInto.html).These traits have a blanket impl based on From and TryFrom. Implement those instead.
295 ///
296 /// Examples from the standard library
297 ///
298 /// From\<u16\> is implemented for u32 because a smaller integer can always be converted to a bigger integer.
299 ///
300 /// From\<u32\> is not implemented for u16 because the conversion may not be possible if the integer is too big.
301 ///
302 /// TryFrom\<u32\> is implemented for u16 and returns an error if the integer is too big to fit in u16.
303 ///
304 /// [From\<Ipv6Addr\>](https://doc.rust-lang.org/std/net/struct.Ipv6Addr.html) is implemented for [IpAddr](https://doc.rust-lang.org/std/net/enum.IpAddr.html), which is a type that can represent both v4 and v6 IP addresses.
305 ///
306 /// [Conversions use the standard traits From, AsRef, AsMut (C-CONV-TRAITS)](https://rust-lang.github.io/api-guidelines/interoperability.html#conversions-use-the-standard-traits-from-asref-asmut-c-conv-traits)
307 ///
308 C_CONV_TRAITS,
309 ///
310 /// [FromIterator](https://doc.rust-lang.org/std/iter/trait.FromIterator.html) and [Extend](https://doc.rust-lang.org/std/iter/trait.Extend.html) enable collections to be used conveniently with the following iterator methods:
311 ///
312 /// [Iterator::collect](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.collect)
313 ///
314 /// [Iterator::partition](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.partition)
315 ///
316 /// [Iterator::unzip](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.unzip)
317 ///
318 /// FromIterator is for creating a new collection containing items from an iterator, and Extend is for adding items from an iterator onto an existing collection.
319 ///
320 /// Examples from the standard library
321 ///
322 /// [Vec<T>](https://doc.rust-lang.org/std/vec/struct.Vec.html) implements both FromIterator<T> and Extend<T>.
323 ///
324 /// [Collections implement FromIterator and Extend (C-COLLECT)](https://rust-lang.github.io/api-guidelines/interoperability.html#collections-implement-fromiterator-and-extend-c-collect)
325 C_COLLECT,
326 /// Types that play the role of a data structure should implement [Serialize](https://docs.serde.rs/serde/trait.Serialize.html) and [Deserialize](https://docs.serde.rs/serde/trait.Deserialize.html).
327 ///
328 /// There is a continuum of types between things that are clearly a data structure and things that are clearly not, with gray area in between. [LinkedHashMap](https://docs.rs/linked-hash-map/0.4.2/linked_hash_map/struct.LinkedHashMap.html) and [ IpAddr ](https://doc.rust-lang.org/std/net/enum.IpAddr.html) are data structures. It would be completely reasonable for somebody to want to read in a LinkedHashMap or IpAddr from a JSON file, or send one over IPC to another process. [ LittleEndian ](https://docs.rs/byteorder/1.0.0/byteorder/enum.LittleEndian.html) is not a data structure. It is a marker used by the byteorder crate to optimize at compile time for bytes in a particular order, and in fact an instance of LittleEndian can never exist at runtime. So these are clear-cut examples; the #rust or #serde IRC channels can help assess more ambiguous cases if necessary.
329 ///
330 /// If a crate does not already depend on Serde for other reasons, it may wish to gate Serde impls behind a Cargo cfg. This way downstream libraries only need to pay the cost of compiling Serde if they need those impls to exist.
331 ///
332 /// [Data structures implement Serde's Serialize, Deserialize (C-SERDE)](https://rust-lang.github.io/api-guidelines/interoperability.html#data-structures-implement-serdes-serialize-deserialize-c-serde)
333 C_SERDE,
334 /// [ Send ](https://doc.rust-lang.org/std/marker/trait.Send.html) and [ Sync ](https://doc.rust-lang.org/std/marker/trait.Sync.html) are automatically implemented when the compiler determines it is appropriate.
335 ///
336 /// In types that manipulate raw pointers, be vigilant that the Send and Sync status of your type accurately reflects its thread safety characteristics. Tests like the following can help catch unintentional regressions in whether the type implements Send or Sync.
337 ///
338 /// ```
339 /// #[test]
340 /// fn test_send() {
341 /// fn assert_send<T: Send>() {}
342 /// assert_send::<MyStrangeType>();
343 /// }
344
345 /// #[test]
346 /// fn test_sync() {
347 /// fn assert_sync<T: Sync>() {}
348 /// assert_sync::<MyStrangeType>();
349 /// }
350 /// ```
351 ///
352 /// [Types are Send and Sync where possible (C-SEND-SYNC)](https://rust-lang.github.io/api-guidelines/interoperability.html#types-are-send-and-sync-where-possible-c-send-sync)
353 C_SEND_SYNC,
354 /// An error type is any type E used in a Result<T, E> returned by any public function of your crate. Error types should always implement the [std::error::Error](https://doc.rust-lang.org/std/error/trait.Error.html) trait which is the mechanism by which error handling libraries like [error-chain](https://docs.rs/error-chain) abstract over different types of errors, and which allows the error to be used as the [source()](https://doc.rust-lang.org/std/error/trait.Error.html#method.source) of another error.
355 ///
356 /// Additionally, error types should implement the [ Send ](https://doc.rust-lang.org/std/marker/trait.Send.html) and [ Sync ](https://doc.rust-lang.org/std/marker/trait.Sync.html) traits. An error that is not Send cannot be returned by a thread run with [thread::spawn](https://doc.rust-lang.org/std/thread/fn.spawn.html). An error that is not Sync cannot be passed across threads using an [Arc](https://doc.rust-lang.org/std/sync/struct.Arc.html). These are common requirements for basic error handling in a multithreaded application.
357 ///
358 /// Send and Sync are also important for being able to package a custom error into an IO error using [std::io::Error::new](https://doc.rust-lang.org/std/io/struct.Error.html#method.new), which requires a trait bound of Error + Send + Sync.
359 ///
360 /// One place to be vigilant about this guideline is in functions that return Error trait objects, for example [reqwest::Error::get_ref](https://docs.rs/reqwest/0.7.2/reqwest/struct.Error.html#method.get_ref). Typically Error + Send + Sync + 'static will be the most useful for callers. The addition of 'static allows the trait object to be used with [Error::downcast_ref](https://doc.rust-lang.org/std/error/trait.Error.html#method.downcast_ref-2).
361 ///
362 /// Never use () as an error type, even where there is no useful additional information for the error to carry.
363 ///
364 /// The error message given by the Display representation of an error type should be lowercase without trailing punctuation, and typically concise.
365 ///
366 /// [Error::description()](https://doc.rust-lang.org/std/error/trait.Error.html#tymethod.description) should not be implemented. It has been deprecated and users should always use Display instead of description() to print the error.
367 ///
368 /// Examples of error messages
369 /// 1. "unexpected end of file"
370 /// 2. "provided string was not `true` or `false`"
371 /// 3. "invalid IP address syntax"
372 /// 4. "second time provided was later than self"
373 /// 5. "invalid UTF-8 sequence of {} bytes from index {}"
374 /// 6. "environment variable was not valid unicode: {:?}"
375 ///
376 /// [Error types are meaningful and well-behaved (C-GOOD-ERR)](https://rust-lang.github.io/api-guidelines/interoperability.html#error-types-are-meaningful-and-well-behaved-c-good-err)
377 C_GOOD_ERR,
378 ///
379 /// [std::fmt::UpperHex](https://doc.rust-lang.org/std/fmt/trait.UpperHex.html)
380 ///
381 /// [std::fmt::LowerHex](https://doc.rust-lang.org/std/fmt/trait.LowerHex.html)
382 ///
383 /// [std::fmt::Octal](https://doc.rust-lang.org/std/fmt/trait.Octal.html)
384 ///
385 /// [std::fmt::Binary](https://doc.rust-lang.org/std/fmt/trait.Binary.html)
386 ///
387 /// These traits control the representation of a type under the {:X}, {:x}, {:o}, and {:b} format specifiers.
388 ///
389 /// [Binary number types provide Hex, Octal, Binary formatting (C-NUM-FMT)](https://rust-lang.github.io/api-guidelines/interoperability.html#binary-number-types-provide-hex-octal-binary-formatting-c-num-fmt)
390 C_NUM_FMT,
391 /// The standard library contains these two impls:
392 /// ```
393 /// impl<'a, R: Read + ?Sized> Read for &'a mut R { /* ... */ }
394
395 /// impl<'a, W: Write + ?Sized> Write for &'a mut W { /* ... */ }
396 /// ```
397 /// That means any function that accepts R: Read or W: Write generic parameters by value can be called with a mut reference if necessary.
398 ///
399 /// In the documentation of such functions, briefly remind users that a mut reference can be passed. New Rust users often struggle with this. They may have opened a file and want to read multiple pieces of data out of it, but the function to read one piece consumes the reader by value, so they are stuck. The solution would be to leverage one of the above impls and pass &mut f instead of f as the reader parameter.
400 ///
401 /// Examples
402 ///
403 /// [flate2::read::GzDecoder::new](https://docs.rs/flate2/0.2/flate2/read/struct.GzDecoder.html#method.new)
404 ///
405 /// [flate2::write::GzEncoder::new](https://docs.rs/flate2/0.2/flate2/write/struct.GzEncoder.html#method.new)
406 ///
407 /// [serde_json::from_reader](https://docs.serde.rs/serde_json/fn.from_reader.html)
408 ///
409 /// [serde_json::to_writer](https://docs.serde.rs/serde_json/fn.to_writer.html)
410 ///
411 /// [Generic reader/writer functions take R: Read and W: Write by value (C-RW-VALUE)](https://rust-lang.github.io/api-guidelines/interoperability.html#generic-readerwriter-functions-take-r-read-and-w-write-by-value-c-rw-value)
412 C_RW_VALUE,
413}
414pub enum Predictability {
415 /// For example, this is why the [Box::into_raw](https://doc.rust-lang.org/std/boxed/struct.Box.html#method.into_raw) function is defined the way it is.
416 ///
417 /// ```
418 /// impl<T> Box<T> where T: ?Sized {
419 /// fn into_raw(b: Box<T>) -> *mut T { /* ... */ }
420 /// }
421 ///let boxed_str: Box<str> = /* ... */;
422 ///let ptr = Box::into_raw(boxed_str);
423 ///}
424 /// ```
425 /// If this were defined as an inherent method instead, it would be confusing at the call site whether the method being called is a method on Box<T> or a method on T.
426 /// ```
427 /// impl<T> Box<T> where T: ?Sized {
428 /// //Do not do this.
429 /// fn into_raw(self) -> *mut T { /* ... */ }
430 /// }
431 /// let boxed_str: Box<str> = /* ... */;
432 /// //This is a method on str accessed through the smart pointer Deref impl.
433 /// boxed_str.chars()
434 /// //This is a method on Box<str>...?
435 /// boxed_str.into_raw()
436 /// ```
437 /// [Smart pointers do not add inherent methods (C-SMART-PTR)](https://rust-lang.github.io/api-guidelines/predictability.html#smart-pointers-do-not-add-inherent-methods-c-smart-ptr)
438 C_SMART_PTR,
439 /// When in doubt, prefer to_/as_/into_ to from_, because they are more ergonomic to use (and can be chained with other methods).
440 ///
441 /// For many conversions between two types, one of the types is clearly more "specific": it provides some additional invariant or interpretation that is not present in the other type. For example, str is more specific than &[u8], since it is a UTF-8 encoded sequence of bytes.
442 ///
443 /// Conversions should live with the more specific of the involved types. Thus, str provides both the [as_bytes](https://doc.rust-lang.org/std/primitive.str.html#method.as_bytes) method and the [from_utf8](https://doc.rust-lang.org/std/str/fn.from_utf8.html) constructor for converting to and from &[u8] values. Besides being intuitive, this convention avoids polluting concrete types like &[u8] with endless conversion methods.
444 ///
445 /// [Conversions live on the most specific type involved (C-CONV-SPECIFIC)](https://rust-lang.github.io/api-guidelines/predictability.html#conversions-live-on-the-most-specific-type-involved-c-conv-specific)
446 C_CONV_SPECIFIC,
447 /// for any operation that is clearly associated with a particular type.
448 ///
449 /// Methods have numerous advantages over functions:
450 /// + They do not need to be imported or qualified to be used: all you need is a value of the appropriate type.
451 /// + Their invocation performs autoborrowing (including mutable borrows).
452 /// + They make it easy to answer the question "what can I do with a value of type T" (especially when using rustdoc).
453 /// + They provide self notation, which is more concise and often more clearly conveys ownership distinctions.
454 ///
455 /// [Functions with a clear receiver are methods (C-METHOD)](https://rust-lang.github.io/api-guidelines/predictability.html#functions-with-a-clear-receiver-are-methods-c-method)
456 ///
457 C_METHOD,
458 /// Prefer
459 /// ```
460 /// fn foo() -> (Bar, Bar)
461 /// ```
462 /// Over
463 /// ```
464 /// fn foo(output: &mut Bar) -> Bar
465 /// ```
466 /// for returning multiple Bar values.
467 ///
468 /// Compound return types like tuples and structs are efficiently compiled and do not require heap allocation. If a function needs to return multiple values, it should do so via one of these types.
469 ///
470 /// The primary exception: sometimes a function is meant to modify data that the caller already owns, for example to re-use a buffer:
471 /// ```
472 /// fn read(&mut self, buf: &mut [u8]) -> io::Result<usize>
473 /// ```
474 /// [Functions do not take out-parameters (C-NO-OUT)](https://rust-lang.github.io/api-guidelines/predictability.html#functions-do-not-take-out-parameters-c-no-out)
475 C_NO_OUT,
476 /// Operators with built in syntax (*, |, and so on) can be provided for a type by implementing the traits in [std::ops](https://doc.rust-lang.org/std/ops/index.html#traits). These operators come with strong expectations: implement Mul only for an operation that bears some resemblance to multiplication (and shares the expected properties, e.g. associativity), and so on for the other traits.
477 ///
478 /// [Operator overloads are unsurprising (C-OVERLOAD)](https://rust-lang.github.io/api-guidelines/predictability.html#operator-overloads-are-unsurprising-c-overload)
479 C_OVERLOAD,
480 /// The Deref traits are used implicitly by the compiler in many circumstances, and interact with method resolution. The relevant rules are designed specifically to accommodate smart pointers, and so the traits should be used only for that purpose.
481 ///
482 /// Examples from the standard library
483 /// + [Box<T>](https://doc.rust-lang.org/std/boxed/struct.Box.html)
484 /// + [String](https://doc.rust-lang.org/std/string/struct.String.html) is a smart pointer to [ str ](https://doc.rust-lang.org/std/primitive.str.html)
485 /// + [Rc<T>](https://doc.rust-lang.org/std/rc/struct.Rc.html)
486 /// + [Arc<T>](https://doc.rust-lang.org/std/sync/struct.Arc.html)
487 /// + [Cow<'a, T>](https://doc.rust-lang.org/std/borrow/enum.Cow.html)
488 ///
489 /// [Only smart pointers implement Deref and DerefMut (C-DEREF)](https://rust-lang.github.io/api-guidelines/predictability.html#only-smart-pointers-implement-deref-and-derefmut-c-deref)
490 C_DEREF,
491 /// In Rust, "constructors" are just a convention. There are a variety of conventions around constructor naming, and the distinctions are often subtle.
492 ///
493 /// A constructor in its most basic form is a new method with no arguments.
494 ///
495 /// Constructors are static (no self) inherent methods for the type that they construct. Combined with the practice of fully importing type names, this convention leads to informative but concise construction:
496 ///
497 /// The name new should generally be used for the primary method of instantiating a type. Sometimes it takes no arguments, as in the examples above. Sometimes it does take arguments, like Box::new which is passed the value to place in the Box.
498 ///
499 /// Some types' constructors, most notably I/O resource types, use distinct naming conventions for their constructors, as in [File::open](https://doc.rust-lang.org/stable/std/fs/struct.File.html#method.open), [Mmap::open](https://docs.rs/memmap/0.5.2/memmap/struct.Mmap.html#method.open), [TcpStream::connect](https://doc.rust-lang.org/stable/std/net/struct.TcpStream.html#method.connect), and [UdpSocket::bind](https://doc.rust-lang.org/stable/std/net/struct.UdpSocket.html#method.bind). In these cases names are chosen as appropriate for the domain.
500 ///
501 /// Often there are multiple ways to construct a type. It's common in these cases for secondary constructors to be suffixed _with_foo, as in [Mmap::open_with_offset](https://docs.rs/memmap/0.5.2/memmap/struct.Mmap.html#method.open_with_offset). If your type has a multiplicity of construction options though, consider the builder pattern ([C-BUILDER](https://rust-lang.github.io/api-guidelines/type-safety.html#c-builder)) instead.
502 ///
503 /// Some constructors are "conversion constructors", methods that create a new type from an existing value of a different type. These typically have names beginning with from_ as in [std::io::Error::from_raw_os_error](https://doc.rust-lang.org/std/io/struct.Error.html#method.from_raw_os_error). Note also though the From trait ([C-CONV-TRAITS](https://rust-lang.github.io/api-guidelines/interoperability.html#c-conv-traits)), which is quite similar. There are three distinctions between a from_-prefixed conversion constructor and a From<T> impl.
504 ///
505 /// + A from_ constructor can be unsafe; a From impl cannot. One example of this is [Box::from_raw](https://doc.rust-lang.org/std/boxed/struct.Box.html#method.from_raw).
506 /// + A from_ constructor can accept additional arguments to disambiguate the meaning of the source data, as in [u64::from_str_radix](https://doc.rust-lang.org/std/primitive.u64.html#method.from_str_radix).
507 /// + A From impl is only appropriate when the source data type is sufficient to determine the encoding of the output data type. When the input is just a bag of bits like in [u64::from_be](https://doc.rust-lang.org/std/primitive.u64.html#method.from_be) or [String::from_utf8](https://doc.rust-lang.org/std/string/struct.String.html#method.from_utf8), the conversion constructor name is able to identify their meaning.
508 ///
509 /// Note that it is common and expected for types to implement both Default and a new constructor. For types that have both, they should have the same behavior. Either one may be implemented in terms of the other.
510 ///
511 /// Examples from the standard library
512 ///
513 /// + [std::io::Error::new](https://doc.rust-lang.org/std/io/struct.Error.html#method.new) is the commonly used constructor for an IO error.
514 /// + [std::io::Error::from_raw_os_error](https://doc.rust-lang.org/std/io/struct.Error.html#method.from_raw_os_error) is a conversion constructor based on an error code received from the operating system.
515 /// + [Box::new](https://doc.rust-lang.org/stable/std/boxed/struct.Box.html#method.new) creates a new container type, taking a single argument.
516 /// + [File::open](https://doc.rust-lang.org/stable/std/fs/struct.File.html#method.open) opens a file resource.
517 /// + [Mmap::open_with_offset](https://docs.rs/memmap/0.5.2/memmap/struct.Mmap.html#method.open_with_offset) opens a memory-mapped file, with additional options.
518 ///
519 /// [Constructors are static, inherent methods (C-CTOR)](https://rust-lang.github.io/api-guidelines/predictability.html#constructors-are-static-inherent-methods-c-ctor)
520 C_CTOR,
521}
522pub enum Flexibility {
523 /// Many functions that answer a question also compute interesting related data. If this data is potentially of interest to the client, consider exposing it in the API.
524 ///
525 /// Examples from the standard library
526 /// + [Vec::binary_search](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.binary_search) does not return a bool of whether the value was found, nor an Option<usize> of the index at which the value was maybe found. Instead it returns information about the index if found, and also the index at which the value would need to be inserted if not found.
527 /// + [String::from_utf8](https://doc.rust-lang.org/std/string/struct.String.html#method.from_utf8) may fail if the input bytes are not UTF-8. In the error case it returns an intermediate result that exposes the byte offset up to which the input was valid UTF-8, as well as handing back ownership of the input bytes.
528 /// + [HashMap::insert](https://doc.rust-lang.org/stable/std/collections/struct.HashMap.html#method.insert) returns an Option<T> that returns the preexisting value for a given key, if any. For cases where the user wants to recover this value having it returned by the insert operation avoids the user having to do a second hash table lookup.
529 ///
530 /// [Functions expose intermediate results to avoid duplicate work (C-INTERMEDIATE)](https://rust-lang.github.io/api-guidelines/flexibility.html#functions-expose-intermediate-results-to-avoid-duplicate-work-c-intermediate)
531 C_INTERMEDIATE,
532 /// If a function requires ownership of an argument, it should take ownership of the argument rather than borrowing and cloning the argument.
533 /// ```
534 /// // Prefer this:
535 /// fn foo(b: Bar) {
536 /// /* use b as owned, directly */
537 /// }
538 /// // Over this:
539 /// fn foo(b: &Bar) {
540 /// let b = b.clone();
541 /// /* use b as owned after cloning */
542 /// }
543 /// ```
544 /// If a function does not require ownership of an argument, it should take a shared or exclusive borrow of the argument rather than taking ownership and dropping the argument.
545 ///
546 /// ```
547 /// // Prefer this:
548 /// fn foo(b: &Bar) {
549 /// /* use b as borrowed */
550 /// }
551 /// // Over this:
552 /// fn foo(b: Bar) {
553 /// /* use b as borrowed, it is implicitly dropped before function returns */
554 /// }
555 /// ```
556 /// The <code>Copy</code> trait should only be used as a bound when absolutely needed, not as a way of signaling that copies should be cheap to make.
557 ///
558 /// [Caller decides where to copy and place data (C-CALLER-CONTROL)](https://rust-lang.github.io/api-guidelines/flexibility.html#caller-decides-where-to-copy-and-place-data-c-caller-control)
559 C_CALLER_CONTROL,
560 /// The fewer assumptions a function makes about its inputs, the more widely usable it becomes.
561 /// ```
562 /// //Prefer
563 /// fn foo<I: IntoIterator<Item = i64>>(iter: I) { /* ... */ }
564 /// //over any of
565 /// fn foo(c: &[i64]) { /* ... */ }
566 /// fn foo(c: &Vec<i64>) { /* ... */ }
567 /// fn foo(c: &SomeOtherCollection<i64>) { /* ... */ }
568 /// ```
569 /// if the function only needs to iterate over the data.
570 ///
571 /// More generally, consider using generics to pinpoint the assumptions a function needs to make about its arguments.
572 ///
573 /// Advantages of generics
574 /// + Reusability. Generic functions can be applied to an open-ended collection of types, while giving a clear contract for the functionality those types must provide.
575
576 /// + Static dispatch and optimization. Each use of a generic function is specialized ("monomorphized") to the particular types implementing the trait bounds, which means that (1) invocations of trait methods are static, direct calls to the implementation and (2) the compiler can inline and otherwise optimize these calls.
577
578 /// + Inline layout. If a struct and enum type is generic over some type parameter T, values of type T will be laid out inline in the struct/enum, without any indirection.
579
580 /// + Inference. Since the type parameters to generic functions can usually be inferred, generic functions can help cut down on verbosity in code where explicit conversions or other method calls would usually be necessary.
581
582 /// + Precise types. Because generics give a name to the specific type implementing a trait, it is possible to be precise about places where that exact type is required or produced. For example, a function
583 /// ```
584 /// fn binary<T: Trait>(x: T, y: T) -> T
585 /// ```
586 /// is guaranteed to consume and produce elements of exactly the same type T; it cannot be invoked with parameters of different types that both implement Trait.
587 ///
588 /// Disadvantages of generics
589 /// + Code size. Specializing generic functions means that the function body is duplicated. The increase in code size must be weighed against the performance benefits of static dispatch.
590 /// + Homogeneous types. This is the other side of the "precise types" coin: if T is a type parameter, it stands for a single actual type. So for example a Vec<T> contains elements of a single concrete type (and, indeed, the vector representation is specialized to lay these out in line). Sometimes heterogeneous collections are useful; see [trait objects](https://rust-lang.github.io/api-guidelines/flexibility.html#c-object).
591 /// + Signature verbosity. Heavy use of generics can make it more difficult to read and understand a function's signature.
592 ///
593 /// Examples from the standard library
594 /// + [std::fs::File::open](https://doc.rust-lang.org/std/fs/struct.File.html#method.open) takes an argument of generic type AsRef<Path>. This allows files to be opened conveniently from a string literal "f.txt", a [ Path ](https://doc.rust-lang.org/std/path/struct.Path.html), an [ OsString ](https://doc.rust-lang.org/std/ffi/struct.OsString.html), and a few other types.
595 ///
596 /// [Functions minimize assumptions about parameters by using generics (C-GENERIC)](https://rust-lang.github.io/api-guidelines/flexibility.html#functions-minimize-assumptions-about-parameters-by-using-generics-c-generic)
597 C_GENERIC,
598 /// Trait objects have some significant limitations: methods invoked through a trait object cannot use generics, and cannot use Self except in receiver position.
599 ///
600 /// It is not possible to use generic methods through trait objects, because trait objects require fixed vtable entries, while generic methods produce an unbounded set of functions and cannot be represented as a single vtable entry, even after monomorphization.
601 ///
602 /// When designing a trait, decide early on whether the trait will be used as an object or as a bound on generics.
603 ///
604 /// If a trait is meant to be used as an object, its methods should take and return trait objects rather than use generics.
605 ///
606 /// A where clause of Self: Sized may be used to exclude specific methods from the trait's object. The following trait is not object-safe due to the generic method.
607 /// ```
608 /// trait MyTrait {
609 /// fn object_safe(&self, i: i32);
610 /// fn not_object_safe<T>(&self, t: T);
611 /// }
612 /// ```
613 /// Adding a requirement of Self: Sized to the generic method excludes it from the trait object and makes the trait object-safe.
614 /// ```
615 /// trait MyTrait {
616 /// fn object_safe(&self, i: i32);
617 /// fn not_object_safe<T>(&self, t: T) where Self: Sized;
618 /// ```
619 /// Advantages of trait objects
620 /// + Heterogeneity. When you need it, you really need it.
621 /// + Code size. Unlike generics, trait objects do not generate specialized (monomorphized) versions of code, which can greatly reduce code size.
622 ///
623 /// Disadvantages of trait objects
624 /// + No generic methods. Trait objects cannot currently provide generic methods.
625 /// + Dynamic dispatch and fat pointers. Trait objects inherently involve indirection and vtable dispatch, which can carry a performance penalty.
626 /// + No Self. Except for the method receiver argument, methods on trait objects cannot use the Self type.
627 ///
628 /// Examples from the standard library
629 /// + The [io::Read](https://doc.rust-lang.org/std/io/trait.Read.html) and [io::Write](https://doc.rust-lang.org/std/io/trait.Write.html) traits are often used as objects.
630 /// + The [Iterator](https://doc.rust-lang.org/std/iter/trait.Iterator.html) trait has several generic methods marked with where Self: Sized to retain the ability to use Iterator as an object.
631 ///
632 /// [Traits are object-safe if they may be useful as a trait object (C-OBJECT)](https://rust-lang.github.io/api-guidelines/flexibility.html#traits-are-object-safe-if-they-may-be-useful-as-a-trait-object-c-object)
633 C_OBJECT,
634}
635pub enum TypeSafety {
636 /// Newtypes can statically distinguish between different interpretations of an underlying type.
637 /// For example, a f64 value might be used to represent a quantity in miles or in kilometers. Using newtypes, we can keep track of the intended interpretation:
638 /// ```
639 /// struct Miles(pub f64);
640 /// struct Kilometers(pub f64);
641 /// impl Miles {
642 /// fn to_kilometers(self) -> Kilometers { /* ... */ }
643 /// }
644 /// impl Kilometers {
645 /// fn to_miles(self) -> Miles { /* ... */ }
646 /// }
647 /// ```
648 /// Once we have separated these two types, we can statically ensure that we do not confuse them. For example, the function
649 ///
650 /// ```
651 /// fn are_we_there_yet(distance_travelled: Miles) -> bool { /* ... */ }
652 /// ```
653 /// cannot accidentally be called with a Kilometers value. The compiler will remind us to perform the conversion, thus averting certain [catastrophic bugs](http://en.wikipedia.org/wiki/Mars_Climate_Orbiter).
654 ///
655 /// [Newtypes provide static distinctions (C-NEWTYPE)](https://rust-lang.github.io/api-guidelines/type-safety.html#newtypes-provide-static-distinctions-c-newtype)
656 C_NEWTYPE,
657 ///
658 /// ```
659 /// // Prefer
660 /// let w = Widget::new(Small, Round)
661 /// // over
662 /// let w = Widget::new(true, false)
663 /// ```
664 /// Core types like bool, u8 and Option have many possible interpretations.
665 ///
666 /// Use a deliberate type (whether enum, struct, or tuple) to convey interpretation and invariants. In the above example, it is not immediately clear what true and false are conveying without looking up the argument names, but Small and Round are more suggestive.
667 ///
668 /// Using custom types makes it easier to expand the options later on, for example by adding an ExtraLarge variant.
669 ///
670 /// See the newtype pattern ([C-NEWTYPE](https://rust-lang.github.io/api-guidelines/type-safety.html#c-newtype)) for a no-cost way to wrap existing types with a distinguished name.
671 ///
672 /// [Arguments convey meaning through types, not bool or Option (C-CUSTOM-TYPE)](https://rust-lang.github.io/api-guidelines/type-safety.html#arguments-convey-meaning-through-types-not-bool-or-option-c-custom-type)
673 C_CUSTOM_TYPE,
674 /// Rust supports enum types with explicitly specified discriminants:
675 /// ```
676 /// enum Color {
677 /// Red = 0xff0000,
678 /// Green = 0x00ff00,
679 /// Blue = 0x0000ff,
680 /// }
681 /// ```
682 /// Custom discriminants are useful when an enum type needs to be serialized to an integer value compatibly with some other system/language. They support "typesafe" APIs: by taking a Color, rather than an integer, a function is guaranteed to get well-formed inputs, even if it later views those inputs as integers.
683 ///
684 /// An enum allows an API to request exactly one choice from among many. Sometimes an API's input is instead the presence or absence of a set of flags. In C code, this is often done by having each flag correspond to a particular bit, allowing a single integer to represent, say, 32 or 64 flags. Rust's [bitflags](https://github.com/bitflags/bitflags) crate provides a typesafe representation of this pattern.
685 /// ```
686 /// use bitflags::bitflags;
687
688 /// bitflags! {
689 /// struct Flags: u32 {
690 /// const FLAG_A = 0b00000001;
691 /// const FLAG_B = 0b00000010;
692 /// const FLAG_C = 0b00000100;
693 /// }
694 /// }
695
696 /// fn f(settings: Flags) {
697 /// if settings.contains(Flags::FLAG_A) {
698 /// println!("doing thing A");
699 /// }
700 /// if settings.contains(Flags::FLAG_B) {
701 /// println!("doing thing B");
702 /// }
703 /// if settings.contains(Flags::FLAG_C) {
704 /// println!("doing thing C");
705 /// }
706 /// }
707
708 /// fn main() {
709 /// f(Flags::FLAG_A | Flags::FLAG_C);
710 /// }
711 /// ```
712 /// [Types for a set of flags are bitflags, not enums (C-BITFLAG)](https://rust-lang.github.io/api-guidelines/type-safety.html#types-for-a-set-of-flags-are-bitflags-not-enums-c-bitflag)
713 C_BITFLAG,
714 /// Some data structures are complicated to construct, due to their construction needing:
715 /// + a large number of inputs
716 /// + compound data (e.g. slices)
717 /// + optional configuration data
718 /// + choice between several flavors
719 ///
720 /// which can easily lead to a large number of distinct constructors with many arguments each.
721 ///
722 /// If T is such a data structure, consider introducing a T builder:
723 /// + Introduce a separate data type TBuilder for incrementally configuring a T value. When possible, choose a better name: e.g. [ Command ](https://doc.rust-lang.org/std/process/struct.Command.html) is the builder for a [child process](https://doc.rust-lang.org/std/process/struct.Child.html), [Url](https://docs.rs/url/1.4.0/url/struct.Url.html) can be created from a [ ParseOptions ](https://docs.rs/url/1.4.0/url/struct.ParseOptions.html).
724 /// + The builder constructor should take as parameters only the data required to make a T.
725 /// + The builder should offer a suite of convenient methods for configuration, including setting up compound inputs (like slices) incrementally. These methods should return self to allow chaining.
726 /// + The builder should provide one or more "terminal" methods for actually building a T.
727 ///
728 /// The builder pattern is especially appropriate when building a T involves side effects, such as spawning a task or launching a process.
729 ///
730 /// In Rust, there are two variants of the builder pattern, differing in the treatment of ownership, as described below.
731 ///
732 /// __Non-consuming builders (preferred)__
733 ///
734 /// In some cases, constructing the final T does not require the builder itself to be consumed. The following variant on std::process::Command is one example
735 ///
736 /// Note that the spawn method, which actually uses the builder configuration to spawn a process, takes the builder by shared reference. This is possible because spawning the process does not require ownership of the configuration data.
737 ///
738 /// Because the terminal spawn method only needs a reference, the configuration methods take and return a mutable borrow of self.
739 ///
740 /// __The benefit__
741 ///
742 /// By using borrows throughout, Command can be used conveniently for both one-liner and more complex constructions:
743 ///
744 /// ```
745 /// // One-liners
746 /// Command::new("/bin/cat").arg("file.txt").spawn();
747
748 /// // Complex configuration
749 /// let mut cmd = Command::new("/bin/ls");
750 /// if size_sorted {
751 /// cmd.arg("-S");
752 /// }
753 /// cmd.arg(".");
754 /// cmd.spawn();
755 /// ```
756 /// Consuming builders
757 ///
758 /// Sometimes builders must transfer ownership when constructing the final type T, meaning that the terminal methods must take self rather than &self.
759 ///
760 /// When the terminal methods of the builder require ownership, there is a basic tradeoff:
761 /// + If the other builder methods take/return a mutable borrow, the complex configuration case will work well, but one-liner configuration becomes impossible.
762 /// + If the other builder methods take/return an owned self, one-liners continue to work well but complex configuration is less convenient.
763 ///
764 /// Under the rubric of making easy things easy and hard things possible, all builder methods for a consuming builder should take and return an owned self. Then client code works as follows:
765 /// ```
766 /// // One-liners
767 /// TaskBuilder::new("my_task").spawn(|| { /* ... */ });
768 /// // Complex configuration
769 /// let mut task = TaskBuilder::new();
770 /// task = task.named("my_task_2"); // must re-assign to retain ownership
771 /// if reroute {
772 /// task = task.stdout(mywriter);
773 /// }
774 /// task.spawn(|| { /* ... */ });
775 /// ```
776 /// One-liners work as before, because ownership is threaded through each of the builder methods until being consumed by spawn. Complex configuration, however, is more verbose: it requires re-assigning the builder at each step.
777 ///
778 /// [Builders enable construction of complex values (C-BUILDER)](https://rust-lang.github.io/api-guidelines/type-safety.html#builders-enable-construction-of-complex-values-c-builder)
779 C_BUILDER,
780}
781pub enum Dependability {
782 /// Rust APIs do not generally follow the [robustness principle](http://en.wikipedia.org/wiki/Robustness_principle): "be conservative in what you send; be liberal in what you accept".
783 ///
784 /// Instead, Rust code should enforce the validity of input whenever practical.
785 ///
786 /// Enforcement can be achieved through the following mechanisms (listed in order of preference).
787 ///
788 /// __Static enforcement__
789 ///
790 /// Choose an argument type that rules out bad inputs.
791 /// ```
792 /// // For example, prefer
793 /// fn foo(a: Ascii) { /* ... */ }
794 /// // over
795 /// fn foo(a: u8) { /* ... */ }
796 /// ```
797 /// where Ascii is a wrapper around u8 that guarantees the highest bit is zero; see newtype patterns ([C-NEWTYPE](https://rust-lang.github.io/api-guidelines/type-safety.html#c-newtype)) for more details on creating typesafe wrappers.
798 ///
799 /// Static enforcement usually comes at little run-time cost: it pushes the costs to the boundaries (e.g. when a u8 is first converted into an Ascii). It also catches bugs early, during compilation, rather than through run-time failures.
800 ///
801 /// On the other hand, some properties are difficult or impossible to express using types.
802 ///
803 /// __Dynamic enforcement__
804 ///
805 /// Validate the input as it is processed (or ahead of time, if necessary). Dynamic checking is often easier to implement than static checking, but has several downsides:
806 /// + Runtime overhead (unless checking can be done as part of processing the input).
807 /// + Delayed detection of bugs.
808 /// + Introduces failure cases, either via panic! or Result/Option types, which must then be dealt with by client code.
809 ///
810 /// __Dynamic enforcement with debug_assert!__
811 ///
812 /// Same as dynamic enforcement, but with the possibility of easily turning off expensive checks for production builds.
813 ///
814 /// __Dynamic enforcement with opt-out__
815 ///
816 /// Same as dynamic enforcement, but adds sibling functions that opt out of the checking.
817 ///
818 /// The convention is to mark these opt-out functions with a suffix like _unchecked or by placing them in a raw submodule.
819 ///
820 /// The unchecked functions can be used judiciously in cases where (1) performance dictates avoiding checks and (2) the client is otherwise confident that the inputs are valid.
821 ///
822 /// [Functions validate their arguments (C-VALIDATE)](https://rust-lang.github.io/api-guidelines/dependability.html#functions-validate-their-arguments-c-validate)
823 C_VALIDATE,
824 /// Destructors are executed while panicking, and in that context a failing destructor causes the program to abort.
825 ///
826 /// Instead of failing in a destructor, provide a separate method for checking for clean teardown, e.g. a close method, that returns a Result to signal problems. If that close method is not called, the Drop implementation should do the teardown and ignore or log/trace any errors it produces.
827 ///
828 /// [Destructors never fail (C-DTOR-FAIL)](https://rust-lang.github.io/api-guidelines/dependability.html#destructors-never-fail-c-dtor-fail)
829 C_DTOR_FAIL,
830 /// Similarly, destructors should not invoke blocking operations, which can make debugging much more difficult. Again, consider providing a separate method for preparing for an infallible, nonblocking teardown.
831 ///
832 /// [Destructors that may block have alternatives (C-DTOR-BLOCK)](https://rust-lang.github.io/api-guidelines/dependability.html#destructors-that-may-block-have-alternatives-c-dtor-block)
833 C_DTOR_BLOCK,
834}
835pub enum Debuggability {
836 /// If there are exceptions, they are rare.
837 ///
838 /// [All public types implement Debug (C-DEBUG)](https://rust-lang.github.io/api-guidelines/debuggability.html#all-public-types-implement-debug-c-debug)
839 C_DEBUG,
840 /// Even for conceptually empty values, the Debug representation should never be empty.
841 /// ```
842 /// let empty_str = "";
843 /// assert_eq!(format!("{:?}", empty_str), "\"\"");
844
845 /// let empty_vec = Vec::<bool>::new();
846 /// assert_eq!(format!("{:?}", empty_vec), "[]");
847 /// ```
848 /// [Debug representation is never empty (C-DEBUG-NONEMPTY)](https://rust-lang.github.io/api-guidelines/debuggability.html#debug-representation-is-never-empty-c-debug-nonempty)
849 C_DEBUG_NONEMPTY,
850}
851pub enum FutureProofing {
852 /// Some traits are only meant to be implemented within the crate that defines them. In such cases, we can retain the ability to make changes to the trait in a non-breaking way by using the sealed trait pattern.
853 /// ```
854 /// /// This trait is sealed and cannot be implemented for types outside this crate.
855 /// pub trait TheTrait: private::Sealed {
856 /// // Zero or more methods that the user is allowed to call.
857 /// fn ...();
858 /// // Zero or more private methods, not allowed for user to call.
859 /// #[doc(hidden)]
860 /// fn ...();
861 /// }
862 /// // Implement for some types.
863 /// impl TheTrait for usize {
864 /// /* ... */
865 /// }
866 /// mod private {
867 /// pub trait Sealed {}
868 /// // Implement for those same types, but no others.
869 /// impl Sealed for usize {}
870 /// }
871 /// ```
872 /// The empty private Sealed supertrait cannot be named by downstream crates, so we are guaranteed that implementations of Sealed (and therefore TheTrait) only exist in the current crate. We are free to add methods to TheTrait in a non-breaking release even though that would ordinarily be a breaking change for traits that are not sealed. Also we are free to change the signature of methods that are not publicly documented.
873 ///
874 /// Note that removing a public method or changing the signature of a public method in a sealed trait are still breaking changes.
875 ///
876 /// To avoid frustrated users trying to implement the trait, it should be documented in rustdoc that the trait is sealed and not meant to be implemented outside of the current crate.
877 ///
878 /// __Examples__
879 /// + [serde_json::value::Index](https://docs.serde.rs/serde_json/value/trait.Index.html)
880 /// + [byteorder::ByteOrder](https://docs.rs/byteorder/1.1.0/byteorder/trait.ByteOrder.html)
881 ///
882 /// [Sealed traits protect against downstream implementations (C-SEALED)](https://rust-lang.github.io/api-guidelines/future-proofing.html#sealed-traits-protect-against-downstream-implementations-c-sealed)
883 C_SEALED,
884 /// Making a field public is a strong commitment: it pins down a representation choice, and prevents the type from providing any validation or maintaining any invariants on the contents of the field, since clients can mutate it arbitrarily.
885 ///
886 /// Public fields are most appropriate for struct types in the C spirit: compound, passive data structures. Otherwise, consider providing getter/setter methods and hiding fields instead.
887 ///
888 /// [Structs have private fields (C-STRUCT-PRIVATE)](https://rust-lang.github.io/api-guidelines/future-proofing.html#structs-have-private-fields-c-struct-private)
889 C_STRUCT_PRIVATE,
890 /// A newtype can be used to hide representation details while making precise promises to the client.
891 ///
892 /// For example, consider a function my_transform that returns a compound iterator type.
893 /// ```
894 /// use std::iter::{Enumerate, Skip};
895 /// pub fn my_transform<I: Iterator>(input: I) -> Enumerate<Skip<I>> {
896 /// input.skip(3).enumerate()
897 ///}
898 /// ```
899 /// We wish to hide this type from the client, so that the client's view of the return type is roughly Iterator<Item = (usize, T)>. We can do so using the newtype pattern:
900 /// ```
901 /// use std::iter::{Enumerate, Skip};
902 /// pub struct MyTransformResult<I>(Enumerate<Skip<I>>);
903 /// impl<I: Iterator> Iterator for MyTransformResult<I> {
904 /// type Item = (usize, I::Item);
905 /// fn next(&mut self) -> Option<Self::Item> {
906 /// self.0.next()
907 /// }
908 /// }
909 /// pub fn my_transform<I: Iterator>(input: I) -> MyTransformResult<I> {
910 /// MyTransformResult(input.skip(3).enumerate())
911 /// }
912 /// ```
913 /// Aside from simplifying the signature, this use of newtypes allows us to promise less to the client. The client does not know how the result iterator is constructed or represented, which means the representation can change in the future without breaking client code.
914 ///
915 /// Rust 1.26 also introduces the [impl Trait](https://github.com/rust-lang/rfcs/blob/master/text/1522-conservative-impl-trait.md) feature, which is more concise than the newtype pattern but with some additional trade offs, namely with impl Trait you are limited in what you can express. For example, returning an iterator that impls Debug or Clone or some combination of the other iterator extension traits can be problematic. In summary impl Trait as a return type is probably great for internal APIs and may even be appropriate for public APIs, but probably not in all cases. See the "[impl Trait for returning complex types with ease](https://rust-lang.github.io/edition-guide/rust-2018/trait-system/impl-trait-for-returning-complex-types-with-ease.html)" section of the Edition Guide for more details.
916 /// ```
917 /// pub fn my_transform<I: Iterator>(input: I) -> impl Iterator<Item = (usize, I::Item)> {
918 /// input.skip(3).enumerate()
919 ///}
920 /// ```
921 /// [Newtypes encapsulate implementation details (C-NEWTYPE-HIDE)](https://rust-lang.github.io/api-guidelines/future-proofing.html#newtypes-encapsulate-implementation-details-c-newtype-hide)
922 C_NEWTYPE_HIDE,
923 /// Generic data structures should not use trait bounds that can be derived or do not otherwise add semantic value. Each trait in the derive attribute will be expanded into a separate impl block that only applies to generic arguments that implement that trait.
924 /// ```
925 /// // Prefer this:
926 /// #[derive(Clone, Debug, PartialEq)]
927 /// struct Good<T> { /* ... */ }
928 /// // Over this:
929 /// #[derive(Clone, Debug, PartialEq)]
930 /// struct Bad<T: Clone + Debug + PartialEq> { /* ... */ }
931 /// ```
932 /// Duplicating derived traits as bounds on Bad is unnecessary and a backwards-compatibiliity hazard. To illustrate this point, consider deriving PartialOrd on the structures in the previous example:
933 /// ```
934 /// // Non-breaking change:
935 /// #[derive(Clone, Debug, PartialEq, PartialOrd)]
936 /// struct Good<T> { /* ... */ }
937
938 /// // Breaking change:
939 /// #[derive(Clone, Debug, PartialEq, PartialOrd)]
940 /// struct Bad<T: Clone + Debug + PartialEq + PartialOrd> { /* ... */ }
941 /// ```
942 /// Generally speaking, adding a trait bound to a data structure is a breaking change because every consumer of that structure will need to start satisfying the additional bound. Deriving more traits from the standard library using the derive attribute is not a breaking change.
943 ///
944 /// The following traits should never be used in bounds on data structures:
945 /// + Clone
946 /// + PartialEq
947 /// + PartialOrd
948 /// + Debug
949 /// + Display
950 /// + Default
951 /// + Error
952 /// + Serialize
953 /// + Deserialize
954 /// + DeserializeOwned
955 ///
956 /// There is a grey area around other non-derivable trait bounds that are not strictly required by the structure definition, like Read or Write. They may communicate the intended behavior of the type better in its definition but also limits future extensibility. Including semantically useful trait bounds on data structures is still less problematic than including derivable traits as bounds.
957 ///
958 /// __Exceptions__
959 ///
960 /// There are three exceptions where trait bounds on structures are required:
961 /// + The data structure refers to an associated type on the trait.
962 /// + The bound is ?Sized.
963 /// + The data structure has a Drop impl that requires trait bounds. Rust currently requires all trait bounds on the Drop impl are also present on the data structure.
964 ///
965 /// __Examples from the standard library__
966 /// + [std::borrow::Cow](https://doc.rust-lang.org/std/borrow/enum.Cow.html) refers to an associated type on the Borrow trait.
967 /// + [std::boxed::Box](https://doc.rust-lang.org/std/boxed/struct.Box.html) opts out of the implicit Sized bound.
968 /// + [std::io::BufWriter](https://doc.rust-lang.org/std/io/struct.BufWriter.html) requires a trait bound in its Drop impl.
969 ///
970 /// [Data structures do not duplicate derived trait bounds (C-STRUCT-BOUNDS)]()
971 C_STRUCT_BOUNDS,
972}
973pub enum Necessities {
974 /// A crate cannot be stable (>=1.0.0) without all of its public dependencies being stable.
975 ///
976 /// Public dependencies are crates from which types are used in the public API of the current crate.
977 /// ```
978 /// pub fn do_my_thing(arg: other_crate::TheirThing) { /* ... */ }
979 /// ```
980 /// A crate containing this function cannot be stable unless other_crate is also stable.
981 ///
982 /// Be careful because public dependencies can sneak in at unexpected places.
983 ///
984 /// [Public dependencies of a stable crate are stable (C-STABLE)](https://rust-lang.github.io/api-guidelines/necessities.html#public-dependencies-of-a-stable-crate-are-stable-c-stable)
985 C_STABLE,
986 /// The software produced by the Rust project is dual-licensed, under either the [MIT](https://github.com/rust-lang/rust/blob/master/LICENSE-MIT) or [Apache 2.0](https://github.com/rust-lang/rust/blob/master/LICENSE-APACHE) licenses. Crates that simply need the maximum compatibility with the Rust ecosystem are recommended to do the same, in the manner described herein. Other options are described below.
987 ///
988 /// These API guidelines do not provide a detailed explanation of Rust's license, but there is a small amount said in the [Rust FAQ](https://github.com/dtolnay/rust-faq#why-a-dual-mitasl2-license). These guidelines are concerned with matters of interoperability with Rust, and are not comprehensive over licensing options.
989 ///
990 /// To apply the Rust license to your project, define the license field in your Cargo.toml as:
991 /// ```
992 /// [package]
993 /// name = "..."
994 /// version = "..."
995 /// authors = ["..."]
996 /// license = "MIT OR Apache-2.0"
997 /// ```
998 /// Then add the files LICENSE-APACHE and LICENSE-MIT in the repository root, containing the text of the licenses (which you can obtain, for instance, from choosealicense.com, for Apache-2.0 and MIT).
999 ///
1000 /// Besides the dual MIT/Apache-2.0 license, another common licensing approach used by Rust crate authors is to apply a single permissive license such as MIT or BSD. This license scheme is also entirely compatible with Rust's, because it imposes the minimal restrictions of Rust's MIT license.
1001 ///
1002 /// Crates that desire perfect license compatibility with Rust are not recommended to choose only the Apache license. The Apache license, though it is a permissive license, imposes restrictions beyond the MIT and BSD licenses that can discourage or prevent their use in some scenarios, so Apache-only software cannot be used in some situations where most of the Rust runtime stack can.
1003 ///
1004 /// The license of a crate's dependencies can affect the restrictions on distribution of the crate itself, so a permissively-licensed crate should generally only depend on permissively-licensed crates.
1005 ///
1006 /// [Crate and its dependencies have a permissive license (C-PERMISSIVE)](https://rust-lang.github.io/api-guidelines/necessities.html#crate-and-its-dependencies-have-a-permissive-license-c-permissive)
1007 C_PERMISSIVE,
1008}
1009pub enum Documentation {
1010 /// See [RFC 1687](https://github.com/rust-lang/rfcs/pull/1687).
1011 ///
1012 /// [Crate level docs are thorough and include examples (C-CRATE-DOC)](https://rust-lang.github.io/api-guidelines/documentation.html#crate-level-docs-are-thorough-and-include-examples-c-crate-doc)
1013 C_CRATE_DOC,
1014 /// Every public module, trait, struct, enum, function, method, macro, and type definition should have an example that exercises the functionality.
1015 ///
1016 /// This guideline should be applied within reason.
1017 ///
1018 /// A link to an applicable example on another item may be sufficient. For example if exactly one function uses a particular type, it may be appropriate to write a single example on either the function or the type and link to it from the other.
1019 ///
1020 /// The purpose of an example is not always to show how to use the item. Readers can be expected to understand how to invoke functions, match on enums, and other fundamental tasks. Rather, an example is often intended to show why someone would want to use the item.
1021 /// ```
1022 /// // This would be a poor example of using clone(). It mechanically shows *how* to
1023 /// // call clone(), but does nothing to show *why* somebody would want this.
1024 /// fn main() {
1025 /// let hello = "hello";
1026 /// hello.clone();
1027 /// }
1028 /// ```
1029 /// [All items have a rustdoc example (C-EXAMPLE)](https://rust-lang.github.io/api-guidelines/documentation.html#all-items-have-a-rustdoc-example-c-example)
1030 C_EXAMPLE,
1031 /// Like it or not, example code is often copied verbatim by users. Unwrapping an error should be a conscious decision that the user needs to make.
1032 ///
1033 /// A common way of structuring fallible example code is the following. The lines beginning with # are compiled by cargo test when building the example but will not appear in user-visible rustdoc.
1034 ///
1035 /// ```
1036 //// ```rust
1037 /// /// # use std::error::Error;
1038 /// /// #
1039 /// /// # fn main() -> Result<(), Box<dyn Error>> {
1040 /// /// your;
1041 /// /// example?;
1042 /// /// code;
1043 /// /// #
1044 /// /// # Ok(())
1045 /// /// # }
1046 /// ```
1047 /// [Examples use ?, not try!, not unwrap (C-QUESTION-MARK)](https://rust-lang.github.io/api-guidelines/documentation.html#examples-use--not-try-not-unwrap-c-question-mark)
1048 C_QUESTION_MARK,
1049 /// Error conditions should be documented in an "Errors" section. This applies to trait methods as well -- trait methods for which the implementation is allowed or expected to return an error should be documented with an "Errors" section.
1050 ///
1051 /// For example in the standard library, Some implementations of the [std::io::Read::read](https://doc.rust-lang.org/std/io/trait.Read.html#tymethod.read) trait method may return an error.
1052 /// ```
1053 /// /// Pull some bytes from this source into the specified buffer, returning
1054 /// /// how many bytes were read.
1055 /// ///
1056 /// /// ... lots more info ...
1057 /// ///
1058 /// /// # Errors
1059 /// ///
1060 /// /// If this function encounters any form of I/O or other error, an error
1061 /// /// variant will be returned. If an error is returned then it must be
1062 /// /// guaranteed that no bytes were read.
1063 /// ```
1064 /// Panic conditions should be documented in a "Panics" section. This applies to trait methods as well -- traits methods for which the implementation is allowed or expected to panic should be documented with a "Panics" section.
1065 ///
1066 /// In the standard library the [Vec::insert](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.insert) method may panic.
1067 /// ```
1068 /// /// Inserts an element at position `index` within the vector, shifting all
1069 /// /// elements after it to the right.
1070 /// ///
1071 /// /// # Panics
1072 /// ///
1073 /// /// Panics if `index` is out of bounds.
1074 /// ```
1075 /// It is not necessary to document all conceivable panic cases, especially if the panic occurs in logic provided by the caller. For example documenting the Display panic in the following code seems excessive. But when in doubt, err on the side of documenting more panic cases.
1076 ///
1077 /// ```
1078 /// /// # Panics
1079 /// ///
1080 /// /// This function panics if `T`'s implementation of `Display` panics.
1081 /// pub fn print<T: Display>(t: T) {
1082 /// println!("{}", t.to_string());
1083 /// }
1084 /// ```
1085 ///
1086 /// Unsafe functions should be documented with a "Safety" section that explains all invariants that the caller is responsible for upholding to use the function correctly.
1087 ///
1088 /// The unsafe [std::ptr::read](https://doc.rust-lang.org/std/ptr/fn.read.html) requires the following of the caller.
1089 /// ```
1090 /// /// Reads the value from `src` without moving it. This leaves the
1091 /// /// memory in `src` unchanged.
1092 /// ///
1093 /// /// # Safety
1094 /// ///
1095 /// /// Beyond accepting a raw pointer, this is unsafe because it semantically
1096 /// /// moves the value out of `src` without preventing further usage of `src`.
1097 /// /// If `T` is not `Copy`, then care must be taken to ensure that the value at
1098 /// /// `src` is not used before the data is overwritten again (e.g. with `write`,
1099 /// /// `zero_memory`, or `copy_memory`). Note that `*src = foo` counts as a use
1100 /// /// because it will attempt to drop the value previously at `*src`.
1101 /// ///
1102 /// /// The pointer must be aligned; use `read_unaligned` if that is not the case.
1103 /// ```
1104 /// [Function docs include error, panic, and safety considerations (C-FAILURE)](https://rust-lang.github.io/api-guidelines/documentation.html#function-docs-include-error-panic-and-safety-considerations-c-failure)
1105 C_FAILURE,
1106 /// Regular links can be added inline with the usual markdown syntax of [text](url). Links to other types can be added by marking them with [`text`], then adding the link target in a new line at the end of the docstring with [`text`]: <target>, where <target> is described below.
1107 ///
1108 /// Link targets to methods within the same type usually look like this:
1109 /// ```
1110 /// [`serialize_struct`]: #method.serialize_struct
1111 /// ```
1112 /// Link targets to other types usually look like this:
1113 /// ```
1114 /// [`Deserialize`]: trait.Deserialize.html
1115 /// ```
1116 /// Link targets may also point to a parent or child module:
1117 /// ```
1118 /// [`Value`]: ../enum.Value.html
1119 /// [`DeserializeOwned`]: de/trait.DeserializeOwned.html
1120 /// ```
1121 /// This guideline is officially recommended by RFC 1574 under the heading "[Link all the things](https://github.com/rust-lang/rfcs/blob/master/text/1574-more-api-documentation-conventions.md#link-all-the-things)".
1122 ///
1123 /// [Prose contains hyperlinks to relevant things (C-LINK)](https://rust-lang.github.io/api-guidelines/documentation.html#prose-contains-hyperlinks-to-relevant-things-c-link)
1124 C_LINK,
1125 /// The [package] section of Cargo.toml should include the following values:
1126 /// + authors
1127 /// + description
1128 /// + license
1129 /// + repository
1130 /// + keywords
1131 /// + categories
1132 ///
1133 /// In addition, there are two optional metadata fields:
1134 /// + documentation
1135 /// + homepage
1136 ///
1137 /// By default, crates.io links to documentation for the crate on [docs.rs](https://docs.rs/). The documentation metadata only needs to be set if the documentation is hosted somewhere other than docs.rs, for example because the crate links against a shared library that is not available in the build environment of docs.rs.
1138 ///
1139 /// The homepage metadata should only be set if there is a unique website for the crate other than the source repository or API documentation. Do not make homepage redundant with either the documentation or repository values. For example, serde sets homepage to https://serde.rs, a dedicated website.
1140 ///
1141 /// [Cargo.toml includes all common metadata (C-METADATA)](https://rust-lang.github.io/api-guidelines/documentation.html#cargotoml-includes-all-common-metadata-c-metadata)
1142 C_METADATA,
1143 /// Users of the crate can read the release notes to find a summary of what changed in each published release of the crate. A link to the release notes, or the notes themselves, should be included in the crate-level documentation and/or the repository linked in Cargo.toml.
1144 ///
1145 /// Breaking changes (as defined in [RFC 1105](https://github.com/rust-lang/rfcs/blob/master/text/1105-api-evolution.md)) should be clearly identified in the release notes.
1146 ///
1147 /// If using Git to track the source of a crate, every release published to crates.io should have a corresponding tag identifying the commit that was published. A similar process should be used for non-Git VCS tools as well.
1148 /// ```
1149 /// # Tag the current commit
1150 /// GIT_COMMITTER_DATE=$(git log -n1 --pretty=%aD) git tag -a -m "Release 0.3.0" 0.3.0
1151 /// git push --tags
1152 /// ```
1153 /// Annotated tags are preferred because some Git commands ignore unannotated tags if any annotated tags exist.
1154 ///
1155 /// __Examples__
1156 /// + [Serde 1.0.0 release notes](https://github.com/serde-rs/serde/releases/tag/v1.0.0)
1157 /// + [Serde 0.9.8 release notes](https://github.com/serde-rs/serde/releases/tag/v0.9.8)
1158 /// + [Serde 0.9.0 release notes](https://github.com/serde-rs/serde/releases/tag/v0.9.0)
1159 /// + [Diesel change log](https://github.com/diesel-rs/diesel/blob/master/CHANGELOG.md)
1160 ///
1161 /// [Release notes document all significant changes (C-RELNOTES)](https://rust-lang.github.io/api-guidelines/documentation.html#release-notes-document-all-significant-changes-c-relnotes)
1162 C_RELNOTES,
1163 /// Rustdoc is supposed to include everything users need to use the crate fully and nothing more. It is fine to explain relevant implementation details in prose but they should not be real entries in the documentation.
1164 ///
1165 /// Especially be selective about which impls are visible in rustdoc -- all the ones that users would need for using the crate fully, but no others. In the following code the rustdoc of PublicError by default would show the From<PrivateError> impl. We choose to hide it with #[doc(hidden)] because users can never have a PrivateError in their code so this impl would never be relevant to them.
1166 /// ```
1167 /// // This error type is returned to users.
1168 /// pub struct PublicError { /* ... */ }
1169
1170 /// // This error type is returned by some private helper functions.
1171 /// struct PrivateError { /* ... */ }
1172
1173 /// // Enable use of `?` operator.
1174 /// #[doc(hidden)]
1175 /// impl From<PrivateError> for PublicError {
1176 /// fn from(err: PrivateError) -> PublicError {
1177 /// /* ... */
1178 /// }
1179 /// }
1180 /// ```
1181 /// [pub(crate)](https://github.com/rust-lang/rfcs/blob/master/text/1422-pub-restricted.md) is another great tool for removing implementation details from the public API. It allows items to be used from outside of their own module but not outside of the same crate.
1182 ///
1183 /// [Rustdoc does not show unhelpful implementation details (C-HIDDEN)](https://rust-lang.github.io/api-guidelines/documentation.html#rustdoc-does-not-show-unhelpful-implementation-details-c-hidden)
1184 C_HIDDEN,
1185}
1186
1187pub enum Macro {
1188 /// Rust macros let you dream up practically whatever input syntax you want. Aim to keep input syntax familiar and cohesive with the rest of your users' code by mirroring existing Rust syntax where possible. Pay attention to the choice and placement of keywords and punctuation.
1189 ///
1190 /// A good guide is to use syntax, especially keywords and punctuation, that is similar to what will be produced in the output of the macro.
1191 ///
1192 /// For example if your macro declares a struct with a particular name given in the input, preface the name with the keyword struct to signal to readers that a struct is being declared with the given name.
1193 /// ```
1194 /// // Prefer this...
1195 /// bitflags! {
1196 /// struct S: u32 { /* ... */ }
1197 /// }
1198
1199 /// // ...over no keyword...
1200 /// bitflags! {
1201 /// S: u32 { /* ... */ }
1202 /// }
1203
1204 /// // ...or some ad-hoc word.
1205 /// bitflags! {
1206 /// flags S: u32 { /* ... */ }
1207 /// }
1208 /// ```
1209 /// Another example is semicolons vs commas. Constants in Rust are followed by semicolons so if your macro declares a chain of constants, they should likely be followed by semicolons even if the syntax is otherwise slightly different from Rust's.
1210 /// ```
1211 /// // Ordinary constants use semicolons.
1212 /// const A: u32 = 0b000001;
1213 /// const B: u32 = 0b000010;
1214
1215 /// // So prefer this...
1216 /// bitflags! {
1217 /// struct S: u32 {
1218 /// const C = 0b000100;
1219 /// const D = 0b001000;
1220 /// }
1221 /// }
1222
1223 /// // ...over this.
1224 /// bitflags! {
1225 /// struct S: u32 {
1226 /// const E = 0b010000,
1227 /// const F = 0b100000,
1228 /// }
1229 /// }
1230 /// ```
1231 /// Macros are so diverse that these specific examples won't be relevant, but think about how to apply the same principles to your situation.
1232 ///
1233 /// [Input syntax is evocative of the output (C-EVOCATIVE)](https://rust-lang.github.io/api-guidelines/macros.html#input-syntax-is-evocative-of-the-output-c-evocative)
1234 C_EVOCATIVE,
1235 /// Macros that produce more than one output item should support adding attributes to any one of those items. One common use case would be putting individual items behind a cfg.
1236 /// ```
1237 /// bitflags! {
1238 /// struct Flags: u8 {
1239 /// #[cfg(windows)]
1240 /// const ControlCenter = 0b001;
1241 /// #[cfg(unix)]
1242 /// const Terminal = 0b010;
1243 /// }
1244 /// }
1245 /// ```
1246 /// Macros that produce a struct or enum as output should support attributes so that the output can be used with derive.
1247 /// ```
1248 /// bitflags! {
1249 /// #[derive(Default, Serialize)]
1250 /// struct Flags: u8 {
1251 /// const ControlCenter = 0b001;
1252 /// const Terminal = 0b010;
1253 /// }
1254 /// }
1255 /// ```
1256
1257 /// [Item macros compose well with attributes (C-MACRO-ATTR)](https://rust-lang.github.io/api-guidelines/macros.html#item-macros-compose-well-with-attributes-c-macro-attr)
1258 C_MACRO_ATTR,
1259 /// Rust allows items to be placed at the module level or within a tighter scope like a function. Item macros should work equally well as ordinary items in all of these places. The test suite should include invocations of the macro in at least the module scope and function scope.
1260 /// ```
1261 /// #[cfg(test)]
1262 /// mod tests {
1263 /// test_your_macro_in_a!(module);
1264 /// #[test]
1265 /// fn anywhere() {
1266 /// test_your_macro_in_a!(function);
1267 /// }
1268 /// }
1269 /// ```
1270 ///
1271 /// As a simple example of how things can go wrong, this macro works great in a module scope but fails in a function scope.
1272 /// ```
1273 /// macro_rules! broken {
1274 /// ($m:ident :: $t:ident) => {
1275 /// pub struct $t;
1276 /// pub mod $m {
1277 /// pub use super::$t;
1278 /// }
1279 /// }
1280 /// }
1281 /// broken!(m::T); // okay, expands to T and m::T
1282 /// fn g() {
1283 /// broken!(m::U); // fails to compile, super::U refers to the containing module not g
1284 /// }
1285 /// ```
1286 /// [Item macros work anywhere that items are allowed (C-ANYWHERE)](https://rust-lang.github.io/api-guidelines/macros.html#item-macros-work-anywhere-that-items-are-allowed-c-anywhere)
1287 C_ANYWHERE,
1288 /// Follow Rust syntax for visibility of items produced by a macro. Private by default, public if pub is specified.
1289 /// ```
1290 /// bitflags! {
1291 /// struct PrivateFlags: u8 {
1292 /// const A = 0b0001;
1293 /// const B = 0b0010;
1294 /// }
1295 /// }
1296 /// bitflags! {
1297 /// pub struct PublicFlags: u8 {
1298 /// const C = 0b0100;
1299 /// const D = 0b1000;
1300 /// }
1301 /// }
1302 /// ```
1303 /// [Item macros support visibility specifiers (C-MACRO-VIS)](https://rust-lang.github.io/api-guidelines/macros.html#item-macros-support-visibility-specifiers-c-macro-vis)
1304 C_MACRO_VIS,
1305 /// If your macro accepts a type fragment like $t:ty in the input, it should be usable with all of the following:
1306 /// + Primitives: u8, &str
1307 /// + Relative paths: m::Data
1308 /// + Absolute paths: ::base::Data
1309 /// + Upward relative paths: super::Data
1310 /// + Generics: Vec<String>
1311 ///
1312 /// As a simple example of how things can go wrong, this macro works great with primitives and absolute paths but fails with relative paths.
1313 /// ```
1314 /// macro_rules! broken {
1315 /// ($m:ident => $t:ty) => {
1316 /// pub mod $m {
1317 /// pub struct Wrapper($t);
1318 /// }
1319 /// }
1320 /// }
1321 /// broken!(a => u8); // okay
1322 /// broken!(b => ::std::marker::PhantomData<()>); // okay
1323 /// struct S;
1324 /// broken!(c => S); // fails to compile
1325 /// ```
1326 ///
1327 /// [Type fragments are flexible (C-MACRO-TY)](https://rust-lang.github.io/api-guidelines/macros.html#type-fragments-are-flexible-c-macro-ty)
1328 ///
1329 C_MACRO_TY,
1330}