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 ch.qos.logback.core.kryo.SerializerBase;
017import com.esotericsoftware.kryo.kryo5.Kryo;
018import com.esotericsoftware.kryo.kryo5.io.Input;
019import com.esotericsoftware.kryo.kryo5.io.Output;
020import com.esotericsoftware.kryo.kryo5.minlog.Log;
021
022import java.io.ByteArrayInputStream;
023import java.io.ByteArrayOutputStream;
024import java.io.IOException;
025import java.util.zip.GZIPInputStream;
026import java.util.zip.GZIPOutputStream;
027
028public class SingleItemCompressingStringSerializer extends SerializerBase<String> {
029
030    static int SIZE_THRESHOLD_FOR_COMPRESSION = 256;
031    static byte UNMODIFIED = 'U';
032    static byte COMPRESSED = 'C';
033
034    int totalGain = 0;
035    private final ReusableUtf8 utf8 = new ReusableUtf8();
036
037    public SingleItemCompressingStringSerializer(int capacity) {
038        super(capacity);
039    }
040
041    public SingleItemCompressingStringSerializer(SerializerBase.BiMapType biMapType, int capacity) {
042        super(biMapType, capacity);
043    }
044
045    @Override
046    protected void writeNewEntry(Kryo kryo, Output output, String value) {
047        Log.trace("writeNewEntry for String: " + value);
048
049        // assume nulls are not permitted
050        if (value == null) {
051            throw new IllegalArgumentException("Null values are not permitted");
052        }
053
054        int length = value.length();
055
056        if (length < SIZE_THRESHOLD_FOR_COMPRESSION) {
057            outputAsString(output, value);
058        } else {
059            int utf8Len = utf8.encode(value);
060            byte[] compressedBytes = gzipCompress(utf8.buffer(), 0, utf8Len);
061            if (compressedBytes.length >= utf8Len) {
062                // compression not effective
063                outputAsString(output, value);
064                Log.trace("String compression not effective, writing unmodified string: " + value);
065            } else {
066                totalGain += utf8Len - compressedBytes.length;
067                Log.debug("Writing compressed string: "+compressedBytes+" instead of  "+utf8Len+" totalGain="+totalGain+" bytes");
068                output.writeByte(COMPRESSED);
069                output.writeInt(compressedBytes.length);
070                output.writeBytes(compressedBytes);
071            }
072        }
073
074    }
075
076    private static void outputAsString(Output output, String value) {
077        output.writeByte(UNMODIFIED);
078        output.writeString(value);
079    }
080
081    @Override
082    protected String readNewEntry(Kryo kryo, Input input) {
083
084        byte entryType = input.readByte();
085
086        if (entryType == UNMODIFIED) {
087            String value = input.readString();
088            Log.trace("readNewEntry for String: " + value);
089            return value;
090        } else { // COMPRESSED
091            int compressedLength = input.readInt();
092            byte[] compressedBytes = input.readBytes(compressedLength);
093            byte[] decompressedBytes = decompressGzip(compressedBytes);
094            String value = utf8.decode(decompressedBytes, 0, decompressedBytes.length);
095            Log.trace("readNewEntry for Compressed String: " + value);
096            return value;
097
098        }
099
100
101    }
102
103    private byte[] decompressGzip(byte[] compressedBytes) {
104
105        ByteArrayInputStream bais = new ByteArrayInputStream(compressedBytes);
106        try (GZIPInputStream gzip = new GZIPInputStream(bais)) {
107            byte[] result = gzip.readAllBytes();
108            return result;
109        } catch (IOException e) {
110            throw new RuntimeException(e);
111        }
112    }
113
114    public static byte[] gzipCompress(byte[] data) {
115        return gzipCompress(data, 0, data.length);
116    }
117
118    public static byte[] gzipCompress(byte[] data, int off, int len) {
119        ByteArrayOutputStream baos = new ByteArrayOutputStream();
120        try (GZIPOutputStream gzip = new GZIPOutputStream(baos)) {
121            gzip.write(data, off, len);
122        } catch (IOException e) {
123            throw new RuntimeException(e);
124        }
125        return baos.toByteArray();
126    }
127}