Skip to content

Commit

Permalink
Bounds checking when creating cursor
Browse files Browse the repository at this point in the history
  • Loading branch information
ept committed Feb 3, 2021
1 parent 08fd595 commit 64d10e6
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 0 deletions.
1 change: 1 addition & 0 deletions frontend/cursor.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ const { isObject } = require('../src/common')
class Cursor {
constructor(object, index, elemId = undefined) {
if (Array.isArray(object) && object[ELEM_IDS] && typeof index === 'number') {
if (index < 0 || index >= object[ELEM_IDS].length) throw new RangeError('list index out of bounds')
this.objectId = object[OBJECT_ID]
this.elemId = object[ELEM_IDS][index]
this.index = index
Expand Down
1 change: 1 addition & 0 deletions frontend/text.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ class Text {
}

getElemId (index) {
if (index < 0 || index >= this.elems.length) throw new RangeError('text index out of bounds')
return this.elems[index].elemId
}

Expand Down
15 changes: 15 additions & 0 deletions test/cursor_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,4 +39,19 @@ describe('Automerge.Cursor', () => {
assert.ok(s3.cursor instanceof Automerge.Cursor)
assert.strictEqual(s3.cursor.elemId, `4@${Automerge.getActorId(s1)}`)
})

it('should not allow an index beyond the length of the list', () => {
assert.throws(() => {
Automerge.change(Automerge.init(), doc => {
doc.list = [1]
doc.cursor = new Automerge.Cursor(doc.list, 1)
})
}, /index out of bounds/)
assert.throws(() => {
Automerge.change(Automerge.init(), doc => {
doc.text = new Automerge.Text('a')
doc.cursor = doc.text.getCursorAt(1)
})
}, /index out of bounds/)
})
})

0 comments on commit 64d10e6

Please sign in to comment.