1
Fork 0

iterator: make advance/rollback more understandable

untested
main
Motiejus Jakštys 2022-08-04 22:51:55 -07:00
parent af7ba5edcf
commit 1dfdd3cdbd
3 changed files with 22 additions and 30 deletions

View File

@ -69,26 +69,22 @@ pub const Iterator = struct {
next_start: usize = 0,
idx: u32 = 0,
total: u32,
advance_by: usize = 0,
advanced_by: usize = 0,
pub fn next(it: *Iterator) ?PackedGroup {
const gr = it.peek() orelse return null;
it.advance();
return gr;
}
pub fn peek(it: *Iterator) ?PackedGroup {
if (it.idx == it.total) return null;
const entry = fromBytes(it.section[it.next_start..]);
it.advance_by = entry.end;
it.idx += 1;
it.next_start += entry.end;
it.advanced_by = entry.end;
return entry.group;
}
pub fn advance(it: *Iterator) void {
assert(it.advance_by > 0);
it.idx += 1;
it.next_start += it.advance_by;
it.advance_by = 0;
pub fn rollback(it: *Iterator) void {
assert(it.advanced_by > 0);
it.idx -= 1;
it.next_start -= it.advanced_by;
it.advanced_by = 0;
}
};

View File

@ -109,26 +109,22 @@ pub const Iterator = struct {
shell_reader: ShellReader,
idx: u32 = 0,
total: u32,
advance_by: usize = 0,
advanced_by: usize = 0,
pub fn next(it: *Iterator) ?PackedUser {
const u = it.peek() orelse return null;
it.advance();
return u;
}
pub fn peek(it: *Iterator) ?PackedUser {
if (it.idx == it.total) return null;
const entry = fromBytes(it.section[it.next_start..]);
it.advance_by = entry.end;
it.idx += 1;
it.next_start += entry.end;
it.advanced_by = entry.end;
return entry.user;
}
pub fn advance(it: *Iterator) void {
assert(it.advance_by > 0);
it.idx += 1;
it.next_start += it.advance_by;
it.advance_by = 0;
pub fn rollback(it: *Iterator) void {
assert(it.advanced_by > 0);
it.idx -= 1;
it.next_start -= it.advanced_by;
it.advanced_by = 0;
}
};

View File

@ -370,7 +370,7 @@ fn getgrent_r(
defer state.getgrent_iterator_mu.unlock();
if (state.getgrent_iterator) |*it| {
const group = it.peek() orelse {
const group = it.next() orelse {
errnop.* = 0;
return c.NSS_STATUS_NOTFOUND;
};
@ -381,11 +381,11 @@ fn getgrent_r(
state.file.db.packCGroup(&group, buffer[0..buflen]);
if (cgroup1) |cgroup| {
it.advance();
result.* = cgroup;
return c.NSS_STATUS_SUCCESS;
} else |err| switch (err) {
error.BufferTooSmall => {
it.rollback();
errnop.* = @enumToInt(os.E.RANGE);
return c.NSS_STATUS_TRYAGAIN;
},
@ -423,7 +423,7 @@ fn getpwent_r(
defer state.getpwent_iterator_mu.unlock();
if (state.getpwent_iterator) |*it| {
const user = it.peek() orelse {
const user = it.next() orelse {
errnop.* = 0;
return c.NSS_STATUS_NOTFOUND;
};
@ -431,12 +431,12 @@ fn getpwent_r(
const buf = buffer[0..buflen];
const cuser = state.file.db.writeUser(user, buf) catch |err| switch (err) {
error.BufferTooSmall => {
it.rollback();
errnop.* = @enumToInt(os.E.RANGE);
return c.NSS_STATUS_TRYAGAIN;
},
};
it.advance();
result.* = cuser;
return c.NSS_STATUS_SUCCESS;
} else {