View Javadoc
1   /*
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2026, QOS.ch. All rights reserved.
4    *
5    * This program and the accompanying materials are dual-licensed under
6    * either the terms of the Eclipse Public License v2.0 as published by
7    * the Eclipse Foundation
8    *
9    *   or (per the licensee's choosing)
10   *
11   * under the terms of the GNU Lesser General Public License version 2.1
12   * as published by the Free Software Foundation.
13   */
14  package ch.qos.logback.classic.kryo;
15  
16  import com.esotericsoftware.kryo.kryo5.Kryo;
17  import com.esotericsoftware.kryo.kryo5.Serializer;
18  import com.esotericsoftware.kryo.kryo5.io.Input;
19  import com.esotericsoftware.kryo.kryo5.io.Output;
20  
21  /**
22   * Serializer for {@code long} values that stores successive values as deltas.
23   *
24   * <p>Each written value is encoded as {@code current - lastWritten} via
25   * {@link Output#writeVarLong(long, boolean)} (zig-zag). On read, the absolute
26   * value is reconstructed by adding the delta to the last reconstructed value.
27   * Write and read state are independent so the same instance can be used for
28   * both directions without interference.
29   *
30   * <p>Typical for monotonically increasing timestamps in a log stream, where
31   * deltas are small and varint-encode well.
32   */
33  public class LongDeltaSerializer extends Serializer<Long> {
34  
35      private long lastWriteValue = 0;
36      private long lastReadValue = 0;
37  
38      public LongDeltaSerializer() {
39          setAcceptsNull(false);
40          setImmutable(true);
41      }
42  
43      /** Writes {@code value} as a zig-zag varint delta from the previous write. */
44      public void writeLong(Output output, long value) {
45          long delta = value - lastWriteValue;
46          lastWriteValue = value;
47          output.writeVarLong(delta, true);
48      }
49  
50      /** Inverse of {@link #writeLong(Output, long)}. */
51      public long readLong(Input input) {
52          long delta = input.readVarLong(true);
53          long value = lastReadValue + delta;
54          lastReadValue = value;
55          return value;
56      }
57  
58      @Override
59      public void write(Kryo kryo, Output output, Long value) {
60          writeLong(output, value);
61      }
62  
63      @Override
64      public Long read(Kryo kryo, Input input, Class<? extends Long> type) {
65          return readLong(input);
66      }
67  }