lib/core: Added new `hexdigest` service on `Text`
[nit.git] / lib / core / bytes.nit
index 356f386..94d3d27 100644 (file)
@@ -32,18 +32,18 @@ redef class Byte
        #
        # ~~~nit
        # intrude import core::bytes
-       # assert not '/'.ascii.to_b.is_valid_hexdigit
-       # assert '0'.ascii.to_b.is_valid_hexdigit
-       # assert '9'.ascii.to_b.is_valid_hexdigit
-       # assert not ':'.ascii.to_b.is_valid_hexdigit
-       # assert not '@'.ascii.to_b.is_valid_hexdigit
-       # assert 'A'.ascii.to_b.is_valid_hexdigit
-       # assert 'F'.ascii.to_b.is_valid_hexdigit
-       # assert not 'G'.ascii.to_b.is_valid_hexdigit
-       # assert not '`'.ascii.to_b.is_valid_hexdigit
-       # assert 'a'.ascii.to_b.is_valid_hexdigit
-       # assert 'f'.ascii.to_b.is_valid_hexdigit
-       # assert not 'g'.ascii.to_b.is_valid_hexdigit
+       # assert not '/'.ascii.is_valid_hexdigit
+       # assert '0'.ascii.is_valid_hexdigit
+       # assert '9'.ascii.is_valid_hexdigit
+       # assert not ':'.ascii.is_valid_hexdigit
+       # assert not '@'.ascii.is_valid_hexdigit
+       # assert 'A'.ascii.is_valid_hexdigit
+       # assert 'F'.ascii.is_valid_hexdigit
+       # assert not 'G'.ascii.is_valid_hexdigit
+       # assert not '`'.ascii.is_valid_hexdigit
+       # assert 'a'.ascii.is_valid_hexdigit
+       # assert 'f'.ascii.is_valid_hexdigit
+       # assert not 'g'.ascii.is_valid_hexdigit
        # ~~~
        private fun is_valid_hexdigit: Bool do
                return (self >= 0x30u8 and self <= 0x39u8) or
@@ -289,6 +289,20 @@ redef class Text
                end
                return ret
        end
+
+       # Gets the hexdigest of the bytes of `self`
+       #
+       #     assert "&lt;STRING&#47;&rt;".hexdigest == "266C743B535452494E47262334373B2672743B"
+       fun hexdigest: String do
+               var ln = bytelen
+               var outns = new NativeString(ln * 2)
+               var oi = 0
+               for i in [0 .. ln[ do
+                       bytes[i].add_digest_at(outns, oi)
+                       oi += 2
+               end
+               return new FlatString.with_infos(outns, ln * 2, 0, ln * 2 - 1)
+       end
 end
 
 redef class FlatText