Fix for x86_64 build fail
[platform/upstream/connectedhomeip.git] / src / lib / support / LifetimePersistedCounter.cpp
1 /*
2  *
3  *    Copyright (c) 2021 Project CHIP Authors
4  *    All rights reserved.
5  *
6  *    Licensed under the Apache License, Version 2.0 (the "License");
7  *    you may not use this file except in compliance with the License.
8  *    You may obtain a copy of the License at
9  *
10  *        http://www.apache.org/licenses/LICENSE-2.0
11  *
12  *    Unless required by applicable law or agreed to in writing, software
13  *    distributed under the License is distributed on an "AS IS" BASIS,
14  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  *    See the License for the specific language governing permissions and
16  *    limitations under the License.
17  */
18 #include "LifetimePersistedCounter.h"
19
20 #include <platform/PersistedStorage.h>
21 #include <support/CodeUtils.h>
22 #include <support/logging/CHIPLogging.h>
23
24 #include <stdlib.h>
25 #include <string.h>
26
27 namespace chip {
28
29 LifetimePersistedCounter::LifetimePersistedCounter() : mId(chip::Platform::PersistedStorage::kEmptyKey) {}
30
31 LifetimePersistedCounter::~LifetimePersistedCounter() {}
32
33 CHIP_ERROR
34 LifetimePersistedCounter::Init(const chip::Platform::PersistedStorage::Key aId)
35 {
36     CHIP_ERROR err = CHIP_NO_ERROR;
37
38     mId = aId;
39     uint32_t startValue;
40
41     // Read our previously-stored starting value.
42     SuccessOrExit(err = ReadStartValue(startValue));
43
44     // This will set the starting value, after which we're ready.
45     SuccessOrExit(err = MonotonicallyIncreasingCounter::Init(startValue));
46
47 exit:
48     return err;
49 }
50
51 CHIP_ERROR
52 LifetimePersistedCounter::Advance()
53 {
54     CHIP_ERROR err = CHIP_NO_ERROR;
55
56     VerifyOrExit(mId != chip::Platform::PersistedStorage::kEmptyKey, err = CHIP_ERROR_INCORRECT_STATE);
57
58     SuccessOrExit(err = MonotonicallyIncreasingCounter::Advance());
59
60     SuccessOrExit(err = chip::Platform::PersistedStorage::Write(mId, GetValue()));
61 exit:
62     return err;
63 }
64
65 CHIP_ERROR
66 LifetimePersistedCounter::ReadStartValue(uint32_t & aStartValue)
67 {
68     CHIP_ERROR err = CHIP_NO_ERROR;
69
70     aStartValue = 0;
71
72     err = chip::Platform::PersistedStorage::Read(mId, aStartValue);
73     if (err == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND)
74     {
75         // No previously-stored value, no worries, the counter is initialized to zero.
76         // Suppress the error.
77         err = CHIP_NO_ERROR;
78     }
79     else
80     {
81         SuccessOrExit(err);
82     }
83 exit:
84     return err;
85 }
86
87 } // namespace chip