| 1815 | } |
| 1816 | |
| 1817 | bool MMKV::enableAutoKeyExpire(uint32_t expiredInSeconds) { |
| 1818 | if (isReadOnly()) { |
| 1819 | MMKVWarning("[%s] file readonly", m_mmapID.c_str()); |
| 1820 | return false; |
| 1821 | } |
| 1822 | SCOPED_LOCK(m_lock); |
| 1823 | SCOPED_LOCK(m_exclusiveProcessLock); |
| 1824 | checkLoadData(); |
| 1825 | if (!isFileValid() || !m_metaFile->isFileValid()) { |
| 1826 | MMKVWarning("[%s] file not valid", m_mmapID.c_str()); |
| 1827 | return false; |
| 1828 | } |
| 1829 | |
| 1830 | if (m_enableCompareBeforeSet) { |
| 1831 | MMKVError("enableCompareBeforeSet will be invalid when Expiration is on"); |
| 1832 | m_enableCompareBeforeSet = false; |
| 1833 | } |
| 1834 | |
| 1835 | if (m_expiredInSeconds != expiredInSeconds) { |
| 1836 | MMKVInfo("expiredInSeconds: %u", expiredInSeconds); |
| 1837 | m_expiredInSeconds = expiredInSeconds; |
| 1838 | } |
| 1839 | m_enableKeyExpire = true; |
| 1840 | if (m_metaInfo->hasFlag(MMKVMetaInfo::EnableKeyExipre)) { |
| 1841 | return true; |
| 1842 | } |
| 1843 | |
| 1844 | auto autoRecordExpireTime = (m_expiredInSeconds != 0); |
| 1845 | auto time = autoRecordExpireTime ? getCurrentTimeInSecond() + m_expiredInSeconds : 0; |
| 1846 | MMKVInfo("turn on recording expire date for all keys inside [%s] from now %u", m_mmapID.c_str(), time); |
| 1847 | m_metaInfo->setFlag(MMKVMetaInfo::EnableKeyExipre); |
| 1848 | m_metaInfo->m_version = MMKVVersionFlag; |
| 1849 | |
| 1850 | if (m_file->getFileSize() == m_expectedCapacity && m_actualSize == 0) { |
| 1851 | MMKVInfo("file is new, don't need a full writeback [%s], just update meta file", m_mmapID.c_str()); |
| 1852 | writeActualSize(0, 0, nullptr, IncreaseSequence); |
| 1853 | m_metaFile->msync(MMKV_SYNC); |
| 1854 | return true; |
| 1855 | } |
| 1856 | |
| 1857 | MMKVVector vec; |
| 1858 | auto packKeyValue = [&](const auto &key, const MMBuffer &value) { |
| 1859 | MMBuffer data(value.length() + Fixed32Size); |
| 1860 | auto ptr = (uint8_t *) data.getPtr(); |
| 1861 | memcpy(ptr, value.getPtr(), value.length()); |
| 1862 | memcpy(ptr + value.length(), &time, Fixed32Size); |
| 1863 | vec.emplace_back(key, std::move(data)); |
| 1864 | }; |
| 1865 | |
| 1866 | auto basePtr = (uint8_t *) (m_file->getMemory()) + Fixed32Size; |
| 1867 | #ifndef MMKV_DISABLE_CRYPT |
| 1868 | if (m_crypter) { |
| 1869 | for (auto &pair : *m_dicCrypt) { |
| 1870 | auto &key = pair.first; |
| 1871 | auto &value = pair.second; |
| 1872 | auto buffer = value.toMMBuffer(basePtr, m_crypter); |
| 1873 | packKeyValue(key, buffer); |
| 1874 | } |