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.Serializer;
019import com.esotericsoftware.kryo.kryo5.io.Input;
020import com.esotericsoftware.kryo.kryo5.io.Output;
021
022import java.util.HashMap;
023import java.util.Map;
024
025/**
026 * Serializer for MDC property maps ({@code Map<String, String>}).
027 *
028 * <p>Each map is written as:
029 * <ol>
030 *   <li>entry count ({@code writeVarInt}), excluding null keys and null values</li>
031 *   <li>for each remaining entry: key string, then value string</li>
032 * </ol>
033 *
034 * <p>The default constructor caches whole maps with {@link BiMapType#DIRECT_MAP}
035 * ({@code equals}/{@code hashCode}). {@link MDCPropertyMapSerializerV5} uses
036 * {@link BiMapType#IDENTITY}. Decode returns {@link Map#copyOf}. An older stream
037 * may still contain a null value; that entry is read and dropped.
038 *
039 * <p>By default key and value strings share one nested string serializer.
040 * {@link MDCPropertyMapSerializerV5} uses {@link BasicStringSerializer} for keys
041 * and a caller-supplied value codec (the V5 message/argument long-string serializer).
042 *
043 * <p>Null maps are not handled here; callers should use {@code writeObjectOrNull} /
044 * {@code readObjectOrNull}.
045 */
046public class MDCPropertyMapSerializer extends SerializerBase<Map<String, String>> {
047
048    private final Serializer<String> keySerializer;
049    private final Serializer<String> valueSerializer;
050
051    /**
052     * @param capacity capacity of the whole-map cache and of the nested string cache
053     */
054    public MDCPropertyMapSerializer(int capacity) {
055        this(BiMapType.DIRECT_MAP, capacity);
056    }
057
058    /**
059     * @param biMapType whole-map cache: {@link BiMapType#DIRECT_MAP} (equals) or
060     *                  {@link BiMapType#IDENTITY} ({@code ==})
061     * @param capacity  capacity of the whole-map cache and of the nested string cache
062     */
063    public MDCPropertyMapSerializer(BiMapType biMapType, int capacity) {
064        this(biMapType, capacity, null, null);
065    }
066
067    /**
068     * @param biMapType        whole-map cache: {@link BiMapType#DIRECT_MAP} (equals) or
069     *                         {@link BiMapType#IDENTITY} ({@code ==})
070     * @param capacity         capacity of the whole-map cache; also used when this
071     *                         constructor allocates nested string serializers
072     * @param keySerializer    key codec; {@code null} means {@link #getNewEntrySerializer(int)}
073     * @param valueSerializer  value codec; {@code null} means the same instance as keys
074     */
075    public MDCPropertyMapSerializer(BiMapType biMapType, int capacity,
076                                    Serializer<String> keySerializer,
077                                    Serializer<String> valueSerializer) {
078        super(biMapType, capacity);
079        setAcceptsNull(false);
080        // acceptsNull stays false: Kryo writeObjectOrNull handles null values via NULL/NOT_NULL.
081        if (keySerializer == null) {
082            keySerializer = getNewEntrySerializer(capacity);
083        }
084        if (valueSerializer == null) {
085            valueSerializer = keySerializer;
086        }
087        this.keySerializer = keySerializer;
088        this.valueSerializer = valueSerializer;
089    }
090
091
092    @Override
093    protected void writeNewEntry(Kryo kryo, Output output, Map<String, String> map) {
094        int count = 0;
095        for (Map.Entry<String, String> entry : map.entrySet()) {
096            if (entry.getKey() != null && entry.getValue() != null) {
097                count++;
098            }
099        }
100        output.writeVarInt(count, true);
101        for (Map.Entry<String, String> entry : map.entrySet()) {
102            String key = entry.getKey();
103            String value = entry.getValue();
104            if (key == null || value == null) {
105                continue;
106            }
107            kryo.writeObject(output, key, keySerializer);
108            kryo.writeObjectOrNull(output, value, valueSerializer);
109        }
110    }
111
112    @Override
113    protected Map<String, String> readNewEntry(Kryo kryo, Input input) {
114        int size = input.readVarInt(true);
115        HashMap<String, String> map = new HashMap<>(Math.max(4, (int) (size / 0.75f) + 1));
116        for (int i = 0; i < size; i++) {
117            String key = kryo.readObject(input, String.class, keySerializer);
118            String value = kryo.readObjectOrNull(input, String.class, valueSerializer);
119            // Older streams included null values in the count and wrote them.
120            if (key == null || value == null) {
121                continue;
122            }
123            map.put(key, value);
124        }
125        return Map.copyOf(map);
126    }
127
128    protected Serializer<String> getNewEntrySerializer(int capacity) {
129        return new BasicStringSerializer(BiMapType.DIRECT_MAP, capacity);
130    }
131}