/*
 * Copyright 2018 Scytl Secure Electronic Voting SA
 *
 * All rights reserved
 *
 * See our extended copyright notice in *file 'Copyright.txt'
 * which is part of this source code package
 */

package com.scytl.slogger.util;

/**
 * Secure String utilities.
 */
public final class SecureStringUtils {

  private SecureStringUtils() {}

  /**
   * Escapes a given message.
   *
   * @param message the message
   * @return the escaped message.
   */
  public static String escape(String message) {
    int length = message.length();
    boolean endsWithBreak = false;
    if (message.endsWith("\r\n")) {
      length -= 2;
      endsWithBreak = true;
    } else if (message.endsWith("\r") || message.endsWith("\n")) {
      length--;
      endsWithBreak = true;
    }
    StringBuilder escaped = new StringBuilder(length);
    for (int i = 0; i < length; i++) {
      char symbol = message.charAt(i);
      switch (symbol) {
        case '\n':
          escaped.append("(n)");
          break;
        case '\r':
          escaped.append("(r)");
          break;
        case '\b':
          escaped.append("(b)");
          break;
        case '\f':
          escaped.append("(f)");
          break;
        default:
          escaped.append(symbol);
          break;
      }
    }
    if (endsWithBreak) {
      escaped.append('\n');
    }
    return escaped.toString();
  }
}
