ProtoLiteUtils { public static <T extends MessageLite> Marshaller<T> marshaller(final T defaultInstance) { @SuppressWarnings("unchecked") final Parser<T> parser = (Parser<T>) defaultInstance.getParserForType(); return new Marshaller<T>() { @Override public InputStream stream(T value) { return new ProtoInputStream(value, parser); } @Override public T parse(InputStream stream) { if (stream instanceof ProtoInputStream) { ProtoInputStream protoStream = (ProtoInputStream) stream; if (protoStream.parser() == parser) { try { @SuppressWarnings("unchecked") T message = (T) ((ProtoInputStream) stream).message(); return message; } catch (IllegalStateException ex) { } } } try { return parseFrom(stream); } catch (InvalidProtocolBufferException ipbe) { throw Status.INTERNAL.withDescription("Invalid protobuf byte sequence") .withCause(ipbe).asRuntimeException(); } } private T parseFrom(InputStream stream) throws InvalidProtocolBufferException { CodedInputStream codedInput = CodedInputStream.newInstance(stream); codedInput.setSizeLimit(Integer.MAX_VALUE); T message = parser.parseFrom(codedInput, globalRegistry); try { codedInput.checkLastTagWas(0); return message; } catch (InvalidProtocolBufferException e) { e.setUnfinishedMessage(message); throw e; } } }; } private  ProtoLiteUtils(); @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1787") static void setExtensionRegistry(ExtensionRegistryLite newRegistry); static Marshaller<T> marshaller(final T defaultInstance); static Metadata.BinaryMarshaller<T> metadataMarshaller(
      final T instance);  }
@Test public void testMismatch() throws Exception { Marshaller<Enum> enumMarshaller = ProtoLiteUtils.marshaller(Enum.getDefaultInstance()); Enum altProto = Enum.newBuilder().setName(proto.getName()).build(); assertEquals(proto, marshaller.parse(enumMarshaller.stream(altProto))); }
@Test public void testEmpty() throws IOException { Marshaller<Empty> marshaller = ProtoLiteUtils.marshaller(Empty.getDefaultInstance()); InputStream is = marshaller.stream(Empty.getDefaultInstance()); assertEquals(0, is.available()); byte[] b = new byte[10]; assertEquals(-1, is.read(b)); assertArrayEquals(new byte[10], b); assertEquals(-1, is.read(b)); assertArrayEquals(new byte[10], b); assertEquals(-1, is.read()); assertEquals(0, is.available()); }