~ubuntu-branches/ubuntu/vivid/nodejs/vivid

« back to all changes in this revision

Viewing changes to .pc/2007_v8_3.5_port.patch/src/node_buffer.cc

  • Committer: Package Import Robot
  • Author(s): James Page
  • Date: 2012-02-09 15:01:27 UTC
  • mfrom: (7.1.18 sid)
  • Revision ID: package-import@ubuntu.com-20120209150127-iiz4z20pppqpu9if
Tags: 0.4.12-3ubuntu1
* Merge from Debian unstable:
  - This package is x86/arm only. Update control to match
  - Drop 2007_remove_internet_test.patch, update
    2005_expected_failing_tests.patch instead:
    + Allow test-dgram-multicast to fail, requires root privileges.
    + Allow test-c-ares, test-regress-GH-819 and test-net-connect-timeout to
      fail, they require network access.
* Rebuild with new version of libv8.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
// Copyright Joyent, Inc. and other Node contributors.
 
2
//
 
3
// Permission is hereby granted, free of charge, to any person obtaining a
 
4
// copy of this software and associated documentation files (the
 
5
// "Software"), to deal in the Software without restriction, including
 
6
// without limitation the rights to use, copy, modify, merge, publish,
 
7
// distribute, sublicense, and/or sell copies of the Software, and to permit
 
8
// persons to whom the Software is furnished to do so, subject to the
 
9
// following conditions:
 
10
//
 
11
// The above copyright notice and this permission notice shall be included
 
12
// in all copies or substantial portions of the Software.
 
13
//
 
14
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 
15
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 
16
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
 
17
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 
18
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
 
19
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
 
20
// USE OR OTHER DEALINGS IN THE SOFTWARE.
 
21
 
 
22
 
 
23
#include <node.h>
 
24
#include <node_buffer.h>
 
25
 
 
26
#include <v8.h>
 
27
 
 
28
#include <assert.h>
 
29
#include <stdlib.h> // malloc, free
 
30
#include <string.h> // memcpy
 
31
 
 
32
#ifdef __MINGW32__
 
33
# include "platform.h"
 
34
# include <platform_win32_winsock.h> // htons, htonl
 
35
#endif
 
36
 
 
37
#ifdef __POSIX__
 
38
# include <arpa/inet.h> // htons, htonl
 
39
#endif
 
40
 
 
41
 
 
42
#define MIN(a,b) ((a) < (b) ? (a) : (b))
 
