[ACP] Provide an interface for creating and modifying instances of fmt::Formatter · Issue #280 · rust-lang/libs-team (original) (raw)
Proposal
Problem statement
Creating a custom Formatter at runtime as well as modifying an existing Formatter
is currently not supported, one can only use the Formatter
s passed in by the formatting macros. Being able to create and modify them could be useful for multiple use cases:
- Calling the formatting code of contained fileds with a modified formatting parameter
- Exposing different formatting methods for different representations/data points on one struct
- Exposing formatting methods that require additional data
- Writing libraries that provide enhanced formatting capabilities
Motivating examples or use cases
- Allow modifying Formatter members rust#19207
- Feature request: Add a way to capture a formatter that can be passed to format helper functions rust#74870
- Unable to create Formatter rust#46591
- Multiple instances fit this use case:
- runtime-fmt (a formatting crate that allows the user to supply the format string at runtime) seems to use the unstable
fmt_internals
feature to build a customstd::fmt::Arguments
which has theFormatter
baked in (or rather the mostly equivalentfmt::rt::Placeholder
struct), see here. In consequence, this crate requires nightly Rust. (Note that the interface isn't the current one as runtime-fmt hasn't been updated since 2019) - rt_format (another runtime formatting crate) handles the problem in another way: Using a macro named generate_code!, it generates a function containing a
format_args!
call for every combination of alignment, signedness, default/alternative representation, zero/space padding, width (via variable), precision (via variable) and formatting trait for a total of 1024format_args!
invocations at the time of writing. Fill characters are not supported, as those cannot be passed via a variable to theformat_args!
call but must be part of the format specifier. (If you are interested to see the result of this approach, runcargo expand
in the crate root and search for a huge function namedformat_value
) - I'd like to experiment with a crate that reimplements the formatting macros but adds some additional features (mostly interpolation). However, it is currently impossible to do this in a manner that is compatible with the std implementation outside of nightly Rust (rt_format is is almost there, but they cannot support fill characters, apart from their solution being quite hacky and probably inefficient).
- runtime-fmt (a formatting crate that allows the user to supply the format string at runtime) seems to use the unstable
Solution sketch
- Add a new function
fn new(write: &'a mut (dyn Write + 'a)) -> Formatter<'a>
toFormatter
that constructs a new instance ofFormatter
that is equivalent to the{}
formatting specifier (no flags, filled with spaces, no alignment, no width, no precision). - Add new methods
set_sign_plus
/set_sign_minus
/set_alternate
/set_sign_aware_zero_pad
/set_fill
/set_align
/set_width
/set_precision
toFormatter
that set the field to the indicated value. - Add a new method
fn clone(&'a mut self) -> Self
toFormatter
that clones the instance. Note that this is not aimpl
of theClone
trait as this method takes a mutable borrow ofself
(instead of an immutable one). The mutable borrow is held for the lifetime of the clone. This is necessary because the cloned instance holds the same mutable reference to the outputWrite
instance as the instance it was cloned from.
Alternatives
Another idea I had was to use the builder pattern to build new Formatter
s. The drawback I see with the builder pattern is that changing a single parameter, as needed in use case 1 above, wouldn't be possible. The user would instead need to create a new builder from the existing Formatter
:
let fmt = FormatterBuilder::from(fmt).set_width(Some(42)).build();
This is quite verbose compared to the proposed solution:
On the other hand, the prposed solution adds 10 functions to Formatter
that most users do not care about and that make the documentation harder to navigate. I am still a bit on the fence about which way to go here – feedback is appeciated.
Also, this proposal passes the output stream as a dyn Trait to the new
function. If in the future, Formatter
gets refactored to be generic struct with the output struct used as a generic type parameter, fn new
will not match this new interface. However,
- I don't see how the proposal could be implemented instead, and
- I don't believe refactoring
Formatter
in this fashion is possible anyway – this would change the interface and therefore would be a breaking change.
Links and related work
Relevant previous libs team discussion: rust-lang/rfcs#3394 (comment)
What happens now?
This issue contains an API change proposal (or ACP) and is part of the libs-api team feature lifecycle. Once this issue is filed, the libs-api team will review open proposals as capability becomes available. Current response times do not have a clear estimate, but may be up to several months.
Possible responses
The libs team may respond in various different ways. First, the team will consider the problem (this doesn't require any concrete solution or alternatives to have been proposed):
- We think this problem seems worth solving, and the standard library might be the right place to solve it.
- We think that this probably doesn't belong in the standard library.
Second, if there's a concrete solution:
- We think this specific solution looks roughly right, approved, you or someone else should implement this. (Further review will still happen on the subsequent implementation PR.)
- We're not sure this is the right solution, and the alternatives or other materials don't give us enough information to be sure about that. Here are some questions we have that aren't answered, or rough ideas about alternatives we'd want to see discussed.