2828
2929#![ allow( clippy:: let_unit_value) ]
3030
31- use core:: fmt:: { self , Write , LowerHex } ;
31+ use core:: fmt:: { self , Write } ;
3232
3333use crate :: { Flags , Bits } ;
3434
@@ -38,7 +38,7 @@ use crate::{Flags, Bits};
3838/// as a hex number.
3939pub fn to_writer < B : Flags > ( flags : & B , mut writer : impl Write ) -> Result < ( ) , fmt:: Error >
4040where
41- B :: Bits : LowerHex ,
41+ B :: Bits : WriteHex ,
4242{
4343 // A formatter for bitflags that produces text output like:
4444 //
6767 writer. write_str ( " | " ) ?;
6868 }
6969
70- write ! ( writer, "{:#x}" , remaining) ?;
70+ writer. write_str ( "0x" ) ?;
71+ remaining. write_hex ( writer) ?;
7172 }
7273
7374 fmt:: Result :: Ok ( ( ) )
@@ -77,7 +78,7 @@ pub(crate) struct AsDisplay<'a, B>(pub(crate) &'a B);
7778
7879impl < ' a , B : Flags > fmt:: Display for AsDisplay < ' a , B >
7980where
80- B :: Bits : LowerHex ,
81+ B :: Bits : WriteHex ,
8182{
8283 fn fmt ( & self , f : & mut fmt:: Formatter < ' _ > ) -> fmt:: Result {
8384 to_writer ( self . 0 , f)
@@ -89,14 +90,12 @@ where
8990/// This function will fail on unknown flags rather than ignore them.
9091pub fn from_str < B : Flags > ( input : & str ) -> Result < B , ParseError >
9192where
92- B :: Bits : FromHex ,
93+ B :: Bits : ParseHex ,
9394{
94- let input = input. trim ( ) ;
95-
9695 let mut parsed_flags = B :: empty ( ) ;
9796
9897 // If the input is empty then return an empty set of flags
99- if input. is_empty ( ) {
98+ if input. trim ( ) . is_empty ( ) {
10099 return Ok ( parsed_flags) ;
101100 }
102101
@@ -111,7 +110,7 @@ where
111110 // If the flag starts with `0x` then it's a hex number
112111 // Parse it directly to the underlying bits type
113112 let parsed_flag = if let Some ( flag) = flag. strip_prefix ( "0x" ) {
114- let bits = <B :: Bits >:: from_hex ( flag) . map_err ( |_| ParseError :: invalid_hex_flag ( flag) ) ?;
113+ let bits = <B :: Bits >:: parse_hex ( flag) . map_err ( |_| ParseError :: invalid_hex_flag ( flag) ) ?;
115114
116115 B :: from_bits_retain ( bits)
117116 }
@@ -128,10 +127,16 @@ where
128127 Ok ( parsed_flags)
129128}
130129
130+ /// Encode a value as a hex string.
131+ pub trait WriteHex {
132+ /// Write the value as hex.
133+ fn write_hex < W : fmt:: Write > ( & self , writer : W ) -> fmt:: Result ;
134+ }
135+
131136/// Parse a value from a number encoded as a hex string.
132- pub trait FromHex {
133- /// Perform the conversion .
134- fn from_hex ( input : & str ) -> Result < Self , ParseError >
137+ pub trait ParseHex {
138+ /// Parse the value from hex .
139+ fn parse_hex ( input : & str ) -> Result < Self , ParseError >
135140 where
136141 Self : Sized ;
137142}
0 commit comments