GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — node/src/node_buffer.cc at master · atian25/node Expand file tree/ Copy pathnode_buffer.ccMore file actions 1242 lines (1019 loc) · 40.1 KB / Copy pathnode_buffer.ccFile metadata and controls1242 lines (1019 loc) · 40.1 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. #include "node_buffer.h" #include "allocated_buffer-inl.h" #include "node.h" #include "node_errors.h" #include "node_external_reference.h" #include "node_internals.h" #include "env-inl.h" #include "string_bytes.h" #include "string_search.h" #include "util-inl.h" #include "v8.h" #include <cstring> #include <climits> #define THROW_AND_RETURN_UNLESS_BUFFER(env, obj) \ THROW_AND_RETURN_IF_NOT_BUFFER(env, obj, "argument") \ #define THROW_AND_RETURN_IF_OOB(r) \ do { \ if ((r).IsNothing()) return; \ if (!(r).FromJust()) \ return node::THROW_ERR_OUT_OF_RANGE(env, "Index out of range"); \ } while (0) \ namespace node { namespace Buffer { using v8::ArrayBuffer; using v8::ArrayBufferView; using v8::BackingStore; using v8::Context; using v8::EscapableHandleScope; using v8::FunctionCallbackInfo; using v8::Global; using v8::HandleScope; using v8::Int32; using v8::Integer; using v8::Isolate; using v8::Just; using v8::Local; using v8::Maybe; using v8::MaybeLocal; using v8::Nothing; using v8::Number; using v8::Object; using v8::String; using v8::Uint32; using v8::Uint32Array; using v8::Uint8Array; using v8::Value; namespace { class CallbackInfo { public: static inline Local<ArrayBuffer> CreateTrackedArrayBuffer( Environment* env, char* data, size_t length, FreeCallback callback, void* hint); CallbackInfo(const CallbackInfo&) = delete; CallbackInfo& operator=(const CallbackInfo&) = delete; private: static void CleanupHook(void* data); inline void OnBackingStoreFree(); inline void CallAndResetCallback(); inline CallbackInfo(Environment* env, FreeCallback callback, char* data, void* hint); Global<ArrayBuffer> persistent_; Mutex mutex_; // Protects callback_. FreeCallback callback_; char* const data_; void* const hint_; Environment* const env_; }; Local<ArrayBuffer> CallbackInfo::CreateTrackedArrayBuffer( Environment* env, char* data, size_t length, FreeCallback callback, void* hint) { CHECK_NOT_NULL(callback); CHECK_IMPLIES(data == nullptr, length == 0); CallbackInfo* self = new CallbackInfo(env, callback, data, hint); std::unique_ptr<BackingStore> bs = ArrayBuffer::NewBackingStore(data, length, [](void*, size_t, void* arg) { static_cast<CallbackInfo*>(arg)->OnBackingStoreFree(); }, self); Local<ArrayBuffer> ab = ArrayBuffer::New(env->isolate(), std::move(bs)); // V8 simply ignores the BackingStore deleter callback if data == nullptr, // but our API contract requires it being called. if (data == nullptr) { ab->Detach(); self->OnBackingStoreFree(); // This calls `callback` asynchronously. } else { // Store the ArrayBuffer so that we can detach it later. self->persistent_.Reset(env->isolate(), ab); self->persistent_.SetWeak(); } return ab; } CallbackInfo::CallbackInfo(Environment* env, FreeCallback callback, char* data, void* hint) : callback_(callback), data_(data), hint_(hint), env_(env) { env->AddCleanupHook(CleanupHook, this); env->isolate()->AdjustAmountOfExternalAllocatedMemory(sizeof(*this)); } void CallbackInfo::CleanupHook(void* data) { CallbackInfo* self = static_cast<CallbackInfo*>(data); { HandleScope handle_scope(self->env_->isolate()); Local<ArrayBuffer> ab = self->persistent_.Get(self->env_->isolate()); if (!ab.IsEmpty() && ab->IsDetachable()) { ab->Detach(); self->persistent_.Reset(); } } // Call the callback in this case, but don't delete `this` yet because the // BackingStore deleter callback will do so later. self->CallAndResetCallback(); } void CallbackInfo::CallAndResetCallback() { FreeCallback callback; { Mutex::ScopedLock lock(mutex_); callback = callback_; callback_ = nullptr; } if (callback != nullptr) { // Clean up all Environment-related state and run the callback. env_->RemoveCleanupHook(CleanupHook, this); int64_t change_in_bytes = -static_cast<int64_t>(sizeof(*this)); env_->isolate()->AdjustAmountOfExternalAllocatedMemory(change_in_bytes); callback(data_, hint_); } } void CallbackInfo::OnBackingStoreFree() { // This method should always release the memory for `this`. std::unique_ptr<CallbackInfo> self { this }; Mutex::ScopedLock lock(mutex_); // If callback_ == nullptr, that means that the callback has already run from // the cleanup hook, and there is nothing left to do here besides to clean // up the memory involved. In particular, the underlying `Environment` may // be gone at this point, so don’t attempt to call SetImmediateThreadsafe(). if (callback_ == nullptr) return; env_->SetImmediateThreadsafe([self = std::move(self)](Environment* env) { CHECK_EQ(self->env_, env); // Consistency check. self->CallAndResetCallback(); }); } // Parse index for external array data. An empty Maybe indicates // a pending exception. `false` indicates that the index is out-of-bounds. inline MUST_USE_RESULT Maybe<bool> ParseArrayIndex(Environment* env, Local<Value> arg, size_t def, size_t* ret) { if (arg->IsUndefined()) { *ret = def; return Just(true); } int64_t tmp_i; if (!arg->IntegerValue(env->context()).To(&tmp_i)) return Nothing<bool>(); if (tmp_i < 0) return Just(false); // Check that the result fits in a size_t. const uint64_t kSizeMax = static_cast<uint64_t>(static_cast<size_t>(-1)); // coverity[pointless_expression] if (static_cast<uint64_t>(tmp_i) > kSizeMax) return Just(false); *ret = static_cast<size_t>(tmp_i); return Just(true); } } // anonymous namespace // Buffer methods bool HasInstance(Local<Value> val) { return val->IsArrayBufferView(); } bool HasInstance(Local<Object> obj) { return obj->IsArrayBufferView(); } char* Data(Local<Value> val) { CHECK(val->IsArrayBufferView()); Local<ArrayBufferView> ui = val.As<ArrayBufferView>(); return static_cast<char*>(ui->Buffer()->GetBackingStore()->Data()) + ui->ByteOffset(); } char* Data(Local<Object> obj) { return Data(obj.As<Value>()); } size_t Length(Local<Value> val) { CHECK(val->IsArrayBufferView()); Local<ArrayBufferView> ui = val.As<ArrayBufferView>(); return ui->ByteLength(); } size_t Length(Local<Object> obj) { CHECK(obj->IsArrayBufferView()); Local<ArrayBufferView> ui = obj.As<ArrayBufferView>(); return ui->ByteLength(); } MaybeLocal<Uint8Array> New(Environment* env, Local<ArrayBuffer> ab, size_t byte_offset, size_t length) { CHECK(!env->buffer_prototype_object().IsEmpty()); Local<Uint8Array> ui = Uint8Array::New(ab, byte_offset, length); Maybe<bool> mb = ui->SetPrototype(env->context(), env->buffer_prototype_object()); if (mb.IsNothing()) return MaybeLocal<Uint8Array>(); return ui; } MaybeLocal<Uint8Array> New(Isolate* isolate, Local<ArrayBuffer> ab, size_t byte_offset, size_t length) { Environment* env = Environment::GetCurrent(isolate); if (env == nullptr) { THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate); return MaybeLocal<Uint8Array>(); } return New(env, ab, byte_offset, length); } MaybeLocal<Object> New(Isolate* isolate, Local<String> string, enum encoding enc) { EscapableHandleScope scope(isolate); size_t length; if (!StringBytes::Size(isolate, string, enc).To(&length)) return Local<Object>(); size_t actual = 0; char* data = nullptr; if (length > 0) { data = UncheckedMalloc(length); if (data == nullptr) { THROW_ERR_MEMORY_ALLOCATION_FAILED(isolate); return Local<Object>(); } actual = StringBytes::Write(isolate, data, length, string, enc); CHECK(actual <= length); if (actual == 0) { free(data); data = nullptr; } else if (actual < length) { data = node::Realloc(data, actual); } } return scope.EscapeMaybe(New(isolate, data, actual)); } MaybeLocal<Object> New(Isolate* isolate, size_t length) { EscapableHandleScope handle_scope(isolate); Local<Object> obj; Environment* env = Environment::GetCurrent(isolate); if (env == nullptr) { THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate); return MaybeLocal<Object>(); } if (Buffer::New(env, length).ToLocal(&obj)) return handle_scope.Escape(obj); return Local<Object>(); } MaybeLocal<Object> New(Environment* env, size_t length) { EscapableHandleScope scope(env->isolate()); // V8 currently only allows a maximum Typed Array index of max Smi. if (length > kMaxLength) { env->isolate()->ThrowException(ERR_BUFFER_TOO_LARGE(env->isolate())); return Local<Object>(); } return scope.EscapeMaybe( AllocatedBuffer::AllocateManaged(env, length).ToBuffer()); } MaybeLocal<Object> Copy(Isolate* isolate, const char* data, size_t length) { EscapableHandleScope handle_scope(isolate); Environment* env = Environment::GetCurrent(isolate); if (env == nullptr) { THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate); return MaybeLocal<Object>(); } Local<Object> obj; if (Buffer::Copy(env, data, length).ToLocal(&obj)) return handle_scope.Escape(obj); return Local<Object>(); } MaybeLocal<Object> Copy(Environment* env, const char* data, size_t length) { EscapableHandleScope scope(env->isolate()); // V8 currently only allows a maximum Typed Array index of max Smi. if (length > kMaxLength) { env->isolate()->ThrowException(ERR_BUFFER_TOO_LARGE(env->isolate())); return Local<Object>(); } AllocatedBuffer ret = AllocatedBuffer::AllocateManaged(env, length); if (length > 0) { memcpy(ret.data(), data, length); } return scope.EscapeMaybe(ret.ToBuffer()); } MaybeLocal<Object> New(Isolate* isolate, char* data, size_t length, FreeCallback callback, void* hint) { EscapableHandleScope handle_scope(isolate); Environment* env = Environment::GetCurrent(isolate); if (env == nullptr) { callback(data, hint); THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate); return MaybeLocal<Object>(); } return handle_scope.EscapeMaybe( Buffer::New(env, data, length, callback, hint)); } MaybeLocal<Object> New(Environment* env, char* data, size_t length, FreeCallback callback, void* hint) { EscapableHandleScope scope(env->isolate()); if (length > kMaxLength) { env->isolate()->ThrowException(ERR_BUFFER_TOO_LARGE(env->isolate())); callback(data, hint); return Local<Object>(); } Local<ArrayBuffer> ab = CallbackInfo::CreateTrackedArrayBuffer(env, data, length, callback, hint); if (ab->SetPrivate(env->context(), env->untransferable_object_private_symbol(), True(env->isolate())).IsNothing()) { return Local<Object>(); } MaybeLocal<Uint8Array> ui = Buffer::New(env, ab, 0, length); if (ui.IsEmpty()) return MaybeLocal<Object>(); return scope.Escape(ui.ToLocalChecked()); } // Warning: This function needs `data` to be allocated with malloc() and not // necessarily isolate's ArrayBuffer::Allocator. MaybeLocal<Object> New(Isolate* isolate, char* data, size_t length) { EscapableHandleScope handle_scope(isolate); Environment* env = Environment::GetCurrent(isolate); if (env == nullptr) { free(data); THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate); return MaybeLocal<Object>(); } Local<Object> obj; if (Buffer::New(env, data, length).ToLocal(&obj)) return handle_scope.Escape(obj); return Local<Object>(); } // The contract for this function is that `data` is allocated with malloc() // and not necessarily isolate's ArrayBuffer::Allocator. MaybeLocal<Object> New(Environment* env, char* data, size_t length) { if (length > 0) { CHECK_NOT_NULL(data); CHECK(length <= kMaxLength); } auto free_callback = [](char* data, void* hint) { free(data); }; return New(env, data, length, free_callback, nullptr); } namespace { void CreateFromString(const FunctionCallbackInfo<Value>& args) { CHECK(args[0]->IsString()); CHECK(args[1]->IsInt32()); enum encoding enc = static_cast<enum encoding>(args[1].As<Int32>()->Value()); Local<Object> buf; if (New(args.GetIsolate(), args[0].As<String>(), enc).ToLocal(&buf)) args.GetReturnValue().Set(buf); } template <encoding encoding> void StringSlice(const FunctionCallbackInfo<Value>& args) { Environment* env = Environment::GetCurrent(args); Isolate* isolate = env->isolate(); THROW_AND_RETURN_UNLESS_BUFFER(env, args.This()); ArrayBufferViewContents<char> buffer(args.This()); if (buffer.length() == 0) return args.GetReturnValue().SetEmptyString(); size_t start = 0; size_t end = 0; THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[0], 0, &start)); THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[1], buffer.length(), &end)); if (end < start) end = start; THROW_AND_RETURN_IF_OOB(Just(end <= buffer.length())); size_t length = end - start; Local<Value> error; MaybeLocal<Value> ret = StringBytes::Encode(isolate, buffer.data() + start, length, encoding, &error); if (ret.IsEmpty()) { CHECK(!error.IsEmpty()); isolate->ThrowException(error); return; } args.GetReturnValue().Set(ret.ToLocalChecked()); } // bytesCopied = copy(buffer, target[, targetStart][, sourceStart][, sourceEnd]) void Copy(const FunctionCallbackInfo<Value> &args) { Environment* env = Environment::GetCurrent(args); THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]); THROW_AND_RETURN_UNLESS_BUFFER(env, args[1]); ArrayBufferViewContents<char> source(args[0]); Local<Object> target_obj = args[1].As<Object>(); SPREAD_BUFFER_ARG(target_obj, target); size_t target_start = 0; size_t source_start = 0; size_t source_end = 0; THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[2], 0, &target_start)); THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[3], 0, &source_start)); THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[4], source.length(), &source_end)); // Copy 0 bytes; we're done if (target_start >= target_length || source_start >= source_end) return args.GetReturnValue().Set(0); if (source_start > source.length()) return THROW_ERR_OUT_OF_RANGE( env, "The value of \"sourceStart\" is out of range."); if (source_end - source_start > target_length - target_start) source_end = source_start + target_length - target_start; uint32_t to_copy = std::min( std::min(source_end - source_start, target_length - target_start), source.length() - source_start); memmove(target_data + target_start, source.data() + source_start, to_copy); args.GetReturnValue().Set(to_copy); } void Fill(const FunctionCallbackInfo<Value>& args) { Environment* env = Environment::GetCurrent(args); Local<Context> ctx = env->context(); THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]); SPREAD_BUFFER_ARG(args[0], ts_obj); size_t start; THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[2], 0, &start)); size_t end; THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[3], 0, &end)); size_t fill_length = end - start; Local<String> str_obj; size_t str_length; enum encoding enc; // OOB Check. Throw the error in JS. if (start > end || fill_length + start > ts_obj_length) return args.GetReturnValue().Set(-2); // First check if Buffer has been passed. if (Buffer::HasInstance(args[1])) { SPREAD_BUFFER_ARG(args[1], fill_obj); str_length = fill_obj_length; memcpy( ts_obj_data + start, fill_obj_data, std::min(str_length, fill_length)); goto start_fill; } // Then coerce everything that's not a string. if (!args[1]->IsString()) { uint32_t val; if (!args[1]->Uint32Value(ctx).To(&val)) return; int value = val & 255; memset(ts_obj_data + start, value, fill_length); return; } str_obj = args[1]->ToString(env->context()).ToLocalChecked(); enc = ParseEncoding(env->isolate(), args[4], UTF8); // Can't use StringBytes::Write() in all cases. For example if attempting // to write a two byte character into a one byte Buffer. if (enc == UTF8) { str_length = str_obj->Utf8Length(env->isolate()); node::Utf8Value str(env->isolate(), args[1]); memcpy(ts_obj_data + start, *str, std::min(str_length, fill_length)); } else if (enc == UCS2) { str_length = str_obj->Length() * sizeof(uint16_t); node::TwoByteValue str(env->isolate(), args[1]); if (IsBigEndian()) SwapBytes16(reinterpret_cast<char*>(&str[0]), str_length); memcpy(ts_obj_data + start, *str, std::min(str_length, fill_length)); } else { // Write initial String to Buffer, then use that memory to copy remainder // of string. Correct the string length for cases like HEX where less than // the total string length is written. str_length = StringBytes::Write(env->isolate(), ts_obj_data + start, fill_length, str_obj, enc, nullptr); } start_fill: if (str_length >= fill_length) return; // If str_length is zero, then either an empty buffer was provided, or Write() // indicated that no bytes could be written. If no bytes could be written, // then return -1 because the fill value is invalid. This will trigger a throw // in JavaScript. Silently failing should be avoided because it can lead to // buffers with unexpected contents. if (str_length == 0) return args.GetReturnValue().Set(-1); size_t in_there = str_length; char* ptr = ts_obj_data + start + str_length; while (in_there < fill_length - in_there) { memcpy(ptr, ts_obj_data + start, in_there); ptr += in_there; in_there *= 2; } if (in_there < fill_length) { memcpy(ptr, ts_obj_data + start, fill_length - in_there); } } template <encoding encoding> void StringWrite(const FunctionCallbackInfo<Value>& args) { Environment* env = Environment::GetCurrent(args); THROW_AND_RETURN_UNLESS_BUFFER(env, args.This()); SPREAD_BUFFER_ARG(args.This(), ts_obj); THROW_AND_RETURN_IF_NOT_STRING(env, args[0], "argument"); Local<String> str = args[0]->ToString(env->context()).ToLocalChecked(); size_t offset; size_t max_length; THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[1], 0, &offset)); if (offset > ts_obj_length) { return node::THROW_ERR_BUFFER_OUT_OF_BOUNDS( env, "\"offset\" is outside of buffer bounds"); } THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[2], ts_obj_length - offset, &max_length)); max_length = std::min(ts_obj_length - offset, max_length); if (max_length == 0) return args.GetReturnValue().Set(0); uint32_t written = StringBytes::Write(env->isolate(), ts_obj_data + offset, max_length, str, encoding, nullptr); args.GetReturnValue().Set(written); } void ByteLengthUtf8(const FunctionCallbackInfo<Value> &args) { Environment* env = Environment::GetCurrent(args); CHECK(args[0]->IsString()); // Fast case: avoid StringBytes on UTF8 string. Jump to v8. args.GetReturnValue().Set(args[0].As<String>()->Utf8Length(env->isolate())); } // Normalize val to be an integer in the range of [1, -1] since // implementations of memcmp() can vary by platform. static int normalizeCompareVal(int val, size_t a_length, size_t b_length) { if (val == 0) { if (a_length > b_length) return 1; else if (a_length < b_length) return -1; } else { if (val > 0) return 1; else return -1; } return val; } void CompareOffset(const FunctionCallbackInfo<Value> &args) { Environment* env = Environment::GetCurrent(args); THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]); THROW_AND_RETURN_UNLESS_BUFFER(env, args[1]); ArrayBufferViewContents<char> source(args[0]); ArrayBufferViewContents<char> target(args[1]); size_t target_start = 0; size_t source_start = 0; size_t source_end = 0; size_t target_end = 0; THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[2], 0, &target_start)); THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[3], 0, &source_start)); THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[4], target.length(), &target_end)); THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[5], source.length(), &source_end)); if (source_start > source.length()) return THROW_ERR_OUT_OF_RANGE( env, "The value of \"sourceStart\" is out of range."); if (target_start > target.length()) return THROW_ERR_OUT_OF_RANGE( env, "The value of \"targetStart\" is out of range."); CHECK_LE(source_start, source_end); CHECK_LE(target_start, target_end); size_t to_cmp = std::min(std::min(source_end - source_start, target_end - target_start), source.length() - source_start); int val = normalizeCompareVal(to_cmp > 0 ? memcmp(source.data() + source_start, target.data() + target_start, to_cmp) : 0, source_end - source_start, target_end - target_start); args.GetReturnValue().Set(val); } void Compare(const FunctionCallbackInfo<Value> &args) { Environment* env = Environment::GetCurrent(args); THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]); THROW_AND_RETURN_UNLESS_BUFFER(env, args[1]); ArrayBufferViewContents<char> a(args[0]); ArrayBufferViewContents<char> b(args[1]); size_t cmp_length = std::min(a.length(), b.length()); int val = normalizeCompareVal(cmp_length > 0 ? memcmp(a.data(), b.data(), cmp_length) : 0, a.length(), b.length()); args.GetReturnValue().Set(val); } // Computes the offset for starting an indexOf or lastIndexOf search. // Returns either a valid offset in [0...<length - 1>], ie inside the Buffer, // or -1 to signal that there is no possible match. int64_t IndexOfOffset(size_t length, int64_t offset_i64, int64_t needle_length, bool is_forward) { int64_t length_i64 = static_cast<int64_t>(length); if (offset_i64 < 0) { if (offset_i64 + length_i64 >= 0) { // Negative offsets count backwards from the end of the buffer. return length_i64 + offset_i64; } else if (is_forward || needle_length == 0) { // indexOf from before the start of the buffer: search the whole buffer. return 0; } else { // lastIndexOf from before the start of the buffer: no match. return -1; } } else { if (offset_i64 + needle_length <= length_i64) { // Valid positive offset. return offset_i64; } else if (needle_length == 0) { // Out of buffer bounds, but empty needle: point to end of buffer. return length_i64; } else if (is_forward) { // indexOf from past the end of the buffer: no match. return -1; } else { // lastIndexOf from past the end of the buffer: search the whole buffer. return length_i64 - 1; } } } void IndexOfString(const FunctionCallbackInfo<Value>& args) { Environment* env = Environment::GetCurrent(args); Isolate* isolate = env->isolate(); CHECK(args[1]->IsString()); CHECK(args[2]->IsNumber()); CHECK(args[3]->IsInt32()); CHECK(args[4]->IsBoolean()); enum encoding enc = static_cast<enum encoding>(args[3].As<Int32>()->Value()); THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]); ArrayBufferViewContents<char> buffer(args[0]); Local<String> needle = args[1].As<String>(); int64_t offset_i64 = args[2].As<Integer>()->Value(); bool is_forward = args[4]->IsTrue(); const char* haystack = buffer.data(); // Round down to the nearest multiple of 2 in case of UCS2. const size_t haystack_length = (enc == UCS2) ? buffer.length() &~ 1 : buffer.length(); // NOLINT(whitespace/operators) size_t needle_length; if (!StringBytes::Size(isolate, needle, enc).To(&needle_length)) return; int64_t opt_offset = IndexOfOffset(haystack_length, offset_i64, needle_length, is_forward); if (needle_length == 0) { // Match String#indexOf() and String#lastIndexOf() behavior. args.GetReturnValue().Set(static_cast<double>(opt_offset)); return; } if (haystack_length == 0) { return args.GetReturnValue().Set(-1); } if (opt_offset <= -1) { return args.GetReturnValue().Set(-1); } size_t offset = static_cast<size_t>(opt_offset); CHECK_LT(offset, haystack_length); if ((is_forward && needle_length + offset > haystack_length) || needle_length > haystack_length) { return args.GetReturnValue().Set(-1); } size_t result = haystack_length; if (enc == UCS2) { String::Value needle_value(isolate, needle); if (*needle_value == nullptr) return args.GetReturnValue().Set(-1); if (haystack_length < 2 || needle_value.length() < 1) { return args.GetReturnValue().Set(-1); } if (IsBigEndian()) { StringBytes::InlineDecoder decoder; if (decoder.Decode(env, needle, enc).IsNothing()) return; const uint16_t* decoded_string = reinterpret_cast<const uint16_t*>(decoder.out()); if (decoded_string == nullptr) return args.GetReturnValue().Set(-1); result = SearchString(reinterpret_cast<const uint16_t*>(haystack), haystack_length / 2, decoded_string, decoder.size() / 2, offset / 2, is_forward); } else { result = SearchString(reinterpret_cast<const uint16_t*>(haystack), haystack_length / 2, reinterpret_cast<const uint16_t*>(*needle_value), needle_value.length(), offset / 2, is_forward); } result *= 2; } else if (enc == UTF8) { String::Utf8Value needle_value(isolate, needle); if (*needle_value == nullptr) return args.GetReturnValue().Set(-1); result = SearchString(reinterpret_cast<const uint8_t*>(haystack), haystack_length, reinterpret_cast<const uint8_t*>(*needle_value), needle_length, offset, is_forward); } else if (enc == LATIN1) { uint8_t* needle_data = node::UncheckedMalloc<uint8_t>(needle_length); if (needle_data == nullptr) { return args.GetReturnValue().Set(-1); } needle->WriteOneByte( isolate, needle_data, 0, needle_length, String::NO_NULL_TERMINATION); result = SearchString(reinterpret_cast<const uint8_t*>(haystack), haystack_length, needle_data, needle_length, offset, is_forward); free(needle_data); } args.GetReturnValue().Set( result == haystack_length ? -1 : static_cast<int>(result)); } void IndexOfBuffer(const FunctionCallbackInfo<Value>& args) { CHECK(args[1]->IsObject()); CHECK(args[2]->IsNumber()); CHECK(args[3]->IsInt32()); CHECK(args[4]->IsBoolean()); enum encoding enc = static_cast<enum encoding>(args[3].As<Int32>()->Value()); THROW_AND_RETURN_UNLESS_BUFFER(Environment::GetCurrent(args), args[0]); THROW_AND_RETURN_UNLESS_BUFFER(Environment::GetCurrent(args), args[1]); ArrayBufferViewContents<char> haystack_contents(args[0]); ArrayBufferViewContents<char> needle_contents(args[1]); int64_t offset_i64 = args[2].As<Integer>()->Value(); bool is_forward = args[4]->IsTrue(); const char* haystack = haystack_contents.data(); const size_t haystack_length = haystack_contents.length(); const char* needle = needle_contents.data(); const size_t needle_length = needle_contents.length(); int64_t opt_offset = IndexOfOffset(haystack_length, offset_i64, needle_length, is_forward); if (needle_length == 0) { // Match String#indexOf() and String#lastIndexOf() behavior. args.GetReturnValue().Set(static_cast<double>(opt_offset)); return; } if (haystack_length == 0) { return args.GetReturnValue().Set(-1); } if (opt_offset <= -1) { return args.GetReturnValue().Set(-1); } size_t offset = static_cast<size_t>(opt_offset); CHECK_LT(offset, haystack_length); if ((is_forward && needle_length + offset > haystack_length) || needle_length > haystack_length) { return args.GetReturnValue().Set(-1); } size_t result = haystack_length; if (enc == UCS2) { if (haystack_length < 2 || needle_length < 2) { return args.GetReturnValue().Set(-1); } result = SearchString( reinterpret_cast<const uint16_t*>(haystack), haystack_length / 2, reinterpret_cast<const uint16_t*>(needle), needle_length / 2, offset / 2, is_forward); result *= 2; } else { result = SearchString( reinterpret_cast<const uint8_t*>(haystack), haystack_length, reinterpret_cast<const uint8_t*>(needle), needle_length, offset, is_forward); } args.GetReturnValue().Set( result == haystack_length ? -1 : static_cast<int>(result)); } void IndexOfNumber(const FunctionCallbackInfo<Value>& args) { CHECK(args[1]->IsUint32()); |
| You are visitor 01402775 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |