/*
 * Copyright 2025 Bloomberg Finance LP
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <buildboxcasd_inodecache.h>

namespace buildboxcasd {

InodeCache::InodeCache() {}

void InodeCache::Key::setFromStat(const struct stat &st)
{
    // Don't define a constructor as that can't guarantee zero initialization
    // of padding bytes, which is required for deterministic hashing
    this->st_dev = st.st_dev;
    this->st_ino = st.st_ino;
    this->st_size = st.st_size;

    this->st_mtim.tv_sec = st.st_mtim.tv_sec;
    this->st_mtim.tv_nsec = st.st_mtim.tv_nsec;
    this->st_ctim.tv_sec = st.st_ctim.tv_sec;
    this->st_ctim.tv_nsec = st.st_ctim.tv_nsec;
}

std::optional<buildboxcommon::Digest>
InodeCache::getDigest(const struct stat &st)
{
    Key key{};
    key.setFromStat(st);

    return getDigest(key);
}

std::optional<buildboxcommon::Digest> InodeCache::getDigest(const Key &key)
{
    const std::lock_guard<std::mutex> lock(d_mutex);

    auto iter = d_inodeDigestMap.find(key);
    if (iter == d_inodeDigestMap.end()) {
        return std::nullopt;
    }
    else {
        return iter->second;
    }
}

void InodeCache::addInode(const struct stat &st,
                          const buildboxcommon::Digest &digest)
{
    Key key{};
    key.setFromStat(st);

    const std::lock_guard<std::mutex> lock(d_mutex);

    d_inodeDigestMap[key] = digest;
}

} // namespace buildboxcasd
