The Labs \ Source Viewer \ SSCLI \ System.Xml \ ByteStack

  1. //------------------------------------------------------------------------------
  2. // <copyright file="ByteStack.cs" company="Microsoft">
  3. //
  4. // Copyright (c) 2006 Microsoft Corporation. All rights reserved.
  5. //
  6. // The use and distribution terms for this software are contained in the file
  7. // named license.txt, which can be found in the root of this distribution.
  8. // By using this software in any fashion, you are agreeing to be bound by the
  9. // terms of this license.
  10. //
  11. // You must not remove this notice, or any other, from this software.
  12. //
  13. // </copyright>
  14. //------------------------------------------------------------------------------
  15. using System;
  16. namespace System.Xml
  17. {
  18.    
  19.     // This stack is designed to minimize object creation for the
  20.     // objects being stored in the stack by allowing them to be
  21.     // re-used over time. It basically pushes the objects creating
  22.     // a high water mark then as Pop() is called they are not removed
  23.     // so that next time Push() is called it simply returns the last
  24.     // object that was already on the stack.
  25.    
  26.     internal class ByteStack
  27.     {
  28.         private byte[] stack;
  29.         private int growthRate;
  30.         private int top;
  31.         private int size;
  32.        
  33.         public ByteStack(int growthRate)
  34.         {
  35.             this.growthRate = growthRate;
  36.             top = 0;
  37.             stack = new byte[growthRate];
  38.             size = growthRate;
  39.         }
  40.        
  41.         public void Push(byte data)
  42.         {
  43.             if (size == top) {
  44.                 byte[] newstack = new byte[size + growthRate];
  45.                 if (top > 0) {
  46.                     Buffer.BlockCopy(stack, 0, newstack, 0, top);
  47.                 }
  48.                 stack = newstack;
  49.                 size += growthRate;
  50.             }
  51.             stack[top++] = data;
  52.         }
  53.        
  54.         public byte Pop()
  55.         {
  56.             if (top > 0) {
  57.                 return stack[--top];
  58.             }
  59.             else {
  60.                 return 0;
  61.             }
  62.         }
  63.        
  64.         public byte Peek()
  65.         {
  66.             if (top > 0) {
  67.                 return stack[top - 1];
  68.             }
  69.             else {
  70.                 return 0;
  71.             }
  72.         }
  73.        
  74.         public int Length {
  75.             get { return top; }
  76.         }
  77.     }
  78. }

Developer Fusion