Skip to content
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

How to add formatter for custom integer-like type #4334

Closed
WerWolv opened this issue Jan 29, 2025 · 3 comments
Closed

How to add formatter for custom integer-like type #4334

WerWolv opened this issue Jan 29, 2025 · 3 comments
Labels

Comments

@WerWolv
Copy link

WerWolv commented Jan 29, 2025

Hey! I'm currently working on integrating the wide-integer library into one of my projects. This library defines types that can portably represent signed and unsigned integers with widths larger than 64 bits.

My goal is to use these types together with my existing libfmt code, how would I go about defining a formatter that can handle these types in a similar fashion as the existing integer types? I'd like to mainly avoid having to manually implement all the different format specifiers manually since there are quite a few available for the built-in integer types. These types support all of the unary and binary operations a regular integer type would too so I'd assume that the existing number formatting algorithms would translate over just fine.

Thanks a lot

@vitaut
Copy link
Contributor

vitaut commented Jan 31, 2025

{fmt} doesn't publicly expose the APIs that are used to build integral formatters at the moment. The relevant internal APIs are

  • Parsing format specifiers:

    fmt/include/fmt/base.h

    Lines 1428 to 1430 in 373855c

    FMT_CONSTEXPR auto parse_format_specs(const Char* begin, const Char* end,
    dynamic_format_specs<Char>& specs,
    parse_context<Char>& ctx, type arg_type)

  • Formatting:

    fmt/include/fmt/format.h

    Lines 2092 to 2093 in 373855c

    FMT_CONSTEXPR FMT_INLINE auto write(basic_appender<Char> out, T value,
    const format_specs& specs, locale_ref loc)

@WerWolv
Copy link
Author

WerWolv commented Feb 1, 2025

Thank you! I tried implementing it using these functions but it ultimately fails because {fmt} tries to cast the value to a built-in integer in a few places. (e.g static_cast<detail::uint64_or_128_t<T>>(arg.abs_value)).

Would you be open to accept a PR that adds a way to do it properly? E.g maybe adding a type trait that can be specialized to allow custom types to be treated as built-in integers?

@vitaut
Copy link
Contributor

vitaut commented Feb 2, 2025

A PR is welcome provided that it doesn't add too much complexity.

@vitaut vitaut closed this as completed Feb 2, 2025
@vitaut vitaut added the question label Feb 2, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants