public static unsafe void Main() { char[] characters = { 'H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!', '\u0000' }; String value; fixed(char *charPtr = characters) { int length = 0; Char *iterator = charPtr; while (*iterator != '\x0000') { if (*iterator == '!' || *iterator == '.') { break; } iterator++; length++; } value = new String(charPtr, 0, length); } Console.WriteLine(value); }
// This method is unsafe because it accesses unmanaged memory private unsafe static void DisplaySecureString(SecureString ss) { Char *pc = null; try { // Decrypt the SecureString into an unmanaged memory buffer pc = (Char *)Marshal.SecureStringToCoTaskMemUnicode(ss); // Access the unmanaged memory buffer that // contains the decrypted SecureString for (Int32 index = 0; pc[index] != 0; index++) { Console.Write(pc[index]); } } finally { // Make sure we zero and free the unmanaged memory buffer that contains // the decrypted SecureString characters if (pc != null) { Marshal.ZeroFreeCoTaskMemUnicode((IntPtr)pc); } } }
public void Dispose() { _P = null; _End = 0; _IsDisposed = true; _Current = '\0'; }
public void Dispose() { _p = null; _end = 0; _isDisposed = true; Current = '\0'; }
/// <summary> /// 获得指定字符串中N个随机的字符 /// </summary> /// <param name="str">字符串</param> /// <param name="length">新字符串的长度</param> /// <returns></returns> unsafe public static string GetRandomText(string str, int length) { if (str == null) { throw new ArgumentNullException("str"); } if (str.Length == 0) { throw new ArgumentException("str", "str 为空字符"); } if (length < 1) { return(String.Empty); } var len = length; var chs = new char[length]; var dl = str.Length; var random = new Random(Interlocked.Increment(ref _seed)); fixed(Char *p_chs = chs) { Char *p_tempchs = p_chs; while (len > 0) { *p_tempchs++ = str[random.Next(0, dl)]; len--; } return(new String(p_chs, 0, length)); } }
unsafe public string GenerationText(int length) { if (length < 1 || Count < 1) { return(String.Empty); } var els = _elements; var dc = els.Count; var random = new Random(Interlocked.Increment(ref ValidateImageHelper._seed)); var chs = new char[length]; var len = length; /* 此外还可以通过循环展开的方式来优化 */ fixed(Char *p_chs = chs) { Char *p_tempchs = p_chs; while (len > 0) { var di = len % dc; //取得当前使用的元素索引 var el = els[di]; //取得相应的元素 * p_tempchs++ = el[random.Next(0, el.Length)]; //在元素内随机取得一个字符 len--; } return(new String(p_chs, 0, length)); } }
public NumberBuffer(Byte *stackBuffer) { baseAddress = stackBuffer; this.digits = (((Char *)stackBuffer) + 6); this.precision = 0; this.scale = 0; this.sign = false; }
public NumberBuffer(Byte* stackBuffer) { this.baseAddress = stackBuffer; this.digits = (((Char*)stackBuffer) + 6); this.precision = 0; this.scale = 0; this.sign = false; }
public unsafe static bool SecureStringEquals(SecureString s1, SecureString s2) { /* Since short ids are SHORT we can not use a hashing function to save them because the collison risk is too hight * So we have to encrypte them * In order to check if two short id are the same we have to decrypte them and compare them * (because the encryptation result change even if the input is the same * The function return true if two encrypted string are equal, else fasle */ if ((s1 == null || s2 == null) || (s1.Length != s2.Length)) { return(false); } //Compare all char in the string in a secure way IntPtr bstr1 = IntPtr.Zero; IntPtr bstr2 = IntPtr.Zero; RuntimeHelpers.PrepareConstrainedRegions(); try { bstr1 = Marshal.SecureStringToBSTR(s1);//create secure space in memory bstr2 = Marshal.SecureStringToBSTR(s2); unsafe { for (Char *ptr1 = (Char *)bstr1.ToPointer(), ptr2 = (Char *)bstr2.ToPointer(); *ptr1 != 0 && *ptr2 != 0; ++ptr1, ++ptr2) { if (*ptr1 != *ptr2)//compare char using pointer to the secure space in memory { return(false); } } } return(true); } finally { /* In fact all the following insctruction remove from memroy the Securestring (and not the copy of the securestring) * if (bstr1 != IntPtr.Zero) * { * Marshal.ZeroFreeBSTR(bstr1);//set all the secure space to a standard value * } * * if (bstr2 != IntPtr.Zero) * { * Marshal.ZeroFreeBSTR(bstr2); * } * * s1.Dispose(); * s2.Dispose();*/ } }
/// <summary> /// Compute the number of bytes encoded in the specified Base 64 char array: /// Walk the entire input counting white spaces and padding chars, then compute result length /// based on 3 bytes per 4 chars. /// </summary> public static unsafe Int32 FromBase64_ComputeResultLength(Char *inputPtr, Int32 inputLength) { const UInt32 intEq = (UInt32)'='; const UInt32 intSpace = (UInt32)' '; Debug.Assert(0 <= inputLength); Char *inputEndPtr = inputPtr + inputLength; Int32 usefulInputLength = inputLength; Int32 padding = 0; while (inputPtr < inputEndPtr) { UInt32 c = (UInt32)(*inputPtr); inputPtr++; // We want to be as fast as possible and filter out spaces with as few comparisons as possible. // We end up accepting a number of illegal chars as legal white-space chars. // This is ok: as soon as we hit them during actual decode we will recognise them as illegal and throw. if (c <= intSpace) { usefulInputLength--; } else if (c == intEq) { usefulInputLength--; padding++; } } Debug.Assert(0 <= usefulInputLength); // For legal input, we can assume that 0 <= padding < 3. But it may be more for illegal input. // We will notice it at decode when we see a '=' at the wrong place. Debug.Assert(0 <= padding); // Perf: reuse the variable that stored the number of '=' to store the number of bytes encoded by the // last group that contains the '=': if (padding != 0) { if (padding == 1) { padding = 2; } else if (padding == 2) { padding = 1; } else { throw new FormatException("SR.Format_BadBase64Char"); } } // Done: return((usefulInputLength / 4) * 3 + padding); }
// Modified from http://social.msdn.microsoft.com/Forums/en-US/clr/thread/555a5cb6-790d-415d-b079-00d62b3a9632/ public override bool Equals(object rhs) { // Ensure we're comparing to another RMSecureString if (!(rhs is RMSecureString)) { return(false); } // Easy check -- see if lengths differ if (this.Length != ((RMSecureString)rhs).Length) { return(false); } IntPtr bstr1 = IntPtr.Zero; IntPtr bstr2 = IntPtr.Zero; RuntimeHelpers.PrepareConstrainedRegions(); try { if (_SecureStringSupported) { bstr1 = Marshal.SecureStringToBSTR((SecureString)_SecureString); bstr2 = Marshal.SecureStringToBSTR((SecureString)((RMSecureString)rhs)._SecureString); } else { bstr1 = Marshal.StringToBSTR(((StringBuilder)_SecureString).ToString()); bstr2 = Marshal.StringToBSTR(((StringBuilder)((RMSecureString)rhs)._SecureString).ToString()); } unsafe { for (Char *ptr1 = (Char *)bstr1.ToPointer(), ptr2 = (Char *)bstr2.ToPointer(); *ptr1 != 0 && *ptr2 != 0; ++ptr1, ++ptr2) { if (*ptr1 != *ptr2) { return(false); } } } return(true); } finally { if (bstr1 != IntPtr.Zero) { Marshal.ZeroFreeBSTR(bstr1); } if (bstr2 != IntPtr.Zero) { Marshal.ZeroFreeBSTR(bstr2); } } }
/// <summary> /// Liefert den Wert (und neuen Offset) von der angegebenen Stelle im Byte-Array. /// </summary> /// <param name="Array"></param> /// <param name="Offset">Position, ab der gelesen wird.</param> unsafe static public (Char, Int32) CopyCharOffset(this byte [] Array, Int32 Offset) { fixed(byte *ptr = Array) { Char *vpChar = (Char *)(ptr + Offset); return(*vpChar, Offset + sizeof(Char)); } }
/// <summary> /// Kopiert die Werte einzeln via *ptr++. /// </summary> /// <param name="Source"></param> /// <param name="Target"></param> /// <param name="Length"></param> unsafe static public void CopyChars(Char *Source, Char *Target, int Length) { for (int i = 0; i < Length; i++) { *Target = *Source; // Source++; Target++; } }
/// <summary> /// Liefert den Wert von der angegebenen Stelle im Byte-Array. /// </summary> /// <param name="Array"></param> /// <param name="Offset"></param> unsafe static public Char CopyChar(this byte [] Array, Int32 Offset) { fixed(byte *ptr = Array) { Char *vpChar = (Char *)(ptr + Offset); return(*vpChar); } }
/// <inheritdoc/> public override unsafe Boolean TryDecode(ReadOnlySpan <Char> text, Span <Byte> output, out Int32 numBytesWritten) { unchecked { Int32 textLen = text.Length; if (textLen == 0) { numBytesWritten = 0; return(true); } if ((textLen & 1) != 0) { numBytesWritten = 0; return(false); } Int32 outputLen = textLen / 2; if (output.Length < outputLen) { numBytesWritten = 0; return(false); } ReadOnlySpan <Byte> table = Alphabet.ReverseLookupTable; fixed(Byte *outputPtr = output) fixed(Char * textPtr = text) { Byte *pOutput = outputPtr; Char *pInput = textPtr; Char *pEnd = pInput + textLen; while (pInput != pEnd) { Int32 b1 = table[pInput[0]] - 1; if (b1 < 0) { throw new ArgumentException($"Invalid hex character: {pInput[0]}"); } Int32 b2 = table[pInput[1]] - 1; if (b2 < 0) { throw new ArgumentException($"Invalid hex character: {pInput[1]}"); } *pOutput++ = (Byte)(b1 << 4 | b2); pInput += 2; } } numBytesWritten = outputLen; return(true); } }
private unsafe static Boolean HexNumberToUInt32(ref NumberBuffer number, ref UInt32 value) { Int32 i = number.scale; if (i > UInt32Precision || i < number.precision) { return(false); } Char *p = number.digits; Debug.Assert(p != null, ""); UInt32 n = 0; while (--i >= 0) { if (n > ((UInt32)0xFFFFFFFF / 16)) { return(false); } n *= 16; if (*p != '\0') { UInt32 newN = n; if (*p != '\0') { if (*p >= '0' && *p <= '9') { newN += (UInt32)(*p - '0'); } else { if (*p >= 'A' && *p <= 'F') { newN += (UInt32)((*p - 'A') + 10); } else { Debug.Assert(*p >= 'a' && *p <= 'f', ""); newN += (UInt32)((*p - 'a') + 10); } } p++; } // Detect an overflow here... if (newN < n) { return(false); } n = newN; } } value = n; return(true); }
private static unsafe void Decode(Int32 length, Char *source, Byte *target) { fixed(Byte *map = &Reversed[0]) { for (int i = 0; i < length; i++) { target[i] = map[source[i] - '!']; } } }
/// <summary> /// Kopiert den Wert an die angegebene Stelle in das Byte-Array. /// </summary> /// <param name="Array"></param> /// <param name="Offset">Position, ab der geschrieben wird. Erhöht sich um die Anzhal der gelesenen Bytes!</param> /// <param name="Value"></param> unsafe static public void CopyChar(this byte [] Array, ref Int32 Offset, Char Value) { fixed(byte *ptr = Array) { Char *vp = (Char *)(ptr + Offset); *vp = Value; Offset += sizeof(Char); } }
public static string protect(SecureString s1) { if (s1 == null) { return(""); } IntPtr bstr1 = IntPtr.Zero; RuntimeHelpers.PrepareConstrainedRegions(); byte[] data = new byte[] { }; string insecure_s1 = ""; try { bstr1 = Marshal.SecureStringToBSTR(s1);//create secure space in memory unsafe { for (Char *ptr1 = (Char *)bstr1.ToPointer(); *ptr1 != 0; ++ptr1) { insecure_s1 += *ptr1; } } data = Encoding.Unicode.GetBytes(insecure_s1); // Encrypt the data using DataProtectionScope.CurrentUser. The result can be decrypted // only by the same current user. byte[] encryptedData = ProtectedData.Protect(data, s_aditionalEntropy, DataProtectionScope.CurrentUser); string SencryptedData = Convert.ToBase64String(encryptedData); Array.Clear(encryptedData, 0, encryptedData.Length); Array.Clear(data, 0, data.Length); return(SencryptedData); } catch { return(null); } finally { if (bstr1 != IntPtr.Zero) { Marshal.ZeroFreeBSTR(bstr1);//set all the secure space to a standard value } s1.Dispose(); Array.Clear(data, 0, data.Length); } }
internal unsafe static Char *ToStringReverse(Char *to, UInt64 x, uint n) { do { // This is to make the code generator generate 1 DIV instead of 2 UInt64 old = x + '0'; x /= 10U; *to-- = (char)(old - x * 10U); // = [old - new * 10] } while (n-- > 0); return(to); }
/// <summary> /// Kopiert den Wert an die angegebene Stelle in das Byte-Array und liefert den neuen Offset zurück. /// </summary> /// <param name="Array"></param> /// <param name="Offset"></param> /// <param name="Value"></param> /// <returns>Liefert den neuen Offset.</returns> unsafe static public Int32 CopyChar(this byte [] Array, Int32 Offset, Char Value) { fixed(byte *ptr = Array) { Char *vp = (Char *)(ptr + Offset); *vp = Value; } return(Offset + sizeof(Char)); }
/// <summary> /// Liefert die Bytes ab der Stelle <paramref name="Offset"/> als Wert. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="Array"></param> /// <param name="Offset">Position, ab der gelesen wird. Erhöht sich um die Anzhal der gelesenen Bytes!</param> /// <returns></returns> unsafe static public dynamic CopyValue <T> (this byte [] Array, ref Int32 Offset) where T : unmanaged { try { fixed(byte *ptr = Array) { switch (Type.GetTypeCode(typeof(T))) { case TypeCode.SByte: SByte *vpSByte = (SByte *)(ptr + Offset); return(*vpSByte); case TypeCode.Byte: Byte *vpByte = (Byte *)(ptr + Offset); return(*vpByte); case TypeCode.Int16: Int16 *vpInt16 = (Int16 *)(ptr + Offset); return(*vpInt16); case TypeCode.UInt16: UInt16 *vpUInt16 = (UInt16 *)(ptr + Offset); return(*vpUInt16); case TypeCode.Int32: Int32 *vpInt32 = (Int32 *)(ptr + Offset); return(*vpInt32); case TypeCode.UInt32: UInt32 *vpUInt32 = (UInt32 *)(ptr + Offset); return(*vpUInt32); case TypeCode.Int64: Int64 *vpInt64 = (Int64 *)(ptr + Offset); return(*vpInt64); case TypeCode.UInt64: UInt64 *vpUInt64 = (UInt64 *)(ptr + Offset); return(*vpUInt64); case TypeCode.Char: Char *vpChar = (Char *)(ptr + Offset); return(*vpChar); case TypeCode.Boolean: Boolean *vpBoolean = (Boolean *)(ptr + Offset); return(*vpBoolean); } } } finally { Offset += sizeof(T); } throw new Exception("Not implemented!"); }
public static unsafe void Utf8ToUtf16(Byte *src, Char *dest, UInt32 length) { for (int i = 0; i < length; i++) { if (src[i] > 127) { throw new NotImplementedException("Utf8 not fully implemented yet"); } dest[i] = (Char)src[i]; } }
/// <summary> 关闭当前实例 /// <para> /// 该行为将清空所有缓冲区中的内容, /// 并阻止除Ready,Close以外的方法调用,直到再次调用Ready方法 /// </para> /// </summary> public void Close() { _buffer[0] = _buffer[1] = _buffer[2] = _buffer[3] = _buffer[4] = _buffer[5] = _buffer[6] = _buffer[7] = null; _length = 0; _position = 0; _endPosition = int.MaxValue; _current = null; }
/// <summary> 由于调用对象将内存指针固定后,通知当前实例指针准备就绪 /// </summary> /// <param name="point">内存指针</param> /// <param name="length">一级缓冲长度0~65536</param> /// <returns></returns> public UnsafeStringWriter Ready(Char *point, ushort length) { if (point == null) { throw new ArgumentNullException("point"); } Close(); _endPosition = length - 1; _current = point; return(this); }
/// <summary> 关闭当前实例 /// <para> /// 该行为将清空所有缓冲区中的内容, /// 并阻止除Ready,Close以外的方法调用,直到再次调用Ready方法 /// </para> /// </summary> public void Close() { _Buffer[0] = _Buffer[1] = _Buffer[2] = _Buffer[3] = _Buffer[4] = _Buffer[5] = _Buffer[6] = _Buffer[7] = null; _Length = 0; _Position = 0; _EndPosition = int.MaxValue; p = null; }
/// <summary> /// Determines whether two SecureString objects contain the same contents /// </summary> /// <param name="s1">A SecureString</param> /// <param name="s2">A SecureString to compare</param> /// <returns>True if the SecureString objects contain the same contents</returns> public static bool Matches(this SecureString s1, SecureString s2) { if (s1 == null) { throw new ArgumentNullException("s1"); } if (s2 == null) { throw new ArgumentNullException("s2"); } if (s1.Length != s2.Length) { return(false); } IntPtr bstr1 = IntPtr.Zero; IntPtr bstr2 = IntPtr.Zero; RuntimeHelpers.PrepareConstrainedRegions(); try { bstr1 = Marshal.SecureStringToBSTR(s1); bstr2 = Marshal.SecureStringToBSTR(s2); unsafe { for (Char *ptr1 = (Char *)bstr1.ToPointer(), ptr2 = (Char *)bstr2.ToPointer(); *ptr1 != 0 && *ptr2 != 0; ++ptr1, ++ptr2) { if (*ptr1 != *ptr2) { return(false); } } } return(true); } finally { if (bstr1 != IntPtr.Zero) { Marshal.ZeroFreeBSTR(bstr1); } if (bstr2 != IntPtr.Zero) { Marshal.ZeroFreeBSTR(bstr2); } } }
public static unsafe void AsciiToUtf16(Byte *src, Char *dest, UInt32 length) { for (int i = 0; i < length; i++) { // TODO: should I be checking this? if (src[i] > 127) { throw new FormatException("Called AsciiToUtf16 on a string with non-ascii characters"); } dest[i] = (Char)src[i]; } }
internal static unsafe void ReplaceChars(String source, Int32 position, Int32 count, Char replacementChar) { fixed(Char *pStr = source) { Char *ch = pStr + position; while (count > 0) { *ch = replacementChar; ch++; count--; } } }
/// <summary> /// Liefert den Wert von der angegebenen Stelle im Byte-Array. /// </summary> /// <param name="Array"></param> /// <param name="Offset">Position, ab der geschrieben wird. Erhöht sich um die Anzhal der gelesenen Bytes!</param> unsafe static public Char CopyChar(this byte [] Array, ref Int32 Offset) { try { fixed(byte *ptr = Array) { Char *vpChar = (Char *)(ptr + Offset); return(*vpChar); } } finally { Offset += sizeof(Char); } }
private static unsafe IList <WaitChainNode> BytesToWaitChainNodeInfoList(Byte[] bytes) { List <WaitChainNode> chain = new List <WaitChainNode>(); for (Int32 index = 0; index < bytes.Length; index += c_SizeOfWaitChainNode) { WctObjectType type = (WctObjectType)BitConverter.ToInt32(bytes, index + 0); WctObjectStatus status = (WctObjectStatus)BitConverter.ToInt32(bytes, index + 4); WaitChainNode wcni; switch (type) { case WctObjectType.CriticalSection: case WctObjectType.Mutex: String name = null; fixed(Byte *pb = &bytes[index + 8]) { Char *pc = (Char *)pb; // Find the first 0 character in the name Int32 length = 0; for (; (pc[length] != 0) && (length < c_ObjectNameLength); length++) { ; } if (length > 0) { name = new String(pc, 0, length); } } Int64 timeout = BitConverter.ToInt64(bytes, index + 8 + (c_ObjectNameLength * 2)); Boolean alertable = BitConverter.ToBoolean(bytes, index + 8 + (c_ObjectNameLength * 2) + 8); wcni = new WaitChainNode(type, status, name, timeout, alertable); break; default: Int32 processId = BitConverter.ToInt32(bytes, index + 8); Int32 threadId = BitConverter.ToInt32(bytes, index + 12); // Can be 0 Int32 waitTime = BitConverter.ToInt32(bytes, index + 16); Int32 contextSwitches = BitConverter.ToInt32(bytes, index + 20); wcni = new WaitChainNode(type, status, processId, threadId, waitTime, contextSwitches); break; } chain.Add(wcni); } return(chain); }
/// <summary> 由于调用对象将内存指针固定后,通知当前实例指针准备就绪 /// </summary> /// <param name="point">内存指针</param> /// <param name="length">一级缓冲长度0~65536</param> /// <returns></returns> public UnsafeStringWriter Ready(Char* point, ushort length) { if (point == null) { throw new ArgumentNullException("point"); } Close(); _endPosition = length - 1; _current = point; return this; }
public void Dispose() { _p = null; _end = 0; _isDisposed = true; Current = '\0'; }
public UnsafeJsonReader(Char* origin, int length) { if (origin == null) { throw new ArgumentNullException("origin"); } if (length <= 0) { throw new ArgumentOutOfRangeException("length"); } _p = origin; _length = length; _end = length - 1; _position = 0; Current = *origin; }
/// <summary> 关闭当前实例 /// <para> /// 该行为将清空所有缓冲区中的内容, /// 并阻止除Ready,Close以外的方法调用,直到再次调用Ready方法 /// </para> /// </summary> public void Close() { _buffer[0] = _buffer[1] = _buffer[2] = _buffer[3] = _buffer[4] = _buffer[5] = _buffer[6] = _buffer[7] = null; _length = 0; _position = 0; _endPosition = int.MaxValue; _current = null; }