1/*
2 * Copyright (c) 2021 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16namespace OHOS {
17namespace AI {
18template<class TYPE>
19Queue<TYPE>::Queue(size_t maxQueueSize)
20        : pushPos_(0), popPos_(0), totalNum_(maxQueueSize), writeAbleCount_(totalNum_), readAbleCount_(0) {
21    AIE_NEW(queue_, QueueNode[maxQueueSize]);
22    CHK_RET_NONE(queue_ == nullptr);
23}
24
25template<class TYPE>
26Queue<TYPE>::~Queue() {
27    AIE_DELETE_ARRAY(queue_);
28}
29
30template<class TYPE>
31bool Queue<TYPE>::IsEmpty() const {
32    return readAbleCount_ == 0;
33}
34
35template<class TYPE>
36bool Queue<TYPE>::IsFull() const {
37    return totalNum_ == readAbleCount_;
38}
39
40template<class TYPE>
41int Queue<TYPE>::PushBack(TYPE &msgBlock) {
42    CHK_RET(writeAbleCount_ == 0, RETCODE_QUEUE_FULL);
43
44    --writeAbleCount_;
45    size_t pushPos = pushPos_++ % totalNum_;
46
47    queue_[pushPos].node = msgBlock;
48    queue_[pushPos].empty = false;
49
50    ++readAbleCount_;
51
52    return RETCODE_SUCCESS;
53}
54
55template<class TYPE>
56int Queue<TYPE>::PopFront(TYPE &msgBlock) {
57    CHK_RET(readAbleCount_ == 0, RETCODE_QUEUE_EMPTY);
58    --readAbleCount_;
59
60    size_t popPos = popPos_ % totalNum_;
61
62    if (queue_[popPos].empty) {
63        ++readAbleCount_;
64        return RETCODE_QUEUE_NODE_INVALID;
65    }
66
67    ++popPos_;
68
69    msgBlock = queue_[popPos].node;
70    queue_[popPos].empty = true;
71
72    ++writeAbleCount_;
73
74    return RETCODE_SUCCESS;
75}
76
77template<class TYPE>
78size_t Queue<TYPE>::Count() const {
79    return readAbleCount_;
80}
81
82template<class TYPE>
83void Queue<TYPE>::Reset() {
84    pushPos_ = 0;
85    popPos_ = 0;
86    writeAbleCount_ = totalNum_;
87    readAbleCount_ = 0;
88
89    for (size_t i = 0; i < totalNum_; ++i) {
90        queue_[i].empty = true;
91    }
92}
93} // namespace AI
94} // namespace OHOS