/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

#include <cassert>
#include <cstring>
#include <fstream>
#include <iostream>
#include <string>

#include "se_defines.h"

SE_GLOBALS()

struct custom_str {
  size_t len;
  char buf[];
};

void test_case(std::string content) {
  if (content.length() < sizeof(size_t)) {
    // Input is small
    return;
  }
  custom_str* str = (custom_str*)content.c_str();
  size_t provided_len = content.length() - 8;

  // Bounds checking for length
  if (str->len < provided_len) {
    // Larger buffer provided
    return;
  }

  // While copying, we'll duplicate each element, so reserving twice the space
  size_t buffer_size = str->len * 2;

  printf("str->len: %zx\nbuffer_size: %zx\n", str->len, buffer_size);

  if (buffer_size < str->len) {
    SE_STEP(true);
  }
  char* buffer = new char[buffer_size];

  for (size_t i = 0; i < provided_len; i += 2) {
    buffer[i] = str->buf[i];
    buffer[i + 1] = str->buf[i];

    if (i > buffer_size) {
      SE_TARGET_STATE(true);
      return;
    }
  }
}

int main(int argc, char* argv[]) {
  std::istream* input;
  std::ifstream file;
  if (argc < 2) {
    input = &std::cin; // No file name provided, read from stdin
  } else {
    file.open(argv[1]);
    if (!file) {
      std::cerr << "Could not open the file.\n";
      return 1;
    }
    input = &file; // File opened successfully, read from file
  }
  std::string content(
      (std::istreambuf_iterator<char>(*input)),
      std::istreambuf_iterator<char>());
  test_case(content);
  return 0;
}
