package com.dangerousthings.aliro;

/**
 * Minimal TLV reader for tests. Supports single-byte tags, multi-byte tags
 * with BER continuation encoding, and short-form lengths (&lt; 128) plus
 * 1- and 2-byte long-form lengths.
 */
final class TlvUtil {

    private TlvUtil() {}

    /**
     * Finds the value bytes of the first TLV with the given tag within the
     * given data, searching only at the top level (not recursing into nested
     * constructed TLVs).
     *
     * @return the value bytes of the first match, or {@code null} if not found.
     */
    static byte[] findTopLevel(byte[] data, int tag) {
        int i = 0;
        while (i < data.length) {
            int tagStart = i;
            int currentTag = data[i++] & 0xFF;
            if ((currentTag & 0x1F) == 0x1F) {
                int next;
                do {
                    next = data[i++] & 0xFF;
                    currentTag = (currentTag << 8) | next;
                } while ((next & 0x80) != 0);
            }
            int length = data[i++] & 0xFF;
            if (length == 0x81) {
                length = data[i++] & 0xFF;
            } else if (length == 0x82) {
                length = ((data[i++] & 0xFF) << 8) | (data[i++] & 0xFF);
            }
            if (currentTag == tag) {
                byte[] value = new byte[length];
                System.arraycopy(data, i, value, 0, length);
                return value;
            }
            i += length;
            // Silence unused-variable warning
            if (tagStart < 0) break;
        }
        return null;
    }
}
