001/*
002 * Logback: the reliable, generic, fast and flexible logging framework.
003 * Copyright (C) 1999-2026, QOS.ch. All rights reserved.
004 *
005 * This program and the accompanying materials are dual-licensed under
006 * either the terms of the Eclipse Public License v2.0 as published by
007 * the Eclipse Foundation
008 *
009 *   or (per the licensee's choosing)
010 *
011 * under the terms of the GNU Lesser General Public License version 2.1
012 * as published by the Free Software Foundation.
013 */
014package ch.qos.logback.classic.kryo;
015
016import com.esotericsoftware.kryo.kryo5.io.Input;
017import com.esotericsoftware.kryo.kryo5.io.Output;
018
019import java.io.PrintStream;
020import java.util.Collections;
021import java.util.LinkedHashMap;
022import java.util.Map;
023import java.util.Map.Entry;
024import java.util.function.LongSupplier;
025
026/**
027 * Accumulates bytes written to an {@link Output} or read from an {@link Input}, keyed by field name.
028 * <p>
029 * Write accounting uses {@link Output#position()} (suitable for a fixed buffer with no flush).
030 * Read accounting uses {@link Input#total()} so deltas remain correct across buffer refills.
031 */
032public class FieldByteAccumulator {
033
034    @FunctionalInterface
035    public interface InputAction<T> {
036        T run();
037    }
038
039    private final Map<String, Long> bytesByField = new LinkedHashMap<>();
040
041    /**
042     * Runs {@code writeAction} and adds the number of bytes written to {@code field}.
043     *
044     * @return bytes written by this call
045     */
046    public int write(Output output, String field, Runnable writeAction) {
047        int before = output.position();
048        writeAction.run();
049        int written = output.position() - before;
050        accumulate(field, written);
051        return written;
052    }
053
054    /**
055     * Runs {@code readAction} and adds the number of bytes read to {@code field}.
056     *
057     * @return the value produced by {@code readAction}
058     */
059    public <T> T read(Input input, String field, InputAction<T> readAction) {
060        long before = input.total();
061        T value = readAction.run();
062        long read = input.total() - before;
063        accumulate(field, read);
064        return value;
065    }
066
067    /**
068     * Like {@link #read(Input, String, InputAction)} but for a primitive {@code long},
069     * so the result is not boxed.
070     */
071    public long readLong(Input input, String field, LongSupplier readAction) {
072        long before = input.total();
073        long value = readAction.getAsLong();
074        accumulate(field, input.total() - before);
075        return value;
076    }
077
078    private void accumulate(String field, long bytes) {
079        bytesByField.merge(field, bytes, Long::sum);
080    }
081
082    /** Unmodifiable view of cumulative bytes per field. */
083    public Map<String, Long> snapshot() {
084        return Collections.unmodifiableMap(bytesByField);
085    }
086
087    public long total() {
088        long sum = 0;
089        for (long v : bytesByField.values()) {
090            sum += v;
091        }
092        return sum;
093    }
094
095    public void reset() {
096        bytesByField.clear();
097    }
098
099    /**
100     * Adds {@code other}'s field totals into this instance. Used when Kryo is rebuilt
101     * on a CLOSE/HEADER so accounting survives a codec-epoch reset.
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    /** Dumps all accumulated field byte counts and the total to {@link System#out}. */
113    public void dump() {
114        dump(System.out);
115    }
116
117    /** Dumps all accumulated field byte counts and the total to {@code out}. */
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}