]> git.ipfire.org Git - thirdparty/squid.git/blame - src/DescriptorSet.cc
Updates for running on squid-cache.org
[thirdparty/squid.git] / src / DescriptorSet.cc
CommitLineData
877ce944
AR
1
2/*
3 * $Id$
4 *
5 * DEBUG: section 5 Comm
6 */
7
8#include "DescriptorSet.h"
9
10// pre-allocates descriptor store and index for Squid_MaxFD descriptors
11DescriptorSet::DescriptorSet(): descriptors_(NULL), index_(NULL),
12 capacity_(0), size_(0)
13{
14 // we allocate once and never realloc, at least for now
15 capacity_ = Squid_MaxFD;
16 descriptors_ = new int[capacity_];
17 index_ = new int[capacity_];
18
19 // fill index with -1s to be able to say whether a descriptor is present
20 // it is not essential to fill the descriptors, but it enables more checks
21 for (int i = 0; i < capacity_; ++i)
22 index_[i] = descriptors_[i] = -1;
23}
24
25DescriptorSet::~DescriptorSet()
26{
27 delete[] descriptors_;
28 delete[] index_;
29}
30
31/// adds if unique; returns true if added
32bool
33DescriptorSet::add(int fd)
34{
35 assert(0 <= fd && fd < capacity_); // \todo: replace with Must()
36
37 if (has(fd))
38 return false; // already have it
39
40 assert(size_ < capacity_); // \todo: replace with Must()
41 const int pos = size_++;
42 index_[fd] = pos;
43 descriptors_[pos] = fd;
44 return true; // really added
45}
46
47/// deletes if there; returns true if deleted
48bool
49DescriptorSet::del(int fd)
50{
51 assert(0 <= fd && fd < capacity_); // \todo: here and below, use Must()
52
53 if (!has(fd))
54 return false; // we do not have it
55
56 assert(!empty());
57 const int delPos = index_[fd];
58 assert(0 <= delPos && delPos < capacity_);
59
60 // move the last descriptor to the deleted fd position
61 // to avoid skipping deleted descriptors in pop()
62 const int lastPos = size_-1;
63 const int lastFd = descriptors_[lastPos];
64 assert(delPos <= lastPos); // may be the same
65 descriptors_[delPos] = lastFd;
66 index_[lastFd] = delPos;
67
68 descriptors_[lastPos] = -1;
69 index_[fd] = -1;
70 --size_;
71
72 return true; // really added
73}
74
75/// ejects one descriptor in unspecified order
76int
77DescriptorSet::pop()
78{
79 assert(!empty());
80 const int lastPos =--size_;
81 const int lastFd = descriptors_[lastPos];
82 assert(0 <= lastFd && lastFd < capacity_);
83
84 // cleanup
85 descriptors_[lastPos] = -1;
86 index_[lastFd] = -1;
87
88 return lastFd;
89}
90
91void
92DescriptorSet::print(std::ostream &os) const
93{
94 // \todo add "name" if the set is used for more than just half-closed FDs
95 os << size_ << " FDs";
96}