rawMember function

String? rawMember(
  1. String text,
  2. String member
)

Returns the exact source text of the top-level member of the JSON object text, or null.

The edge embeds the stored bundle text byte-for-byte; hashing that span avoids depending on re-serialisation. When the member occurs more than once the LAST one wins, like JSON.parse.

Implementation

String? rawMember(String text, String member) {
  var i = 0;
  final n = text.length;
  bool isWs(int c) => c == 0x20 || c == 0x0a || c == 0x0d || c == 0x09;
  void ws() {
    while (i < n && isWs(text.codeUnitAt(i))) {
      i++;
    }
  }

  String? str() {
    if (i >= n || text.codeUnitAt(i) != 0x22) return null;
    final start = i++;
    while (i < n) {
      final c = text.codeUnitAt(i);
      if (c == 0x5c) {
        i += 2;
      } else if (c == 0x22) {
        return text.substring(start, ++i);
      } else {
        i++;
      }
    }
    return null;
  }

  bool value() {
    ws();
    if (i >= n) return false;
    final c = text.codeUnitAt(i);
    if (c == 0x22) return str() != null;
    if (c == 0x7b || c == 0x5b) {
      var depth = 0;
      while (i < n) {
        final d = text.codeUnitAt(i);
        if (d == 0x22) {
          if (str() == null) return false;
          continue;
        }
        if (d == 0x7b || d == 0x5b) {
          depth++;
        } else if (d == 0x7d || d == 0x5d) {
          depth--;
        }
        i++;
        if (depth == 0) return true;
      }
      return false;
    }
    final start = i;
    while (i < n && !',}] \n\r\t'.contains(text[i])) {
      i++;
    }
    return i > start;
  }

  ws();
  if (i >= n || text.codeUnitAt(i) != 0x7b) return null;
  i++;
  String? found;
  for (;;) {
    ws();
    if (i < n && text.codeUnitAt(i) == 0x7d) return found;
    final key = str();
    if (key == null) return null;
    ws();
    if (i >= n || text.codeUnitAt(i) != 0x3a) return null;
    i++;
    ws();
    final start = i;
    if (!value()) return null;
    Object? name;
    try {
      name = jsonDecode(key);
    } on FormatException {
      return null;
    }
    if (name == member) found = text.substring(start, i);
    ws();
    if (i < n && text.codeUnitAt(i) == 0x2c) {
      i++;
    } else if (i < n && text.codeUnitAt(i) == 0x7d) {
      return found;
    } else {
      return null;
    }
  }
}