• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.textclassifier.utils;
18 
19 import com.google.common.base.Preconditions;
20 import com.google.errorprone.annotations.CanIgnoreReturnValue;
21 import java.io.PrintWriter;
22 
23 /**
24  * A print writer that supports indentation.
25  *
26  * @see PrintWriter
27  */
28 public final class IndentingPrintWriter {
29   static final String SINGLE_INDENT = "  ";
30 
31   private final PrintWriter writer;
32   private final StringBuilder indentBuilder = new StringBuilder();
33   private String currentIndent = "";
34 
IndentingPrintWriter(PrintWriter writer)35   public IndentingPrintWriter(PrintWriter writer) {
36     this.writer = Preconditions.checkNotNull(writer);
37   }
38 
39   /** Prints a string. */
40   @CanIgnoreReturnValue
println(String string)41   public IndentingPrintWriter println(String string) {
42     writer.print(currentIndent);
43     writer.print(string);
44     writer.println();
45     return this;
46   }
47 
48   /** Prints a empty line */
49   @CanIgnoreReturnValue
println()50   public IndentingPrintWriter println() {
51     writer.println();
52     return this;
53   }
54 
55   /** Increases indents for subsequent texts. */
56   @CanIgnoreReturnValue
increaseIndent()57   public IndentingPrintWriter increaseIndent() {
58     indentBuilder.append(SINGLE_INDENT);
59     currentIndent = indentBuilder.toString();
60     return this;
61   }
62 
63   /** Decreases indents for subsequent texts. */
64   @CanIgnoreReturnValue
decreaseIndent()65   public IndentingPrintWriter decreaseIndent() {
66     indentBuilder.delete(0, SINGLE_INDENT.length());
67     currentIndent = indentBuilder.toString();
68     return this;
69   }
70 
71   /** Prints a key-valued pair. */
72   @CanIgnoreReturnValue
printPair(String key, Object value)73   public IndentingPrintWriter printPair(String key, Object value) {
74     println(String.format("%s=%s", key, String.valueOf(value)));
75     return this;
76   }
77 
78   /** Flushes the stream. */
flush()79   public void flush() {
80     writer.flush();
81   }
82 }
83