001 /*
002 * Java Genetic Algorithm Library (jenetics-7.1.1).
003 * Copyright (c) 2007-2022 Franz Wilhelmstötter
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 *
017 * Author:
018 * Franz Wilhelmstötter (franz.wilhelmstoetter@gmail.com)
019 */
020 package io.jenetics.ext.rewriting;
021
022 import java.io.Externalizable;
023 import java.io.IOException;
024 import java.io.ObjectInput;
025 import java.io.ObjectOutput;
026 import java.io.Serial;
027 import java.io.StreamCorruptedException;
028
029 /**
030 * @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
031 * @version 7.0
032 * @since 5.0
033 */
034 final class SerialProxy implements Externalizable {
035
036 @Serial
037 private static final long serialVersionUID = 1;
038
039 static final byte TREE_PATTERN = 1;
040 static final byte TREE_REWRITE_RULE = 4;
041 static final byte TRS_KEY = 5;
042
043 /**
044 * The type being serialized.
045 */
046 private byte _type;
047
048 /**
049 * The object being serialized.
050 */
051 private Object _object;
052
053 /**
054 * Constructor for deserialization.
055 */
056 public SerialProxy() {
057 }
058
059 /**
060 * Creates an instance for serialization.
061 *
062 * @param type the type
063 * @param object the object
064 */
065 SerialProxy(final byte type, final Object object) {
066 _type = type;
067 _object = object;
068 }
069
070 @Override
071 public void writeExternal(final ObjectOutput out) throws IOException {
072 out.writeByte(_type);
073 switch (_type) {
074 case TREE_PATTERN -> ((TreePattern<?>)_object).write(out);
075 case TREE_REWRITE_RULE -> ((TreeRewriteRule<?>)_object).write(out);
076 case TRS_KEY -> ((TRS<?>)_object).write(out);
077 default -> throw new StreamCorruptedException("Unknown serialized type.");
078 }
079 }
080
081 @Override
082 public void readExternal(final ObjectInput in)
083 throws IOException, ClassNotFoundException
084 {
085 _type = in.readByte();
086 _object = switch (_type) {
087 case TREE_PATTERN -> TreePattern.read(in);
088 case TREE_REWRITE_RULE -> TreeRewriteRule.read(in);
089 case TRS_KEY -> TRS.read(in);
090 default -> throw new StreamCorruptedException("Unknown serialized type.");
091 };
092 }
093
094 @Serial
095 private Object readResolve() {
096 return _object;
097 }
098
099 }
|