Deprecate CheckedValue.orElseThrow(Supplier)
[yangtools.git] / common / concepts / src / main / java / org / opendaylight / yangtools / concepts / PrettyTreeIndent.java
1 /*
2  * Copyright (c) 2021 PANTHEON.tech, s.r.o. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yangtools.concepts;
9
10 import org.slf4j.Logger;
11 import org.slf4j.LoggerFactory;
12
13 /**
14  * Indentation handling for {@link PrettyTree}. This class is split out to defer initialization of the string table --
15  * it might never be used after all.
16  *
17  * <p>
18  * We want to be formatting strings quickly and a lot of that can very easily be dominated by dealing with indents.
19  * To deal with that we pre-compute a few indentation strings and then append them directly using a specialized
20  * method. We allow tuning the default indentation at runtime, but choose a fixed string table size.
21  */
22 final class PrettyTreeIndent {
23     private static final Logger LOG = LoggerFactory.getLogger(PrettyTreeIndent.class);
24     private static final int DEFAULT_INDENT = 4;
25     /**
26      * Size of indent table. The idea is to strike a balance between memory footprint and the number of operations we
27      * perform in {@link #indent(StringBuilder, int)}. Indentation up to {@value #INDENT_STRINGS_SIZE} result in a
28      * single operation.
29      */
30     private static final int INDENT_STRINGS_SIZE = 16;
31     private static final String[] INDENT_STRINGS;
32
33     static {
34         int indent = Integer.getInteger("org.opendaylight.yangtools.concepts.pretty-tree-indent", DEFAULT_INDENT);
35         if (indent < 1) {
36             LOG.warn("Invalid pretty-tree-indent {}, using {} instead", indent, DEFAULT_INDENT);
37             indent = DEFAULT_INDENT;
38         } else if (indent != DEFAULT_INDENT) {
39             LOG.info("Using pretty-tree-indent {}", indent);
40         }
41
42         final String one = " ".repeat(indent);
43         final String[] strings = new String[INDENT_STRINGS_SIZE];
44         for (int i = 0; i < INDENT_STRINGS_SIZE; i++) {
45             strings[i] = one.repeat(i).intern();
46         }
47         INDENT_STRINGS = strings;
48     }
49
50     private PrettyTreeIndent() {
51         // Hidden on purpose
52     }
53
54     static void indent(final StringBuilder sb, final int depth) {
55         int remaining = depth;
56         while (remaining >= INDENT_STRINGS_SIZE) {
57             sb.append(INDENT_STRINGS[INDENT_STRINGS_SIZE - 1]);
58             remaining -= INDENT_STRINGS_SIZE;
59         }
60         sb.append(INDENT_STRINGS[remaining]);
61     }
62 }