-
Notifications
You must be signed in to change notification settings - Fork 1.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Hexadecimal integers with fmt::Debug, including within larger types #2226
Conversation
```rust println!("{:02X?}", b"AZaz\0") ``` ``` [41, 5A, 61, 7A, 00] ```
It seems like the output of current Re 'Unresolved questions': given that you're asking about other possible formatting styles, adding an 'ASCII literal' style for |
That unresolved question is specifically about other existing formatting traits like |
FWIW |
The problem here is that So we need to decide whether |
What makes hexadecimal so special? I've wanted this kind of argument forwarding for floats since forever, considering that the default format is prone to generate things like |
Hexadecimal is special because one octet (which is a fairly fundamental unit) is exactly 2 hex digits, so it is a compact way to visualize bit-packed data. Before this RFC, hexadecimal and " I’m not sure what’s your point about floats. If you want to use fixed-precision formatting for floats within larger structures, the formatting string syntax already allows you to specify both a precision and |
Does #46233 enable the use of |
Ah ok, sorry I misunderstood your previous comment. I think that fits in the “Other formatting types/traits?” unresolved question. I don’t have an opinion on it. |
Okay. Even if this does not include such capability, I think my primary concern more than anything else is to make sure that this does not preclude future extensions such as (strawman syntax) Personally, I'm still holding out for some kind of "general number formatting" option like // Added in e.g. Rust 1.25
fn number_radix(&self) -> u32;
fn number_uppercase(&self) -> bool;
// Added in e.g. Rust 1.27
// true for {:e?} and {:E?}
fn number_exponential(&self) -> bool;
// Added in e.g. Rust 1.33
// true for {:g?} and {:G?}
// never simultaneously true with number_exponential()
fn number_general(&self) -> bool; |
Right, the |
cc @rust-lang/libs, highfive failed to assign a reviewer here. |
If it can help, one possible alternative would be to have both the decimal and hexadecimal representations. The idea is that Debug is meant for debugging, so we don't really know in advance what we want to see. If there is a debugging level, it could be used to control the amount of displayed information.
The size used for the hexadecimal comments could be inferred from the type ( Advantages:
Disadvantages:
I have no opinion about which way to go, but just felt that such an alternative could be considered before committing to a decision (in particular if we have a way to control the debug verbosity). |
This example is a very small slice. This formatting would get overly verbose very quickly.
Such control belongs inside the formatting string. It should be written once by the person that wrote for example the unit test, not up to every user not to forget to set some boilerplate environment variable. |
Yes, ideally the debug verbosity level would be in the format string, although that would change the format string API. If it's fine to go that way, then the remaining differences would be:
would give
instead of
I guess it depends on the use-case. For slices, it seems better to choose only one of decimal or hexadecimal since the values are homogeneous. But for more complex values, enforcing the user to choose one seems too constraining. |
This RFC is proposing to extend the formatting string syntax and And to be honest, using comment syntax in formatting output seems really unusual and not appropriate for |
I am not sure this is unusual when you are debugging. For example some debuggers comment the assembly with the decimal, hexadecimal, character, or string value based on heuristics: Is the issue with heterogeneous values (see |
cc @sfackler @alexcrichton, can one of you take a look at this RFC? |
This seems like a pretty slick RFC, thanks again for writing it up @SimonSapin! I'm mostly eyeing this from the perspective of "what do we need to stabilize to get the maximal benefit from this". It'd all for sure start out as unstable, but one part I like about this RFC is that there's a very tiny sliver I think we'll need to stabilize to actually get benefits, namely the new syntax in format strings. I'm not so sure about the Along those lines I sort of mostly see this RFC as "let's add some more syntax and then here's some details of how to implement it in libstd", where for now the biggest thing to debate I think is the syntax and the mechanics that go along with it. I personally really like that you don't need to add to Overall I'd be willing to merge, but would just want a gut check against other languages (especially Python) to see if this is already a feature somewhere else that we can draw experience from. |
Python classes can have separate As to hexadecimal formatting, Python also has |
Oh ok so just to confirm, at least with Python, if you have a custom composite like: struct Foo {
a: i64,
} There's no automatic way to format that with hex vs decimal? |
No, there's a magic method you can implement that allows you to customize formatting: class MyHex:
def __init__(self, val):
self.val = val
def __format__(self, spec):
if spec == 'x':
return hex(self.val)
if spec == '':
return str(self.val)
return 'unknown spec' >>> h = MyHex(89)
>>> '{:x}'.format(h)
'0x59'
>>> '{}'.format(h)
'89'
>>> '{:jk}'.format(h)
'unknown spec' You get the raw string, so you would need to implement all the custom hex In general Python doesn't have anything nearly as fancy as |
There's no way to automatically format that, period.
so basically you need to do what |
Ok thanks for the info @quodlibetor and @ExpHP! In that case sounds like there's not a lot of prior art on this specifically. As a result since it seems reasonable to me I'll.... @rfcbot fcp merge |
Team member @alexcrichton has proposed to merge this. The next step is review by the rest of the tagged teams: No concerns currently listed. Once a majority of reviewers approve (and none object), this will enter its final comment period. If you spot a major issue that hasn't been raised at any point in this process, please speak up! See this document for info about what commands tagged team members can give me. |
text/0000-fmt-debug-hex.md
Outdated
[summary]: #summary | ||
|
||
Add support for formatting integers as hexadecimal with the `fmt::Debug` trait, | ||
including when the occur within larger types. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
nit: s/the/they
text/0000-fmt-debug-hex.md
Outdated
For example, an RGBA color encoded in `u32` with 8 bits per channel is easier to understand | ||
when shown as `00CC44FF` than `13387007`. | ||
|
||
The `std::fmt::UpperHex` and `std::fmt::LowerHex` provide hexadecimal formatting |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
nit: The std::fmt::UpperHex
and std::fmt::LowerHex
traits?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fixed, thanks.
🔔 This is now entering its final comment period, as per the review above. 🔔 |
1 similar comment
🔔 This is now entering its final comment period, as per the review above. 🔔 |
The final comment period is now complete. |
Ok! I'll now merge this with a tracking issue |
The correct rendered link (the target of the original comment is deleted) is now: /~https://github.com/rust-lang/rfcs/blob/master/text/2226-fmt-debug-hex.md |
@quodlibetor Fixed, thanks! |
rust-lang/rust#48978 implements this RFC, but without the new |
This can be used for integers within a larger types which implements Debug (possibly through derive) but not fmt::UpperHex or fmt::LowerHex. ```rust assert!(format!("{:02x?}", b"Foo\0") == "[46, 6f, 6f, 00]"); assert!(format!("{:02X?}", b"Foo\0") == "[46, 6F, 6F, 00]"); ``` RFC: rust-lang/rfcs#2226
Add hexadecimal formatting of integers with fmt::Debug This can be used for integers within a larger types which implements Debug (possibly through derive) but not fmt::UpperHex or fmt::LowerHex. ```rust assert!(format!("{:02x?}", b"Foo\0") == "[46, 6f, 6f, 00]"); assert!(format!("{:02X?}", b"Foo\0") == "[46, 6F, 6F, 00]"); ``` RFC: rust-lang/rfcs#2226 The new formatting string syntax (`x?` and `X?`) is insta-stable in this PR because I don’t know how to change a built-in proc macro’s behavior based of a feature gate. I can look into adding that, but I also strongly suspect that keeping this feature unstable for a time period would not be useful as possibly no-one would use it during that time. This PR does not add the new (public) `fmt::Formatter` proposed in the API because: * There was some skepticism on response to this part of the RFC * It is not possible to implement as-is without larger changes to `fmt`, because `Formatter` at the moment has no easy way to tell apart for example `Octal` from `Binary`: it only has a function pointer for the relevant `fmt()` method. If some integer-like type outside of `std` want to implement this behavior, another RFC will likely need to propose a different public API for `Formatter`.
Add support for formatting integers as hexadecimal with the
fmt::Debug
trait,including when they occur within larger types.
Rendered