1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-27 03:57:44 +00:00

LibCore: Introduce Core::Environment wrapper

Core::System already had some wrappers for *env() functions, which I've
copied over. But 1) the set of functions there was incomplete, and 2)
the environment feels like an object in its own right, so let's treat it
as one. :^)

Also add `Core::Environment::has(StringView)` for situations where we
just care if a variable is defined.
This commit is contained in:
Sam Atkins 2024-02-26 11:23:14 +00:00 committed by Sam Atkins
parent 55dc69625a
commit b9dc2d7ebf
3 changed files with 251 additions and 0 deletions

View file

@ -0,0 +1,81 @@
/*
* Copyright (c) 2024, Sam Atkins <atkinssj@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
#include <AK/Error.h>
#include <AK/Function.h>
#include <AK/IterationDecision.h>
#include <AK/Optional.h>
#include <AK/StringView.h>
#include <AK/Vector.h>
namespace Core::Environment {
char** raw_environ();
struct Entry {
StringView full_entry;
StringView name;
StringView value;
static Entry from_chars(char const* input);
static Entry from_string(StringView input);
};
class EntryIterator {
public:
constexpr bool operator==(EntryIterator other) const { return m_index == other.m_index; }
constexpr bool operator!=(EntryIterator other) const { return m_index != other.m_index; }
constexpr EntryIterator operator++()
{
++m_index;
return *this;
}
constexpr EntryIterator operator++(int)
{
auto result = *this;
++m_index;
return result;
}
Entry operator*() { return Entry::from_chars(raw_environ()[m_index]); }
static EntryIterator begin();
static EntryIterator end();
private:
explicit constexpr EntryIterator(size_t index)
: m_index(index)
{
}
size_t m_index { 0 };
};
EntryIterator entries();
size_t size();
bool has(StringView name);
enum class SecureOnly {
No,
Yes,
};
Optional<StringView> get(StringView name, SecureOnly = SecureOnly::No);
enum class Overwrite {
No,
Yes,
};
ErrorOr<void> set(StringView name, StringView value, Overwrite);
ErrorOr<void> unset(StringView name);
ErrorOr<void> put(StringView env);
ErrorOr<void> clear();
}