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 java.util.Objects; 017 018/** 019 * Restricts objects to types that are cheap and safe to serialize (strings and 020 * primitive wrappers). Anything else is reduced via {@link Object#toString()}. 021 * Used for KVP values and similar free-form fields before Kryo encoding. 022 */ 023public class SafeObjectTransformer { 024 025 /** Sentinel written in place of a null when a non-null object is required. */ 026 final public static String NULL_PROXY = "0<|null|>1"; 027 028 /** 029 * Like {@link #asAllowedObject(Object)}, but maps {@code null} to {@link #NULL_PROXY}. 030 */ 031 static Object asAllowedNonNullObject(Object o) { 032 if (o == null) 033 return NULL_PROXY; 034 035 return asAllowedObject(o); 036 } 037 038 /** 039 * {@code true} if {@code o} can be written by {@link SafeObjectCodec} without 040 * {@link Object#toString()}. {@code o} must not be null. 041 */ 042 static boolean isAllowedType(Object o) { 043 return o instanceof String 044 || o instanceof Integer 045 || o instanceof Long 046 || o instanceof Float 047 || o instanceof Double 048 || o instanceof Short; 049 } 050 051 /** 052 * Returns {@code o} if it is a {@link String} or a numeric wrapper; otherwise 053 * {@code o.toString()}. {@code o} must not be null. 054 */ 055 static Object asAllowedObject(Object o) { 056 Objects.requireNonNull(o); 057 if (isAllowedType(o)) { 058 return o; 059 } 060 return o.toString(); 061 } 062}