def quote(s):
    """
    Encodes a byte string using URL encoding. This replaces bytes with their
    URL-encoded equivalent %XX where XX is the hexadecimal value of the byte.
    In particular, the bytes that are encoded include:

    1. Bytes < 0x20 or >= 0x7F (C0 and C1 control codes)
    2. Quote/apostrophe (0x27), double quote (0x22), and percent (0x25)

    This will always return a byte string. If the argument is a unicode string
    then it will be utf-8 encoded before being quoted.
    """

    if not isinstance(s, bytes):
        if isinstance(s, str):
            # We need to utf-8 encode unicode strings
            s = s.encode("utf-8")
        else:
            raise TypeError("Not a string: %s" % str(s))

    buf = []
    for byte in s:
        c = chr(byte)
        if byte < 0x20 or byte >= 0x7F:
            # Any byte less than 0x20 is a control character
            # any byte >= 0x7F is either a control character
            # or a multibyte unicode character
            buf.append("%%%02X" % byte)
        elif c == "%":
            buf.append("%25")
        elif c == "'":
            buf.append("%27")
        elif c == '"':
            buf.append("%22")
        else:
            # These are regular bytes
            buf.append(c)

    return "".join(buf)