StringHeap.cs 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. //
  2. // Author:
  3. // Jb Evain (jbevain@gmail.com)
  4. //
  5. // Copyright (c) 2008 - 2015 Jb Evain
  6. // Copyright (c) 2008 - 2011 Novell, Inc.
  7. //
  8. // Licensed under the MIT/X11 license.
  9. //
  10. using System;
  11. using System.Collections.Generic;
  12. using System.Text;
  13. namespace ILRuntime.Mono.Cecil.Metadata {
  14. class StringHeap : Heap {
  15. readonly Dictionary<uint, string> strings = new Dictionary<uint, string> ();
  16. public StringHeap (byte [] data)
  17. : base (data)
  18. {
  19. }
  20. public string Read (uint index)
  21. {
  22. if (index == 0)
  23. return string.Empty;
  24. string @string;
  25. if (strings.TryGetValue (index, out @string))
  26. return @string;
  27. if (index > data.Length - 1)
  28. return string.Empty;
  29. @string = ReadStringAt (index);
  30. if (@string.Length != 0)
  31. strings.Add (index, @string);
  32. return @string;
  33. }
  34. protected virtual string ReadStringAt (uint index)
  35. {
  36. int length = 0;
  37. int start = (int) index;
  38. for (int i = start; ; i++) {
  39. if (data [i] == 0)
  40. break;
  41. length++;
  42. }
  43. return Encoding.UTF8.GetString (data, start, length);
  44. }
  45. }
  46. }