Strings
General string utilities.
using System;
using System.Text;
namespace Org.BouncyCastle.Utilities
{
public static class Strings
{
internal static void AppendFromByteArray(StringBuilder sb, byte[] buf, int off, int len)
{
sb.EnsureCapacity(sb.Length + len);
for (int i = 0; i < len; i++) {
sb.Append(Convert.ToChar(buf[off + i]));
}
}
internal static bool IsOneOf(string s, params string[] candidates)
{
foreach (string b in candidates) {
if (s == b)
return true;
}
return false;
}
public static string FromByteArray(byte[] bs)
{
if (bs == null)
throw new ArgumentNullException("bs");
return string.Create(bs.Length, bs, delegate(Span<char> chars, byte[] bytes) {
for (int i = 0; i < chars.Length; i++) {
chars[i] = Convert.ToChar(bytes[i]);
}
});
}
public static string FromByteArray(byte[] buf, int off, int len)
{
Arrays.ValidateSegment(buf, off, len);
return string.Create(len, buf.AsMemory(off, len), delegate(Span<char> chars, Memory<byte> bytes) {
Span<byte> span = bytes.Span;
for (int i = 0; i < chars.Length; i++) {
chars[i] = Convert.ToChar(span[i]);
}
});
}
public static byte[] ToByteArray(char[] cs)
{
byte[] array = new byte[cs.Length];
for (int i = 0; i < array.Length; i++) {
array[i] = Convert.ToByte(cs[i]);
}
return array;
}
public static byte[] ToByteArray(string s)
{
byte[] array = new byte[s.Length];
for (int i = 0; i < array.Length; i++) {
array[i] = Convert.ToByte(s[i]);
}
return array;
}
public static byte[] ToByteArray(ReadOnlySpan<char> cs)
{
byte[] array = new byte[cs.Length];
for (int i = 0; i < array.Length; i++) {
array[i] = Convert.ToByte(cs[i]);
}
return array;
}
public static string FromAsciiByteArray(byte[] bytes)
{
return Encoding.ASCII.GetString(bytes);
}
public static byte[] ToAsciiByteArray(char[] cs)
{
return Encoding.ASCII.GetBytes(cs);
}
public static byte[] ToAsciiByteArray(string s)
{
return Encoding.ASCII.GetBytes(s);
}
public static string FromUtf8ByteArray(byte[] bytes)
{
return Encoding.UTF8.GetString(bytes);
}
public static string FromUtf8ByteArray(byte[] bytes, int index, int count)
{
return Encoding.UTF8.GetString(bytes, index, count);
}
public static byte[] ToUtf8ByteArray(char[] cs)
{
return Encoding.UTF8.GetBytes(cs);
}
public static byte[] ToUtf8ByteArray(string s)
{
return Encoding.UTF8.GetBytes(s);
}
public static byte[] ToUtf8ByteArray(ReadOnlySpan<char> cs)
{
byte[] array = new byte[Encoding.UTF8.GetByteCount(cs)];
Encoding.UTF8.GetBytes(cs, array);
return array;
}
}
}