<?php

namespace Buckhill\Support;

class RFC4226Truncate
{
    /**
     * @param string $hash
     * @param int $length
     * @return string
     */
    public static function truncate(string $hash, int $length): string
    {
        $offset = ord($hash[strlen($hash) - 1]) & 0xf;

        $value = (
            ((ord($hash[$offset + 0]) & 0x7f) << 24) |
            ((ord($hash[$offset + 1]) & 0xff) << 16) |
            ((ord($hash[$offset + 2]) & 0xff) << 8) |
            (ord($hash[$offset + 3]) & 0xff)
        );

        return (string)substr($value, -1 * $length);
    }
}