using System;
using System.Collections.Generic;
namespace MsgReader.Mime.Decode
{
///
/// Contains common operations needed while decoding.
///
internal static class Utility
{
#region RemoveQuotesIfAny
///
/// Remove quotes, if found, around the string.
///
/// Text with quotes or without quotes
/// Text without quotes
/// If is
public static string RemoveQuotesIfAny(string text)
{
if (text == null)
throw new ArgumentNullException(nameof(text));
// Check if there are quotes at both ends and have at least two characters
if (text.Length > 1 && text[0] == '"' && text[text.Length - 1] == '"')
{
// Remove quotes at both ends
return text.Substring(1, text.Length - 2);
}
// If no quotes were found, the text is just returned
return text;
}
#endregion
#region SplitStringWithCharNotInsideQuotes
///
/// Split a string into a list of strings using a specified character.
/// Everything inside quotes are ignored.
///
/// A string to split
/// The character to use to split with
/// A List of strings that was delimited by the character
public static List SplitStringWithCharNotInsideQuotes(string input, char toSplitAt)
{
var elements = new List();
var lastSplitLocation = 0;
var insideQuote = false;
var characters = input.ToCharArray();
for (var i = 0; i < characters.Length; i++)
{
var character = characters[i];
if (character == '\"')
insideQuote = !insideQuote;
// Only split if we are not inside quotes
if (character != toSplitAt || insideQuote) continue;
// We need to split
var length = i - lastSplitLocation;
elements.Add(input.Substring(lastSplitLocation, length));
// Update last split location
// + 1 so that we do not include the character used to split with next time
lastSplitLocation = i + 1;
}
// Add the last part
elements.Add(input.Substring(lastSplitLocation, input.Length - lastSplitLocation));
return elements;
}
#endregion
}
}