001/*
002 * Copyright (c) 2012-2017 Institut National des Sciences Appliquées de Lyon (INSA-Lyon)
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the Eclipse Public License v1.0
006 * which accompanies this distribution, and is available at
007 * http://www.eclipse.org/legal/epl-v10.html
008 */
009
010package org.eclipse.golo.compiler.utils;
011
012public final class StringUnescaping {
013
014  private StringUnescaping() {
015    //utility class
016  }
017
018  public static String unescape(String str) {
019    StringBuilder sb = new StringBuilder(str.length());
020    for (int i = 0; i < str.length(); i++) {
021      char ch = str.charAt(i);
022      if (ch == '\\') {
023        char nextChar = (i == str.length() - 1) ? '\\' : str.charAt(i + 1);
024        switch (nextChar) {
025          case 'u':
026            ch = (char) Integer.parseInt(str.substring(i + 2, i + 6), 16);
027            i = i + 4;
028            break;
029          case '\\':
030            ch = '\\';
031            break;
032          case 'b':
033            ch = '\b';
034            break;
035          case 'f':
036            ch = '\f';
037            break;
038          case 'n':
039            ch = '\n';
040            break;
041          case 'r':
042            ch = '\r';
043            break;
044          case 't':
045            ch = '\t';
046            break;
047          case '\"':
048            ch = '\"';
049            break;
050          case '\'':
051            ch = '\'';
052            break;
053          default:
054            // not a special char, do nothing
055            break;
056        }
057        i++;
058      }
059      sb.append(ch);
060    }
061    return sb.toString();
062  }
063}