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.Kryo; 017import com.esotericsoftware.kryo.kryo5.Serializer; 018import com.esotericsoftware.kryo.kryo5.io.Input; 019import com.esotericsoftware.kryo.kryo5.io.Output; 020 021/** 022 * Serializer for {@code long} values that stores successive values as deltas. 023 * 024 * <p>Each written value is encoded as {@code current - lastWritten} via 025 * {@link Output#writeVarLong(long, boolean)} (zig-zag). On read, the absolute 026 * value is reconstructed by adding the delta to the last reconstructed value. 027 * Write and read state are independent so the same instance can be used for 028 * both directions without interference. 029 * 030 * <p>Typical for monotonically increasing timestamps in a log stream, where 031 * deltas are small and varint-encode well. 032 */ 033public class LongDeltaSerializer extends Serializer<Long> { 034 035 private long lastWriteValue = 0; 036 private long lastReadValue = 0; 037 038 public LongDeltaSerializer() { 039 setAcceptsNull(false); 040 setImmutable(true); 041 } 042 043 /** Writes {@code value} as a zig-zag varint delta from the previous write. */ 044 public void writeLong(Output output, long value) { 045 long delta = value - lastWriteValue; 046 lastWriteValue = value; 047 output.writeVarLong(delta, true); 048 } 049 050 /** Inverse of {@link #writeLong(Output, long)}. */ 051 public long readLong(Input input) { 052 long delta = input.readVarLong(true); 053 long value = lastReadValue + delta; 054 lastReadValue = value; 055 return value; 056 } 057 058 @Override 059 public void write(Kryo kryo, Output output, Long value) { 060 writeLong(output, value); 061 } 062 063 @Override 064 public Long read(Kryo kryo, Input input, Class<? extends Long> type) { 065 return readLong(input); 066 } 067}