ByteArrayHelperWithString.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. //----------------------------------------------------------------
  2. // Copyright (c) Microsoft Corporation. All rights reserved.
  3. //----------------------------------------------------------------
  4. namespace System.Runtime.Serialization.Json
  5. {
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Text;
  9. using System.Xml;
  10. class ByteArrayHelperWithString : ArrayHelper<string, byte>
  11. {
  12. static public readonly ByteArrayHelperWithString Instance = new ByteArrayHelperWithString();
  13. internal void WriteArray(XmlWriter writer, byte[] array, int offset, int count)
  14. {
  15. XmlJsonReader.CheckArray(array, offset, count);
  16. writer.WriteAttributeString(string.Empty, JsonGlobals.typeString, string.Empty, JsonGlobals.arrayString);
  17. for (int i = 0; i < count; i++)
  18. {
  19. writer.WriteStartElement(JsonGlobals.itemString, string.Empty);
  20. writer.WriteAttributeString(string.Empty, JsonGlobals.typeString, string.Empty, JsonGlobals.numberString);
  21. writer.WriteValue((int)array[offset + i]);
  22. writer.WriteEndElement();
  23. }
  24. }
  25. protected override int ReadArray(XmlDictionaryReader reader, string localName, string namespaceUri, byte[] array, int offset, int count)
  26. {
  27. XmlJsonReader.CheckArray(array, offset, count);
  28. int actual = 0;
  29. while (actual < count && reader.IsStartElement(JsonGlobals.itemString, string.Empty))
  30. {
  31. array[offset + actual] = ToByte(reader.ReadElementContentAsInt());
  32. actual++;
  33. }
  34. return actual;
  35. }
  36. protected override void WriteArray(XmlDictionaryWriter writer, string prefix, string localName, string namespaceUri, byte[] array, int offset, int count)
  37. {
  38. WriteArray(writer, array, offset, count);
  39. }
  40. void ThrowConversionException(string value, string type)
  41. {
  42. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.XmlInvalidConversion, value, type)));
  43. }
  44. byte ToByte(int value)
  45. {
  46. if (value < byte.MinValue || value > byte.MaxValue)
  47. {
  48. ThrowConversionException(value.ToString(System.Globalization.NumberFormatInfo.CurrentInfo), "Byte");
  49. }
  50. return (byte)value;
  51. }
  52. }
  53. }