001/*
002 * Java Genetic Algorithm Library (jenetics-8.0.0).
003 * Copyright (c) 2007-2024 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 */
020package io.jenetics.ext.internal.util;
021
022/**
023 * @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
024 * @version 5.0
025 * @since 5.0
026 */
027public final class Escaper {
028
029        private final char[] _protect;
030        private final char _escape;
031
032
033        public Escaper(final char escape, final char... protect) {
034                _protect = protect.clone();
035                _escape = escape;
036        }
037
038        public String escape(final CharSequence value) {
039                final StringBuilder result = new StringBuilder();
040                for (int i = 0; i < value.length(); ++i) {
041                        final char c = value.charAt(i);
042                        if (isProtectedChar(c)) {
043                                result.append(_escape);
044                        }
045                        result.append(c);
046                }
047
048                return result.toString();
049        }
050
051        private boolean isProtectedChar(final char c) {
052                for (var c1 : _protect) {
053                        if (c == c1) return true;
054                }
055                return false;
056        }
057
058
059        public String unescape(final CharSequence value) {
060                final StringBuilder result = new StringBuilder();
061
062                boolean escaping = false;
063                for (int i = 0; i < value.length(); ++i) {
064                        final char c = value.charAt(i);
065
066                        if (c == _escape &&
067                                !escaping &&
068                                i + 1 < value.length() &&
069                                isProtectedChar(value.charAt(i + 1)))
070                        {
071                                escaping = true;
072                                continue;
073                        }
074
075                        if (escaping) {
076                                escaping = false;
077                        }
078                        result.append(c);
079                }
080
081                return result.toString();
082        }
083
084}