more type fixes and rethinking writeStructs

This commit is contained in:
Kevin Jahns
2019-04-02 23:08:58 +02:00
parent 73c28952c2
commit e23582b1cd
35 changed files with 952 additions and 695 deletions

View File

@@ -4,6 +4,8 @@
import * as decoding from 'lib0/decoding.js'
import * as encoding from 'lib0/encoding.js'
import * as error from 'lib0/error.js'
import { AbstractType } from '../types/AbstractType.js' // eslint-disable-line
export class ID {
/**
@@ -46,14 +48,19 @@ export class ID {
}
}
/**
* @param {ID} a
* @param {ID} b
* @return {boolean}
*/
export const compareIDs = (a, b) => a === b || (a !== null && b !== null && a.client === b.client && a.clock === b.clock)
/**
* @param {number} client
* @param {number} clock
*/
export const createID = (client, clock) => new ID(client, clock)
const isNullID = 0xFFFFFF
/**
* @param {encoding.Encoder} encoder
* @param {ID} id
@@ -63,21 +70,31 @@ export const writeID = (encoder, id) => {
encoding.writeVarUint(encoder, id.clock)
}
/**
* @param {encoding.Encoder} encoder
*/
export const writeNullID = (encoder) =>
encoding.writeVarUint(encoder, isNullID)
/**
* Read ID.
* * If first varUint read is 0xFFFFFF a RootID is returned.
* * Otherwise an ID is returned
*
* @param {decoding.Decoder} decoder
* @return {ID | null}
* @return {ID}
*/
export const readID = decoder => {
const client = decoding.readVarUint(decoder)
return client === isNullID ? null : createID(client, decoding.readVarUint(decoder))
export const readID = decoder =>
createID(decoding.readVarUint(decoder), decoding.readVarUint(decoder))
/**
* The top types are mapped from y.share.get(keyname) => type.
* `type` does not store any information about the `keyname`.
* This function finds the correct `keyname` for `type` and throws otherwise.
*
* @param {AbstractType} type
* @return {string}
*/
export const findRootTypeKey = type => {
// @ts-ignore _y must be defined, otherwise unexpected case
for (let [key, value] of type._y.share) {
if (value === type) {
return key
}
}
throw error.unexpectedCase()
}