diffusion
Version:
Diffusion JavaScript client
107 lines (79 loc) • 2.75 kB
JavaScript
var BinaryDeltaTypeImpl = require('data/binary/binary-delta-type-impl');
var BinaryDeltaImpl = require('data/binary/binary-delta-impl');
var BytesImpl = require('data/bytes-impl');
module.exports = function(
typeName,
valueClass,
implementation,
vToC,
cToV,
converters,
withBinaryDelta) {
var binaryDeltaType = withBinaryDelta ?
new BinaryDeltaTypeImpl(implementation, vToC, cToV) :
null;
var valueConverters = {};
converters.forEach(function(impl) {
valueConverters[impl.toString()] = function(buffer, offset, length) {
return new impl(buffer, offset, length);
};
});
this.valueClass = valueClass;
this.name = function() {
return typeName;
};
this.toString = function() {
return typeName + " data type";
};
this.writeValue = function(value) {
var internal = vToC(value);
if (internal === null) {
throw new Error(this + " cannot write " + value);
}
return internal.asBuffer();
};
this.toBytes = function(value) {
var bytes = vToC(value);
if (bytes) {
return bytes;
}
throw new Error(this + " cannot convert value to Bytes: " + value);
};
this.readValue = function(buffer, offset, length) {
if (buffer.$buffer) {
return cToV(buffer);
}
return cToV(new implementation(buffer, offset, length));
};
valueConverters[BytesImpl.toString()] = function(buffer, offset, length) {
return new BytesImpl(buffer, offset, length);
};
valueConverters[valueClass.toString()] = this.readValue;
this.canReadAs = function(valueClass) {
return valueConverters[valueClass] !== undefined;
};
this.readAs = function(valueClass, buffer, offset, length) {
if (buffer.$buffer) {
if (buffer instanceof implementation) {
return buffer;
}
return this.readAs(valueClass, buffer.$buffer, buffer.$offset, buffer.$length);
}
if (valueConverters[valueClass]) {
return valueConverters[valueClass](buffer, offset, length);
}
throw new Error(this + " is incompatible with values of " + valueClass);
};
this.deltaType = function(name) {
if (!name || name === "binary" || BinaryDeltaImpl.isPrototypeOf(name)) {
return this.binaryDeltaType();
}
throw new Error(this + " has no '" + name + "' delta type");
};
this.binaryDeltaType = function() {
if (binaryDeltaType) {
return binaryDeltaType;
}
throw new Error(this + " has no binary delta type");
};
};