Debian Codegraph @

debian/missing-sources/derive_more-impl/doc/from_str.md

raw symbols SCIP
1 # What `#[derive(FromStr)]` generates
2
3 Deriving `FromStr` only works for enums/structs with no fields
4 or newtypes (structs with only a single field). The result is
5 that you will be able to call the `parse()` method on a string
6 to convert it to your newtype. This only works when the wrapped
7 type implements `FromStr` itself.
8
9
10
11
12 ## Forwarding
13
14 Deriving forwarding implementation is only supported for newtypes
15 (structs with only a single field).
16
17
18 ### Tuple structs
19
20 When deriving `FromStr` for a tuple struct with one field:
21 ```rust
22 # use derive_more::FromStr;
23 #
24 #[derive(FromStr, Debug, Eq, PartialEq)]
25 struct MyInt(i32);
26
27 assert_eq!("5".parse::<MyInt>().unwrap(), MyInt(5));
28 ```
29
30 Code like this is generated:
31 ```rust
32 # struct MyInt(i32);
33 impl derive_more::core::str::FromStr for MyInt {
34 type Err = <i32 as derive_more::core::str::FromStr>::Err;
35 fn from_str(s: &str) -> Result<Self, Self::Err> {
36 Ok(Self(i32::from_str(s)?))
37 }
38 }
39 ```
40
41
42 ### Regular structs
43
44 When deriving `FromStr` for a regular struct with one field:
45 ```rust
46 # use derive_more::FromStr;
47 #
48 #[derive(FromStr, Debug, Eq, PartialEq)]
49 struct Point1D {
50 x: i32,
51 }
52
53 assert_eq!("100".parse::<Point1D>().unwrap(), Point1D { x: 100 });
54 ```
55
56 Code like this is generated:
57 ```rust
58 # struct Point1D {
59 # x: i32,
60 # }
61 impl derive_more::core::str::FromStr for Point1D {
62 type Err = <i32 as derive_more::core::str::FromStr>::Err;
63 fn from_str(s: &str) -> Result<Self, Self::Err> {
64 Ok(Self {
65 x: i32::from_str(s)?,
66 })
67 }
68 }
69 ```
70
71
72
73
74 ## Flat representation
75
76 Deriving flat string representation is only supported for empty enums and
77 structs (with no fields).
78
79
80 ### Empty enums
81
82 When deriving `FromStr` for enums with empty variants, it will generate a
83 `from_str()` method converting strings matching the variant name to the variant.
84 If using a case-insensitive match would give a unique variant (i.e. you don't have
85 both `MyEnum::Foo` and `MyEnum::foo` variants), then case-insensitive matching will
86 be used, otherwise it will fall back to exact string matching.
87
88 Since the string may not match any variants an error type is needed, so the
89 `derive_more::FromStrError` is used for that purpose.
90
91 Given the following enum:
92 ```rust
93 # use derive_more::FromStr;
94 #
95 #[derive(FromStr, Debug, Eq, PartialEq)]
96 enum EnumNoFields {
97 Foo,
98 Bar,
99 Baz,
100 BaZ,
101 }
102
103 assert_eq!("foo".parse::<EnumNoFields>().unwrap(), EnumNoFields::Foo);
104 assert_eq!("Foo".parse::<EnumNoFields>().unwrap(), EnumNoFields::Foo);
105 assert_eq!("FOO".parse::<EnumNoFields>().unwrap(), EnumNoFields::Foo);
106
107 assert_eq!("Bar".parse::<EnumNoFields>().unwrap(), EnumNoFields::Bar);
108 assert_eq!("bar".parse::<EnumNoFields>().unwrap(), EnumNoFields::Bar);
109
110 assert_eq!("Baz".parse::<EnumNoFields>().unwrap(), EnumNoFields::Baz);
111 assert_eq!("BaZ".parse::<EnumNoFields>().unwrap(), EnumNoFields::BaZ);
112 assert_eq!(
113 "other".parse::<EnumNoFields>().unwrap_err().to_string(),
114 "Invalid `EnumNoFields` string representation",
115 );
116 ```
117
118 Code like this is generated:
119 ```rust
120 # use core::str::FromStr;
121 #
122 # enum EnumNoFields {
123 # Foo,
124 # Bar,
125 # Baz,
126 # BaZ,
127 # }
128 #
129 impl derive_more::core::str::FromStr for EnumNoFields {
130 type Err = derive_more::FromStrError;
131 fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
132 Ok(match s.to_lowercase().as_str() {
133 "foo" => Self::Foo,
134 "bar" => Self::Bar,
135 "baz" if s == "Baz" => Self::Baz,
136 "baz" if s == "BaZ" => Self::BaZ,
137 _ => return Err(derive_more::FromStrError::new("EnumNoFields")),
138 })
139 }
140 }
141 ```
142
143
144 ### Empty structs
145
146 Deriving `FromStr` for structs with no fields is similar to enums,
147 but involves only case-insensitive matching by now.
148
149 Given the following struct:
150 ```rust
151 # use derive_more::FromStr;
152 #
153 #[derive(FromStr, Debug, Eq, PartialEq)]
154 struct Foo;
155
156 assert_eq!("foo".parse::<Foo>().unwrap(), Foo);
157 assert_eq!("Foo".parse::<Foo>().unwrap(), Foo);
158 assert_eq!("FOO".parse::<Foo>().unwrap(), Foo);
159 ```
160
161 Code like this is generated:
162 ```rust
163 # use core::str::FromStr;
164 #
165 # struct Foo;
166 #
167 impl derive_more::core::str::FromStr for Foo {
168 type Err = derive_more::FromStrError;
169 fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
170 Ok(match s.to_lowercase().as_str() {
171 "foo" => Self,
172 _ => return Err(derive_more::FromStrError::new("Foo")),
173 })
174 }
175 }
176 ```
177
178
179 ### The `rename_all` attribute
180
181 To control the concrete string representation of the name verbatim,
182 the `#[from_str(rename_all = "...")]` attribute can be placed on structs,
183 enums and variants.
184
185 The available casings are:
186 - `lowercase`
187 - `UPPERCASE`
188 - `PascalCase`
189 - `camelCase`
190 - `snake_case`
191 - `SCREAMING_SNAKE_CASE`
192 - `kebab-case`
193 - `SCREAMING-KEBAB-CASE`
194
195 ```rust
196 # use derive_more::FromStr;
197 #
198 #[derive(FromStr, Debug, Eq, PartialEq)]
199 #[from_str(rename_all = "lowercase")]
200 enum Enum {
201 VariantOne,
202 #[from_str(rename_all = "kebab-case")] // overrides the top-level one
203 VariantTwo
204 }
205
206 assert_eq!("variantone".parse::<Enum>().unwrap(), Enum::VariantOne);
207 assert_eq!("variant-two".parse::<Enum>().unwrap(), Enum::VariantTwo);
208 ```
209
210 > **NOTE**: Using `#[from_str(rename_all = "...")]` attribute disables
211 > any case-insensitivity where applied. This is also true for any enum
212 > variant whose name or string representation is similar to the variant
213 > being marked:
214 > ```rust
215 > # use derive_more::FromStr;
216 > #
217 > # #[allow(non_camel_case_types)]
218 > #[derive(FromStr, Debug, Eq, PartialEq)]
219 > enum Enum {
220 > Foo, // case-insensitive
221 > #[from_str(rename_all = "SCREAMING_SNAKE_CASE")]
222 > BaR, // case-sensitive (marked with attribute)
223 > Bar, // case-sensitive (name is similar to the marked `BaR` variant)
224 > Ba_R, // case-sensitive (string representation is similar to the marked `BaR` variant)
225 > }
226 > #
227 > # assert_eq!("Foo".parse::<Enum>().unwrap(), Enum::Foo);
228 > # assert_eq!("FOO".parse::<Enum>().unwrap(), Enum::Foo);
229 > # assert_eq!("foo".parse::<Enum>().unwrap(), Enum::Foo);
230 > #
231 > # assert_eq!("BA_R".parse::<Enum>().unwrap(), Enum::BaR);
232 > # assert_eq!("Bar".parse::<Enum>().unwrap(), Enum::Bar);
233 > # assert_eq!("Ba_R".parse::<Enum>().unwrap(), Enum::Ba_R);
234 > ```
235
236
237
238
239 ## Custom error
240
241 The `#[from_str(error(<ty>[, <conv>]))]` attribute can be used to convert the `FromStr`' `Err` type
242 into a custom error type.
243
244 If the conversion function is not provided, the custom error type must implement `From<FromStr::Err>`.
245 The conversion function could be provided in the following forms:
246 - function (like `CustomError::new`);
247 - closure (like `|e| CustomError::new(e)`);
248 - function call (like `CustomError::factory()`).
249
250
251 ### Forwarding
252
253 Given the following struct:
254 ```rust
255 # use derive_more::{From, FromStr};
256 #
257 #[derive(From)]
258 struct CustomError(core::num::ParseIntError);
259
260 #[derive(FromStr, Debug, Eq, PartialEq)]
261 #[from_str(error(CustomError))]
262 struct MyInt(i32);
263 ```
264 Code like this is generated:
265 ```rust
266 # use core::str::FromStr;
267 # use derive_more::From;
268 #
269 # #[derive(From)]
270 # struct CustomError(core::num::ParseIntError);
271 #
272 # struct MyInt(i32);
273 #
274 impl derive_more::core::str::FromStr for MyInt {
275 type Err = CustomError;
276 fn from_str(s: &str) -> Result<Self, Self::Err> {
277 FromStr::from_str(s)
278 .map(|v| Self(v))
279 .map_err(Into::into)
280 }
281 }
282 ```
283
284 For the explicitly specified error conversion:
285 ```rust
286 # use derive_more::FromStr;
287 #
288 struct CustomError(core::num::ParseIntError);
289
290 impl CustomError {
291 fn new(err: core::num::ParseIntError) -> Self {
292 Self(err)
293 }
294 }
295
296 #[derive(FromStr, Debug, Eq, PartialEq)]
297 #[from_str(error(CustomError, CustomError::new))]
298 struct MyInt(i32);
299 ```
300 Code like this is generated:
301 ```rust
302 # use core::str::FromStr;
303 #
304 # struct CustomError(core::num::ParseIntError);
305 #
306 # impl CustomError {
307 # fn new(err: core::num::ParseIntError) -> Self {
308 # Self(err)
309 # }
310 # }
311 #
312 # struct MyInt(i32);
313 #
314 impl derive_more::core::str::FromStr for MyInt {
315 type Err = CustomError;
316 fn from_str(s: &str) -> Result<Self, Self::Err> {
317 FromStr::from_str(s)
318 .map(|v| Self(v))
319 .map_err(CustomError::new)
320 }
321 }
322 ```
323
324 Custom error for a newtype struct with one named field, *e.g*,
325 ```rust
326 # use derive_more::{From, FromStr};
327 #
328 #[derive(From)]
329 struct CustomError(core::num::ParseIntError);
330
331 #[derive(FromStr)]
332 #[from_str(error(CustomError))]
333 struct Point1D {
334 x: i32,
335 }
336 ```
337 works similarly.
338
339
340 ### Flat representation
341
342 Custom error type is also supported for empty enums and unit structs.
343
344 Given the following enum:
345 ```rust
346 # use derive_more::{From, FromStr};
347 #
348 #[derive(From)]
349 struct CustomError(derive_more::FromStrError);
350
351 #[derive(FromStr, Debug, Eq, PartialEq)]
352 #[from_str(error(CustomError))]
353 enum EnumNoFields {
354 Foo,
355 Bar,
356 Baz,
357 }
358 ```
359 Code like this is generated:
360 ```rust
361 # use core::str::FromStr;
362 # use derive_more::From;
363 #
364 # #[derive(From)]
365 # struct CustomError(derive_more::FromStrError);
366 #
367 # enum EnumNoFields {
368 # Foo,
369 # Bar,
370 # Baz,
371 # }
372 #
373 impl derive_more::core::str::FromStr for EnumNoFields {
374 type Err = CustomError;
375 fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
376 Ok(match s.to_lowercase().as_str() {
377 "foo" => Self::Foo,
378 "bar" => Self::Bar,
379 "baz" => Self::Baz,
380 _ => return Err(derive_more::FromStrError::new("EnumNoFields").into()),
381 })
382 }
383 }
384 ```
385
386 For the explicitly specified error conversion:
387 ```rust
388 # use derive_more::FromStr;
389 #
390 struct CustomError(derive_more::FromStrError);
391
392 impl CustomError {
393 pub fn new(err: derive_more::FromStrError) -> Self {
394 Self(err)
395 }
396 }
397
398 #[derive(FromStr, Debug, Eq, PartialEq)]
399 #[from_str(error(CustomError, CustomError::new))]
400 enum EnumNoFields {
401 Foo,
402 Bar,
403 Baz,
404 }
405 ```
406 Code like this is generated:
407 ```rust
408 # use core::str::FromStr;
409 #
410 # struct CustomError(derive_more::FromStrError);
411 #
412 # impl CustomError {
413 # pub fn new(err: derive_more::FromStrError) -> Self {
414 # Self(err)
415 # }
416 # }
417 #
418 # enum EnumNoFields {
419 # Foo,
420 # Bar,
421 # Baz,
422 # }
423 #
424 impl derive_more::core::str::FromStr for EnumNoFields {
425 type Err = CustomError;
426 fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
427 Ok(match s.to_lowercase().as_str() {
428 "foo" => Self::Foo,
429 "bar" => Self::Bar,
430 "baz" => Self::Baz,
431 _ => return Err(CustomError::new(derive_more::FromStrError::new("EnumNoFields"))),
432 })
433 }
434 }
435 ```
436
437 Custom error type for unit structs, *e.g*,
438 ```rust
439 # use derive_more::{From, FromStr};
440 #
441 #[derive(From)]
442 struct CustomError(derive_more::FromStrError);
443
444 #[derive(FromStr)]
445 #[from_str(error(CustomError))]
446 struct Foo;
447 ```
448 works similarly.