Skip to content

Lightpanda: the headless browser designed for AI and automation

js: add js.EnforceRange

Karl Seguine0209cb8d8b3
diff --git a/src/browser/js/Local.zig b/src/browser/js/Local.zig
index 1a00867cd..99509629e 100644
--- a/src/browser/js/Local.zig
+++ b/src/browser/js/Local.zig
@@ -749,6 +749,10 @@ fn jsValueToStruct(self: *const Local, comptime T: type, js_val: js.Value) !?T {
return T{ .value = try self.jsValueToZig(T.js_nullable, js_val) };
}
+ if (@hasDecl(T, "js_enforce_range")) {
+ return T{ .value = try js.enforceRange(T.js_enforce_range, try js_val.toF64()) };
+ }
+
return switch (T) {
js.Function, js.Function.Global => {
if (!js_val.isFunction()) {
diff --git a/src/browser/js/js.zig b/src/browser/js/js.zig
index 7df199112..556988c63 100644
--- a/src/browser/js/js.zig
+++ b/src/browser/js/js.zig
@@ -331,6 +331,30 @@ pub fn Nullable(comptime T: type) type {
};
}
+// A WebIDL [EnforceRange] integer. NaN, +/i infinity and values outside of T's
+// range are a TypeError.
+pub fn EnforceRange(comptime T: type) type {
+ return struct {
+ value: T = 0,
+
+ pub const js_enforce_range = T;
+ };
+}
+
+pub fn enforceRange(comptime T: type, value: f64) !T {
+ if (std.math.isFinite(value) == false) {
+ return error.TypeError;
+ }
+ // [EnforceRange] long long is limited to the safe integer range.
+ const min: f64 = @floatFromInt(@max(std.math.minInt(T), -9007199254740991));
+ const max: f64 = @floatFromInt(@min(std.math.maxInt(T), 9007199254740991));
+ const truncated = @trunc(value);
+ if (truncated < min or truncated > max) {
+ return error.TypeError;
+ }
+ return @intFromFloat(truncated);
+}
+
pub const Exception = struct {
local: *const Local,
handle: *const v8.Value,
@@ -513,7 +537,7 @@ pub export fn v8_inspector__Client__IMPL__descriptionForValueSubtype(
test "TaggedAnyOpaque" {
// If we grow this, fine, but it should be a conscious decision
- try std.testing.expectEqual(24, @sizeOf(TaggedOpaque));
+ try testing.expectEqual(24, @sizeOf(TaggedOpaque));
}
test "js: ArrayBuffers crossing Zig don't keep a reference to their backing store" {
@@ -641,3 +665,15 @@ pub fn writeStackTrace(isolate: *v8.Isolate, stack_handle: *const v8.StackTrace,
});
}
}
+
+test "js: enforceRange" {
+ try testing.expectEqual(@as(u32, 5), try enforceRange(u32, 5.9));
+ try testing.expectEqual(@as(i64, -10), try enforceRange(i64, -10));
+ try testing.expectError(error.TypeError, enforceRange(u32, -1));
+ try testing.expectError(error.TypeError, enforceRange(u32, 4294967296));
+ try testing.expectError(error.TypeError, enforceRange(i64, std.math.nan(f64)));
+ try testing.expectError(error.TypeError, enforceRange(u64, std.math.inf(f64)));
+ try testing.expectError(error.TypeError, enforceRange(u64, 9007199254740992));
+ try testing.expectEqual(@as(u16, 65535), try enforceRange(u16, 65535.5));
+ try testing.expectError(error.TypeError, enforceRange(u16, 65536));
+}
diff --git a/src/browser/tests/crypto.html b/src/browser/tests/crypto.html
index 7623c6142..52677c769 100644
--- a/src/browser/tests/crypto.html
+++ b/src/browser/tests/crypto.html
@@ -125,6 +125,46 @@
});
</script>
+<script id=deriveBits-length type=module>
+ const state = await testing.async();
+ const subtle = crypto.subtle;
+ const errorName = async (fn) => {
+ try {
+ await fn();
+ return null;
+ } catch (err) {
+ return err.name;
+ }
+ };
+ const key = await subtle.importKey("raw", new TextEncoder().encode("password"), "PBKDF2", false, ["deriveBits"]);
+ const pbkdf2 = (iterations) => ({ name: "PBKDF2", hash: "SHA-256", salt: new Uint8Array(16), iterations });
+ const derive = (length, iterations = 1000) => errorName(() => subtle.deriveBits(pbkdf2(iterations), key, length));
+
+ const results = {
+ ok: await derive(256),
+ nullLength: await derive(null),
+ // [EnforceRange]: -8 used to wrap to 2^32 - 8 bits.
+ nan: await derive(NaN),
+ infinity: await derive(Infinity),
+ negative: await derive(-8),
+ tooLarge: await derive(2 ** 32 + 8),
+ // Valid lengths whose cost (blocks * iterations) is over the PBKDF2 limit.
+ hugeLength: await derive(2 ** 32 - 8, 100000),
+ hugeIterations: await derive(256, 2 ** 24 + 1),
+ };
+
+ state.resolve();
+ await state.done(() => {
+ testing.expectEqual(null, results.ok);
+ testing.expectEqual("OperationError", results.nullLength);
+ for (const name of ["nan", "infinity", "negative", "tooLarge"]) {
+ testing.expectEqual(`${name}: TypeError`, `${name}: ${results[name]}`);
+ }
+ testing.expectEqual("OperationError", results.hugeLength);
+ testing.expectEqual("OperationError", results.hugeIterations);
+ });
+</script>
+
<script id=rsa-oaep-roundtrip type=module>
const state = await testing.async();
const { privateKey, publicKey } = await crypto.subtle.generateKey(
diff --git a/src/browser/webapi/Crypto.zig b/src/browser/webapi/Crypto.zig
index a3576d180..569af9b8c 100644
--- a/src/browser/webapi/Crypto.zig
+++ b/src/browser/webapi/Crypto.zig
@@ -96,5 +96,7 @@ pub const JsApi = struct {
const testing = @import("../../testing.zig");
test "WebApi: Crypto" {
+ // pbkdf2 limit tests
+ testing.expectLog(&.{ .js, .js });
try testing.htmlRunner("crypto.html", .{});
}
diff --git a/src/browser/webapi/SubtleCrypto.zig b/src/browser/webapi/SubtleCrypto.zig
index 73aac52e2..89d7a2719 100644
--- a/src/browser/webapi/SubtleCrypto.zig
+++ b/src/browser/webapi/SubtleCrypto.zig
@@ -389,16 +389,16 @@ fn exportJwk(key: *CryptoKey, exec: *const Execution) !Jwk {
}
/// Derive an array of bits from a base key. `length` is in bits and may be null
-/// (the WebIDL type is `unsigned long?`).
+/// (the WebIDL type is `[EnforceRange] unsigned long?`).
pub fn deriveBits(
_: *const SubtleCrypto,
algo: algorithm.Derive,
base_key: *const CryptoKey,
- length: ?u32,
+ length: ?js.EnforceRange(u32),
exec: *const Execution,
) !js.Promise {
const local = exec.js.local.?;
- const bits = try deriveRaw(algo, base_key, length, base_key.canDeriveBits(), exec);
+ const bits = try deriveRaw(algo, base_key, if (length) |l| l.value else null, base_key.canDeriveBits(), exec);
return local.resolvePromise(js.ArrayBuffer{ .values = bits });
}
diff --git a/src/browser/webapi/crypto/KDF.zig b/src/browser/webapi/crypto/KDF.zig
index 5f312f1df..2343253ff 100644
--- a/src/browser/webapi/crypto/KDF.zig
+++ b/src/browser/webapi/crypto/KDF.zig
@@ -20,6 +20,7 @@
//! on a raw "secret" base key (imported via the `raw` format).
const std = @import("std");
+const lp = @import("lightpanda");
const js = @import("../../js/js.zig");
const CryptoKey = @import("../CryptoKey.zig");
@@ -28,6 +29,11 @@ const crypto = @import("../../../sys/libcrypto.zig");
const algorithm = @import("algorithm.zig");
const Execution = js.Execution;
+const log = lp.log;
+
+/// PBKDF2 runs synchronously on the JS thread and can't be interrupted, so cap
+/// its cost.
+const PBKDF2_MAX_WORK: u64 = 1 << 24;
/// Errors a derivation can raise, each mapping to a specific DOMException name.
pub const Error = error{ InvalidAccessError, NotSupported, OperationError, OutOfMemory };
@@ -64,13 +70,21 @@ pub fn pbkdf2(
) Error![]const u8 {
try checkBaseKey(base_key, "PBKDF2", usage_ok);
const digest = crypto.findDigest(params.hash.name()) catch return error.NotSupported;
- const out = try exec.local_arena.alloc(u8, try outputLen(length));
+ const out_len = try outputLen(length);
// A zero-length derivation is valid and yields an empty buffer; the C
// routines reject a zero output length, so short-circuit here.
- if (out.len == 0) {
- return out;
+ if (out_len == 0) {
+ return &.{};
}
+ const blocks = std.math.divCeil(usize, out_len, crypto.EVP_MD_size(digest)) catch unreachable;
+ if (@as(u64, blocks) * params.iterations > PBKDF2_MAX_WORK) {
+ log.warn(.js, "PBKDF2 work limit", .{ .length = out_len, .iterations = params.iterations });
+ return error.OperationError;
+ }
+
+ const out = try exec.local_arena.alloc(u8, out_len);
+
const salt = params.salt.values;
const res = crypto.PKCS5_PBKDF2_HMAC(
@ptrCast(base_key._key.ptr),
diff --git a/src/browser/webapi/webcodecs/AudioData.zig b/src/browser/webapi/webcodecs/AudioData.zig
index f8de12a24..7eea1d8b7 100644
--- a/src/browser/webapi/webcodecs/AudioData.zig
+++ b/src/browser/webapi/webcodecs/AudioData.zig
@@ -68,18 +68,18 @@ pub const Format = enum {
const Init = struct {
data: js.AllowSharedBufferSource,
format: []const u8,
- numberOfChannels: f64,
- numberOfFrames: f64,
+ numberOfChannels: js.EnforceRange(u32),
+ numberOfFrames: js.EnforceRange(u32),
sampleRate: f64,
- timestamp: f64,
+ timestamp: js.EnforceRange(i64),
transfer: []const js.Value = &.{},
};
fn init(init_: Init, exec: *const Execution) !*AudioData {
const format = std.meta.stringToEnum(Format, init_.format) orelse return error.TypeError;
- const frames = try common.enforceRange(u32, init_.numberOfFrames);
- const channels = try common.enforceRange(u32, init_.numberOfChannels);
- const timestamp = try common.enforceRange(i64, init_.timestamp);
+ const frames = init_.numberOfFrames.value;
+ const channels = init_.numberOfChannels.value;
+ const timestamp = init_.timestamp.value;
if (std.math.isFinite(init_.sampleRate) == false) {
return error.TypeError;
}
@@ -194,9 +194,9 @@ fn getDuration(self: *const AudioData) u64 {
const CopyToOptions = struct {
format: ?[]const u8 = null,
- frameCount: ?f64 = null,
- frameOffset: f64 = 0,
- planeIndex: f64,
+ frameCount: ?js.EnforceRange(u32) = null,
+ frameOffset: js.EnforceRange(u32) = .{},
+ planeIndex: js.EnforceRange(u32),
};
// The parsed options, after "Compute Copy Element Count".
@@ -214,9 +214,9 @@ const Copy = struct {
fn computeCopy(self: *const AudioData, options: CopyToOptions) !Copy {
const source_format = self._format orelse return error.InvalidStateError;
- const plane_index = try common.enforceRange(u32, options.planeIndex);
- const frame_offset = try common.enforceRange(u32, options.frameOffset);
- const requested_count = try common.optionalEnforceRange(u32, options.frameCount);
+ const plane_index = options.planeIndex.value;
+ const frame_offset = options.frameOffset.value;
+ const requested_count = if (options.frameCount) |c| c.value else null;
const format = if (options.format) |f|
std.meta.stringToEnum(Format, f) orelse return error.TypeError
diff --git a/src/browser/webapi/webcodecs/AudioDecoder.zig b/src/browser/webapi/webcodecs/AudioDecoder.zig
index e7732eb9e..16ea776b8 100644
--- a/src/browser/webapi/webcodecs/AudioDecoder.zig
+++ b/src/browser/webapi/webcodecs/AudioDecoder.zig
@@ -43,8 +43,8 @@ _core: codec.Core(AudioDecoder),
pub const Config = struct {
codec: []const u8,
description: ?js.Value = null,
- numberOfChannels: f64,
- sampleRate: f64,
+ numberOfChannels: js.EnforceRange(u32),
+ sampleRate: js.EnforceRange(u32),
// "valid AudioDecoderConfig", plus the Opus registration's check.
pub fn isValid(self: Config) bool {
@@ -52,8 +52,8 @@ pub const Config = struct {
if (self.description) |d| {
if (codec.isDetachedBuffer(d)) return false;
}
- const channels = common.enforceRange(u32, self.numberOfChannels) catch return false;
- const sample_rate = common.enforceRange(u32, self.sampleRate) catch return false;
+ const channels = self.numberOfChannels.value;
+ const sample_rate = self.sampleRate.value;
if (channels == 0 or sample_rate == 0) return false;
if (std.mem.eql(u8, self.codec, "opus") and channels > 2 and self.description == null) return false;
return true;
diff --git a/src/browser/webapi/webcodecs/AudioEncoder.zig b/src/browser/webapi/webcodecs/AudioEncoder.zig
index 671f418a8..801b17b97 100644
--- a/src/browser/webapi/webcodecs/AudioEncoder.zig
+++ b/src/browser/webapi/webcodecs/AudioEncoder.zig
@@ -42,13 +42,13 @@ _core: codec.Core(AudioEncoder),
pub const Config = struct {
aac: ?Aac = null,
- bitrate: ?f64 = null,
+ bitrate: ?js.EnforceRange(u64) = null,
bitrateMode: []const u8 = "variable",
codec: []const u8,
flac: ?Flac = null,
- numberOfChannels: f64,
+ numberOfChannels: js.EnforceRange(u32),
opus: ?Opus = null,
- sampleRate: f64,
+ sampleRate: js.EnforceRange(u32),
// AacEncoderConfig, from the AAC registration
const Aac = struct {
@@ -57,17 +57,17 @@ pub const Config = struct {
// FlacEncoderConfig, from the FLAC registration
const Flac = struct {
- blockSize: f64 = 0,
- compressLevel: f64 = 5,
+ blockSize: js.EnforceRange(u32) = .{},
+ compressLevel: js.EnforceRange(u32) = .{ .value = 5 },
};
// OpusEncoderConfig, from the Opus registration
const Opus = struct {
application: []const u8 = "audio",
- complexity: ?f64 = null,
+ complexity: ?js.EnforceRange(u32) = null,
format: []const u8 = "opus",
- frameDuration: f64 = 20000,
- packetlossperc: f64 = 0,
+ frameDuration: js.EnforceRange(u64) = .{ .value = 20000 },
+ packetlossperc: js.EnforceRange(u32) = .{},
signal: []const u8 = "auto",
usedtx: bool = false,
useinbandfec: bool = false,
@@ -77,13 +77,12 @@ pub const Config = struct {
if (codec.checkEnum(self.format, &.{ "opus", "ogg" }) == false) return false;
if (codec.checkEnum(self.signal, &.{ "auto", "music", "voice" }) == false) return false;
// RFC 6716 frames are 2.5 to 20ms; a packet holds up to 120ms of them
- const duration = common.enforceRange(u64, self.frameDuration) catch return false;
+ const duration = self.frameDuration.value;
if (duration < 2500 or duration > 120_000 or duration % 2500 != 0) return false;
- if (common.optionalEnforceRange(u32, self.complexity) catch return false) |complexity| {
- if (complexity > 10) return false;
+ if (self.complexity) |complexity| {
+ if (complexity.value > 10) return false;
}
- const packetlossperc = common.enforceRange(u32, self.packetlossperc) catch return false;
- return packetlossperc <= 100;
+ return self.packetlossperc.value <= 100;
}
};
@@ -91,21 +90,15 @@ pub const Config = struct {
pub fn isValid(self: Config) bool {
if (codec.isEmptyCodec(self.codec)) return false;
if (codec.checkEnum(self.bitrateMode, &.{ "constant", "variable" }) == false) return false;
- const channels = common.enforceRange(u32, self.numberOfChannels) catch return false;
- const sample_rate = common.enforceRange(u32, self.sampleRate) catch return false;
- if (channels == 0 or sample_rate == 0) return false;
+ if (self.numberOfChannels.value == 0 or self.sampleRate.value == 0) return false;
- const bitrate = common.optionalEnforceRange(u64, self.bitrate) catch return false;
+ const bitrate = if (self.bitrate) |b| b.value else null;
// Not in the spec, but every engine and WPT reject it.
if (bitrate == 0) return false;
if (self.aac) |aac| {
if (codec.checkEnum(aac.format, &.{ "aac", "adts" }) == false) return false;
}
- if (self.flac) |flac| {
- _ = common.enforceRange(u32, flac.blockSize) catch return false;
- _ = common.enforceRange(u32, flac.compressLevel) catch return false;
- }
if (std.mem.eql(u8, self.codec, "opus")) {
if (self.opus) |opus| {
if (opus.isValid() == false) return false;
diff --git a/src/browser/webapi/webcodecs/VideoDecoder.zig b/src/browser/webapi/webcodecs/VideoDecoder.zig
index d78ed5c08..a321ad231 100644
--- a/src/browser/webapi/webcodecs/VideoDecoder.zig
+++ b/src/browser/webapi/webcodecs/VideoDecoder.zig
@@ -43,12 +43,12 @@ _core: codec.Core(VideoDecoder),
pub const Config = struct {
codec: []const u8,
- codedHeight: ?f64 = null,
- codedWidth: ?f64 = null,
+ codedHeight: ?js.EnforceRange(u32) = null,
+ codedWidth: ?js.EnforceRange(u32) = null,
colorSpace: ?VideoColorSpace.Init = null,
description: ?js.Value = null,
- displayAspectHeight: ?f64 = null,
- displayAspectWidth: ?f64 = null,
+ displayAspectHeight: ?js.EnforceRange(u32) = null,
+ displayAspectWidth: ?js.EnforceRange(u32) = null,
flip: bool = false,
hardwareAcceleration: []const u8 = "no-preference",
optimizeForLatency: bool = false,
@@ -71,11 +71,10 @@ pub const Config = struct {
}
// Both or neither, and neither zero.
- fn pairIsInvalid(a: ?f64, b: ?f64) bool {
- if ((a == null) != (b == null)) return true;
- const x = common.optionalEnforceRange(u32, a) catch return true;
- const y = common.optionalEnforceRange(u32, b) catch return true;
- return x == 0 or y == 0;
+ fn pairIsInvalid(a: ?js.EnforceRange(u32), b: ?js.EnforceRange(u32)) bool {
+ const x = a orelse return b != null;
+ const y = b orelse return true;
+ return x.value == 0 or y.value == 0;
}
};
diff --git a/src/browser/webapi/webcodecs/VideoEncoder.zig b/src/browser/webapi/webcodecs/VideoEncoder.zig
index 6d6d2d39e..f492240dd 100644
--- a/src/browser/webapi/webcodecs/VideoEncoder.zig
+++ b/src/browser/webapi/webcodecs/VideoEncoder.zig
@@ -44,19 +44,19 @@ pub const Config = struct {
alpha: []const u8 = "discard",
av1: ?Av1 = null,
avc: ?Avc = null,
- bitrate: ?f64 = null,
+ bitrate: ?js.EnforceRange(u64) = null,
bitrateMode: []const u8 = "variable",
codec: []const u8,
contentHint: ?[]const u8 = null,
- displayHeight: ?f64 = null,
- displayWidth: ?f64 = null,
+ displayHeight: ?js.EnforceRange(u32) = null,
+ displayWidth: ?js.EnforceRange(u32) = null,
framerate: ?f64 = null,
hardwareAcceleration: []const u8 = "no-preference",
- height: f64,
+ height: js.EnforceRange(u32),
hevc: ?Hevc = null,
latencyMode: []const u8 = "quality",
scalabilityMode: ?[]const u8 = null,
- width: f64,
+ width: js.EnforceRange(u32),
// the codec registrations' extensions
const Av1 = struct {
@@ -86,16 +86,18 @@ pub const Config = struct {
if (std.math.isFinite(framerate) == false) return false;
}
- const width = common.enforceRange(u32, self.width) catch return false;
- const height = common.enforceRange(u32, self.height) catch return false;
- if (width == 0 or height == 0) return false;
- const display_width = common.optionalEnforceRange(u32, self.displayWidth) catch return false;
- const display_height = common.optionalEnforceRange(u32, self.displayHeight) catch return false;
- if (display_width == 0 or display_height == 0) return false;
+ if (self.width.value == 0 or self.height.value == 0) return false;
+ if (self.displayWidth) |w| {
+ if (w.value == 0) return false;
+ }
+ if (self.displayHeight) |h| {
+ if (h.value == 0) return false;
+ }
- const bitrate = common.optionalEnforceRange(u64, self.bitrate) catch return false;
- // Not in the spec, but every engine and WPT reject it.
- if (bitrate == 0) return false;
+ if (self.bitrate) |b| {
+ // Not in the spec, but every engine and WPT reject it.
+ if (b.value == 0) return false;
+ }
return true;
}
};
diff --git a/src/browser/webapi/webcodecs/VideoFrame.zig b/src/browser/webapi/webcodecs/VideoFrame.zig
index 9f510d3d3..b6133e816 100644
--- a/src/browser/webapi/webcodecs/VideoFrame.zig
+++ b/src/browser/webapi/webcodecs/VideoFrame.zig
@@ -215,8 +215,8 @@ const RectInit = struct {
};
const PlaneLayoutInit = struct {
- offset: f64,
- stride: f64,
+ offset: js.EnforceRange(u32),
+ stride: js.EnforceRange(u32),
};
const PlaneLayout = struct {
@@ -226,17 +226,17 @@ const PlaneLayout = struct {
// VideoFrameBufferInit
const BufferInit = struct {
- codedHeight: f64,
- codedWidth: f64,
+ codedHeight: js.EnforceRange(u32),
+ codedWidth: js.EnforceRange(u32),
colorSpace: ?VideoColorSpace.Init = null,
- displayHeight: ?f64 = null,
- displayWidth: ?f64 = null,
- duration: ?f64 = null,
+ displayHeight: ?js.EnforceRange(u32) = null,
+ displayWidth: ?js.EnforceRange(u32) = null,
+ duration: ?js.EnforceRange(u64) = null,
flip: bool = false,
format: []const u8,
layout: ?[]const PlaneLayoutInit = null,
rotation: f64 = 0,
- timestamp: f64,
+ timestamp: js.EnforceRange(i64),
transfer: []const js.Value = &.{},
visibleRect: ?RectInit = null,
};
@@ -244,12 +244,12 @@ const BufferInit = struct {
// VideoFrameInit
const ImageInit = struct {
alpha: []const u8 = "keep",
- displayHeight: ?f64 = null,
- displayWidth: ?f64 = null,
- duration: ?f64 = null,
+ displayHeight: ?js.EnforceRange(u32) = null,
+ displayWidth: ?js.EnforceRange(u32) = null,
+ duration: ?js.EnforceRange(u64) = null,
flip: bool = false,
rotation: f64 = 0,
- timestamp: ?f64 = null,
+ timestamp: ?js.EnforceRange(i64) = null,
visibleRect: ?RectInit = null,
};
@@ -337,12 +337,12 @@ fn rectMember(value: f64) !u32 {
const DisplaySize = struct { width: u32, height: u32 };
-fn explicitDisplaySize(width: ?f64, height: ?f64) !?DisplaySize {
+fn explicitDisplaySize(width: ?js.EnforceRange(u32), height: ?js.EnforceRange(u32)) !?DisplaySize {
if ((width == null) != (height == null)) {
return error.TypeError;
}
- const w = try common.optionalEnforceRange(u32, width) orelse return null;
- const h = (try common.optionalEnforceRange(u32, height)).?;
+ const w = (width orelse return null).value;
+ const h = height.?.value;
if (w == 0 or h == 0) {
return error.TypeError;
}
@@ -351,10 +351,10 @@ fn explicitDisplaySize(width: ?f64, height: ?f64) !?DisplaySize {
fn fromBuffer(data: []const u8, init: BufferInit, page: *Page) !*VideoFrame {
const format = try parseFormat(init.format);
- const coded_width = try common.enforceRange(u32, init.codedWidth);
- const coded_height = try common.enforceRange(u32, init.codedHeight);
- const timestamp = try common.enforceRange(i64, init.timestamp);
- const duration = try common.optionalEnforceRange(u64, init.duration);
+ const coded_width = init.codedWidth.value;
+ const coded_height = init.codedHeight.value;
+ const timestamp = init.timestamp.value;
+ const duration = if (init.duration) |d| d.value else null;
const display = try explicitDisplaySize(init.displayWidth, init.displayHeight);
const rotation = try parseRotation(init.rotation);
const color_space: VideoColorSpace.Value = if (init.colorSpace) |cs| try cs.toValue() else defaultColorSpace(format);
@@ -447,8 +447,8 @@ fn fromFrame(other: *const VideoFrame, init: ImageInit, page: *Page) !*VideoFram
const resource = other._resource.?;
const keep_alpha = try parseAlpha(init.alpha);
const format = if (keep_alpha) other_format else other_format.opaqueFormat();
- const timestamp = if (init.timestamp) |t| try common.enforceRange(i64, t) else other._timestamp;
- const duration = if (init.duration) |d| try common.enforceRange(u64, d) else other._duration;
+ const timestamp = if (init.timestamp) |t| t.value else other._timestamp;
+ const duration = if (init.duration) |d| d.value else other._duration;
const self = try create(resource.acquire(), page);
errdefer self.deinit(page);
@@ -485,8 +485,8 @@ fn fromCanvas(width: u32, height: u32, init: ImageInit, page: *Page) !*VideoFram
if (width > max_canvas_dimension or height > max_canvas_dimension or @as(u64, width) * height > max_canvas_pixels) {
return error.InvalidStateError;
}
- const timestamp = try common.enforceRange(i64, init.timestamp orelse return error.TypeError);
- const duration = try common.optionalEnforceRange(u64, init.duration);
+ const timestamp = (init.timestamp orelse return error.TypeError).value;
+ const duration = if (init.duration) |d| d.value else null;
const keep_alpha = try parseAlpha(init.alpha);
const format: PixelFormat = if (keep_alpha) .RGBA else .RGBX;
@@ -684,9 +684,9 @@ fn computeLayout(rect: Rect, format: PixelFormat, layout: ?[]const PlaneLayoutIn
.stride = undefined,
};
if (layout) |l| {
- const stride = try common.enforceRange(u32, l[i].stride);
+ const stride = l[i].stride.value;
if (stride < computed.source_width_bytes) return error.TypeError;
- computed.offset = try common.enforceRange(u32, l[i].offset);
+ computed.offset = l[i].offset.value;
computed.stride = stride;
} else {
computed.offset = min_size;
diff --git a/src/browser/webapi/webcodecs/codec.zig b/src/browser/webapi/webcodecs/codec.zig
index 8f612d9ff..f4796a672 100644
--- a/src/browser/webapi/webcodecs/codec.zig
+++ b/src/browser/webapi/webcodecs/codec.zig
@@ -319,6 +319,8 @@ fn cloneMember(local: *const js.Local, object: js.Object, comptime name: []const
// description: an AllowSharedBufferSource
const bytes = (try value.toZig(js.AllowSharedBufferSource)).bytes;
_ = try object.set(name, js.ArrayBuffer{ .values = bytes }, .{});
+ } else if (comptime @typeInfo(T) == .@"struct" and @hasDecl(T, "js_enforce_range")) {
+ _ = try object.set(name, value.value, .{});
} else if (T != []const u8 and @typeInfo(T) == .@"struct") {
_ = try object.set(name, try cloneConfig(local, value), .{});
} else {
diff --git a/src/browser/webapi/webcodecs/common.zig b/src/browser/webapi/webcodecs/common.zig
index 584fdb1f6..0ffdd186d 100644
--- a/src/browser/webapi/webcodecs/common.zig
+++ b/src/browser/webapi/webcodecs/common.zig
@@ -18,38 +18,8 @@
// Helpers shared by the WebCodecs interfaces.
-const std = @import("std");
-
const js = @import("../../js/js.zig");
-// WebIDL [EnforceRange]: we take such members as f64 since our integer
-// conversion wraps (ToInt32 and friends) instead of throwing.
-pub fn enforceRange(comptime T: type, value: f64) !T {
- if (std.math.isFinite(value) == false) {
- return error.TypeError;
- }
- const truncated = @trunc(value);
- const min: f64 = switch (T) {
- u32 => 0,
- u64 => 0,
- i64 => -9007199254740991,
- else => @compileError("unsupported [EnforceRange] type"),
- };
- const max: f64 = switch (T) {
- u32 => 4294967295,
- u64, i64 => 9007199254740991,
- else => unreachable,
- };
- if (truncated < min or truncated > max) {
- return error.TypeError;
- }
- return @intFromFloat(truncated);
-}
-
-pub fn optionalEnforceRange(comptime T: type, value: ?f64) !?T {
- return try enforceRange(T, value orelse return null);
-}
-
// The `transfer` member of the WebCodecs init dictionaries. Checked before
// anything is copied, and detached once the copy is made.
pub const Transfer = struct {
@@ -86,13 +56,3 @@ pub const Transfer = struct {
return detached.isTrue();
}
};
-
-const testing = std.testing;
-test "webcodecs: enforceRange" {
- try testing.expectEqual(@as(u32, 5), try enforceRange(u32, 5.9));
- try testing.expectEqual(@as(i64, -10), try enforceRange(i64, -10));
- try testing.expectError(error.TypeError, enforceRange(u32, -1));
- try testing.expectError(error.TypeError, enforceRange(u32, 4294967296));
- try testing.expectError(error.TypeError, enforceRange(i64, std.math.nan(f64)));
- try testing.expectError(error.TypeError, enforceRange(u64, std.math.inf(f64)));
-}
diff --git a/src/browser/webapi/webcodecs/encoded_chunk.zig b/src/browser/webapi/webcodecs/encoded_chunk.zig
index f9df0d4c3..8f3dc2014 100644
--- a/src/browser/webapi/webcodecs/encoded_chunk.zig
+++ b/src/browser/webapi/webcodecs/encoded_chunk.zig
@@ -50,16 +50,16 @@ fn EncodedChunk(comptime interface_name: [:0]const u8) type {
const Init = struct {
data: js.AllowSharedBufferSource,
- duration: ?f64 = null,
- timestamp: f64,
+ duration: ?js.EnforceRange(u64) = null,
+ timestamp: js.EnforceRange(i64),
transfer: []const js.Value = &.{},
type: []const u8,
};
pub fn init(init_: Init, exec: *const Execution) !*Self {
const chunk_type = std.meta.stringToEnum(Type, init_.type) orelse return error.TypeError;
- const timestamp = try common.enforceRange(i64, init_.timestamp);
- const duration = try common.optionalEnforceRange(u64, init_.duration);
+ const timestamp = init_.timestamp.value;
+ const duration = if (init_.duration) |d| d.value else null;
const transfer: common.Transfer = .{ .buffers = init_.transfer };
try transfer.check();
diff --git a/src/network/cache/SqliteCache.zig b/src/network/cache/SqliteCache.zig
index 457510107..aa865fc31 100644
--- a/src/network/cache/SqliteCache.zig
+++ b/src/network/cache/SqliteCache.zig
@@ -441,7 +441,7 @@ pub fn renew(self: *SqliteCache, _: std.mem.Allocator, req: RenewResponse) !void
});
}
-const testing = std.testing;
+const testing = @import("../../testing.zig");
fn setupCache(allocator: std.mem.Allocator) !Cache {
return Cache{ .kind = .{ .sqlite = try .init(allocator, .memory, 0) } };
@@ -489,9 +489,9 @@ test "SqliteCache: basic put and get" {
);
try testing.expect(result == .hit);
- try testing.expectEqualStrings("hello world", result.hit.data.buffer);
+ try testing.expectEqual("hello world", result.hit.data.buffer);
try testing.expectEqual(@as(u16, 200), result.hit.status);
- try testing.expectEqualStrings("text/html", result.hit.content_type);
+ try testing.expectEqual("text/html", result.hit.content_type);
}
test "SqliteCache: get expiration" {
@@ -538,7 +538,7 @@ test "SqliteCache: get expiration" {
},
);
try testing.expect(stale == .revalidate);
- try testing.expectEqualStrings("hello world", stale.revalidate.data.buffer);
+ try testing.expectEqual("hello world", stale.revalidate.data.buffer);
}
test "SqliteCache: get expiration (without validators)" {
@@ -615,7 +615,7 @@ test "SqliteCache: put override" {
},
);
try testing.expect(result == .hit);
- try testing.expectEqualStrings("hello world", result.hit.data.buffer);
+ try testing.expectEqual("hello world", result.hit.data.buffer);
}
{
@@ -640,7 +640,7 @@ test "SqliteCache: put override" {
},
);
try testing.expect(result == .hit);
- try testing.expectEqualStrings("goodbye world", result.hit.data.buffer);
+ try testing.expectEqual("goodbye world", result.hit.data.buffer);
}
}
@@ -673,7 +673,7 @@ test "SqliteCache: vary hit and miss" {
.request_headers = &.{.{ .name = "Accept-Encoding", .value = "gzip" }},
});
try testing.expect(hit == .hit);
- try testing.expectEqualStrings("hello world", hit.hit.data.buffer);
+ try testing.expectEqual("hello world", hit.hit.data.buffer);
const mismatch = try cache.get(arena.allocator(), .{
.url = "https://example.com",
@@ -723,7 +723,7 @@ test "SqliteCache: vary multiple headers" {
},
});
try testing.expect(hit == .hit);
- try testing.expectEqualStrings("hello world", hit.hit.data.buffer);
+ try testing.expectEqual("hello world", hit.hit.data.buffer);
const mismatch = try cache.get(arena.allocator(), .{
.url = "https://example.com",
@@ -844,7 +844,7 @@ test "SqliteCache: put after clear works" {
},
);
try testing.expect(result == .hit);
- try testing.expectEqualStrings("after clear", result.hit.data.buffer);
+ try testing.expectEqual("after clear", result.hit.data.buffer);
}
test "SqliteCache: evict removes entry" {
@@ -966,7 +966,7 @@ test "SqliteCache: renew preserves body" {
},
);
try testing.expect(result == .hit);
- try testing.expectEqualStrings("original body", result.hit.data.buffer);
+ try testing.expectEqual("original body", result.hit.data.buffer);
}
test "SqliteCache: renew merges the 304's headers into the stored ones" {
@@ -1024,8 +1024,8 @@ test "SqliteCache: renew merges the 304's headers into the stored ones" {
const headers = result.hit.headers;
try testing.expectEqual(expected.len, headers.len);
for (expected, headers) |e, h| {
- try testing.expectEqualStrings(e.name, h.name);
- try testing.expectEqualStrings(e.value, h.value);
+ try testing.expectEqual(e.name, h.name);
+ try testing.expectEqual(e.value, h.value);
}
}
@@ -1157,11 +1157,12 @@ test "SqliteCache: evicts oldest entries over the limit" {
.request_headers = &.{},
});
try testing.expect(hit == .hit);
- try testing.expectEqualStrings(url, hit.hit.data.buffer);
+ try testing.expectEqual(url, hit.hit.data.buffer);
}
}
test "SqliteCache: starts over from an unreadable database" {
+ testing.expectLog(&.{.cache});
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
try tmp.dir.writeFile(testing.io, .{ .sub_path = "cache.db", .data = "This is not an SQLite database, only a page of text where its header would be." });
@@ -1194,5 +1195,5 @@ test "SqliteCache: starts over from an unreadable database" {
.request_headers = &.{},
});
try testing.expect(result == .hit);
- try testing.expectEqualStrings("hello world", result.hit.data.buffer);
+ try testing.expectEqual("hello world", result.hit.data.buffer);
}