BufferValidator.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. using System;
  2. namespace MECF.Framework.Common.Communications.Tcp.Buffer
  3. {
  4. public class BufferValidator
  5. {
  6. public static void ValidateBuffer(byte[] buffer, int offset, int count,
  7. string bufferParameterName = null,
  8. string offsetParameterName = null,
  9. string countParameterName = null)
  10. {
  11. if (buffer == null)
  12. {
  13. throw new ArgumentNullException(!string.IsNullOrEmpty(bufferParameterName) ? bufferParameterName : "buffer");
  14. }
  15. if (offset < 0 || offset > buffer.Length)
  16. {
  17. throw new ArgumentOutOfRangeException(!string.IsNullOrEmpty(offsetParameterName) ? offsetParameterName : "offset");
  18. }
  19. if (count < 0 || count > (buffer.Length - offset))
  20. {
  21. throw new ArgumentOutOfRangeException(!string.IsNullOrEmpty(countParameterName) ? countParameterName : "count");
  22. }
  23. }
  24. public static void ValidateArraySegment<T>(ArraySegment<T> arraySegment, string arraySegmentParameterName = null)
  25. {
  26. if (arraySegment.Array == null)
  27. {
  28. throw new ArgumentNullException((!string.IsNullOrEmpty(arraySegmentParameterName) ? arraySegmentParameterName : "arraySegment") + ".Array");
  29. }
  30. if (arraySegment.Offset < 0 || arraySegment.Offset > arraySegment.Array.Length)
  31. {
  32. throw new ArgumentOutOfRangeException((!string.IsNullOrEmpty(arraySegmentParameterName) ? arraySegmentParameterName : "arraySegment") + ".Offset");
  33. }
  34. if (arraySegment.Count < 0 || arraySegment.Count > (arraySegment.Array.Length - arraySegment.Offset))
  35. {
  36. throw new ArgumentOutOfRangeException((!string.IsNullOrEmpty(arraySegmentParameterName) ? arraySegmentParameterName : "arraySegment") + ".Count");
  37. }
  38. }
  39. }
  40. }