How to implement Python's digest function in Raku?

Viewed 101

In Python, there is a function called digest from hashlib module, which returns the digest of a byte string:

import hashlib

id = "65766"
song_id = bytearray(id, "u8")

m = hashlib.md5(song_id)
result = m.digest()
print(result)

# Output
# b"\xc9j\xa4/vy}+'\xe6\x8e\xe4\xcc\xd8\xa8\xc8"

I find a module from raku.land named Digest::MD5, but it doesn't provide the digest sub:

my $d = Digest::MD5.new;
my $id = "65766";
my Buf $md5-buf = $d.md5_buf($id);

# ???

And I don't want to introduce Inline::Python or Inline::Perl5 into my project, Is it possible to implement digest sub in Raku?

1 Answers

TL;DR Try the md5 sub of the Digest package.

Digest

A glance at raku.land shows various options. The first one was last updated an hour ago, and while that doesn't prove anything about quality or functionality, it's at least "promising". (And it's grondilu. I trust cosimo too, but the updates suggest grondilu is engaged and cosimo isn't.)

So I suggest you read Digest's README and/or install it and read its code. At a glance I would expect the md5 sub to work.

Digest::MD5

From its README:

An interface-compatible port of Perl 5 Digest::MD5

Raku's standard strings are dramatically different from Perl's or Python's. I won't comment further other than to say this seems likely to be a major source of friction that is pointless unless you really need to have interface compatibility with Perl.

Should work with latest (2012.01) release of Rakudo

Wow. It's had an update in 2017, but I see unresolved PRs and, well, to be as open minded as possible, I'll say this package might work for folk who are:

  • Needing the same interface as the corresponding Perl package.

  • OK with presuming that everything is as it was more than 10 years ago (4 years before the first official version of the language and compiler were released) or updating the package if needed.

  • Willing to consider a package that seems to be no longer actively stewarded.

To be pragmatic / closed minded, I'd initially presume this package should only be considered if all of the above applies and you've failed to meet your (relatively simple/basic) needs some much more promising way.

Related