/// <summary> /// Writes the character or surrogate pair for the given code point into the buffer. /// </summary> /// <param name="buffer">The buffer into which to write the character(s). This /// may be reallocated if there is not enough space.</param> /// <param name="position">The position in <paramref name="buffer"/> into which to /// write the character(s). The number of characters written will be added.</param> /// <param name="value">A Unicode code point value.</param> private static void _writeCodePoint(ref char[] buffer, ref int position, int value) { if (buffer.Length - position < 2) { DataStructureUtil.expandArray(ref buffer, 2); } if (value > 0xFFFF) { // Split into surrogate pairs. int offsetValue = value - 0x10000; buffer[position] = (char)(0xD800 | (offsetValue >> 10)); buffer[position + 1] = (char)(0xDC00 | (offsetValue & 0x3FF)); position += 2; } else { buffer[position] = (char)value; position++; } }
public static string escape(string str = "undefined") { if (str == null) { return("null"); } int strlen = str.Length; char[] buffer = new char[strlen]; int bufPos = 0, bufLen = 0; for (int i = 0; i < str.Length; i++) { char ch = str[i]; bool noEncode = ((uint)(ch - '0') <= 9) || ((uint)(ch - 'A') <= 25) || ((uint)(ch - 'a') <= 25) || (ch <= 0x7F && ESCAPE_NO_ENCODE.Contains(ch)); if (noEncode) { // No percent encoding if (bufPos == bufLen) { DataStructureUtil.expandArray(ref buffer); bufLen = buffer.Length; } buffer[bufPos++] = ch; continue; } if (ch > 0xFF) { if (bufLen - bufPos < 6) { DataStructureUtil.expandArray(ref buffer, 6); bufLen = buffer.Length; } var bufferSpan = buffer.AsSpan(6); bufferSpan[0] = '%'; bufferSpan[1] = 'u'; URIUtil.byteToHex((byte)(ch >> 8), bufferSpan.Slice(2)); URIUtil.byteToHex((byte)ch, bufferSpan.Slice(4)); bufPos += 6; } else { if (bufLen - bufPos < 3) { DataStructureUtil.expandArray(ref buffer, 3); bufLen = buffer.Length; } buffer[bufPos] = '%'; URIUtil.byteToHex((byte)ch, buffer.AsSpan(bufPos + 1)); bufPos += 3; } } return(new string(buffer, 0, bufPos)); }