4.49. kink/hash/BIN_HASHER

Algorithms of mappings from arbitrary length bins to fixed length bins.

Example: MD5-hash of byte strings

:BIN.require_from('kink/')
:BIN_HASHER.require_from('kink/hash/')

:md5 <- {(:Bins)
  :H = BIN_HASHER.new_for('md5')
  Bins.each{(:B)
    H.push(B)
  }
  stdout.print_line(H.hash.repr)
}

# MD5-hash of the emtpy byte string:
md5([BIN.of()])
# => (bin 0xd4 0x1d 0x8c 0xd9 0x8f 0x00 0xb2 0x04 0xe9 0x80 0x09 0x98 0xec 0xf8 0x42 0x7e)

# The same hash value is generated for the same byte string:

md5([BIN.of(1 2 3 4 5 6)])
# => (bin 0x6a 0xc1 0xe5 0x6b 0xc7 0x8f 0x03 0x10 0x59 0xbe 0x7b 0xe8 0x54 0x52 0x2c 0x4c)

md5([BIN.of(1 2) BIN.of(3 4) BIN.of(5 6)])
# => (bin 0x6a 0xc1 0xe5 0x6b 0xc7 0x8f 0x03 0x10 0x59 0xbe 0x7b 0xe8 0x54 0x52 0x2c 0x4c)

Example: Hash values of the empty byte string for various hash algorithms

:BIN.require_from('kink/')
:BIN_HASHER.require_from('kink/hash/')

:hash_empty <- {(:Algorithm)
  BIN_HASHER.new_for(Algorithm){(:C)
    C.on_present{(:H)
      H.push(BIN.of())
      stdout.print_line(H.hash.repr)
    }
    C.on_absent{
      stdout.print_line('not supported: {}'.format(Algorithm))
    }
  }
}

hash_empty('md5')
# => (bin 0xd4 0x1d 0x8c 0xd9 0x8f 0x00 0xb2 0x04 0xe9 0x80 0x09 0x98 0xec 0xf8 0x42 0x7e)

hash_empty('sha-1')
# => (bin 0xda 0x39 0xa3 0xee 0x5e 0x6b 0x4b 0x0d 0x32 0x55 0xbf 0xef 0x95 0x60 0x18 0x90 0xaf 0xd8 0x07 0x09)

hash_empty('foobar')
# => not supported: foobar

4.49.1. type bin_hasher

A `bin_hasher` value consumes an arbitrary length bin as an input, and generates a bin value as the output.

4.49.1.1. Bin_hasher.push(Bin)

`push` adds `Bin` to the end of the input bin.

Precondition:

• `Bin` must be a bin.

4.49.1.2. Bin_hasher.hash

`hash` generates the hash value of the input bin. The result is a bin val.

4.49.1.3. Bin_hasher.algorithm

`algorithm` returns the name of the hash algorithm as a str value.

4.49.2. BIN_HASHER.new_for(Algorithm ...[$config={}])

`new_for` makes a new `bin_hasher` of the specified hash algorithm.

Preconditions

• `Algorithm` must be a str

• $config must be a fun which takes a config value.

Config value

The config value provides two methods:

• C.on_present($present_cont): specifies $present_cont as the present cont. $present_cont must be a fun which takes a `bin_hasher` value.

• C.on_absent($absent_cont): specifies $absent_cont as the absent cont. $absent_cont must be a thunk.

Default continuations

The default present cont is `{(:H) H }`, which returns the `bin_hasher` value passed as the argument.

The default absent cont is a thunk which raises an exception.

Result

If the runtime supports the algorithm specified by `Algorithm`, `new_for` makes a new `bin_hasher` value and tail-calls the present cont with the `bin_hasher` value.

If the runtime does not support the algorithm specified by `Algorithm`, `new_for` calls the absent cont.

4.49.3. BIN_HASHER.is?(Val)

`is?` returns whether `Val` is a `bin_hasher` value.