tor_netdoc/parse/keyword.rs
1//! Declaration for the Keyword trait.
2
3use crate::parse::rules;
4use std::hash::Hash;
5
6/// A Keyword identifies the possible types of a keyword for an Item.
7///
8/// These do not map one-to-one to Item strings: several Item strings
9/// may be placed in a single Keyword -- for example, when their order
10/// is significant with respect to one another, like "accept" and
11/// "reject" in router descriptors.
12///
13/// Every keyword has an "index", which is a small number suitable for
14/// indexing an array. These are used in Section and SectionRules.
15///
16/// Turning a string into a keyword cannot fail: there is always an
17/// "UNRECOGNIZED" keyword.
18///
19/// See macro::decl_keyword! for help defining a Keyword type for a
20/// network document.
21pub(crate) trait Keyword:
22 crate::KeywordEncodable + Hash + Eq + PartialEq + Copy + Clone
23{
24 /// Find a Keyword corresponding to a string that appears in a
25 /// network document.
26 fn from_str(s: &str) -> Self;
27 /// Try to find the keyword corresponding to a given index value,
28 /// as used in Section and SectionRules.
29 #[allow(unused)] // TODO keep Keyword::from_idx ?
30 fn from_idx(i: usize) -> Option<Self>;
31 /// Return the index for this keyword.
32 fn idx(self) -> usize;
33 /// Return the number of indices for this keyword.
34 fn n_vals() -> usize;
35 /// Return the "UNRECOGNIZED" keyword.
36 fn unrecognized() -> Self;
37 /// Return the "ANN_UNRECOGNIZED" keyword.
38 fn ann_unrecognized() -> Self;
39 /// Return true iff this keyword denotes an annotation.
40 fn is_annotation(self) -> bool;
41 /// Convert from an index to a human-readable string.
42 #[allow(unused)] // TODO keep Keyword::idx_to_str ?
43 fn idx_to_str(i: usize) -> &'static str {
44 Self::from_idx(i)
45 .map(|x| x.to_str())
46 .unwrap_or("<out of range>")
47 }
48 /// Return a new TokenFmtBuilder for creating rules about this keyword.
49 fn rule(self) -> rules::TokenFmtBuilder<Self> {
50 rules::TokenFmtBuilder::new(self)
51 }
52}