| 159 | } |
| 160 | |
| 161 | bool MemoryFile::truncate(size_t size, FileLock *fileLock) { |
| 162 | if (m_isMayflyFD) { |
| 163 | openIfNeeded(); |
| 164 | } |
| 165 | if (!m_diskFile.isFileValid()) { |
| 166 | return false; |
| 167 | } |
| 168 | if (size == m_size) { |
| 169 | return true; |
| 170 | } |
| 171 | if (m_readOnly) { |
| 172 | // truncate readonly file not allow |
| 173 | return false; |
| 174 | } |
| 175 | # ifdef MMKV_ANDROID |
| 176 | if (m_diskFile.m_fileType == MMFILE_TYPE_ASHMEM) { |
| 177 | if (size > m_size) { |
| 178 | MMKVError("ashmem %s reach size limit:%zu, consider configure with larger size", m_diskFile.m_path.c_str(), m_size); |
| 179 | } else { |
| 180 | MMKVInfo("no way to trim ashmem %s from %zu to smaller size %zu", m_diskFile.m_path.c_str(), m_size, size); |
| 181 | } |
| 182 | return false; |
| 183 | } |
| 184 | # endif // MMKV_ANDROID |
| 185 | |
| 186 | auto oldSize = m_size; |
| 187 | m_size = size; |
| 188 | // round up to (n * pagesize) |
| 189 | if (m_size < DEFAULT_MMAP_SIZE || (m_size % DEFAULT_MMAP_SIZE != 0)) { |
| 190 | m_size = ((m_size / DEFAULT_MMAP_SIZE) + 1) * DEFAULT_MMAP_SIZE; |
| 191 | } |
| 192 | |
| 193 | if (::ftruncate(m_diskFile.m_fd, static_cast<off_t>(m_size)) != 0) { |
| 194 | MMKVError("fail to truncate [%s] to size %zu, %s", m_diskFile.m_path.c_str(), m_size, strerror(errno)); |
| 195 | m_size = oldSize; |
| 196 | return false; |
| 197 | } |
| 198 | if (m_size > oldSize) { |
| 199 | if (!zeroFillFile(m_diskFile.m_fd, oldSize, m_size - oldSize)) { |
| 200 | MMKVError("fail to zeroFile [%s] to size %zu, %s", m_diskFile.m_path.c_str(), m_size, strerror(errno)); |
| 201 | m_size = oldSize; |
| 202 | |
| 203 | // redo ftruncate to its previous size |
| 204 | int status = ::ftruncate(m_diskFile.m_fd, static_cast<off_t>(m_size)); |
| 205 | if (status != 0) { |
| 206 | MMKVError("failed to truncate back [%s] to size %zu, %s", m_diskFile.m_path.c_str(), m_size, strerror(errno)); |
| 207 | } else { |
| 208 | MMKVError("success to truncate [%s] back to size %zu", m_diskFile.m_path.c_str(), m_size); |
| 209 | MMKVError("after truncate, file size = %zu", getActualFileSize()); |
| 210 | } |
| 211 | |
| 212 | return false; |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | if (m_ptr) { |
| 217 | if (munmap(m_ptr, oldSize) != 0) { |
| 218 | MMKVError("fail to munmap [%s], %s", m_diskFile.m_path.c_str(), strerror(errno)); |
no test coverage detected