/*
 * 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>

#include <buildboxcommon_digestgenerator.h>
#include <buildboxcommon_protos.h>

#include <gtest/gtest.h>

using buildboxcommon::Digest;
using buildboxcommon::DigestGenerator;

namespace {
const auto digestFunctionInitializer = []() {
    buildboxcommon::DigestGenerator::init();
    return 0;
}();
} // namespace

TEST(InodeCache, Basic)
{
    struct stat st{};
    ASSERT_EQ(stat(".", &st), 0);

    const Digest digest = DigestGenerator::hash(".");

    buildboxcasd::InodeCache cache;
    EXPECT_FALSE(cache.getDigest(st).has_value());

    cache.addInode(st, digest);
    EXPECT_EQ(cache.getDigest(st), digest);
}

// Test that `addInode()` or `getDigest()` don't hash any non-zero padding
// bytes (which would result in non-deterministic hashing and thus, extra cache
// misses)
TEST(InodeCache, Zero)
{
    struct stat st{};
    buildboxcasd::InodeCache::Key key{};
    // memset is redundant with the above declarations with a correctly working
    // compiler, but let's be explicit that we want to zero the whole structs
    // for this test (including any padding bytes).
    memset(&st, 0, sizeof(st));
    memset(&key, 0, sizeof(key));

    const Digest digest = DigestGenerator::hash("zero");

    buildboxcasd::InodeCache cache;
    EXPECT_FALSE(cache.getDigest(st).has_value());
    EXPECT_FALSE(cache.getDigest(key).has_value());

    cache.addInode(st, digest);
    EXPECT_EQ(cache.getDigest(st), digest);
    EXPECT_EQ(cache.getDigest(key), digest);
}