43
 
 
44
namespace node {
 
45
 
 
46
using namespace v8;
 
47
 
 
48
#define SLICE_ARGS(start_arg, end_arg)                               \
 
49
  if (!start_arg->IsInt32() || !end_arg->IsInt32()) {                \
 
50
    return ThrowException(Exception::TypeError(                      \
 
51
          String::New("Bad argument.")));                            \
 
52
  }                                                                  \
 
53
  int32_t start = start_arg->Int32Value();                           \
 
54
  int32_t end = end_arg->Int32Value();                               \
 
55
  if (start < 0 || end < 0) {                                        \
 
56
    return ThrowException(Exception::TypeError(                      \
 
57
          String::New("Bad argument.")));                            \
 
58
  }                                                                  \
 
59
  if (!(start <= end)) {                                             \
 
60
    return ThrowException(Exception::Error(                          \
 
61
          String::New("Must have start <= end")));                   \
 
62
  }                                                                  \
 
63
  if ((size_t)end > parent->length_) {                               \
 
64
    return ThrowException(Exception::Error(                          \
 
65
          String::New("end cannot be longer than parent.length")));  \
 
66
  }
 
67
 
 
68
 
 
69
static Persistent<String> length_symbol;
 
70
static Persistent<String> chars_written_sym;
 
71
static Persistent<String> write_sym;
 
72
Persistent<FunctionTemplate> Buffer::constructor_template;
 
73
 
 
74
 
 
75
static inline size_t base64_decoded_size(const char *src, size_t size) {
 
76
  const char *const end = src + size;
 
77
  const int remainder = size % 4;
 
78
 
 
79
  size = (size / 4) * 3;
 
80
  if (remainder) {
 
81
    if (size == 0 && remainder == 1) {
 
82
      // special case: 1-byte input cannot be decoded
 
83
      size = 0;
 
84
    } else {
 
85
      // non-padded input, add 1 or 2 extra bytes
 
86
      size += 1 + (remainder == 3);
 
87
    }
 
88
  }
 
89
 
 
90
  // check for trailing padding (1 or 2 bytes)
 
91
  if (size > 0) {
 
92
    if (end[-1] == '=') size--;
 
93
    if (end[-2] == '=') size--;
 
94
  }
 
95
 
 
96
  return size;
 
97
}
 
98
 
 
99
 
 
100
static size_t ByteLength (Handle<String> string, enum encoding enc) {
 
101
  HandleScope scope;
 
102
 
 
103
  if (enc == UTF8) {
 
104
    return string->Utf8Length();
 
105
  } else if (enc == BASE64) {
 
106
    String::Utf8Value v(string);
 
107
    return base64_decoded_size(*v, v.length());
 
108
  } else if (enc == UCS2) {
 
109
    return string->Length() * 2;
 
110
  } else {
 
111
    return string->Length();
 
112
  }
 
113
}
 
114
 
 
115
 
 
116
Handle<Object> Buffer::New(Handle<String> string) {
 
117
  HandleScope scope;
 
118
 
 
119
  // get Buffer from global scope.
 
120
  Local<Object> global = v8::Context::GetCurrent()->Global();
 
121
  Local<Value> bv = global->Get(String::NewSymbol("Buffer"));
 
122
  assert(bv->IsFunction());
 
123
  Local<Function> b = Local<Function>::Cast(bv);
 
124
 
 
125
  Local<Value> argv[1] = { Local<Value>::New(string) };
 
126
  Local<Object> instance = b->NewInstance(1, argv);
 
127
 
 
128
  return scope.Close(instance);
 
129
}
 
130
 
 
131
 
 
132
Buffer* Buffer::New(size_t length) {
 
133
  HandleScope scope;
 
134
 
 
135
  Local<Value> arg = Integer::NewFromUnsigned(length);
 
136
  Local<Object> b = constructor_template->GetFunction()->NewInstance(1, &arg);
 
137
  if (b.IsEmpty()) return NULL;
 
138
 
 
139
  return ObjectWrap::Unwrap<Buffer>(b);
 
140
}
 
141
 
 
142
 
 
143
Buffer* Buffer::New(char* data, size_t length) {
 
144
  HandleScope scope;
 
145
 
 
146
  Local<Value> arg = Integer::NewFromUnsigned(0);
 
147
  Local<Object> obj = constructor_template->GetFunction()->NewInstance(1, &arg);
 
148
 
 
149
  Buffer *buffer = ObjectWrap::Unwrap<Buffer>(obj);
 
150
  buffer->Replace(data, length, NULL, NULL);
 
151
 
 
152
  return buffer;
 
153
}
 
154
 
 
155
 
 
156
Buffer* Buffer::New(char *data, size_t length,
 
157
                    free_callback callback, void *hint) {
 
158
  HandleScope scope;
 
159
 
 
160
  Local<Value> arg = Integer::NewFromUnsigned(0);
 
161
  Local<Object> obj = constructor_template->GetFunction()->NewInstance(1, &arg);
 
162
 
 
163
  Buffer *buffer = ObjectWrap::Unwrap<Buffer>(obj);
 
164
  buffer->Replace(data, length, callback, hint);
 
165
 
 
166
  return buffer;
 
167
}
 
168
 
 
169
 
 
170
Handle<Value> Buffer::New(const Arguments &args) {
 
171
  if (!args.IsConstructCall()) {
 
172
    return FromConstructorTemplate(constructor_template, args);
 
173
  }
 
174
 
 
175
  HandleScope scope;
 
176
 
 
177
  Buffer *buffer;
 
178
  if (args[0]->IsInt32()) {
 
179
    // var buffer = new Buffer(1024);
 
180
    size_t length = args[0]->Uint32Value();
 
181
    buffer = new Buffer(args.This(), length);
 
182
  } else {
 
183
    return ThrowException(Exception::TypeError(String::New("Bad argument")));
 
184
  }
 
185
  return args.This();
 
186
}
 
187
 
 
188
 
 
189
Buffer::Buffer(Handle<Object> wrapper, size_t length) : ObjectWrap() {
 
190
  Wrap(wrapper);
 
191
 
 
192
  length_ = 0;
 
193
  callback_ = NULL;
 
194
 
 
195
  Replace(NULL, length, NULL, NULL);
 
196
}
 
197
 
 
198
 
 
199
Buffer::~Buffer() {
 
200
  Replace(NULL, 0, NULL, NULL);
 
201
}
 
202
 
 
203
 
 
204
void Buffer::Replace(char *data, size_t length,
 
205
                     free_callback callback, void *hint) {
 
206
  HandleScope scope;
 
207
 
 
208
  if (callback_) {
 
209
    callback_(data_, callback_hint_);
 
210
  } else if (length_) {
 
211
    delete [] data_;
 
212
    V8::AdjustAmountOfExternalAllocatedMemory(-(sizeof(Buffer) + length_));
 
213
  }
 
214
 
 
215
  length_ = length;
 
216
  callback_ = callback;
 
217
  callback_hint_ = hint;
 
218
 
 
219
  if (callback_) {
 
220
    data_ = data;
 
221
  } else if (length_) {
 
222
    data_ = new char[length_];
 
223
    if (data)
 
224
      memcpy(data_, data, length_);
 
225
    V8::AdjustAmountOfExternalAllocatedMemory(sizeof(Buffer) + length_);
 
226
  } else {
 
227
    data_ = NULL;
 
228
  }
 
229
 
 
230
  handle_->SetIndexedPropertiesToExternalArrayData(data_,
 
231
                                                   kExternalUnsignedByteArray,
 
232
                                                   length_);
 
233
  handle_->Set(length_symbol, Integer::NewFromUnsigned(length_));
 
234
}
 
235
 
 
236
 
 
237
Handle<Value> Buffer::BinarySlice(const Arguments &args) {
 
238
  HandleScope scope;
 
239
  Buffer *parent = ObjectWrap::Unwrap<Buffer>(args.This());
 
240
  SLICE_ARGS(args[0], args[1])
 
241
 
 
242
  char *data = parent->data_ + start;
 
243
  //Local<String> string = String::New(data, end - start);
 
244
 
 
245
  Local<Value> b =  Encode(data, end - start, BINARY);
 
246
 
 
247
  return scope.Close(b);
 
248
}
 
249
 
 
250
 
 
251
Handle<Value> Buffer::AsciiSlice(const Arguments &args) {
 
252
  HandleScope scope;
 
253
  Buffer *parent = ObjectWrap::Unwrap<Buffer>(args.This());
 
254
  SLICE_ARGS(args[0], args[1])
 
255
 
 
256
  char* data = parent->data_ + start;
 
257
  Local<String> string = String::New(data, end - start);
 
258
 
 
259
  return scope.Close(string);
 
260
}
 
261
 
 
262
 
 
263
Handle<Value> Buffer::Utf8Slice(const Arguments &args) {
 
264
  HandleScope scope;
 
265
  Buffer *parent = ObjectWrap::Unwrap<Buffer>(args.This());
 
266
  SLICE_ARGS(args[0], args[1])
 
267
  char *data = parent->data_ + start;
 
268
  Local<String> string = String::New(data, end - start);
 
269
  return scope.Close(string);
 
270
}
 
271
 
 
272
Handle<Value> Buffer::Ucs2Slice(const Arguments &args) {
 
273
  HandleScope scope;
 
274
  Buffer *parent = ObjectWrap::Unwrap<Buffer>(args.This());
 
275
  SLICE_ARGS(args[0], args[1])
 
276
  uint16_t *data = (uint16_t*)(parent->data_ + start);
 
277
  Local<String> string = String::New(data, (end - start) / 2);
 
278
  return scope.Close(string);
 
279
}
 
280
 
 
281
static const char *base64_table = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
 
282
                                  "abcdefghijklmnopqrstuvwxyz"
 
283
                                  "0123456789+/";
 
284
static const int unbase64_table[] =
 
285
  {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-2,-1,-1,-2,-1,-1
 
286
  ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
 
287
  ,-2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63
 
288
  ,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1
 
289
  ,-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14
 
290
  ,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1
 
291
  ,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40
 
292
  ,41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1
 
293
  ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
 
294
  ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
 
295
  ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
 
296
  ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
 
297
  ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
 
298
  ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
 
299
  ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
 
300
  ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
 
301
  };
 
302
#define unbase64(x) unbase64_table[(uint8_t)(x)]
 
303
 
 
304
 
 
305
Handle<Value> Buffer::Base64Slice(const Arguments &args) {
 
306
  HandleScope scope;
 
307
  Buffer *parent = ObjectWrap::Unwrap<Buffer>(args.This());
 
308
  SLICE_ARGS(args[0], args[1])
 
309
 
 
310
  int n = end - start;
 
311
  int out_len = (n + 2 - ((n + 2) % 3)) / 3 * 4;
 
312
  char *out = new char[out_len];
 
313
 
 
314
  uint8_t bitbuf[3];
 
315
  int i = start; // data() index
 
316
  int j = 0; // out index
 
317
  char c;
 
318
  bool b1_oob, b2_oob;
 
319
 
 
320
  while (i < end) {
 
321
    bitbuf[0] = parent->data_[i++];
 
322
 
 
323
    if (i < end) {
 
324
      bitbuf[1] = parent->data_[i];
 
325
      b1_oob = false;
 
326
    }  else {
 
327
      bitbuf[1] = 0;
 
328
      b1_oob = true;
 
329
    }
 
330
    i++;
 
331
 
 
332
    if (i < end) {
 
333
      bitbuf[2] = parent->data_[i];
 
334
      b2_oob = false;
 
335
    }  else {
 
336
      bitbuf[2] = 0;
 
337
      b2_oob = true;
 
338
    }
 
339
    i++;
 
340
 
 
341
 
 
342
    c = bitbuf[0] >> 2;
 
343
    assert(c < 64);
 
344
    out[j++] = base64_table[(int)c];
 
345
    assert(j < out_len);
 
346
 
 
347
    c = ((bitbuf[0] & 0x03) << 4) | (bitbuf[1] >> 4);
 
348
    assert(c < 64);
 
349
    out[j++] = base64_table[(int)c];
 
350
    assert(j < out_len);
 
351
 
 
352
    if (b1_oob) {
 
353
      out[j++] = '=';
 
354
    } else {
 
355
      c = ((bitbuf[1] & 0x0F) << 2) | (bitbuf[2] >> 6);
 
356
      assert(c < 64);
 
357
      out[j++] = base64_table[(int)c];
 
358
    }
 
359
    assert(j < out_len);
 
360
 
 
361
    if (b2_oob) {
 
362
      out[j++] = '=';
 
363
    } else {
 
364
      c = bitbuf[2] & 0x3F;
 
365
      assert(c < 64);
 
366
      out[j++]  = base64_table[(int)c];
 
367
    }
 
368
    assert(j <= out_len);
 
369
  }
 
370
 
 
371
  Local<String> string = String::New(out, out_len);
 
372
  delete [] out;
 
373
  return scope.Close(string);
 
374
}
 
375
 
 
376
 
 
377
// var bytesCopied = buffer.copy(target, targetStart, sourceStart, sourceEnd);
 
378
Handle<Value> Buffer::Copy(const Arguments &args) {
 
379
  HandleScope scope;
 
380
 
 
381
  Buffer *source = ObjectWrap::Unwrap<Buffer>(args.This());
 
382
 
 
383
  if (!Buffer::HasInstance(args[0])) {
 
384
    return ThrowException(Exception::TypeError(String::New(
 
385
            "First arg should be a Buffer")));
 
386
  }
 
387
 
 
388
  Local<Object> target = args[0]->ToObject();
 
389
  char *target_data = Buffer::Data(target);
 
390
  ssize_t target_length = Buffer::Length(target);
 
391
 
 
392
  ssize_t target_start = args[1]->Int32Value();
 
393
  ssize_t source_start = args[2]->Int32Value();
 
394
  ssize_t source_end = args[3]->IsInt32() ? args[3]->Int32Value()
 
395
                                          : source->length_;
 
396
 
 
397
  if (source_end < source_start) {
 
398
    return ThrowException(Exception::Error(String::New(
 
399
            "sourceEnd < sourceStart")));
 
400
  }
 
401
 
 
402
  // Copy 0 bytes; we're done
 
403
  if (source_end == source_start) {
 
404
    return scope.Close(Integer::New(0));
 
405
  }
 
406
 
 
407
  if (target_start < 0 || target_start >= target_length) {
 
408
    return ThrowException(Exception::Error(String::New(
 
409
            "targetStart out of bounds")));
 
410
  }
 
411
 
 
412
  if (source_start < 0 || source_start >= source->length_) {
 
413
    return ThrowException(Exception::Error(String::New(
 
414
            "sourceStart out of bounds")));
 
415
  }
 
416
 
 
417
  if (source_end < 0 || source_end > source->length_) {
 
418
    return ThrowException(Exception::Error(String::New(
 
419
            "sourceEnd out of bounds")));
 
420
  }
 
421
 
 
422
  ssize_t to_copy = MIN(MIN(source_end - source_start,
 
423
                            target_length - target_start),
 
424
                            source->length_ - source_start);
 
425
 
 
426
 
 
427
  // need to use slightly slower memmove is the ranges might overlap
 
428
  memmove((void *)(target_data + target_start),
 
429
          (const void*)(source->data_ + source_start),
 
430
          to_copy);
 
431
 
 
432
  return scope.Close(Integer::New(to_copy));
 
433
}
 
434
 
 
435
 
 
436
// var charsWritten = buffer.utf8Write(string, offset, [maxLength]);
 
437
Handle<Value> Buffer::Utf8Write(const Arguments &args) {
 
438
  HandleScope scope;
 
439
  Buffer *buffer = ObjectWrap::Unwrap<Buffer>(args.This());
 
440
 
 
441
  if (!args[0]->IsString()) {
 
442
    return ThrowException(Exception::TypeError(String::New(
 
443
            "Argument must be a string")));
 
444
  }
 
445
 
 
446
  Local<String> s = args[0]->ToString();
 
447
 
 
448
  size_t offset = args[1]->Uint32Value();
 
449
 
 
450
  int length = s->Length();
 
451
 
 
452
  if (length == 0) {
 
453
    constructor_template->GetFunction()->Set(chars_written_sym,
 
454
                                             Integer::New(0));
 
455
    return scope.Close(Integer::New(0));
 
456
  }
 
457
 
 
458
  if (length > 0 && offset >= buffer->length_) {
 
459
    return ThrowException(Exception::TypeError(String::New(
 
460
            "Offset is out of bounds")));
 
461
  }
 
462
 
 
463
  size_t max_length = args[2]->IsUndefined() ? buffer->length_ - offset
 
464
                                             : args[2]->Uint32Value();
 
465
  max_length = MIN(buffer->length_ - offset, max_length);
 
466
 
 
467
  char* p = buffer->data_ + offset;
 
468
 
 
469
  int char_written;
 
470
 
 
471
  int written = s->WriteUtf8(p,
 
472
                             max_length,
 
473
                             &char_written,
 
474
                             String::HINT_MANY_WRITES_EXPECTED);
 
475
 
 
476
  constructor_template->GetFunction()->Set(chars_written_sym,
 
477
                                           Integer::New(char_written));
 
478
 
 
479
  if (written > 0 && p[written-1] == '\0' && char_written == length) {
 
480
    uint16_t last_char;
 
481
    s->Write(&last_char, length - 1, 1, String::NO_HINTS);
 
482
    if (last_char != 0 || written > s->Utf8Length()) {
 
483
      written--;
 
484
    }
 
485
  }
 
486
 
 
487
  return scope.Close(Integer::New(written));
 
488
}
 
489
 
 
490
 
 
491
// var charsWritten = buffer.ucs2Write(string, offset, [maxLength]);
 
492
Handle<Value> Buffer::Ucs2Write(const Arguments &args) {
 
493
  HandleScope scope;
 
494
  Buffer *buffer = ObjectWrap::Unwrap<Buffer>(args.This());
 
495
 
 
496
  if (!args[0]->IsString()) {
 
497
    return ThrowException(Exception::TypeError(String::New(
 
498
            "Argument must be a string")));
 
499
  }
 
500
 
 
501
  Local<String> s = args[0]->ToString();
 
502
 
 
503
  size_t offset = args[1]->Uint32Value();
 
504
 
 
505
  if (s->Length() > 0 && offset >= buffer->length_) {
 
506
    return ThrowException(Exception::TypeError(String::New(
 
507
            "Offset is out of bounds")));
 
508
  }
 
509
 
 
510
  size_t max_length = args[2]->IsUndefined() ? buffer->length_ - offset
 
511
                                             : args[2]->Uint32Value();
 
512
  max_length = MIN(buffer->length_ - offset, max_length) / 2;
 
513
 
 
514
  uint16_t* p = (uint16_t*)(buffer->data_ + offset);
 
515
 
 
516
  int written = s->Write(p,
 
517
                         0,
 
518
                         max_length,
 
519
                         String::HINT_MANY_WRITES_EXPECTED);
 
520
 
 
521
  constructor_template->GetFunction()->Set(chars_written_sym,
 
522
                                           Integer::New(written));
 
523
 
 
524
  return scope.Close(Integer::New(written * 2));
 
525
}
 
526
 
 
527
 
 
528
// var charsWritten = buffer.asciiWrite(string, offset);
 
529
Handle<Value> Buffer::AsciiWrite(const Arguments &args) {
 
530
  HandleScope scope;
 
531
 
 
532
  Buffer *buffer = ObjectWrap::Unwrap<Buffer>(args.This());
 
533
 
 
534
  if (!args[0]->IsString()) {
 
535
    return ThrowException(Exception::TypeError(String::New(
 
536
            "Argument must be a string")));
 
537
  }
 
538
 
 
539
  Local<String> s = args[0]->ToString();
 
540
 
 
541
  size_t offset = args[1]->Int32Value();
 
542
 
 
543
  if (s->Length() > 0 && offset >= buffer->length_) {
 
544
    return ThrowException(Exception::TypeError(String::New(
 
545
            "Offset is out of bounds")));
 
546
  }
 
547
 
 
548
  size_t max_length = args[2]->IsUndefined() ? buffer->length_ - offset
 
549
                                             : args[2]->Uint32Value();
 
550
  max_length = MIN(s->Length(), MIN(buffer->length_ - offset, max_length));
 
551
 
 
552
  char *p = buffer->data_ + offset;
 
553
 
 
554
  int written = s->WriteAscii(p,
 
555
                              0,
 
556
                              max_length,
 
557
                              String::HINT_MANY_WRITES_EXPECTED);
 
558
 
 
559
  constructor_template->GetFunction()->Set(chars_written_sym,
 
560
                                           Integer::New(written));
 
561
 
 
562
  return scope.Close(Integer::New(written));
 
563
}
 
564
 
 
565
 
 
566
// var bytesWritten = buffer.base64Write(string, offset, [maxLength]);
 
567
Handle<Value> Buffer::Base64Write(const Arguments &args) {
 
568
  HandleScope scope;
 
569
 
 
570
  assert(unbase64('/') == 63);
 
571
  assert(unbase64('+') == 62);
 
572
  assert(unbase64('T') == 19);
 
573
  assert(unbase64('Z') == 25);
 
574
  assert(unbase64('t') == 45);
 
575
  assert(unbase64('z') == 51);
 
576
 
 
577
  assert(unbase64(' ') == -2);
 
578
  assert(unbase64('\n') == -2);
 
579
  assert(unbase64('\r') == -2);
 
580
 
 
581
  Buffer *buffer = ObjectWrap::Unwrap<Buffer>(args.This());
 
582
 
 
583
  if (!args[0]->IsString()) {
 
584
    return ThrowException(Exception::TypeError(String::New(
 
585
            "Argument must be a string")));
 
586
  }
 
587
 
 
588
  String::AsciiValue s(args[0]->ToString());
 
589
  size_t offset = args[1]->Int32Value();
 
590
 
 
591
  // handle zero-length buffers graciously
 
592
  if (offset == 0 && buffer->length_ == 0) {
 
593
    return scope.Close(Integer::New(0));
 
594
  }
 
595
 
 
596
  if (offset >= buffer->length_) {
 
597
    return ThrowException(Exception::TypeError(String::New(
 
598
            "Offset is out of bounds")));
 
599
  }
 
600
 
 
601
  const size_t size = base64_decoded_size(*s, s.length());
 
602
  if (size > buffer->length_ - offset) {
 
603
    // throw exception, don't silently truncate
 
604
    return ThrowException(Exception::TypeError(String::New(
 
605
            "Buffer too small")));
 
606
  }
 
607
 
 
608
  char a, b, c, d;
 
609
  char* start = buffer->data_ + offset;
 
610
  char* dst = start;
 
611
  const char *src = *s;
 
612
  const char *const srcEnd = src + s.length();
 
613
 
 
614
  while (src < srcEnd) {
 
615
    int remaining = srcEnd - src;
 
616
 
 
617
    while (unbase64(*src) < 0 && src < srcEnd) {
 
618
      src++;
 
619
      remaining--;
 
620
    }
 
621
    if (remaining == 0 || *src == '=') break;
 
622
    a = unbase64(*src++);
 
623
 
 
624
    while (unbase64(*src) < 0 && src < srcEnd) {
 
625
      src++;
 
626
      remaining--;
 
627
    }
 
628
    if (remaining <= 1 || *src == '=') break;
 
629
    b = unbase64(*src++);
 
630
    *dst++ = (a << 2) | ((b & 0x30) >> 4);
 
631
 
 
632
    while (unbase64(*src) < 0 && src < srcEnd) {
 
633
      src++;
 
634
      remaining--;
 
635
    }
 
636
    if (remaining <= 2 || *src == '=') break;
 
637
    c = unbase64(*src++);
 
638
    *dst++ = ((b & 0x0F) << 4) | ((c & 0x3C) >> 2);
 
639
 
 
640
    while (unbase64(*src) < 0 && src < srcEnd) {
 
641
      src++;
 
642
      remaining--;
 
643
    }
 
644
    if (remaining <= 3 || *src == '=') break;
 
645
    d = unbase64(*src++);
 
646
    *dst++ = ((c & 0x03) << 6) | (d & 0x3F);
 
647
  }
 
648
 
 
649
  constructor_template->GetFunction()->Set(chars_written_sym,
 
650
                                           Integer::New(s.length()));
 
651
 
 
652
  return scope.Close(Integer::New(dst - start));
 
653
}
 
654
 
 
655
 
 
656
Handle<Value> Buffer::BinaryWrite(const Arguments &args) {
 
657
  HandleScope scope;
 
658
 
 
659
  Buffer *buffer = ObjectWrap::Unwrap<Buffer>(args.This());
 
660
 
 
661
  if (!args[0]->IsString()) {
 
662
    return ThrowException(Exception::TypeError(String::New(
 
663
            "Argument must be a string")));
 
664
  }
 
665
 
 
666
  Local<String> s = args[0]->ToString();
 
667
 
 
668
  size_t offset = args[1]->Int32Value();
 
669
 
 
670
  if (s->Length() > 0 && offset >= buffer->length_) {
 
671
    return ThrowException(Exception::TypeError(String::New(
 
672
            "Offset is out of bounds")));
 
673
  }
 
674
 
 
675
  char *p = (char*)buffer->data_ + offset;
 
676
 
 
677
  size_t max_length = args[2]->IsUndefined() ? buffer->length_ - offset
 
678
                                             : args[2]->Uint32Value();
 
679
  max_length = MIN(s->Length(), MIN(buffer->length_ - offset, max_length));
 
680
 
 
681
  int written = DecodeWrite(p, max_length, s, BINARY);
 
682
 
 
683
  constructor_template->GetFunction()->Set(chars_written_sym,
 
684
                                           Integer::New(written));
 
685
 
 
686
  return scope.Close(Integer::New(written));
 
687
}
 
688
 
 
689
 
 
690
// var nbytes = Buffer.byteLength("string", "utf8")
 
691
Handle<Value> Buffer::ByteLength(const Arguments &args) {
 
692
  HandleScope scope;
 
693
 
 
694
  if (!args[0]->IsString()) {
 
695
    return ThrowException(Exception::TypeError(String::New(
 
696
            "Argument must be a string")));
 
697
  }
 
698
 
 
699
  Local<String> s = args[0]->ToString();
 
700
  enum encoding e = ParseEncoding(args[1], UTF8);
 
701
 
 
702
  return scope.Close(Integer::New(node::ByteLength(s, e)));
 
703
}
 
704
 
 
705
 
 
706
Handle<Value> Buffer::MakeFastBuffer(const Arguments &args) {
 
707
  HandleScope scope;
 
708
 
 
709
  if (!Buffer::HasInstance(args[0])) {
 
710
    return ThrowException(Exception::TypeError(String::New(
 
711
            "First argument must be a Buffer")));
 
712
  }
 
713
 
 
714
  Buffer *buffer = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject());
 
715
  Local<Object> fast_buffer = args[1]->ToObject();;
 
716
  uint32_t offset = args[2]->Uint32Value();
 
717
  uint32_t length = args[3]->Uint32Value();
 
718
 
 
719
  fast_buffer->SetIndexedPropertiesToExternalArrayData(buffer->data_ + offset,
 
720
                                                       kExternalUnsignedByteArray,
 
721
                                                       length);
 
722
 
 
723
  return Undefined();
 
724
}
 
