ByteStack.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. //------------------------------------------------------------------------------
  2. // <copyright file="ByteStack.cs" company="Microsoft">
  3. // Copyright (c) Microsoft Corporation. All rights reserved.
  4. // </copyright>
  5. // <owner current="true" primary="true">Microsoft</owner>
  6. //------------------------------------------------------------------------------
  7. using System;
  8. namespace System.Xml {
  9. // This stack is designed to minimize object creation for the
  10. // objects being stored in the stack by allowing them to be
  11. // re-used over time. It basically pushes the objects creating
  12. // a high water mark then as Pop() is called they are not removed
  13. // so that next time Push() is called it simply returns the last
  14. // object that was already on the stack.
  15. internal class ByteStack {
  16. private byte[] stack;
  17. private int growthRate;
  18. private int top;
  19. private int size;
  20. public ByteStack(int growthRate) {
  21. this.growthRate = growthRate;
  22. top = 0;
  23. stack = new byte[growthRate];
  24. size = growthRate;
  25. }
  26. public void Push(byte data) {
  27. if (size == top) {
  28. byte[] newstack = new byte[size + growthRate];
  29. if (top > 0) {
  30. Buffer.BlockCopy(stack, 0, newstack, 0, top);
  31. }
  32. stack = newstack;
  33. size += growthRate;
  34. }
  35. stack[top++] = data;
  36. }
  37. public byte Pop() {
  38. if (top > 0) {
  39. return stack[--top];
  40. } else {
  41. return 0;
  42. }
  43. }
  44. public byte Peek() {
  45. if (top > 0) {
  46. return stack[top - 1];
  47. } else {
  48. return 0;
  49. }
  50. }
  51. public int Length {
  52. get {
  53. return top;
  54. }
  55. }
  56. }
  57. }