crypto.hash_string?
BlueSlimee opened this issue · comments
Hi there!
A hash_string
function would be very nice to have, instead of being required to use BitString
.
Let's say we want to hash a string composed of other strings without compromising performance (a very common operation with crypto-releated stuff).
With Elixir, we could do something like this:
def hash_block(block) do
:crypto.hash(:sha256, [block.id, block.data, Integer.to_string(block.timestamp])
end
With Gleam this is a little bit more complicated, since crypto.hash method requires a BitString. The code above would probably look like something like this:
pub fn hash_block(block: Block) {
bit_builder.from_string(block.id)
|> bit_builder.append_string(block.data)
|> bit_builder.append_string(int.to_string(block.timestamp))
|> bit_builder.to_bit_string
|> crypto.hash(crypto.Sha256, _)
...
}
This is obviously too much.
Instead, there could be a function that takes String
as an input. The code above would look something like this:
pub fn hash_block(block: Block) {
string_builder.from_strings([
block.id,
block.data,
int.to_string(block.timestamp)
])
|> string_builder.to_string
|> crypto.hash_string(crypto.Sha256, _)
...
}
Much better!
NOTE: I tried adding the function and it works just fine, passes all tests + new ones I added for this purpose specifically. I don't think it will cause any problems since Gleam already uses UTF-8 binaries under the hood. If it sounds good to you guys I can create the pull request with everything.
Could be handy, though in this specific case I would use a bit string literal.
pub fn hash_block(block: Block) {
crypto.hash(
crypto.Sha256,
<<
block.id:utf8,
block.data:utf8,
int.to_string(block.timestamp):utf8,
>>
)
}
Closing due to lack of activity.