class LuhnCheckFunction {

    @Description("Checks that a string of digits is valid according to the Luhn algorithm")
    @ScalarFunction("luhn_check")
    @SqlType(StandardTypes.BOOLEAN)
    public static boolean LuhnCheck(@SqlType(StandardTypes.VARCHAR) Slice slice)
    {
        if (slice.length() == 0) {
            return false;
        }

        int nDigits = slice.length();
        int sum = 0;
        boolean secondNumber = false;

        for (int i = nDigits - 1; i >= 0; i--) {
            byte b = slice.getByte(i);
            checkCondition(b >= '0' && b <= '9', INVALID_FUNCTION_ARGUMENT, "Input contains non-digit character");
            int n = b - '0';

            // starting from the right double the value of every other number
            if (secondNumber) {
                n *= 2;
            }

            // if the value is greater than 9 subtract 9 from n
            if (n > 9) {
                n -= 9;
            }

            // add to sum
            sum += n;

            // update second number check
            secondNumber = !secondNumber;
        }
        //check returns true if mod 10 is zero
        return (sum % 10 == 0);
    }

    private  LuhnCheckFunction();

}