tlvDecode method

List<TLV> tlvDecode(
  1. String data
)

Decodes a TLV encoded string into a list of TLV objects.

The method iterates through the provided TLV encoded string, extracting the tag, length, and value for each TLV item and converts them into a list of TLV objects. It validates the TLV structure and skips invalid tags in the range of 00-99. If the data is malformed or incomplete, the method may stop parsing further.

  • Parameters:

    • data: The TLV encoded string to decode. The string should be in the standard TLV format (tag, length, value).
  • Returns: A list of TLV objects representing the decoded tags, lengths, and values.

  • Example:

    TLVService tlvService = TLVService();
    List<TLV> decoded = tlvService.tlvDecode('0012345A0103ABC');
    print(decoded); // [TLV("00", 12, "345A"), TLV("01", 3, "ABC")]
    

Implementation

List<TLV> tlvDecode(String data) {
  List<TLV> tlvList = [];
  int index = 0;
  int dataLength = data.length;

  try {
    while (index + 4 <= dataLength) {
      final tag = data[index] + data[index + 1]; // Tag as a string "XX"
      index += 2;

      if (!_isValidTag(tag)) {
        'Invalid tag: $tag, skipping...'.qrLog();
        index += 2; // Skip length (2 digits) and value (based on length)

        //! DISABLED for This Version
        // if (tag != "5B") {
        //   throw TLVException(
        //     'Invalid TAG',
        //     tag: tag,
        //     position: index,
        //     additionalInfo: 'Skipped tag: $tag',
        //   );
        // } else {
        //   continue;
        // }
        continue;
      }

      final tagValueLengthStr =
          data[index] + data[index + 1]; // Length as "XX"
      index += 2;

      final tagValueLength = int.tryParse(tagValueLengthStr) ?? 0;
      if (index + tagValueLength > dataLength) {
        break; // Validate if we have enough data for the tag
      }

      final value = data.substring(index, index + tagValueLength);
      index += tagValueLength;

      tlvList.add(TLV(tag, tagValueLength, value));
    }

    return tlvList;
  } catch (e) {
    throw TLVException(
      'Error decoding TLV data',
      tag: '',
      position: index,
      additionalInfo: e.toString(),
    );
  }
}