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;
020import org.slf4j.event.KeyValuePair;
021
022/**
023 * V5 serializer for a single {@link KeyValuePair}.
024 *
025 * <p>Keys use {@link BasicStringSerializer} (short repeating names, id cache).
026 * String values use the caller-supplied codec, typically the same
027 * {@link MultiEventCompressedStringSerializer} as the event message so there is one deflate stream.
028 */
029public class KeyValuePairSerializerV5 extends Serializer<KeyValuePair> {
030
031    private final Serializer<String> keySerializer;
032    private final Serializer<String> valueStringSerializer;
033
034    public KeyValuePairSerializerV5(int stringCapacity) {
035        this(new BasicStringSerializer(stringCapacity), new MultiEventCompressedStringSerializer(stringCapacity));
036    }
037
038    public KeyValuePairSerializerV5(Serializer<String> keySerializer,
039                                    Serializer<String> valueStringSerializer) {
040        if (keySerializer == null || valueStringSerializer == null) {
041            throw new IllegalArgumentException("key and value string serializers cannot be null");
042        }
043        this.keySerializer = keySerializer;
044        this.valueStringSerializer = valueStringSerializer;
045        setAcceptsNull(false);
046    }
047
048    @Override
049    public void write(Kryo kryo, Output output, KeyValuePair keyValuePair) {
050        kryo.writeObject(output, keyValuePair.key, keySerializer);
051        SafeObjectCodec.write(kryo, output, valueStringSerializer, keyValuePair.value);
052    }
053
054    @Override
055    public KeyValuePair read(Kryo kryo, Input input, Class<? extends KeyValuePair> type) {
056        String key = kryo.readObject(input, String.class, keySerializer);
057        Object value = SafeObjectCodec.read(kryo, input, valueStringSerializer);
058        return new KeyValuePair(key, value);
059    }
060}