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.core.kryo;
015
016import java.util.HashMap;
017import java.util.LinkedHashMap;
018import java.util.Map;
019
020import static ch.qos.logback.core.kryo.KryoCoreConstants.cappedSerializerCapacity;
021
022/**
023 * Value↔id map keyed by object identity ({@code ==} / {@link System#identityHashCode}),
024 * with access-order LRU eviction at {@code capacity}.
025 *
026 * <p>Equal-but-distinct instances are different keys. {@link #getIdByValue} and
027 * {@link #getValueById} count as uses. Evicted ids are reused for later inserts.
028 * {@code idToValue} is a plain {@link HashMap}; LRU order lives only in {@code valueToId}.
029 *
030 * @see SerializerBase.BiMapType#IDENTITY
031 */
032public class BidirectionalObjectToIdMapIdentity<V> implements BidirectionalObjectToIdMap<V> {
033
034    static final boolean ACCESS_ORDER = true;
035
036    final int capacity;
037
038    private final Map<Integer, V> idToValue;
039    private final LinkedHashMap<IdentityKey<V>, Integer> valueToId;
040    /** Reused for lookups so {@link #getIdByValue} / {@link #getValueById} do not allocate. */
041    private final IdentityKey<V> lookupKey = new IdentityKey<>(null);
042    private final SerializerIdPool idPool = new DualSerializerIdPool();
043
044    public BidirectionalObjectToIdMapIdentity(int capacity) {
045        this.capacity = cappedSerializerCapacity(capacity);
046        this.idToValue = new HashMap<>(this.capacity);
047        this.valueToId = new LinkedHashMap<>(this.capacity, 0.75f, ACCESS_ORDER) {
048            @Override
049            protected boolean removeEldestEntry(Map.Entry<IdentityKey<V>, Integer> eldest) {
050                if (size() > BidirectionalObjectToIdMapIdentity.this.capacity) {
051                    recycle(eldest.getValue());
052                    return true;
053                }
054                return false;
055            }
056        };
057    }
058
059    @Override
060    public Integer getIdByValue(V value) {
061        lookupKey.ref = value;
062        Integer id = valueToId.get(lookupKey);
063        lookupKey.ref = null;
064        return id;
065    }
066
067    @Override
068    public Integer insertNewEntryOnWrite(V value) {
069        ensureIdAvailable();
070        Integer boxed = idPool.allocate();
071        V existingValue = idToValue.put(boxed, value);
072        if (existingValue != null) {
073            valueToId.remove(IdentityKey.of(existingValue));
074        }
075        valueToId.put(IdentityKey.of(value), boxed);
076        return boxed;
077    }
078
079    @Override
080    public V insertNewEntryOnRead(int id, V value) {
081        Integer boxed = BoxedIds.of(id);
082        idPool.unfree(boxed);
083        V existingValue = idToValue.put(boxed, value);
084        if (existingValue != null) {
085            valueToId.remove(IdentityKey.of(existingValue));
086        }
087        Integer previousId = valueToId.put(IdentityKey.of(value), boxed);
088        if (previousId != null && previousId.intValue() != id) {
089            recycle(previousId);
090        }
091        return existingValue;
092    }
093
094    @Override
095    public V getValueById(int id) {
096        V value = idToValue.get(BoxedIds.of(id));
097        if (value != null) {
098            lookupKey.ref = value;
099            valueToId.get(lookupKey);
100            lookupKey.ref = null;
101        }
102        return value;
103    }
104
105    private void ensureIdAvailable() {
106        if (!idPool.hasFree() && valueToId.size() >= capacity && !valueToId.isEmpty()) {
107            Map.Entry<IdentityKey<V>, Integer> eldest = valueToId.entrySet().iterator().next();
108            valueToId.remove(eldest.getKey());
109            recycle(eldest.getValue());
110        }
111    }
112
113    private void recycle(Integer id) {
114        idToValue.remove(id);
115        idPool.recycle(id);
116    }
117
118    static final class IdentityKey<V> {
119        V ref;
120
121        static <V> IdentityKey<V> of(V ref) {
122            return new IdentityKey<>(ref);
123        }
124
125        IdentityKey(V ref) {
126            this.ref = ref;
127        }
128
129        @Override
130        public int hashCode() {
131            return System.identityHashCode(ref);
132        }
133
134        @Override
135        public boolean equals(Object o) {
136            return o instanceof IdentityKey && ((IdentityKey<?>) o).ref == ref;
137        }
138    }
139}