Slice.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #region Copyright notice and license
  2. // Copyright 2019 The gRPC Authors
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. #endregion
  16. using System;
  17. using System.Runtime.InteropServices;
  18. using System.Threading;
  19. using Grpc.Core.Utils;
  20. namespace Grpc.Core.Internal
  21. {
  22. /// <summary>
  23. /// Slice of native memory.
  24. /// Rough equivalent of grpc_slice (but doesn't support inlined slices, just a pointer to data and length)
  25. /// </summary>
  26. internal struct Slice
  27. {
  28. private readonly IntPtr dataPtr;
  29. private readonly int length;
  30. public Slice(IntPtr dataPtr, int length)
  31. {
  32. this.dataPtr = dataPtr;
  33. this.length = length;
  34. }
  35. public int Length => length;
  36. public Span<byte> ToSpanUnsafe()
  37. {
  38. unsafe
  39. {
  40. return new Span<byte>((byte*) dataPtr, length);
  41. }
  42. }
  43. /// <summary>
  44. /// Returns a <see cref="System.String"/> that represents the current <see cref="Grpc.Core.Internal.Slice"/>.
  45. /// </summary>
  46. public override string ToString()
  47. {
  48. return string.Format("[Slice: dataPtr={0}, length={1}]", dataPtr, length);
  49. }
  50. }
  51. }