fish-shell/src/intern.cpp
Kurtis Rader 509ee64fc9 implement our own assert() function
I recently upgraded the software on my macOS server and was dismayed to
see that cppcheck reported a huge number of format string errors due to
mismatches between the format string and its arguments from calls to
`assert()`. It turns out they are due to the macOS header using `%lu`
for the line number which is obviously wrong since it is using the C
preprocessor `__LINE__` symbol which evaluates to a signed int.

I also noticed that the macOS implementation writes to stdout, rather
than stderr. It also uses `printf()` which can be a problem on some
platforms if the stream is already in wide mode which is the normal case
for fish.

So implement our own `assert()` implementation. This also eliminates
double-negative warnings that we get from some of our calls to
`assert()` on some platforms by oclint.

Also reimplement the `DIE()` macro in terms of our internal
implementation.

Rewrite `assert(0 && msg)` statements to `DIE(msg)` for clarity and to
eliminate oclint warnings about constant expressions.

Fixes #3276, albeit not in the fashion I originally envisioned.
2017-02-14 18:48:27 -08:00

41 lines
1.2 KiB
C++

// Library for pooling common strings.
#include "config.h" // IWYU pragma: keep
#include <stddef.h>
#include <wchar.h>
#include <algorithm>
#include <memory>
#include <vector>
#include "common.h"
#include "fallback.h" // IWYU pragma: keep
#include "intern.h"
bool string_less_than_string(const wchar_t *a, const wchar_t *b) { return wcscmp(a, b) < 0; }
/// The table of intern'd strings.
owning_lock<std::vector<const wchar_t *>> string_table;
static const wchar_t *intern_with_dup(const wchar_t *in, bool dup) {
if (!in) return NULL;
debug(5, L"intern %ls", in);
auto lock_string_table = string_table.acquire();
std::vector<const wchar_t *> &string_table = lock_string_table.value;
const wchar_t *result;
auto iter =
std::lower_bound(string_table.begin(), string_table.end(), in, string_less_than_string);
if (iter != string_table.end() && wcscmp(*iter, in) == 0) {
result = *iter;
} else {
result = dup ? wcsdup(in) : in;
string_table.insert(iter, result);
}
return result;
}
const wchar_t *intern(const wchar_t *in) { return intern_with_dup(in, true); }
const wchar_t *intern_static(const wchar_t *in) { return intern_with_dup(in, false); }