Skip to content

Commit

Permalink
Update multiple files to use KJ_IF_SOME (#1154)
Browse files Browse the repository at this point in the history
  • Loading branch information
jasnell authored Sep 19, 2023
1 parent eb5c66b commit 2c2648a
Show file tree
Hide file tree
Showing 11 changed files with 84 additions and 84 deletions.
4 changes: 2 additions & 2 deletions src/workerd/tests/test-fixture.h
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,8 @@ struct TestFixture {
-> typename RunReturnType<decltype(callback(kj::instance<const Environment&>()))>::Type {
auto request = createIncomingRequest();
kj::WaitScope* waitScope;
KJ_IF_MAYBE(ws, params.waitScope) {
waitScope = ws;
KJ_IF_SOME(ws, params.waitScope) {
waitScope = &ws;
} else {
waitScope = &KJ_REQUIRE_NONNULL(io).waitScope;
}
Expand Down
8 changes: 4 additions & 4 deletions src/workerd/tools/api-encoder.c++
Original file line number Diff line number Diff line change
Expand Up @@ -182,8 +182,8 @@ struct ApiEncoderMain {

capnp::MallocMessageBuilder flagsMessage;
CompatibilityFlags::Reader flags;
KJ_IF_MAYBE (date, compatibilityDate) {
flags = compileFlags(flagsMessage, *date, false, {});
KJ_IF_SOME (date, compatibilityDate) {
flags = compileFlags(flagsMessage, date, false, {});
} else {
flags = compileAllFlags(flagsMessage);
}
Expand All @@ -208,9 +208,9 @@ struct ApiEncoderMain {
#undef EW_TYPE_GROUP_WRITE

// Write structure groups to a file or stdout if none specifed
KJ_IF_MAYBE (value, output) {
KJ_IF_SOME (value, output) {
auto fs = kj::newDiskFilesystem();
auto path = kj::Path::parse(*value);
auto path = kj::Path::parse(value);
auto writeMode = kj::WriteMode::CREATE | kj::WriteMode::MODIFY |
kj::WriteMode::CREATE_PARENT;
auto file = fs->getCurrent().openFile(path, writeMode);
Expand Down
8 changes: 4 additions & 4 deletions src/workerd/util/batch-queue.h
Original file line number Diff line number Diff line change
Expand Up @@ -109,11 +109,11 @@ class BatchQueue {

template <typename T>
BatchQueue<T>::Batch::~Batch() noexcept(false) {
KJ_IF_MAYBE(bq, batchQueue) {
bq->popBuffer.clear();
if (auto capacity = bq->popBuffer.capacity(); capacity > bq->maxCapacity) {
KJ_IF_SOME(bq, batchQueue) {
bq.popBuffer.clear();
if (auto capacity = bq.popBuffer.capacity(); capacity > bq.maxCapacity) {
// Reset the queue to avoid letting it grow unbounded.
bq->popBuffer = kj::Vector<T>(bq->initialCapacity);
bq.popBuffer = kj::Vector<T>(bq.initialCapacity);
}
}
}
Expand Down
16 changes: 8 additions & 8 deletions src/workerd/util/canceler.h
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ class RefcountedCanceler: public kj::Refcounted {
friend class RefcountedCanceler;
};

RefcountedCanceler(kj::Maybe<kj::Exception> reason = nullptr): reason(kj::mv(reason)) {}
RefcountedCanceler(kj::Maybe<kj::Exception> reason = kj::none): reason(kj::mv(reason)) {}

~RefcountedCanceler() noexcept(false) {
// `listeners` has to be empty since each listener should have held a strong reference.
Expand All @@ -53,21 +53,21 @@ class RefcountedCanceler: public kj::Refcounted {

template <typename T>
kj::Promise<T> wrap(kj::Promise<T> promise) {
KJ_IF_MAYBE(ex, reason) {
return kj::cp(*ex);
KJ_IF_SOME(ex, reason) {
return kj::cp(ex);
}
return canceler.wrap(kj::mv(promise));
}

void cancel(kj::StringPtr cancelReason) {
if (reason == nullptr) {
if (reason == kj::none) {
cancel(kj::Exception(kj::Exception::Type::DISCONNECTED, __FILE__, __LINE__,
kj::str(cancelReason)));
}
}

void cancel(const kj::Exception& exception) {
if (reason == nullptr) {
if (reason == kj::none) {
reason = kj::cp(exception);
canceler.cancel(exception);
for (auto& listener : listeners) {
Expand All @@ -79,12 +79,12 @@ class RefcountedCanceler: public kj::Refcounted {
bool isEmpty() const { return canceler.isEmpty(); }

void throwIfCanceled() {
KJ_IF_MAYBE(ex, reason) {
kj::throwFatalException(kj::cp(*ex));
KJ_IF_SOME(ex, reason) {
kj::throwFatalException(kj::cp(ex));
}
}

bool isCanceled() const { return reason != nullptr; }
bool isCanceled() const { return reason != kj::none; }

void addListener(Listener& listener) {
listeners.add(listener);
Expand Down
18 changes: 9 additions & 9 deletions src/workerd/util/mimetype-test.c++
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,8 @@ KJ_TEST("Basic MimeType parsing works") {
KJ_ASSERT(mimeType.subtype() == test.subtype);
KJ_ASSERT(mimeType.toString() == test.output);

KJ_IF_MAYBE(params, test.params) {
for (auto& param : *params) {
KJ_IF_SOME(params, test.params) {
for (auto& param : params) {
auto& value = KJ_ASSERT_NONNULL(mimeType.params().find(param.key));
KJ_ASSERT(value == param.value);
}
Expand All @@ -104,7 +104,7 @@ KJ_TEST("Basic MimeType parsing works") {
};

for (auto& test : kErrorTests) {
KJ_ASSERT(MimeType::tryParse(test.input) == nullptr, test.input);
KJ_ASSERT(MimeType::tryParse(test.input) == kj::none, test.input);
}
}

Expand All @@ -121,9 +121,9 @@ KJ_TEST("Building MimeType works") {

KJ_ASSERT(type.toString() == "text/plain;a=b");

KJ_ASSERT(type.params().find("a"_kj) != nullptr);
KJ_ASSERT(type.params().find("b"_kj) == nullptr);
KJ_ASSERT(type.params().find("z"_kj) == nullptr);
KJ_ASSERT(type.params().find("a"_kj) != kj::none);
KJ_ASSERT(type.params().find("b"_kj) == kj::none);
KJ_ASSERT(type.params().find("z"_kj) == kj::none);

// Comparing based solely on type/subtype works
KJ_ASSERT(MimeType::PLAINTEXT == type);
Expand Down Expand Up @@ -382,11 +382,11 @@ KJ_TEST("WHATWG tests") {
};

for (const auto& test : kTests) {
KJ_IF_MAYBE(output, test.output) {
KJ_IF_SOME(output, test.output) {
auto result = KJ_ASSERT_NONNULL(MimeType::tryParse(test.input));
KJ_ASSERT(result.toString() == *output);
KJ_ASSERT(result.toString() == output);
} else {
KJ_ASSERT(MimeType::tryParse(test.input) == nullptr);
KJ_ASSERT(MimeType::tryParse(test.input) == kj::none);
}
}

Expand Down
72 changes: 36 additions & 36 deletions src/workerd/util/mimetype.c++
Original file line number Diff line number Diff line change
Expand Up @@ -58,15 +58,15 @@ kj::Maybe<size_t> findParamDelimiter(kj::ArrayPtr<const char> str) {
if (*ptr == ';' || *ptr == '=') return ptr - str.begin();
++ptr;
}
return nullptr;
return kj::none;
}

kj::String unescape(kj::ArrayPtr<const char> str) {
auto result = kj::strTree();
while (str.size() > 0) {
KJ_IF_MAYBE(pos, str.findFirst('\\')) {
result = kj::strTree(kj::mv(result), str.slice(0, *pos));
str = str.slice(*pos + 1, str.size());
KJ_IF_SOME(pos, str.findFirst('\\')) {
result = kj::strTree(kj::mv(result), str.slice(0, pos));
str = str.slice(pos + 1, str.size());
} else {
// No more backslashes
result = kj::strTree(kj::mv(result), str);
Expand All @@ -85,40 +85,40 @@ MimeType MimeType::parse(kj::StringPtr input, ParseOptions options) {
kj::Maybe<MimeType> MimeType::tryParse(kj::StringPtr input, ParseOptions options) {
// Skip leading whitespace from start
input = skipWhitespace(input);
if (input.size() == 0) return nullptr;
if (input.size() == 0) return kj::none;

kj::Maybe<kj::String> maybeType;
// Let's try to find the solidus that separates the type and subtype
KJ_IF_MAYBE(n, input.findFirst('/')) {
auto typeCandidate = input.slice(0, *n);
KJ_IF_SOME(n, input.findFirst('/')) {
auto typeCandidate = input.slice(0, n);
if (typeCandidate.size() == 0 || hasInvalidCodepoints(typeCandidate, isTokenChar)) {
return nullptr;
return kj::none;
}
maybeType = kj::str(typeCandidate);
input = input.slice(*n + 1);
input = input.slice(n + 1);
} else {
// If the solidus is not found, then it's not a valid mime type
return nullptr;
return kj::none;
}
auto& type = KJ_ASSERT_NONNULL(maybeType);

// If there's nothing else to parse at this point, it's not a valid mime type.
if (input.size() == 0) return nullptr;
if (input.size() == 0) return kj::none;

kj::Maybe<kj::String> maybeSubtype;
KJ_IF_MAYBE(n, input.findFirst(';')) {
KJ_IF_SOME(n, input.findFirst(';')) {
// If a semi-colon is found, the subtype is everything up to that point
// minus trailing whitespace.
auto subtypeCandidate = trimWhitespace(input.slice(0, *n));
auto subtypeCandidate = trimWhitespace(input.slice(0, n));
if (subtypeCandidate.size() == 0 || hasInvalidCodepoints(subtypeCandidate, isTokenChar)) {
return nullptr;
return kj::none;
}
maybeSubtype = kj::str(subtypeCandidate);
input = input.slice(*n + 1);
input = input.slice(n + 1);
} else {
auto subtypeCandidate = trimWhitespace(input.asArray());
if (subtypeCandidate.size() == 0 || hasInvalidCodepoints(subtypeCandidate, isTokenChar)) {
return nullptr;
return kj::none;
}
maybeSubtype = kj::str(subtypeCandidate);
input = input.slice(input.size());
Expand All @@ -132,20 +132,20 @@ kj::Maybe<MimeType> MimeType::tryParse(kj::StringPtr input, ParseOptions options
while (input.size() > 0) {
input = skipWhitespace(input);
if (input.size() == 0) break;
KJ_IF_MAYBE(n, findParamDelimiter(input)) {
KJ_IF_SOME(n, findParamDelimiter(input)) {
// If the delimiter found is a ; then the parameter is invalid here, and
// we will ignore it.
if (input[*n] == ';') {
input = input.slice(*n + 1);
if (input[n] == ';') {
input = input.slice(n + 1);
continue;
}
KJ_ASSERT(input[*n] == '=');
auto nameCandidate = input.slice(0, *n);
input = input.slice(*n + 1);
KJ_ASSERT(input[n] == '=');
auto nameCandidate = input.slice(0, n);
input = input.slice(n + 1);
if (nameCandidate.size() == 0 || hasInvalidCodepoints(nameCandidate, isTokenChar)) {
// The name is invalid, try skipping to the next...
KJ_IF_MAYBE(p, input.findFirst(';')) {
input = input.slice(*p + 1);
KJ_IF_SOME(p, input.findFirst(';')) {
input = input.slice(p + 1);
continue;
} else {
break;
Expand All @@ -157,15 +157,15 @@ kj::Maybe<MimeType> MimeType::tryParse(kj::StringPtr input, ParseOptions options
input = input.slice(1);
// Our parameter value is quoted. Next we'll scan up until the next
// quote or until the end of the string.
KJ_IF_MAYBE(p, input.findFirst('"')) {
auto valueCandidate = input.slice(0, *p);
input = input.slice(*p + 1);
KJ_IF_SOME(p, input.findFirst('"')) {
auto valueCandidate = input.slice(0, p);
input = input.slice(p + 1);
if (hasInvalidCodepoints(valueCandidate, isQuotedStringTokenChar)) {
continue;
}
result.addParam(nameCandidate, unescape(valueCandidate));
KJ_IF_MAYBE(y, input.findFirst(';')) {
input = input.slice(*y + 1);
KJ_IF_SOME(y, input.findFirst(';')) {
input = input.slice(y + 1);
continue;
}
} else if (!hasInvalidCodepoints(input, isQuotedStringTokenChar)) {
Expand All @@ -174,9 +174,9 @@ kj::Maybe<MimeType> MimeType::tryParse(kj::StringPtr input, ParseOptions options
break;
} else {
// The parameter is not quoted. Let's scan ahead for the next semi-colon.
KJ_IF_MAYBE(p, input.findFirst(';')) {
auto valueCandidate = trimWhitespace(input.slice(0, *p));
input = input.slice(*p + 1);
KJ_IF_SOME(p, input.findFirst(';')) {
auto valueCandidate = trimWhitespace(input.slice(0, p));
input = input.slice(p + 1);
if (valueCandidate.size() > 0 &&
!hasInvalidCodepoints(valueCandidate, isQuotedStringTokenChar)) {
result.addParam(nameCandidate, valueCandidate);
Expand Down Expand Up @@ -209,7 +209,7 @@ MimeType::MimeType(kj::StringPtr type,
kj::Maybe<MimeParams> params)
: type_(toLowerCopy(type)),
subtype_(toLowerCopy(subtype)) {
KJ_IF_MAYBE(p, params) { params_ = kj::mv(*p); }
KJ_IF_SOME(p, params) { params_ = kj::mv(p); }
}

kj::StringPtr MimeType::type() const {
Expand Down Expand Up @@ -271,9 +271,9 @@ void MimeType::paramsToString(MimeType::ToStringBuffer& buffer) const {
auto view = param.value.asPtr();
buffer.append("\"");
while (view.size() > 0) {
KJ_IF_MAYBE(pos, view.findFirst('"')) {
buffer.append(view.slice(0, *pos), "\\\"");
view = view.slice(*pos + 1);
KJ_IF_SOME(pos, view.findFirst('"')) {
buffer.append(view.slice(0, pos), "\\\"");
view = view.slice(pos + 1);
} else {
buffer.append(view);
view = view.slice(view.size());
Expand Down
14 changes: 7 additions & 7 deletions src/workerd/util/symbolizer.c++
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,11 @@ struct Subprocess {

if (pipe(in)) {
KJ_LOG(ERROR, "can't allocate in pipe", strerror(errno));
return nullptr;
return kj::none;
}
if (pipe(out)){
KJ_LOG(ERROR, "can't allocate out pipe", strerror(errno));
return nullptr;
return kj::none;
}

auto pid = fork();
Expand Down Expand Up @@ -114,7 +114,7 @@ String stringifyStackTrace(ArrayPtr<void* const> trace) {
return false;
}();

KJ_IF_MAYBE(subprocess, Subprocess::exec(argv)) {
KJ_IF_SOME(subprocess, Subprocess::exec(argv)) {
// write addresses as "CODE <file_name> <hex_address>" lines.
auto addrs = strArray(KJ_MAP(addr, trace) {
Dl_info info;
Expand All @@ -126,17 +126,17 @@ String stringifyStackTrace(ArrayPtr<void* const> trace) {
return kj::str("CODE 0x", reinterpret_cast<void*>(addr));
}
}, "\n");
if (write(subprocess->in, addrs.cStr(), addrs.size()) != addrs.size()) {
if (write(subprocess.in, addrs.cStr(), addrs.size()) != addrs.size()) {
// Ignore EPIPE, which means the process exited early. We'll deal with it below, presumably.
if (errno != EPIPE) {
KJ_LOG(ERROR, "write error", strerror(errno));
return nullptr;
}
}
close(subprocess->in);
close(subprocess.in);

// read result
auto out = fdopen(subprocess->out, "r");
auto out = fdopen(subprocess.out, "r");
if (!out) {
KJ_LOG(ERROR, "fdopen error", strerror(errno));
return nullptr;
Expand All @@ -149,7 +149,7 @@ String stringifyStackTrace(ArrayPtr<void* const> trace) {
lines[i++] = kj::str(line);
}
}
int status = subprocess->closeAndWait();
int status = subprocess.closeAndWait();
if (WIFEXITED(status)) {
if (WEXITSTATUS(status) != 0) {
if (WEXITSTATUS(status) == 2) {
Expand Down
10 changes: 5 additions & 5 deletions src/workerd/util/thread-scopes.c++
Original file line number Diff line number Diff line change
Expand Up @@ -92,14 +92,14 @@ ThreadProgressCounter::~ThreadProgressCounter() noexcept(false) {
}

bool ThreadProgressCounter::hasProgress() {
KJ_IF_MAYBE(progressCounter, activeProgressCounter) {
KJ_IF_SOME(progressCounter, activeProgressCounter) {
// The counter itself may be incremented by any thread, but there's no real synchronization
// concern, so we can use relaxed memory ordering. If the machine is so bogged down that a
// stale value causes a false positive, then crashing seems reasonable.
auto currentValue = __atomic_load_n(&progressCounter->counter, __ATOMIC_RELAXED);
auto currentValue = __atomic_load_n(&progressCounter.counter, __ATOMIC_RELAXED);

// `savedValue` is only ever accessed by our own thread, so no need for atomics here.
if (progressCounter->savedValue != currentValue) {
if (progressCounter.savedValue != currentValue) {
return true;
}
}
Expand All @@ -108,8 +108,8 @@ bool ThreadProgressCounter::hasProgress() {
}

void ThreadProgressCounter::acknowledgeProgress() {
KJ_IF_MAYBE(progressCounter, activeProgressCounter) {
progressCounter->savedValue = __atomic_load_n(&progressCounter->counter, __ATOMIC_RELAXED);
KJ_IF_SOME(progressCounter, activeProgressCounter) {
progressCounter.savedValue = __atomic_load_n(&progressCounter.counter, __ATOMIC_RELAXED);
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/workerd/util/uuid.c++
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ namespace workerd {
kj::String randomUUID(kj::Maybe<kj::EntropySource&> optionalEntropySource) {
kj::byte buffer[16];

KJ_IF_MAYBE(entropySource, optionalEntropySource) {
entropySource->generate(buffer);
KJ_IF_SOME(entropySource, optionalEntropySource) {
entropySource.generate(buffer);
} else {
KJ_ASSERT(RAND_bytes(buffer, sizeof(buffer)) == 1);
}
Expand Down
Loading

0 comments on commit 2c2648a

Please sign in to comment.