aboutsummaryrefslogtreecommitdiff
path: root/libxsde/xsde/cxx/stack.ixx
blob: bc40e4a960e4df8e4884f71b6f846c9eca006fb5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
// file      : xsde/cxx/stack.ixx
// copyright : Copyright (c) 2005-2011 Code Synthesis Tools CC
// license   : GNU GPL v2 + exceptions; see accompanying LICENSE file

#ifdef XSDE_CUSTOM_ALLOCATOR
#  include <xsde/cxx/allocator.hxx>
#else
#  include <new> // operator new/delete
#endif

namespace xsde
{
  namespace cxx
  {
    inline stack::
    stack (size_t el_size, void* first_el)
        : el_size_ (el_size),
          cur_ (static_cast<block*> (first_el)),
          next_ (0),
          cap_ (1),
          num_ (0)
    {
    }

    inline void stack::
    pop ()
    {
      if (cap_ == 1)
        --num_;
      else
      {
        if (num_ > 1)
          --num_;
        else
        {
          // Move to the previous block.
          //
          cap_ = cur_ == next_ ? 1 : cap_ / 2;
          cur_ = cur_->prev;
          num_ = cap_;
        }
      }
    }

#ifdef XSDE_EXCEPTIONS
    inline void stack::
#else
    inline stack::error stack::
#endif
    push ()
    {
      if (num_ < cap_)
      {
        num_++;
#ifndef XSDE_EXCEPTIONS
        return error_none;
#endif
      }
      else
      {
#ifdef XSDE_EXCEPTIONS
        push_impl ();
#else
        return push_impl ();
#endif
      }
    }

    inline void* stack::
    top ()
    {
      if (cap_ == 1)
        return cur_;
      else
      {
        char* data = reinterpret_cast<char*> (cur_) + sizeof (block);
        return data + (num_ - 1) * el_size_;
      }
    }

    inline void stack::
    clear ()
    {
      cap_ = 1;
      num_ = 0;

      // Reset cur_ to the first block.
      //
      if (next_)
        cur_ = next_->prev;
    }

    inline bool stack::
    empty () const
    {
      return num_ == 0;
    }

    inline size_t stack::
    element_size () const
    {
      return el_size_;
    }
  }
}