1 /* Copyright © 2023 Valve Corporation
2 *
3 * Permission is hereby granted, free of charge, to any person obtaining a
4 * copy of this software and associated documentation files (the "Software"),
5 * to deal in the Software without restriction, including without limitation
6 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
7 * and/or sell copies of the Software, and to permit persons to whom the
8 * Software is furnished to do so, subject to the following conditions:
9 *
10 * The above copyright notice and this permission notice (including the next
11 * paragraph) shall be included in all copies or substantial portions of the
12 * Software.
13 *
14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
17 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
19 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
20 * DEALINGS IN THE SOFTWARE.
21 */
22
23 #include <string.h>
24 #include <inttypes.h>
25 #include "mesa-blake3.h"
26 #include "hex.h"
27
_mesa_blake3_format(char * buf,const unsigned char * blake3)28 void _mesa_blake3_format(char *buf, const unsigned char *blake3)
29 {
30 mesa_bytes_to_hex(buf, blake3, BLAKE3_OUT_LEN);
31 }
32
_mesa_blake3_hex_to_blake3(unsigned char * buf,const char * hex)33 void _mesa_blake3_hex_to_blake3(unsigned char *buf, const char *hex)
34 {
35 mesa_hex_to_bytes(buf, hex, BLAKE3_OUT_LEN);
36 }
37
_mesa_blake3_compute(const void * data,size_t size,blake3_hash result)38 void _mesa_blake3_compute(const void *data, size_t size, blake3_hash result)
39 {
40 struct mesa_blake3 ctx;
41 _mesa_blake3_init(&ctx);
42 _mesa_blake3_update(&ctx, data, size);
43 _mesa_blake3_final(&ctx, result);
44 }
45
46 static void
blake3_to_uint32(const blake3_hash blake3,uint32_t out[BLAKE3_OUT_LEN32])47 blake3_to_uint32(const blake3_hash blake3,
48 uint32_t out[BLAKE3_OUT_LEN32])
49 {
50 memset(out, 0, BLAKE3_OUT_LEN);
51
52 for (unsigned i = 0; i < BLAKE3_OUT_LEN; i++)
53 out[i / 4] |= (uint32_t)blake3[i] << ((i % 4) * 8);
54 }
55
56 void
_mesa_blake3_print(FILE * f,const blake3_hash blake3)57 _mesa_blake3_print(FILE *f, const blake3_hash blake3)
58 {
59 uint32_t u32[BLAKE3_OUT_LEN32];
60 blake3_to_uint32(blake3, u32);
61 for (unsigned i = 0; i < BLAKE3_OUT_LEN32; i++) {
62 fprintf(f, i ? ", 0x%08" PRIx32 : "0x%08" PRIx32, u32[i]);
63 }
64 }
65
66 bool
_mesa_printed_blake3_equal(const blake3_hash blake3,const uint32_t printed_blake3[BLAKE3_OUT_LEN32])67 _mesa_printed_blake3_equal(const blake3_hash blake3,
68 const uint32_t printed_blake3[BLAKE3_OUT_LEN32])
69 {
70 uint32_t u32[BLAKE3_OUT_LEN32];
71 blake3_to_uint32(blake3, u32);
72
73 return memcmp(u32, printed_blake3, sizeof(u32)) == 0;
74 }