#pragma once
#include "shim_support.h"
#include <cstring>
#include <string>
#include <vector>
namespace llama_shim {
void set_error(const std::string & what);
void clear_error();
const std::string & last_error();
template <typename Fn> int32_t guard(Fn && fn) {
clear_error();
try {
return fn();
} catch (const std::exception & e) {
set_error(e.what());
return LLAMA_SHIM_THROWN;
} catch (...) {
set_error("unknown C++ exception");
return LLAMA_SHIM_THROWN;
}
}
inline int32_t emit(const std::string & src, char * out_buf, size_t out_len, size_t * expected_len) {
const size_t needed = src.size() + 1;
if (expected_len) {
*expected_len = needed;
}
if (!out_buf || out_len < needed) {
return LLAMA_SHIM_BUFFER_TOO_SMALL;
}
std::memcpy(out_buf, src.data(), src.size());
out_buf[src.size()] = '\0';
return LLAMA_SHIM_OK;
}
template <typename T>
int32_t emit_tokens(const std::vector<T> & src, int32_t * out, size_t out_cap, size_t * out_len) {
if (out_len) {
*out_len = src.size();
}
if (!out || out_cap < src.size()) {
return LLAMA_SHIM_BUFFER_TOO_SMALL;
}
for (size_t i = 0; i < src.size(); i++) {
out[i] = static_cast<int32_t>(src[i]);
}
return LLAMA_SHIM_OK;
}
inline std::string str_or_empty(const char * s) {
return s ? std::string(s) : std::string();
}
inline bool blank(const char * s) {
return !s || *s == '\0';
}
}