Created
May 14, 2013 23:35
-
-
Save elisee/5580599 to your computer and use it in GitHub Desktop.
Read binary data written with .NET's BinaryWriter in CoffeeScript / JavaScript. Simply pass an ArrayBuffer to the constructor and then call the Read* methods.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CSPlayer.BinaryReader | |
if TextDecoder? | |
# The TextDecoder API properly decodes UTF-8 | |
textDecoder = new TextDecoder() | |
@DecodeString = (array) -> textDecoder.decode array | |
else | |
# If the TextDecoder API isn't available, fall back to ASCII decoding | |
@DecodeString = (array) -> String.fromCharCode.apply null, array | |
constructor: (buffer) -> | |
@view = new DataView buffer | |
@cursor = 0 | |
ReadUInt8: -> | |
val = @view.getUint8(@cursor) | |
@cursor += 1 | |
val | |
ReadUInt16: -> | |
val = @view.getUint16(@cursor, true) | |
@cursor += 2 | |
val | |
ReadInt32: -> | |
val = @view.getInt32(@cursor, true) | |
@cursor += 4 | |
val | |
ReadUInt32: -> | |
val = @view.getUint32(@cursor, true) | |
@cursor += 4 | |
val | |
ReadFloat32: -> | |
val = @view.getFloat32(@cursor, true) | |
@cursor += 4 | |
val | |
ReadFloat64: -> | |
val = @view.getFloat64(@cursor, true) | |
@cursor += 8 | |
val | |
Read7BitEncodedInt: -> | |
returnValue = 0 | |
bitIndex = 0 | |
loop | |
if bitIndex != 35 | |
num = @ReadUInt8() | |
returnValue |= (num & 127) << bitIndex | |
bitIndex += 7 | |
else | |
throw new Error "Invalid 7-bit encoded int" | |
break unless (num & 128) != 0 | |
return returnValue | |
ReadBoolean: -> @ReadUInt8() != 0 | |
ReadString: -> | |
length = @Read7BitEncodedInt() | |
val = CSPlayer.BinaryReader.DecodeString new Uint8Array(@view.buffer.slice(@cursor, @cursor + length)) | |
@cursor += length | |
val | |
ReadPoint: -> { x: @ReadInt32(), y: @ReadInt32() } | |
ReadVector2: -> new THREE.Vector2 @ReadFloat32(), @ReadFloat32() | |
ReadVector3: -> new THREE.Vector3 @ReadFloat32(), @ReadFloat32(), @ReadFloat32() | |
ReadIntVector3: -> new THREE.Vector3 @ReadInt32(), @ReadInt32(), @ReadInt32() | |
ReadQuaternion: -> | |
w = @ReadFloat32() | |
new THREE.Quaternion @ReadFloat32(), @ReadFloat32(), @ReadFloat32(), w | |
ReadBytes: (length) -> | |
bytes = new Uint8Array @view.buffer.slice @cursor, @cursor + length | |
@cursor += length | |
bytes |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment