package me.teafry.voipmessages; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * A decoded protobuf message, read by field number (Google Voice responses; * field numbers are in the desktop's src/main/gvoice/schema.ts). Unknown and * missing fields read as defaults, like proto3. */ final class Pb { private final Map> fields = new HashMap<>(); static Pb parse(byte[] buf) { Pb p = new Pb(); int[] pos = {0}; while (pos[0] < buf.length) { long tag = varint(buf, pos); int num = (int) (tag >>> 3), wire = (int) (tag & 7); Object v; switch (wire) { case 0: v = varint(buf, pos); break; case 1: v = fixed(buf, pos, 8); break; case 2: { int len = (int) varint(buf, pos); byte[] b = new byte[len]; System.arraycopy(buf, pos[0], b, 0, len); pos[0] += len; v = b; break; } case 5: v = fixed(buf, pos, 4); break; default: throw new IllegalArgumentException("protobuf: wire type " + wire); } p.fields.computeIfAbsent(num, k -> new ArrayList<>()).add(v); } return p; } private static long varint(byte[] b, int[] pos) { long r = 0; int shift = 0; while (true) { if (pos[0] >= b.length) throw new IllegalArgumentException("protobuf: truncated"); int x = b[pos[0]++] & 0xff; r |= (long) (x & 0x7f) << shift; if ((x & 0x80) == 0) return r; shift += 7; } } private static long fixed(byte[] b, int[] pos, int n) { long r = 0; for (int i = 0; i < n; i++) r |= (long) (b[pos[0] + i] & 0xff) << (8 * i); pos[0] += n; return r; } private Object last(int n) { List l = fields.get(n); return l == null || l.isEmpty() ? null : l.get(l.size() - 1); } String str(int n) { Object v = last(n); return v instanceof byte[] ? new String((byte[]) v, StandardCharsets.UTF_8) : ""; } long num(int n) { Object v = last(n); return v instanceof Long ? (Long) v : 0; } boolean bool(int n) { return num(n) != 0; } Pb msg(int n) { Object v = last(n); return v instanceof byte[] ? parse((byte[]) v) : new Pb(); } boolean has(int n) { return fields.containsKey(n); } List msgs(int n) { List out = new ArrayList<>(); List l = fields.get(n); if (l != null) for (Object v : l) if (v instanceof byte[]) out.add(parse((byte[]) v)); return out; } List strs(int n) { List out = new ArrayList<>(); List l = fields.get(n); if (l != null) for (Object v : l) if (v instanceof byte[]) out.add(new String((byte[]) v, StandardCharsets.UTF_8)); return out; } }