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

Support truncation when formatting #101

Closed
tcharding opened this issue Aug 22, 2024 · 5 comments
Closed

Support truncation when formatting #101

tcharding opened this issue Aug 22, 2024 · 5 comments

Comments

@tcharding
Copy link
Member

The following should work

format!("{:016x}", hash);

I.e we should support truncation by way of the precise formatting paramater because hashes are not integral types.

@apoelstra
Copy link
Member

I'm certain we support this. This was a feature request on day one and one of the first things we implemented.

@apoelstra
Copy link
Member

Yeah, weirdly we don't have a unit test in hashes/ but you can add one

    #[test]
    fn sha256_truncated() {
        #[rustfmt::skip]
        static HASH_BYTES: [u8; 32] = [
            0xef, 0x53, 0x7f, 0x25, 0xc8, 0x95, 0xbf, 0xa7,
            0x82, 0x52, 0x65, 0x29, 0xa9, 0xb6, 0x3d, 0x97,
            0xaa, 0x63, 0x15, 0x64, 0xd5, 0xd7, 0x89, 0xc2,
            0xb7, 0x65, 0x44, 0x8c, 0x86, 0x35, 0xfb, 0x6c,
        ];

        let hash = sha256::Hash::from_slice(&HASH_BYTES).expect("right number of bytes");

        assert_eq!(
            format!("{:.8}", hash),
            "ef537f25",
        );
    }

passes.

@tcharding
Copy link
Member Author

Oh nice, you are correct. So the bug is actually in the issue (and in secp)

Wrong: format!("{:016x}", hash);
Right: format!("{:.8}", hash);

It is width vs precision but I was reading the docs wrong and had them backwards. Thanks

@apoelstra
Copy link
Member

Yeah, this is a terminology issue in format_args that has burned me in the past. In my old hashes::hex code I used width because that's what makes intuitive sense. But Kix corrected me that actually "width" means "minimum width" and "precision" means "maximum width". Approximately.

@Kixunil
Copy link
Collaborator

Kixunil commented Aug 23, 2024

What confuses me more is that .43 looks like decimal number so it never occurs to me that it should work for anything other than floats.

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

No branches or pull requests

3 participants