The Labs \ Source Viewer \ SSCLI \ System \ UnSafeCharBuffer

  1. // ==++==
  2. //
  3. //
  4. // Copyright (c) 2006 Microsoft Corporation. All rights reserved.
  5. //
  6. // The use and distribution terms for this software are contained in the file
  7. // named license.txt, which can be found in the root of this distribution.
  8. // By using this software in any fashion, you are agreeing to be bound by the
  9. // terms of this license.
  10. //
  11. // You must not remove this notice, or any other, from this software.
  12. //
  13. //
  14. // ==--==
  15. /*============================================================
  16. **
  17. ** Class:  UnSafeBuffer
  18. **
  19. ** Purpose: A class to detect incorrect usage of UnSafeBuffer
  20. **
  21. **
  22. ===========================================================*/
  23. namespace System
  24. {
  25.     using System.Diagnostics;
  26.    
  27.     unsafe internal struct UnSafeCharBuffer
  28.     {
  29.         char* m_buffer;
  30.         int m_totalSize;
  31.         int m_length;
  32.        
  33.         public UnSafeCharBuffer(char* buffer, int bufferSize)
  34.         {
  35.             BCLDebug.Assert(buffer != null, "buffer pointer can't be null.");
  36.             BCLDebug.Assert(bufferSize >= 0, "buffer size can't be negative.");
  37.             m_buffer = buffer;
  38.             m_totalSize = bufferSize;
  39.             m_length = 0;
  40.         }
  41.        
  42.         public void AppendString(string stringToAppend)
  43.         {
  44.             if (String.IsNullOrEmpty(stringToAppend)) {
  45.                 return;
  46.             }
  47.            
  48.             if ((m_totalSize - m_length) < stringToAppend.Length) {
  49.                 throw new IndexOutOfRangeException();
  50.             }
  51.            
  52.             fixed (char* pointerToString = stringToAppend) {
  53.                 Buffer.memcpyimpl((byte*)pointerToString, (byte*)(m_buffer + m_length), stringToAppend.Length * sizeof(char));
  54.             }
  55.            
  56.             m_length += stringToAppend.Length;
  57.             BCLDebug.Assert(m_length <= m_totalSize, "Buffer has been overflowed!");
  58.         }
  59.        
  60.         public int Length {
  61.             get { return m_length; }
  62.         }
  63.     }
  64. }

Developer Fusion