• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 package com.google.protobuf;
2 
3 /**
4  * ProtobufToStringOutput controls the output format of {@link Message#toString()}. Specifically, for
5  * the Runnable object passed to `callWithDebugFormat` and `callWithTextFormat`, Message.toString()
6  * will always output the specified format unless ProtobufToStringOutput is used again to change the
7  * output format.
8  */
9 public final class ProtobufToStringOutput {
10   private enum OutputMode {
11     DEBUG_FORMAT,
12     TEXT_FORMAT
13   }
14 
15   private static final ThreadLocal<OutputMode> outputMode =
16       new ThreadLocal<OutputMode>() {
17         @Override
18         protected OutputMode initialValue() {
19           return OutputMode.TEXT_FORMAT;
20         }
21       };
22 
ProtobufToStringOutput()23   private ProtobufToStringOutput() {}
24 
25   @CanIgnoreReturnValue
setOutputMode(OutputMode newMode)26   private static OutputMode setOutputMode(OutputMode newMode) {
27     OutputMode oldMode = outputMode.get();
28     outputMode.set(newMode);
29     return oldMode;
30   }
31 
callWithSpecificFormat(Runnable impl, OutputMode mode)32   private static void callWithSpecificFormat(Runnable impl, OutputMode mode) {
33     OutputMode oldMode = setOutputMode(mode);
34     try {
35       impl.run();
36     } finally {
37       OutputMode unused = setOutputMode(oldMode);
38     }
39   }
40 
callWithDebugFormat(Runnable impl)41   public static void callWithDebugFormat(Runnable impl) {
42     callWithSpecificFormat(impl, OutputMode.DEBUG_FORMAT);
43   }
44 
callWithTextFormat(Runnable impl)45   public static void callWithTextFormat(Runnable impl) {
46     callWithSpecificFormat(impl, OutputMode.TEXT_FORMAT);
47   }
48 
shouldOutputDebugFormat()49   public static boolean shouldOutputDebugFormat() {
50     return outputMode.get() == OutputMode.DEBUG_FORMAT;
51   }
52 }
53