ObjectReferenceStack.cs 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. //------------------------------------------------------------
  2. // Copyright (c) Microsoft Corporation. All rights reserved.
  3. //------------------------------------------------------------
  4. namespace System.Runtime.Serialization
  5. {
  6. using System;
  7. using System.Xml;
  8. using System.Collections.Generic;
  9. struct ObjectReferenceStack
  10. {
  11. const int MaximumArraySize = 16;
  12. const int InitialArraySize = 4;
  13. int count;
  14. object[] objectArray;
  15. bool[] isReferenceArray;
  16. Dictionary<object, object> objectDictionary;
  17. internal void Push(object obj)
  18. {
  19. if (objectArray == null)
  20. {
  21. objectArray = new object[InitialArraySize];
  22. objectArray[count++] = obj;
  23. }
  24. else if (count < MaximumArraySize)
  25. {
  26. if (count == objectArray.Length)
  27. Array.Resize<object>(ref objectArray, objectArray.Length * 2);
  28. objectArray[count++] = obj;
  29. }
  30. else
  31. {
  32. if (objectDictionary == null)
  33. objectDictionary = new Dictionary<object, object>();
  34. objectDictionary.Add(obj, null);
  35. count++;
  36. }
  37. }
  38. internal void EnsureSetAsIsReference(object obj)
  39. {
  40. if (count == 0)
  41. return;
  42. if (count > MaximumArraySize)
  43. {
  44. if (objectDictionary == null)
  45. {
  46. Fx.Assert("Object reference stack in invalid state");
  47. }
  48. objectDictionary.Remove(obj);
  49. }
  50. else
  51. {
  52. if ((objectArray != null) && objectArray[count - 1] == obj)
  53. {
  54. if (isReferenceArray == null)
  55. {
  56. isReferenceArray = new bool[InitialArraySize];
  57. }
  58. else if (count == isReferenceArray.Length)
  59. {
  60. Array.Resize<bool>(ref isReferenceArray, isReferenceArray.Length * 2);
  61. }
  62. isReferenceArray[count - 1] = true;
  63. }
  64. }
  65. }
  66. internal void Pop(object obj)
  67. {
  68. if (count > MaximumArraySize)
  69. {
  70. if (objectDictionary == null)
  71. {
  72. Fx.Assert("Object reference stack in invalid state");
  73. }
  74. objectDictionary.Remove(obj);
  75. }
  76. count--;
  77. }
  78. internal bool Contains(object obj)
  79. {
  80. int currentCount = count;
  81. if (currentCount > MaximumArraySize)
  82. {
  83. if (objectDictionary != null && objectDictionary.ContainsKey(obj))
  84. return true;
  85. currentCount = MaximumArraySize;
  86. }
  87. for (int i = (currentCount - 1); i >= 0; i--)
  88. {
  89. if (Object.ReferenceEquals(obj, objectArray[i]) && isReferenceArray != null && !isReferenceArray[i])
  90. return true;
  91. }
  92. return false;
  93. }
  94. internal int Count
  95. {
  96. get { return count; }
  97. }
  98. }
  99. }