binary.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. 'use strict';
  2. /**
  3. * A class representation of the BSON Binary type.
  4. */
  5. class Binary {
  6. /**
  7. * Create a Binary type
  8. *
  9. * Sub types
  10. * - **BSON.BSON_BINARY_SUBTYPE_DEFAULT**, default BSON type.
  11. * - **BSON.BSON_BINARY_SUBTYPE_FUNCTION**, BSON function type.
  12. * - **BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY**, BSON byte array type.
  13. * - **BSON.BSON_BINARY_SUBTYPE_UUID**, BSON uuid type.
  14. * - **BSON.BSON_BINARY_SUBTYPE_MD5**, BSON md5 type.
  15. * - **BSON.BSON_BINARY_SUBTYPE_USER_DEFINED**, BSON user defined type.
  16. *
  17. * @param {Buffer} buffer a buffer object containing the binary data.
  18. * @param {Number} [subType] the option binary type.
  19. * @return {Binary}
  20. */
  21. constructor(buffer, subType) {
  22. if (
  23. buffer != null &&
  24. !(typeof buffer === 'string') &&
  25. !Buffer.isBuffer(buffer) &&
  26. !(buffer instanceof Uint8Array) &&
  27. !Array.isArray(buffer)
  28. ) {
  29. throw new TypeError('only String, Buffer, Uint8Array or Array accepted');
  30. }
  31. this.sub_type = subType == null ? BSON_BINARY_SUBTYPE_DEFAULT : subType;
  32. this.position = 0;
  33. if (buffer != null && !(buffer instanceof Number)) {
  34. // Only accept Buffer, Uint8Array or Arrays
  35. if (typeof buffer === 'string') {
  36. // Different ways of writing the length of the string for the different types
  37. if (typeof Buffer !== 'undefined') {
  38. this.buffer = Buffer.from(buffer);
  39. } else if (typeof Uint8Array !== 'undefined' || Array.isArray(buffer)) {
  40. this.buffer = writeStringToArray(buffer);
  41. } else {
  42. throw new TypeError('only String, Buffer, Uint8Array or Array accepted');
  43. }
  44. } else {
  45. this.buffer = buffer;
  46. }
  47. this.position = buffer.length;
  48. } else {
  49. if (typeof Buffer !== 'undefined') {
  50. this.buffer = Buffer.alloc(Binary.BUFFER_SIZE);
  51. } else if (typeof Uint8Array !== 'undefined') {
  52. this.buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE));
  53. } else {
  54. this.buffer = new Array(Binary.BUFFER_SIZE);
  55. }
  56. }
  57. }
  58. /**
  59. * Updates this binary with byte_value.
  60. *
  61. * @method
  62. * @param {string} byte_value a single byte we wish to write.
  63. */
  64. put(byte_value) {
  65. // If it's a string and a has more than one character throw an error
  66. if (byte_value['length'] != null && typeof byte_value !== 'number' && byte_value.length !== 1)
  67. throw new TypeError('only accepts single character String, Uint8Array or Array');
  68. if ((typeof byte_value !== 'number' && byte_value < 0) || byte_value > 255)
  69. throw new TypeError('only accepts number in a valid unsigned byte range 0-255');
  70. // Decode the byte value once
  71. let decoded_byte = null;
  72. if (typeof byte_value === 'string') {
  73. decoded_byte = byte_value.charCodeAt(0);
  74. } else if (byte_value['length'] != null) {
  75. decoded_byte = byte_value[0];
  76. } else {
  77. decoded_byte = byte_value;
  78. }
  79. if (this.buffer.length > this.position) {
  80. this.buffer[this.position++] = decoded_byte;
  81. } else {
  82. if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) {
  83. // Create additional overflow buffer
  84. let buffer = Buffer.alloc(Binary.BUFFER_SIZE + this.buffer.length);
  85. // Combine the two buffers together
  86. this.buffer.copy(buffer, 0, 0, this.buffer.length);
  87. this.buffer = buffer;
  88. this.buffer[this.position++] = decoded_byte;
  89. } else {
  90. let buffer = null;
  91. // Create a new buffer (typed or normal array)
  92. if (isUint8Array(this.buffer)) {
  93. buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE + this.buffer.length));
  94. } else {
  95. buffer = new Array(Binary.BUFFER_SIZE + this.buffer.length);
  96. }
  97. // We need to copy all the content to the new array
  98. for (let i = 0; i < this.buffer.length; i++) {
  99. buffer[i] = this.buffer[i];
  100. }
  101. // Reassign the buffer
  102. this.buffer = buffer;
  103. // Write the byte
  104. this.buffer[this.position++] = decoded_byte;
  105. }
  106. }
  107. }
  108. /**
  109. * Writes a buffer or string to the binary.
  110. *
  111. * @method
  112. * @param {(Buffer|string)} string a string or buffer to be written to the Binary BSON object.
  113. * @param {number} offset specify the binary of where to write the content.
  114. * @return {null}
  115. */
  116. write(string, offset) {
  117. offset = typeof offset === 'number' ? offset : this.position;
  118. // If the buffer is to small let's extend the buffer
  119. if (this.buffer.length < offset + string.length) {
  120. let buffer = null;
  121. // If we are in node.js
  122. if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) {
  123. buffer = Buffer.alloc(this.buffer.length + string.length);
  124. this.buffer.copy(buffer, 0, 0, this.buffer.length);
  125. } else if (isUint8Array(this.buffer)) {
  126. // Create a new buffer
  127. buffer = new Uint8Array(new ArrayBuffer(this.buffer.length + string.length));
  128. // Copy the content
  129. for (let i = 0; i < this.position; i++) {
  130. buffer[i] = this.buffer[i];
  131. }
  132. }
  133. // Assign the new buffer
  134. this.buffer = buffer;
  135. }
  136. if (typeof Buffer !== 'undefined' && Buffer.isBuffer(string) && Buffer.isBuffer(this.buffer)) {
  137. string.copy(this.buffer, offset, 0, string.length);
  138. this.position =
  139. offset + string.length > this.position ? offset + string.length : this.position;
  140. // offset = string.length
  141. } else if (
  142. typeof Buffer !== 'undefined' &&
  143. typeof string === 'string' &&
  144. Buffer.isBuffer(this.buffer)
  145. ) {
  146. this.buffer.write(string, offset, 'binary');
  147. this.position =
  148. offset + string.length > this.position ? offset + string.length : this.position;
  149. // offset = string.length;
  150. } else if (isUint8Array(string) || (Array.isArray(string) && typeof string !== 'string')) {
  151. for (let i = 0; i < string.length; i++) {
  152. this.buffer[offset++] = string[i];
  153. }
  154. this.position = offset > this.position ? offset : this.position;
  155. } else if (typeof string === 'string') {
  156. for (let i = 0; i < string.length; i++) {
  157. this.buffer[offset++] = string.charCodeAt(i);
  158. }
  159. this.position = offset > this.position ? offset : this.position;
  160. }
  161. }
  162. /**
  163. * Reads **length** bytes starting at **position**.
  164. *
  165. * @method
  166. * @param {number} position read from the given position in the Binary.
  167. * @param {number} length the number of bytes to read.
  168. * @return {Buffer}
  169. */
  170. read(position, length) {
  171. length = length && length > 0 ? length : this.position;
  172. // Let's return the data based on the type we have
  173. if (this.buffer['slice']) {
  174. return this.buffer.slice(position, position + length);
  175. }
  176. // Create a buffer to keep the result
  177. const buffer =
  178. typeof Uint8Array !== 'undefined'
  179. ? new Uint8Array(new ArrayBuffer(length))
  180. : new Array(length);
  181. for (let i = 0; i < length; i++) {
  182. buffer[i] = this.buffer[position++];
  183. }
  184. // Return the buffer
  185. return buffer;
  186. }
  187. /**
  188. * Returns the value of this binary as a string.
  189. *
  190. * @method
  191. * @return {string}
  192. */
  193. value(asRaw) {
  194. asRaw = asRaw == null ? false : asRaw;
  195. // Optimize to serialize for the situation where the data == size of buffer
  196. if (
  197. asRaw &&
  198. typeof Buffer !== 'undefined' &&
  199. Buffer.isBuffer(this.buffer) &&
  200. this.buffer.length === this.position
  201. )
  202. return this.buffer;
  203. // If it's a node.js buffer object
  204. if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) {
  205. return asRaw
  206. ? this.buffer.slice(0, this.position)
  207. : this.buffer.toString('binary', 0, this.position);
  208. } else {
  209. if (asRaw) {
  210. // we support the slice command use it
  211. if (this.buffer['slice'] != null) {
  212. return this.buffer.slice(0, this.position);
  213. } else {
  214. // Create a new buffer to copy content to
  215. const newBuffer = isUint8Array(this.buffer)
  216. ? new Uint8Array(new ArrayBuffer(this.position))
  217. : new Array(this.position);
  218. // Copy content
  219. for (let i = 0; i < this.position; i++) {
  220. newBuffer[i] = this.buffer[i];
  221. }
  222. // Return the buffer
  223. return newBuffer;
  224. }
  225. } else {
  226. return convertArraytoUtf8BinaryString(this.buffer, 0, this.position);
  227. }
  228. }
  229. }
  230. /**
  231. * Length.
  232. *
  233. * @method
  234. * @return {number} the length of the binary.
  235. */
  236. length() {
  237. return this.position;
  238. }
  239. /**
  240. * @ignore
  241. */
  242. toJSON() {
  243. return this.buffer != null ? this.buffer.toString('base64') : '';
  244. }
  245. /**
  246. * @ignore
  247. */
  248. toString(format) {
  249. return this.buffer != null ? this.buffer.slice(0, this.position).toString(format) : '';
  250. }
  251. /**
  252. * @ignore
  253. */
  254. toExtendedJSON() {
  255. const base64String = Buffer.isBuffer(this.buffer)
  256. ? this.buffer.toString('base64')
  257. : Buffer.from(this.buffer).toString('base64');
  258. const subType = Number(this.sub_type).toString(16);
  259. return {
  260. $binary: {
  261. base64: base64String,
  262. subType: subType.length === 1 ? '0' + subType : subType
  263. }
  264. };
  265. }
  266. /**
  267. * @ignore
  268. */
  269. static fromExtendedJSON(doc) {
  270. const type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0;
  271. const data = new Buffer(doc.$binary.base64, 'base64');
  272. return new Binary(data, type);
  273. }
  274. }
  275. /**
  276. * Binary default subtype
  277. * @ignore
  278. */
  279. const BSON_BINARY_SUBTYPE_DEFAULT = 0;
  280. function isUint8Array(obj) {
  281. return Object.prototype.toString.call(obj) === '[object Uint8Array]';
  282. }
  283. /**
  284. * @ignore
  285. */
  286. function writeStringToArray(data) {
  287. // Create a buffer
  288. const buffer =
  289. typeof Uint8Array !== 'undefined'
  290. ? new Uint8Array(new ArrayBuffer(data.length))
  291. : new Array(data.length);
  292. // Write the content to the buffer
  293. for (let i = 0; i < data.length; i++) {
  294. buffer[i] = data.charCodeAt(i);
  295. }
  296. // Write the string to the buffer
  297. return buffer;
  298. }
  299. /**
  300. * Convert Array ot Uint8Array to Binary String
  301. *
  302. * @ignore
  303. */
  304. function convertArraytoUtf8BinaryString(byteArray, startIndex, endIndex) {
  305. let result = '';
  306. for (let i = startIndex; i < endIndex; i++) {
  307. result = result + String.fromCharCode(byteArray[i]);
  308. }
  309. return result;
  310. }
  311. Binary.BUFFER_SIZE = 256;
  312. /**
  313. * Default BSON type
  314. *
  315. * @classconstant SUBTYPE_DEFAULT
  316. **/
  317. Binary.SUBTYPE_DEFAULT = 0;
  318. /**
  319. * Function BSON type
  320. *
  321. * @classconstant SUBTYPE_DEFAULT
  322. **/
  323. Binary.SUBTYPE_FUNCTION = 1;
  324. /**
  325. * Byte Array BSON type
  326. *
  327. * @classconstant SUBTYPE_DEFAULT
  328. **/
  329. Binary.SUBTYPE_BYTE_ARRAY = 2;
  330. /**
  331. * OLD UUID BSON type
  332. *
  333. * @classconstant SUBTYPE_DEFAULT
  334. **/
  335. Binary.SUBTYPE_UUID_OLD = 3;
  336. /**
  337. * UUID BSON type
  338. *
  339. * @classconstant SUBTYPE_DEFAULT
  340. **/
  341. Binary.SUBTYPE_UUID = 4;
  342. /**
  343. * MD5 BSON type
  344. *
  345. * @classconstant SUBTYPE_DEFAULT
  346. **/
  347. Binary.SUBTYPE_MD5 = 5;
  348. /**
  349. * User BSON type
  350. *
  351. * @classconstant SUBTYPE_DEFAULT
  352. **/
  353. Binary.SUBTYPE_USER_DEFINED = 128;
  354. Object.defineProperty(Binary.prototype, '_bsontype', { value: 'Binary' });
  355. module.exports = Binary;