环形缓存消息队列 C++

 1 #include<iostream>
 2 #include<string.h>
 3 using namespace std;
 4 
 5 class CircleMessage
 6 {
 7     public:
 8         CircleMessage(int size)
 9         {
10             _size = size;
11             _free_size = size;
12             Buf = new char[size];
13             _head = 0;
14             _tail = 0;
15         }
16         ~CircleMessage()
17         {
18             if (Buf)
19             {
20                 delete[] Buf;
21             }
22         }
23         int GetLength()
24         {
25             return _free_size;
26         }
27         bool WriteBuffer(char *buf, int len)
28         {
29             if (len > _free_size) return false;
30             if (_size - _tail >= len)
31             {
32                 memcpy(Buf + _tail, buf, len);
33             }
34             else
35             {
36                 memcpy(Buf + _tail, buf, _size - _tail);
37                 memcpy(Buf, buf + _size - _tail, len - _size + _tail);
38             }
39             _tail += len;
40             if (_tail >= _size) _tail -= _size;
41             _free_size -= len;
42             return true;
43         }
44         bool ReadBuffer(char *buf, int len)
45         {
46             if (len > _size - _free_size) return false;
47             if (_size - _head >= len)
48             {
49                 memcpy(buf, Buf + _head, len);
50                 cout << "len=" << Buf[_head] << len << endl;
51             }
52             else
53             {
54                 memcpy(buf, Buf + _head, _size - _head);
55                 memcpy(buf + _size - _head, Buf, len - _size + _head);
56             }
57             _head += len;
58             if (_head >= _size) _head -= _size;
59             _free_size += len;
60             return true;
61         }
62         
63     private:
64         int _head, _tail, _size, _free_size;
65         char *Buf;
66 };
67 
68 int main()
69 {
70     CircleMessage A(10);
71     char test1[10] = "first";
72     char test2[10] = "second78";
73     char x[10], y[10], z[10], p[10];
74     
75     cout << A.GetLength() << endl;
76     bool try11 = A.WriteBuffer(test1, 5);
77     cout << A.GetLength() << endl;
78     bool try12 = A.ReadBuffer(x, 3);
79     bool try21 = A.WriteBuffer(test2, 8);
80     bool try22 = A.ReadBuffer(y, 6);
81     bool try31 = A.ReadBuffer(z, 1);
82     bool try32 = A.ReadBuffer(p, 3);
83     cout << try11 << try12 << try21 << try22 << try31 << try32 << endl;
84     cout << x << endl;
85     cout << y << endl;
86     cout << z << endl;
87     cout << p << endl;
88     cout << A.GetLength() << endl;
89     return  0;
90 }

 

posted on 2020-09-16 17:26  xiao_xin  阅读(241)  评论(0)    收藏  举报

导航