Skip to content

Commit

Permalink
fix: prevent segmentation fault if mesuring empty text
Browse files Browse the repository at this point in the history
Close #426
  • Loading branch information
Brooooooklyn committed Mar 10, 2022
1 parent 4c9ac1e commit 2117ddb
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
14 changes: 14 additions & 0 deletions __test__/draw.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -578,6 +578,20 @@ test('measureText', (t) => {
t.true(Math.abs(metrics.actualBoundingBoxRight - 372) < 0.001)
})

test('measureText with empty string should not throw', (t) => {
const { ctx } = t.context
ctx.font = '50px Iosevka Slab'
t.deepEqual(ctx.measureText(''), {
actualBoundingBoxAscent: 0,
actualBoundingBoxDescent: 0,
actualBoundingBoxLeft: 0,
actualBoundingBoxRight: 0,
fontBoundingBoxAscent: 0,
fontBoundingBoxDescent: 0,
width: 0,
})
})

test('moveTo', async (t) => {
const { ctx } = t.context
ctx.beginPath()
Expand Down
16 changes: 14 additions & 2 deletions src/ctx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1338,11 +1338,23 @@ fn line_to(ctx: CallContext) -> Result<JsUndefined> {
fn measure_text(ctx: CallContext) -> Result<JsObject> {
let text = ctx.get::<JsString>(0)?.into_utf8()?;
let this = ctx.this_unchecked::<JsObject>();
let mut metrics = ctx.env.create_object()?;
let text_str = text.as_str()?;
if text_str.is_empty() {
metrics.set_named_property("actualBoundingBoxAscent", ctx.env.create_double(0.0f64)?)?;
metrics.set_named_property("actualBoundingBoxDescent", ctx.env.create_double(0.0f64)?)?;
metrics.set_named_property("actualBoundingBoxLeft", ctx.env.create_double(0.0f64)?)?;
metrics.set_named_property("actualBoundingBoxRight", ctx.env.create_double(0.0f64)?)?;
metrics.set_named_property("fontBoundingBoxAscent", ctx.env.create_double(0.0f64)?)?;
metrics.set_named_property("fontBoundingBoxDescent", ctx.env.create_double(0.0f64)?)?;
metrics.set_named_property("width", ctx.env.create_double(0.0f64)?)?;
return Ok(metrics);
}

let context_2d = ctx.env.unwrap::<Context>(&this)?;

let m = context_2d.get_line_metrics(text.as_str()?)?.0;
let m = context_2d.get_line_metrics(text_str)?.0;

let mut metrics = ctx.env.create_object()?;
metrics.set_named_property(
"actualBoundingBoxAscent",
ctx.env.create_double(m.ascent as f64)?,
Expand Down

0 comments on commit 2117ddb

Please sign in to comment.