1
2
3
4
5
6
7
8
9
10
11
12
13
14 package ch.qos.logback.classic.kryo;
15
16 import com.esotericsoftware.kryo.kryo5.io.Input;
17 import com.esotericsoftware.kryo.kryo5.io.Output;
18
19 import java.io.PrintStream;
20 import java.util.Collections;
21 import java.util.LinkedHashMap;
22 import java.util.Map;
23 import java.util.Map.Entry;
24 import java.util.function.LongSupplier;
25
26
27
28
29
30
31
32 public class FieldByteAccumulator {
33
34 @FunctionalInterface
35 public interface InputAction<T> {
36 T run();
37 }
38
39 private final Map<String, Long> bytesByField = new LinkedHashMap<>();
40
41
42
43
44
45
46 public int write(Output output, String field, Runnable writeAction) {
47 int before = output.position();
48 writeAction.run();
49 int written = output.position() - before;
50 accumulate(field, written);
51 return written;
52 }
53
54
55
56
57
58
59 public <T> T read(Input input, String field, InputAction<T> readAction) {
60 long before = input.total();
61 T value = readAction.run();
62 long read = input.total() - before;
63 accumulate(field, read);
64 return value;
65 }
66
67
68
69
70
71 public long readLong(Input input, String field, LongSupplier readAction) {
72 long before = input.total();
73 long value = readAction.getAsLong();
74 accumulate(field, input.total() - before);
75 return value;
76 }
77
78 private void accumulate(String field, long bytes) {
79 bytesByField.merge(field, bytes, Long::sum);
80 }
81
82
83 public Map<String, Long> snapshot() {
84 return Collections.unmodifiableMap(bytesByField);
85 }
86
87 public long total() {
88 long sum = 0;
89 for (long v : bytesByField.values()) {
90 sum += v;
91 }
92 return sum;
93 }
94
95 public void reset() {
96 bytesByField.clear();
97 }
98
99
100
101
102
103 public void merge(FieldByteAccumulator other) {
104 if (other == null || other == this) {
105 return;
106 }
107 for (Entry<String, Long> entry : other.bytesByField.entrySet()) {
108 bytesByField.merge(entry.getKey(), entry.getValue(), Long::sum);
109 }
110 }
111
112
113 public void dump() {
114 dump(System.out);
115 }
116
117
118 public void dump(PrintStream out) {
119 out.println("FieldByteAccumulator:");
120 if (bytesByField.isEmpty()) {
121 out.println(" (empty)");
122 return;
123 }
124 long sum = 0;
125 for (Entry<String, Long> entry : bytesByField.entrySet()) {
126 long bytes = entry.getValue();
127 sum += bytes;
128 out.println(" " + entry.getKey() + "=" + bytes);
129 }
130 out.println(" total=" + sum);
131 }
132
133 @Override
134 public String toString() {
135 return bytesByField.toString();
136 }
137 }