725
 
 
726
 
 
727
bool Buffer::HasInstance(v8::Handle<v8::Value> val) {
 
728
  if (!val->IsObject()) return false;
 
729
  v8::Local<v8::Object> obj = val->ToObject();
 
730
 
 
731
  if (obj->GetIndexedPropertiesExternalArrayDataType() == kExternalUnsignedByteArray)
 
732
    return true;
 
733
 
 
734
  // Also check for SlowBuffers that are empty.
 
735
  if (constructor_template->HasInstance(obj))
 
736
    return true;
 
737
 
 
738
  return false;
 
739
}
 
740
 
 
741
 
 
742
void Buffer::Initialize(Handle<Object> target) {
 
743
  HandleScope scope;
 
744
 
 
745
  length_symbol = Persistent<String>::New(String::NewSymbol("length"));
 
746
  chars_written_sym = Persistent<String>::New(String::NewSymbol("_charsWritten"));
 
747
 
 
748
  Local<FunctionTemplate> t = FunctionTemplate::New(Buffer::New);
 
749
  constructor_template = Persistent<FunctionTemplate>::New(t);
 
750
  constructor_template->InstanceTemplate()->SetInternalFieldCount(1);
 
751
  constructor_template->SetClassName(String::NewSymbol("SlowBuffer"));
 
752
 
 
753
  // copy free
 
754
  NODE_SET_PROTOTYPE_METHOD(constructor_template, "binarySlice", Buffer::BinarySlice);
 
755
  NODE_SET_PROTOTYPE_METHOD(constructor_template, "asciiSlice", Buffer::AsciiSlice);
 
756
  NODE_SET_PROTOTYPE_METHOD(constructor_template, "base64Slice", Buffer::Base64Slice);
 
757
  NODE_SET_PROTOTYPE_METHOD(constructor_template, "ucs2Slice", Buffer::Ucs2Slice);
 
758
  // TODO NODE_SET_PROTOTYPE_METHOD(t, "utf16Slice", Utf16Slice);
 
759
  // copy
 
760
  NODE_SET_PROTOTYPE_METHOD(constructor_template, "utf8Slice", Buffer::Utf8Slice);
 
761
 
 
762
  NODE_SET_PROTOTYPE_METHOD(constructor_template, "utf8Write", Buffer::Utf8Write);
 
763
  NODE_SET_PROTOTYPE_METHOD(constructor_template, "asciiWrite", Buffer::AsciiWrite);
 
764
  NODE_SET_PROTOTYPE_METHOD(constructor_template, "binaryWrite", Buffer::BinaryWrite);
 
765
  NODE_SET_PROTOTYPE_METHOD(constructor_template, "base64Write", Buffer::Base64Write);
 
766
  NODE_SET_PROTOTYPE_METHOD(constructor_template, "ucs2Write", Buffer::Ucs2Write);
 
767
  NODE_SET_PROTOTYPE_METHOD(constructor_template, "copy", Buffer::Copy);
 
768
 
 
769
  NODE_SET_METHOD(constructor_template->GetFunction(),
 
770
                  "byteLength",
 
771
                  Buffer::ByteLength);
 
772
  NODE_SET_METHOD(constructor_template->GetFunction(),
 
773
                  "makeFastBuffer",
 
774
                  Buffer::MakeFastBuffer);
 
775
 
 
776
  target->Set(String::NewSymbol("SlowBuffer"), constructor_template->GetFunction());
 
777
}
 
778
 
 
779
 
 
780
}  // namespace node
 
781
 
 
782
NODE_MODULE(node_buffer, node::Buffer::Initialize);