001    /*
002     * Copyright 2010-2015 JetBrains s.r.o.
003     *
004     * Licensed under the Apache License, Version 2.0 (the "License");
005     * you may not use this file except in compliance with the License.
006     * You may obtain a copy of the License at
007     *
008     * http://www.apache.org/licenses/LICENSE-2.0
009     *
010     * Unless required by applicable law or agreed to in writing, software
011     * distributed under the License is distributed on an "AS IS" BASIS,
012     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013     * See the License for the specific language governing permissions and
014     * limitations under the License.
015     */
016    
017    package org.jetbrains.kotlin.utils;
018    
019    import org.jetbrains.annotations.NotNull;
020    import org.jetbrains.annotations.Nullable;
021    
022    public class WrappedValues {
023        private static final Object NULL_VALUE = new Object() {
024            @Override
025            public String toString() {
026                return "NULL_VALUE";
027            }
028        };
029    
030        private final static class ThrowableWrapper {
031            private final Throwable throwable;
032    
033            private ThrowableWrapper(@NotNull Throwable throwable) {
034                this.throwable = throwable;
035            }
036    
037            @NotNull
038            public Throwable getThrowable() {
039                return throwable;
040            }
041    
042            @Override
043            public String toString() {
044                return throwable.toString();
045            }
046        }
047    
048        private WrappedValues() {
049        }
050    
051        @Nullable
052        @SuppressWarnings("unchecked")
053        public static <V> V unescapeNull(@NotNull Object value) {
054            if (value == NULL_VALUE) return null;
055            return (V) value;
056        }
057    
058        @NotNull
059        public static <V> Object escapeNull(@Nullable V value) {
060            if (value == null) return NULL_VALUE;
061            return value;
062        }
063    
064        @NotNull
065        public static Object escapeThrowable(@NotNull Throwable throwable) {
066            return new ThrowableWrapper(throwable);
067        }
068    
069        @Nullable
070        public static <V> V unescapeExceptionOrNull(@NotNull Object value) {
071            return unescapeNull(unescapeThrowable(value));
072        }
073    
074        @Nullable
075        public static <V> V unescapeThrowable(@Nullable Object value) {
076            if (value instanceof ThrowableWrapper) {
077                throw ExceptionUtilsKt.rethrow(((ThrowableWrapper) value).getThrowable());
078            }
079    
080            //noinspection unchecked
081            return (V) value;
082        }
083    }