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

Add Display and DisplayAlternative wrapper types #19

Merged
merged 3 commits into from
Jan 9, 2025

Conversation

tyranron
Copy link
Contributor

@tyranron tyranron commented Jan 8, 2025

Follows #16, #17

Motivation

Applying the base62::encode_fmt() in my codebases, I've found that it doesn't play smooth with macro-based or non-transparent APIs (like derive_more::Display or thiserror::Error).

Consider the code before applying #17:

#[derive(derive_more::Display)]
#[display("{:0>22}", base62::encode(*_0))]
pub struct Version(u128);

This code now should be written "by hand", since base62::encode() cannot be substituted with base62::encode_fmt() trivially here.

Solution

This PR introduces two functions: base62::fmt() and base62::fmt_alt(). They allow applying base62 encoding easily in any format!()-like expressions, still avoiding unnecessary allocations.

#[derive(derive_more::Display)]
#[display("{:0>22}", base62::fmt(*_0))]
pub struct Version(u128);

@tyranron tyranron changed the title Add types Add Display and DisplayAlternative wrapper types Jan 8, 2025
@tyranron
Copy link
Contributor Author

tyranron commented Jan 8, 2025

Alternative naming could be: base62::Fmt and base62::FmtAlternative.

@fbernier
Copy link
Owner

fbernier commented Jan 8, 2025

Hey, thanks for the great explanation. I'm not against adding this. I left a few comments so let me know what you think and if you want to do these changes yourself.

Thanks!

@tyranron
Copy link
Contributor Author

tyranron commented Jan 9, 2025

@fbernier reworked!

@tyranron tyranron requested a review from fbernier January 9, 2025 11:24
@fbernier fbernier merged commit 49d91c1 into fbernier:master Jan 9, 2025
@fbernier
Copy link
Owner

fbernier commented Jan 9, 2025

Much cleaner, thanks! Cutting a release soon.

@tyranron tyranron deleted the fmt-wrapper branch January 9, 2025 14:41
@fbernier
Copy link
Owner

fbernier commented Jan 9, 2025

I ended up reworking things a bit. I replaced encode_fmt and encode_fmt_alternative with the fmt helper functions. One can use format! or write! macro on these functions as needed.

Released as 2.2.0

Thanks again and let me know if I missed anything

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants