coverity issues fix
[platform/core/system/sensord.git] / src / sensor / pedometer / average_filter.cpp
1 /*
2  *  Copyright (c) 2016-2017 Samsung Electronics Co., Ltd.
3  *
4  *  Licensed under the Apache License, Version 2.0 (the "License");
5  *  you may not use this file except in compliance with the License.
6  *  You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  *  Unless required by applicable law or agreed to in writing, software
11  *  distributed under the License is distributed on an "AS IS" BASIS,
12  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  *  See the License for the specific language governing permissions and
14  *  limitations under the License.
15  */
16
17 #include "average_filter.h"
18
19 #include <memory>
20 #include <stdlib.h>
21
22 static double mean(double *array, int size)
23 {
24         double avrg = 0;
25
26         for (int i = 0; i < size; ++i)
27                 avrg = avrg + array[i];
28
29         return avrg / size;
30 }
31
32 average_filter::average_filter(int sz)
33 : m_size(sz)
34 , m_index(0)
35 , m_ready(false)
36 {
37         m_array = (double *)calloc(sz, sizeof(double));
38 }
39
40 average_filter::~average_filter()
41 {
42         if (m_array == NULL)
43                 return;
44
45         free(m_array);
46         m_array = NULL;
47         m_size = 0;
48 }
49
50 double average_filter::filter(double value)
51 {
52         m_array[m_index++] = value;
53
54         if (m_index >= m_size) {
55                 m_ready = true;
56                 m_index = 0;
57         }
58         return mean(m_array, (m_ready ? m_size : m_index));
59 }
60
61 void average_filter::reset(void)
62 {
63         m_index = 0;
64         m_ready = false;
65 }