Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions lib/projection.js
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,12 @@ class Emitter {
out.push(`${indent}} else {`)
out.push(`${indent} if (!Array.isArray(${src})) typeMismatch(${this.pointerIndex(pointer)})`)
out.push(`${indent} const ${n} = ${src}.length`)
out.push(`${indent} ${pool}.length = ${n}`)
// Assigning to `length` is not a plain store: it goes through the array
// length setter even when the value does not change, and that costs more
// than copying a few items. Skip it when the pool already has the right
// length, which is the case whenever two consecutive calls serialize an
// array of the same size.
out.push(`${indent} if (${pool}.length !== ${n}) ${pool}.length = ${n}`)
if (items.type === 'object' || items.type === 'array') {
// Pool of per-element slot holders; each holder owns the scratch tree of
// one element (nested objects and arrays included). Grows to the longest
Expand Down Expand Up @@ -329,13 +334,13 @@ const projectionHelpers = `
const asStringValue = (v) => {
if (typeof v === 'string') return v
if (v === null) return ''
if (v instanceof Date) return v.toISOString()
if (v instanceof Date) return serializer.asDateTimeValue(v)
if (v instanceof RegExp) return v.source
return v.toString()
}
const asDateTimeValue = (v) => {
if (v === null) return ''
if (v instanceof Date) return v.toISOString()
if (v instanceof Date) return serializer.asDateTimeValue(v)
if (typeof v === 'string') return v
throw new Error('The value "' + v + '" cannot be converted to a date-time.')
}
Expand Down
27 changes: 27 additions & 0 deletions lib/serializer.js
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,33 @@ module.exports = class Serializer {
throw new Error(`The value "${date}" cannot be converted to a time.`)
}

// The ISO 8601 date-time of a Date, without quotes: the same string as
// Date.prototype.toISOString(), for the objectMechanism 'native' scratch.
// It is built with a single String.fromCharCode() call so that it is a flat
// string: the native JSON.stringify is much slower on a string made by
// concatenation, which is what asDateTime() returns.
asDateTimeValue (date) {
const year = date.getUTCFullYear()
// also true for an invalid Date, whose toISOString() throws
if (!(year >= 0 && year <= 9999)) return date.toISOString()
const month = date.getUTCMonth() + 1
const day = date.getUTCDate()
const hours = date.getUTCHours()
const minutes = date.getUTCMinutes()
const seconds = date.getUTCSeconds()
const ms = date.getUTCMilliseconds()
return String.fromCharCode(
48 + (year / 1000 | 0), 48 + (year / 100 | 0) % 10, 48 + (year / 10 | 0) % 10, 48 + year % 10,
45, 48 + (month / 10 | 0), 48 + month % 10,
45, 48 + (day / 10 | 0), 48 + day % 10,
84, 48 + (hours / 10 | 0), 48 + hours % 10,
58, 48 + (minutes / 10 | 0), 48 + minutes % 10,
58, 48 + (seconds / 10 | 0), 48 + seconds % 10,
46, 48 + (ms / 100 | 0), 48 + (ms / 10 | 0) % 10, 48 + ms % 10,
90
)
}

asString (str) {
return asString(str)
}
Expand Down
75 changes: 75 additions & 0 deletions test/object-mechanism-native.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,81 @@ test('native mechanism: array root of primitives', t => {
}
})

test('native mechanism: Date values match the default mechanism', t => {
const schema = {
type: 'object',
properties: {
at: { type: 'string', format: 'date-time' },
maybe: { type: ['string', 'null'], format: 'date-time' },
list: { type: 'array', items: { type: 'string', format: 'date-time' } },
plain: { type: 'string' },
plainMaybe: { type: ['string', 'null'] },
plainList: { type: 'array', items: { type: 'string' } }
}
}
const def = build(schema)
const nat = build(schema, { objectMechanism: 'native' })

class LocalDate extends Date {
toISOString () { return 'overridden' }
}

const dates = [
new Date(0),
new Date(1),
new Date(-1),
new Date('2024-02-29T23:59:59.999Z'),
new Date('1999-12-31T00:00:00.000Z'),
new Date('2026-01-09T08:07:06.005Z'),
new Date('0000-01-01T00:00:00.000Z'),
new Date('9999-12-31T23:59:59.999Z'),
new Date(-62167219200001), // one millisecond before year 0
new Date(253402300800000), // first millisecond of year 10000
new Date(8.64e15),
new Date(-8.64e15),
new Date(NaN),
new LocalDate(86400000)
]

t.plan(dates.length + 2)
for (const date of dates) {
const input = { at: date, maybe: date, list: [date, date], plain: date, plainMaybe: date, plainList: [date, date] }
t.assert.deepStrictEqual(run(nat, input), run(def, input), String(date.getTime()))
}
t.assert.equal(
nat({ at: new Date(0), maybe: null, list: [], plain: new Date(1), plainMaybe: null, plainList: [] }),
'{"at":"1970-01-01T00:00:00.000Z","maybe":null,"list":[],"plain":"1970-01-01T00:00:00.001Z","plainMaybe":null,"plainList":[]}'
)
t.assert.equal(nat({ at: '2020-01-01T00:00:00.000Z' }), def({ at: '2020-01-01T00:00:00.000Z' }))
})

test('native mechanism: arrays that keep their length, grow, shrink and become null between calls', t => {
const schema = {
type: 'object',
properties: {
tags: { type: 'array', items: { type: 'string' } },
scores: { type: 'array', items: { type: 'number' } },
rows: {
type: 'array',
items: { type: 'object', properties: { id: { type: 'integer' }, labels: { type: 'array', items: { type: 'string' } } } }
}
}
}
const def = build(schema)
const nat = build(schema, { objectMechanism: 'native' })
const make = (n, seed) => ({
tags: Array.from({ length: n }, (_, i) => 't' + seed + i),
scores: Array.from({ length: n }, (_, i) => seed + i + 0.5),
rows: Array.from({ length: n }, (_, i) => ({ id: seed + i, labels: Array.from({ length: (i + n) % 4 }, (_, j) => 'l' + seed + j) }))
})
const inputs = [
make(0, 1), make(0, 2), make(5, 3), make(5, 4), make(2, 5), make(9, 6), make(9, 7),
{ tags: null, scores: null, rows: null }, make(3, 8), {}, make(3, 9), make(1, 10), make(9, 11)
]
t.plan(inputs.length)
for (const input of inputs) t.assert.equal(nat(input), def(input))
})

test('native mechanism generates projection code only for projectable schemas', t => {
const projectable = [
userSchema,
Expand Down
Loading