From a238ec8da173c0eb00bb60aae90f07c82af387ae Mon Sep 17 00:00:00 2001 From: Alexander Polyakov Date: Fri, 20 Dec 2024 14:35:04 +0300 Subject: [PATCH 1/3] Apply new .clang-format --- .clang-format | 93 +- .../core/allocator/runtime-allocator.h | 20 +- .../core/allocator/script-allocator-managed.h | 18 +- runtime-common/core/array_access.h | 11 +- .../class-instance/class-instance-decl.inl | 114 +- .../core/class-instance/class-instance.inl | 42 +- .../class-instance/refcountable-php-classes.h | 50 +- runtime-common/core/core-context.h | 2 +- .../core/core-types/comparison_operators.inl | 626 +++-- .../core/core-types/conversions_types.inl | 188 +- .../core/core-types/decl/array_decl.inl | 439 ++-- .../core/core-types/decl/array_iterator.h | 104 +- .../core/core-types/decl/declarations.h | 9 +- .../core/core-types/decl/mixed_decl.inl | 358 ++- .../core/core-types/decl/optional.h | 151 +- runtime-common/core/core-types/decl/shape.h | 122 +- .../core-types/decl/string_buffer_decl.inl | 49 +- .../core/core-types/decl/string_decl.inl | 203 +- .../core/core-types/definition/array.inl | 1323 ++++++----- .../core/core-types/definition/mixed.cpp | 1975 ++++++++-------- .../core/core-types/definition/mixed.inl | 173 +- .../core/core-types/definition/string.cpp | 4 +- .../core/core-types/definition/string.inl | 594 ++--- .../core-types/definition/string_buffer.cpp | 11 +- .../core-types/definition/string_buffer.inl | 86 +- .../core-types/definition/string_cache.cpp | 6 +- .../core/core-types/definition/string_cache.h | 71 +- .../core/core-types/kphp_type_traits.h | 78 +- runtime-common/core/include.h | 45 +- .../details/memory_chunk_list.h | 26 +- .../details/memory_chunk_tree.cpp | 117 +- .../details/memory_chunk_tree.h | 38 +- .../details/memory_ordered_chunk_list.cpp | 45 +- .../details/memory_ordered_chunk_list.h | 28 +- .../details/universal_reallocate.h | 8 +- .../core/memory-resource/extra-memory-pool.h | 38 +- .../core/memory-resource/memory_resource.h | 16 +- .../monotonic_buffer_resource.cpp | 4 +- .../monotonic_buffer_resource.h | 55 +- .../core/memory-resource/resource_allocator.h | 48 +- .../unsynchronized_pool_resource.cpp | 20 +- .../unsynchronized_pool_resource.h | 46 +- runtime-common/core/runtime-core.h | 1463 ++++++------ runtime-common/core/utils/hash.h | 4 +- runtime-common/core/utils/kphp-assert-core.h | 30 +- runtime-common/core/utils/migration-php8.cpp | 12 +- .../core/utils/small-object-storage.h | 32 +- .../stdlib/array/array-functions.cpp | 108 +- runtime-common/stdlib/array/array-functions.h | 490 ++-- .../stdlib/array/to-array-processor.h | 77 +- .../stdlib/math/bcmath-functions.cpp | 92 +- runtime-common/stdlib/math/bcmath-functions.h | 18 +- runtime-common/stdlib/math/math-context.cpp | 11 +- runtime-common/stdlib/math/math-context.h | 4 +- runtime-common/stdlib/math/math-functions.cpp | 4 +- runtime-common/stdlib/math/math-functions.h | 96 +- .../serialization/from-json-processor.h | 86 +- .../stdlib/serialization/json-functions.cpp | 660 +++--- .../stdlib/serialization/json-functions.h | 68 +- .../serialization/json-processor-utils.h | 13 +- .../stdlib/serialization/json-writer.cpp | 114 +- .../stdlib/serialization/json-writer.h | 10 +- .../serialization/serialization-context.h | 2 +- .../serialization/serialize-functions.cpp | 332 ++- .../serialization/serialize-functions.h | 44 +- .../stdlib/serialization/to-json-processor.h | 142 +- .../stdlib/server/url-functions.cpp | 164 +- runtime-common/stdlib/server/url-functions.h | 18 +- .../stdlib/string/mbstring-functions.cpp | 168 +- .../stdlib/string/mbstring-functions.h | 30 +- .../stdlib/string/regex-functions.cpp | 74 +- .../stdlib/string/regex-functions.h | 2 +- runtime-common/stdlib/string/string-context.h | 4 +- .../stdlib/string/string-functions.cpp | 2006 ++++++++--------- .../stdlib/string/string-functions.h | 280 ++- .../stdlib/tracing/tracing-context.h | 2 +- .../stdlib/tracing/tracing-functions.h | 4 +- runtime-common/stdlib/tracing/tracing.h | 4 +- .../stdlib/visitors/common-visitors-methods.h | 2 +- runtime-light/allocator/allocator.h | 5 +- .../allocator/libc-alloc-wrapper.cpp | 16 +- .../allocator/runtime-light-allocator.cpp | 44 +- runtime-light/core/globals/php-init-scripts.h | 2 +- .../core/globals/php-script-globals.cpp | 14 +- .../core/globals/php-script-globals.h | 40 +- .../core/kphp-core-impl/kphp-core-context.cpp | 8 +- runtime-light/coroutine/awaitable.h | 169 +- runtime-light/coroutine/task.h | 130 +- runtime-light/k2-platform/k2-api.h | 140 +- runtime-light/k2-platform/k2-header.h | 66 +- .../monotonic-light-buffer-resource.cpp | 2 +- runtime-light/runtime-light.cpp | 18 +- runtime-light/scheduler/scheduler.cpp | 122 +- runtime-light/scheduler/scheduler.h | 89 +- .../server/http/http-server-state.cpp | 4 +- runtime-light/server/http/http-server-state.h | 15 +- runtime-light/server/http/init-functions.cpp | 50 +- runtime-light/server/http/init-functions.h | 4 +- runtime-light/server/init-functions.h | 26 +- .../server/job-worker/init-functions.h | 6 +- .../job-worker/job-worker-server-state.cpp | 4 +- .../job-worker/job-worker-server-state.h | 2 +- runtime-light/state/component-state.h | 16 +- runtime-light/state/image-state.h | 14 +- runtime-light/state/init-functions.cpp | 42 +- runtime-light/state/init-functions.h | 4 +- runtime-light/state/instance-state.cpp | 110 +- runtime-light/state/instance-state.h | 52 +- runtime-light/stdlib/array/array-functions.h | 201 +- .../stdlib/component/component-api.h | 22 +- .../stdlib/confdata/confdata-functions.cpp | 6 +- .../stdlib/confdata/confdata-functions.h | 2 +- .../stdlib/crypto/crypto-functions.cpp | 46 +- .../stdlib/crypto/crypto-functions.h | 22 +- runtime-light/stdlib/crypto/crypto-state.cpp | 4 +- runtime-light/stdlib/crypto/crypto-state.h | 2 +- runtime-light/stdlib/curl/curl-functions.h | 6 +- runtime-light/stdlib/curl/curl-state.cpp | 4 +- runtime-light/stdlib/curl/curl-state.h | 2 +- .../stdlib/exception/exception-functions.h | 34 +- runtime-light/stdlib/exit/exit-functions.cpp | 8 +- runtime-light/stdlib/exit/exit-functions.h | 6 +- .../stdlib/file/file-system-functions.cpp | 16 +- .../stdlib/file/file-system-functions.h | 18 +- .../stdlib/file/file-system-state.cpp | 4 +- runtime-light/stdlib/file/file-system-state.h | 2 +- runtime-light/stdlib/file/resource.cpp | 90 +- runtime-light/stdlib/file/resource.h | 18 +- runtime-light/stdlib/fork/fork-functions.h | 65 +- runtime-light/stdlib/fork/fork-state.cpp | 4 +- runtime-light/stdlib/fork/fork-state.h | 18 +- .../stdlib/instance-cache/instance-cache.h | 8 +- .../stdlib/job-worker/job-worker-api.cpp | 14 +- .../stdlib/job-worker/job-worker-api.h | 4 +- .../job-worker/job-worker-client-state.cpp | 4 +- .../job-worker/job-worker-client-state.h | 2 +- runtime-light/stdlib/job-worker/job-worker.h | 36 +- runtime-light/stdlib/math/math-state.cpp | 8 +- runtime-light/stdlib/math/random-functions.h | 12 +- runtime-light/stdlib/math/random-state.cpp | 4 +- runtime-light/stdlib/math/random-state.h | 2 +- runtime-light/stdlib/output/http-functions.h | 5 +- runtime-light/stdlib/output/output-buffer.cpp | 24 +- runtime-light/stdlib/output/output-buffer.h | 2 +- .../stdlib/output/print-functions.cpp | 288 ++- runtime-light/stdlib/output/print-functions.h | 50 +- runtime-light/stdlib/rpc/rpc-api.cpp | 72 +- runtime-light/stdlib/rpc/rpc-api.h | 48 +- .../stdlib/rpc/rpc-extra-headers.cpp | 48 +- runtime-light/stdlib/rpc/rpc-extra-headers.h | 2 +- runtime-light/stdlib/rpc/rpc-extra-info.cpp | 6 +- runtime-light/stdlib/rpc/rpc-extra-info.h | 2 +- runtime-light/stdlib/rpc/rpc-state.cpp | 12 +- runtime-light/stdlib/rpc/rpc-state.h | 19 +- runtime-light/stdlib/rpc/rpc-tl-defs.h | 19 +- runtime-light/stdlib/rpc/rpc-tl-error.cpp | 2 +- runtime-light/stdlib/rpc/rpc-tl-error.h | 8 +- runtime-light/stdlib/rpc/rpc-tl-func-base.h | 2 +- runtime-light/stdlib/rpc/rpc-tl-function.h | 90 +- .../stdlib/rpc/rpc-tl-kphp-request.h | 15 +- runtime-light/stdlib/rpc/rpc-tl-query.cpp | 28 +- runtime-light/stdlib/rpc/rpc-tl-query.h | 12 +- runtime-light/stdlib/rpc/rpc-tl-request.cpp | 31 +- runtime-light/stdlib/rpc/rpc-tl-request.h | 6 +- .../stdlib/serialization/instance-serialize.h | 18 +- .../serialization/serialization-state.cpp | 4 +- runtime-light/stdlib/server/args-functions.h | 4 +- .../stdlib/server/handler-functions.h | 21 +- .../stdlib/server/http-functions.cpp | 14 +- runtime-light/stdlib/server/http-functions.h | 6 +- .../stdlib/string/regex-functions.cpp | 258 ++- runtime-light/stdlib/string/regex-functions.h | 60 +- runtime-light/stdlib/string/regex-include.h | 2 +- runtime-light/stdlib/string/regex-state.cpp | 24 +- runtime-light/stdlib/string/regex-state.h | 6 +- runtime-light/stdlib/string/string-state.cpp | 8 +- .../stdlib/system/system-functions.h | 62 +- runtime-light/stdlib/system/system-state.cpp | 4 +- runtime-light/stdlib/system/system-state.h | 2 +- runtime-light/stdlib/time/time-functions.cpp | 416 ++-- runtime-light/stdlib/time/time-functions.h | 12 +- runtime-light/stdlib/time/timer-functions.h | 6 +- .../stdlib/tracing/tracing-functions.h | 7 +- runtime-light/stdlib/value/value-functions.h | 4 +- runtime-light/stdlib/zlib/zlib-functions.cpp | 16 +- runtime-light/stdlib/zlib/zlib-functions.h | 4 +- runtime-light/streams/streams.cpp | 32 +- runtime-light/streams/streams.h | 12 +- runtime-light/tl/tl-builtins.cpp | 100 +- runtime-light/tl/tl-builtins.h | 215 +- runtime-light/tl/tl-core.cpp | 72 +- runtime-light/tl/tl-core.h | 35 +- runtime-light/tl/tl-functions.cpp | 22 +- runtime-light/tl/tl-functions.h | 22 +- runtime-light/tl/tl-types.cpp | 82 +- runtime-light/tl/tl-types.h | 282 +-- runtime-light/utils/concepts.h | 4 +- runtime-light/utils/null_coalesce.h | 104 +- runtime-light/utils/php_assert.cpp | 12 +- runtime/allocator.cpp | 183 +- runtime/allocator.h | 59 +- runtime/array_functions.cpp | 1 - runtime/array_functions.h | 394 ++-- runtime/bcmath.cpp | 4 +- runtime/common_template_instantiations.cpp | 2 +- runtime/confdata-functions.cpp | 96 +- runtime/confdata-functions.h | 7 +- runtime/confdata-global-manager.cpp | 27 +- runtime/confdata-global-manager.h | 69 +- runtime/confdata-keys.cpp | 53 +- runtime/confdata-keys.h | 65 +- runtime/context/runtime-context.cpp | 8 +- runtime/context/runtime-core-allocator.cpp | 42 +- runtime/critical_section.cpp | 8 +- runtime/critical_section.h | 12 +- runtime/ctype.cpp | 48 +- runtime/ctype.h | 22 +- runtime/curl-async.cpp | 4 +- runtime/curl.cpp | 694 +++--- runtime/curl.h | 19 +- runtime/datetime/date_interval.cpp | 6 +- runtime/datetime/date_interval.h | 18 +- runtime/datetime/datetime.cpp | 39 +- runtime/datetime/datetime.h | 40 +- runtime/datetime/datetime_functions.cpp | 496 ++-- runtime/datetime/datetime_functions.h | 32 +- runtime/datetime/datetime_immutable.cpp | 48 +- runtime/datetime/datetime_immutable.h | 46 +- runtime/datetime/datetime_interface.h | 4 +- runtime/datetime/datetime_zone.cpp | 6 +- runtime/datetime/datetime_zone.h | 12 +- runtime/datetime/timelib_wrapper.cpp | 698 +++--- runtime/datetime/timelib_wrapper.h | 68 +- runtime/dummy-visitor-methods.h | 8 +- runtime/env.cpp | 12 +- runtime/env.h | 2 +- runtime/exception.cpp | 59 +- runtime/exception.h | 190 +- runtime/exec.cpp | 109 +- runtime/exec.h | 14 +- runtime/ffi.cpp | 29 +- runtime/ffi.h | 433 ++-- runtime/files.cpp | 332 ++- runtime/files.h | 53 +- runtime/instance-cache.cpp | 257 +-- runtime/instance-cache.h | 43 +- runtime/instance-copy-processor.cpp | 21 +- runtime/instance-copy-processor.h | 181 +- runtime/inter-process-mutex.cpp | 13 +- runtime/inter-process-mutex.h | 2 +- runtime/inter-process-resource.h | 58 +- runtime/interface.cpp | 742 +++--- runtime/interface.h | 116 +- runtime/job-workers/client-functions.cpp | 74 +- runtime/job-workers/client-functions.h | 6 +- runtime/job-workers/job-interface.cpp | 39 +- runtime/job-workers/job-interface.h | 76 +- runtime/job-workers/processing-jobs.cpp | 24 +- runtime/job-workers/processing-jobs.h | 18 +- runtime/job-workers/server-functions.cpp | 12 +- runtime/job-workers/server-functions.h | 2 +- runtime/json-functions.h | 6 +- runtime/kphp-backtrace.cpp | 46 +- runtime/kphp-backtrace.h | 23 +- runtime/kphp_ml/kml-files-reader.cpp | 114 +- runtime/kphp_ml/kml-files-reader.h | 2 +- runtime/kphp_ml/kphp_ml.cpp | 34 +- runtime/kphp_ml/kphp_ml.h | 6 +- runtime/kphp_ml/kphp_ml_catboost.cpp | 121 +- runtime/kphp_ml/kphp_ml_catboost.h | 23 +- runtime/kphp_ml/kphp_ml_init.cpp | 26 +- runtime/kphp_ml/kphp_ml_init.h | 11 +- runtime/kphp_ml/kphp_ml_interface.cpp | 46 +- runtime/kphp_ml/kphp_ml_interface.h | 16 +- runtime/kphp_ml/kphp_ml_xgboost.cpp | 138 +- runtime/kphp_ml/kphp_ml_xgboost.h | 12 +- runtime/kphp_tracing.cpp | 178 +- runtime/kphp_tracing.h | 121 +- runtime/kphp_tracing_binlog.cpp | 65 +- runtime/kphp_tracing_binlog.h | 89 +- runtime/mail.cpp | 9 +- runtime/mail.h | 2 +- runtime/math-context.cpp | 8 +- runtime/math_functions.cpp | 73 +- runtime/math_functions.h | 60 +- runtime/memcache.cpp | 221 +- runtime/memcache.h | 61 +- runtime/memory_resource_impl/dealer.cpp | 5 +- runtime/memory_resource_impl/dealer.h | 30 +- .../memory_resource_impl/heap_resource.cpp | 12 +- runtime/memory_resource_impl/heap_resource.h | 8 +- .../memory_resource_stats.cpp | 2 +- .../memory_resource_stats.h | 2 +- .../monotonic_runtime_buffer_resource.cpp | 10 +- runtime/memory_usage.cpp | 2 +- runtime/memory_usage.h | 129 +- runtime/misc.cpp | 711 +++--- runtime/misc.h | 33 +- runtime/msgpack-serialization.h | 48 +- runtime/msgpack/adaptor_base.h | 14 +- runtime/msgpack/adaptors.h | 388 ++-- runtime/msgpack/check_instance_depth.h | 12 +- runtime/msgpack/object.h | 12 +- runtime/msgpack/object_visitor.cpp | 39 +- runtime/msgpack/object_visitor.h | 24 +- runtime/msgpack/packer.cpp | 70 +- runtime/msgpack/packer.h | 41 +- runtime/msgpack/parser.cpp | 639 +++--- runtime/msgpack/parser.h | 24 +- runtime/msgpack/sysdep.h | 137 +- runtime/msgpack/unpacker.cpp | 22 +- runtime/msgpack/unpacker.h | 5 +- runtime/msgpack/zone.cpp | 30 +- runtime/msgpack/zone.h | 10 +- runtime/mysql.cpp | 279 ++- runtime/mysql.h | 16 +- runtime/net_events.cpp | 91 +- runtime/net_events.h | 10 +- runtime/null_coalesce.h | 85 +- runtime/on_kphp_warning_callback.cpp | 13 +- runtime/on_kphp_warning_callback.h | 13 +- runtime/oom_handler.cpp | 14 +- runtime/oom_handler.h | 7 +- runtime/openssl.cpp | 753 +++---- runtime/openssl.h | 55 +- runtime/pdo/abstract_pdo_driver.cpp | 4 +- runtime/pdo/abstract_pdo_driver.h | 10 +- runtime/pdo/abstract_pdo_statement.h | 4 +- runtime/pdo/mysql/mysql_pdo_driver.cpp | 55 +- runtime/pdo/mysql/mysql_pdo_driver.h | 10 +- .../mysql/mysql_pdo_emulated_statement.cpp | 48 +- .../pdo/mysql/mysql_pdo_emulated_statement.h | 6 +- runtime/pdo/pdo.cpp | 68 +- runtime/pdo/pdo.h | 23 +- runtime/pdo/pdo_statement.cpp | 6 +- runtime/pdo/pdo_statement.h | 14 +- runtime/pdo/pgsql/pgsql_pdo_driver.cpp | 40 +- runtime/pdo/pgsql/pgsql_pdo_driver.h | 10 +- .../pgsql/pgsql_pdo_emulated_statement.cpp | 40 +- .../pdo/pgsql/pgsql_pdo_emulated_statement.h | 6 +- runtime/php-script-globals.cpp | 10 +- runtime/php-script-globals.h | 18 +- runtime/php_assert.cpp | 85 +- runtime/php_assert.h | 14 +- runtime/profiler.cpp | 247 +- runtime/profiler.h | 111 +- runtime/regexp.cpp | 606 +++-- runtime/regexp.h | 294 ++- runtime/resumable.cpp | 365 ++- runtime/resumable.h | 172 +- runtime/rpc.cpp | 728 +++--- runtime/rpc.h | 119 +- runtime/rpc_extra_info.cpp | 7 +- runtime/rpc_extra_info.h | 12 +- runtime/serialize-context.cpp | 4 +- runtime/signal_safe_hashtable.h | 21 +- runtime/spl/array_iterator.cpp | 4 +- runtime/spl/array_iterator.h | 28 +- runtime/storage.cpp | 5 +- runtime/storage.h | 53 +- runtime/streams.cpp | 490 ++-- runtime/streams.h | 105 +- runtime/string-context.cpp | 8 +- runtime/string-list.h | 35 +- runtime/string_functions.cpp | 18 +- runtime/string_functions.h | 14 +- runtime/tcp.cpp | 83 +- runtime/thread-pool.cpp | 1 - runtime/thread-pool.h | 20 +- runtime/tl/rpc_function.h | 42 +- runtime/tl/rpc_request.h | 30 +- runtime/tl/rpc_response.cpp | 4 +- runtime/tl/rpc_response.h | 10 +- runtime/tl/rpc_server.cpp | 15 +- runtime/tl/rpc_server.h | 5 +- runtime/tl/rpc_tl_query.cpp | 22 +- runtime/tl/rpc_tl_query.h | 18 +- runtime/tl/tl_builtins.h | 286 +-- runtime/tl/tl_func_base.h | 4 +- runtime/tl/tl_magics_decoding.cpp | 6 +- runtime/tl/tl_magics_decoding.h | 2 +- runtime/typed_rpc.cpp | 114 +- runtime/typed_rpc.h | 51 +- runtime/uber-h3.cpp | 120 +- runtime/uber-h3.h | 16 +- runtime/udp.cpp | 60 +- runtime/url.cpp | 20 +- runtime/url.h | 25 +- runtime/vkext.cpp | 256 +-- runtime/vkext.h | 26 +- runtime/vkext_stats.cpp | 90 +- runtime/vkext_stats.h | 14 +- runtime/zlib.cpp | 161 +- runtime/zlib.h | 20 +- runtime/zstd.cpp | 37 +- runtime/zstd.h | 8 +- 396 files changed, 16484 insertions(+), 19335 deletions(-) diff --git a/.clang-format b/.clang-format index f4e0133c59..fe90ee9189 100644 --- a/.clang-format +++ b/.clang-format @@ -1,86 +1,13 @@ --- -Language: Cpp -# BasedOnStyle: LLVM -AccessModifierOffset: -2 -AlignAfterOpenBracket: Align -AlignConsecutiveAssignments: false -AlignConsecutiveDeclarations: false -AlignEscapedNewlinesLeft: false -AlignOperands: true -AlignTrailingComments: true -AllowAllParametersOfDeclarationOnNextLine: true -AllowShortBlocksOnASingleLine: false -AllowShortCaseLabelsOnASingleLine: false -AllowShortFunctionsOnASingleLine: Empty -AllowShortIfStatementsOnASingleLine: false -AllowShortLoopsOnASingleLine: false -AlwaysBreakAfterDefinitionReturnType: None -AlwaysBreakAfterReturnType: None -AlwaysBreakBeforeMultilineStrings: false -AlwaysBreakTemplateDeclarations: true -BinPackArguments: true -BinPackParameters: true -BraceWrapping: - AfterClass: false - AfterControlStatement: false - AfterEnum: true - AfterFunction: false - AfterNamespace: false - AfterObjCDeclaration: false - AfterStruct: false - AfterUnion: false - BeforeCatch: false - BeforeElse: false - IndentBraces: false -BreakBeforeBinaryOperators: NonAssignment -BreakBeforeBraces: Attach -BreakBeforeTernaryOperators: true -BreakConstructorInitializers: BeforeComma -ColumnLimit: 160 -CommentPragmas: '^ IWYU pragma:' -ConstructorInitializerAllOnOneLineOrOnePerLine: false -ConstructorInitializerIndentWidth: 2 -ContinuationIndentWidth: 2 -Cpp11BracedListStyle: true -DerivePointerAlignment: false -ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH ] -IncludeBlocks: Preserve -IncludeCategories: - - Regex: '^<' - Priority: 1 -IndentCaseLabels: true -IndentWidth: 2 -IndentWrappedFunctionNames: false -KeepEmptyLinesAtTheStartOfBlocks: true -MacroBlockBegin: '^TL_[A-Z_]+_FUN$|^REGISTER_MODULE$' -MacroBlockEnd: '^TL_[A-Z_]+_FUN_END$|^REGISTER_MODULE_END$' -MaxEmptyLinesToKeep: 1 -NamespaceIndentation: None -ObjCBlockIndentWidth: 2 -ObjCSpaceAfterProperty: false -ObjCSpaceBeforeProtocolList: true -PenaltyBreakBeforeFirstCallParameter: 1100 -PenaltyBreakComment: 300 -PenaltyBreakFirstLessLess: 120 -PenaltyBreakString: 1000 -PenaltyExcessCharacter: 1000000 -PenaltyReturnTypeOnItsOwnLine: 60 -PointerAlignment: Right -ReflowComments: true -SortIncludes: true -SpaceAfterCStyleCast: false -SpaceAfterTemplateKeyword: false -SpaceBeforeAssignmentOperators: true -SpaceBeforeParens: ControlStatements -SpaceInEmptyParentheses: false -SpacesBeforeTrailingComments: 1 -SpacesInAngles: false -SpacesInContainerLiterals: true -SpacesInCStyleCastParentheses: false -SpacesInParentheses: false -SpacesInSquareBrackets: false -Standard: c++17 -TabWidth: 2 -UseTab: Never +Language: Cpp +BasedOnStyle: LLVM +ColumnLimit: 160 +PointerAlignment: Left +ReferenceAlignment: Pointer +Standard: c++20 +UseTab: Never +AlwaysBreakTemplateDeclarations: Yes +RequiresClausePosition: OwnLine +IndentRequiresClause: No ... diff --git a/runtime-common/core/allocator/runtime-allocator.h b/runtime-common/core/allocator/runtime-allocator.h index 9ec6a13eb0..c67e6d8731 100644 --- a/runtime-common/core/allocator/runtime-allocator.h +++ b/runtime-common/core/allocator/runtime-allocator.h @@ -10,23 +10,23 @@ #include "runtime-common/core/memory-resource/unsynchronized_pool_resource.h" struct RuntimeAllocator final : vk::not_copyable { - static RuntimeAllocator &get() noexcept; + static RuntimeAllocator& get() noexcept; RuntimeAllocator() = default; RuntimeAllocator(size_t script_mem_size, size_t oom_handling_mem_size); - void init(void *buffer, size_t script_mem_size, size_t oom_handling_mem_size); + void init(void* buffer, size_t script_mem_size, size_t oom_handling_mem_size); void free(); - void *alloc_script_memory(size_t size) noexcept; - void *alloc0_script_memory(size_t size) noexcept; - void *realloc_script_memory(void *mem, size_t new_size, size_t old_size) noexcept; - void free_script_memory(void *mem, size_t size) noexcept; + void* alloc_script_memory(size_t size) noexcept; + void* alloc0_script_memory(size_t size) noexcept; + void* realloc_script_memory(void* mem, size_t new_size, size_t old_size) noexcept; + void free_script_memory(void* mem, size_t size) noexcept; - void *alloc_global_memory(size_t size) noexcept; - void *alloc0_global_memory(size_t size) noexcept; - void *realloc_global_memory(void *mem, size_t new_size, size_t old_size) noexcept; - void free_global_memory(void *mem, size_t size) noexcept; + void* alloc_global_memory(size_t size) noexcept; + void* alloc0_global_memory(size_t size) noexcept; + void* realloc_global_memory(void* mem, size_t new_size, size_t old_size) noexcept; + void free_global_memory(void* mem, size_t size) noexcept; memory_resource::unsynchronized_pool_resource memory_resource; }; diff --git a/runtime-common/core/allocator/script-allocator-managed.h b/runtime-common/core/allocator/script-allocator-managed.h index 0e34ba85b5..1304d5b427 100644 --- a/runtime-common/core/allocator/script-allocator-managed.h +++ b/runtime-common/core/allocator/script-allocator-managed.h @@ -10,21 +10,15 @@ class ScriptAllocatorManaged { public: - static void *operator new(size_t size) noexcept { - return RuntimeAllocator::get().alloc_script_memory(size); - } + static void* operator new(size_t size) noexcept { return RuntimeAllocator::get().alloc_script_memory(size); } - static void *operator new(size_t, void *ptr) noexcept { - return ptr; - } + static void* operator new(size_t, void* ptr) noexcept { return ptr; } - static void operator delete(void *ptr, size_t size) noexcept { - RuntimeAllocator::get().free_script_memory(ptr, size); - } + static void operator delete(void* ptr, size_t size) noexcept { RuntimeAllocator::get().free_script_memory(ptr, size); } - static void *operator new[](size_t count) = delete; - static void operator delete[](void *ptr, size_t sz) = delete; - static void operator delete[](void *ptr) = delete; + static void* operator new[](size_t count) = delete; + static void operator delete[](void* ptr, size_t sz) = delete; + static void operator delete[](void* ptr) = delete; protected: ~ScriptAllocatorManaged() = default; diff --git a/runtime-common/core/array_access.h b/runtime-common/core/array_access.h index ddf132f01c..faefb8cd40 100644 --- a/runtime-common/core/array_access.h +++ b/runtime-common/core/array_access.h @@ -7,7 +7,7 @@ #include "runtime-common/core/class-instance/refcountable-php-classes.h" #ifndef INCLUDED_FROM_KPHP_CORE - #error "this file must be included only from runtime-core.h" +#error "this file must be included only from runtime-core.h" #endif struct C$ArrayAccess : public may_be_mixed_base { @@ -17,8 +17,7 @@ struct C$ArrayAccess : public may_be_mixed_base { ~C$ArrayAccess() override __attribute__((always_inline)) = default; }; - -bool f$ArrayAccess$$offsetExists(class_instance const & /*v$this*/, mixed const & /*v$offset*/) noexcept; -mixed f$ArrayAccess$$offsetGet(class_instance const & /*v$this*/, mixed const & /*v$offset*/) noexcept; -void f$ArrayAccess$$offsetSet(class_instance const & /*v$this*/, mixed const & /*v$offset*/, mixed const & /*v$value*/) noexcept; -void f$ArrayAccess$$offsetUnset(class_instance const & /*v$this*/, mixed const & /*v$offset*/) noexcept; +bool f$ArrayAccess$$offsetExists(class_instance const& /*v$this*/, mixed const& /*v$offset*/) noexcept; +mixed f$ArrayAccess$$offsetGet(class_instance const& /*v$this*/, mixed const& /*v$offset*/) noexcept; +void f$ArrayAccess$$offsetSet(class_instance const& /*v$this*/, mixed const& /*v$offset*/, mixed const& /*v$value*/) noexcept; +void f$ArrayAccess$$offsetUnset(class_instance const& /*v$this*/, mixed const& /*v$offset*/) noexcept; diff --git a/runtime-common/core/class-instance/class-instance-decl.inl b/runtime-common/core/class-instance/class-instance-decl.inl index 5b3fb60b69..cc7e5ec1c1 100644 --- a/runtime-common/core/class-instance/class-instance-decl.inl +++ b/runtime-common/core/class-instance/class-instance-decl.inl @@ -3,12 +3,12 @@ #include "common/smart_ptrs/intrusive_ptr.h" #ifndef INCLUDED_FROM_KPHP_CORE - #error "this file must be included only from runtime-core.h" +#error "this file must be included only from runtime-core.h" #endif // PHP classes produce the C++ structures of the form: // -//struct C$Classes$A { +// struct C$Classes$A { // int ref_cnt; // int $a; // string $str; @@ -21,7 +21,7 @@ class abstract_refcountable_php_interface; -template +template class class_instance { vk::intrusive_ptr o; @@ -31,50 +31,44 @@ public: using ClassType = T; class_instance() = default; - class_instance(const class_instance &) = default; - class_instance(class_instance &&) noexcept = default; + class_instance(const class_instance&) = default; + class_instance(class_instance&&) noexcept = default; - class_instance(const Optional &null) noexcept { - php_assert(null.value_state() == OptionalState::null_value); - } + class_instance(const Optional& null) noexcept { php_assert(null.value_state() == OptionalState::null_value); } - template{}>> - class_instance(const class_instance &d) - : o(d.o) { - } + template {}>> + class_instance(const class_instance& d) : o(d.o) {} - template{}>> - class_instance(class_instance &&d) noexcept - : o(std::move(d.o)) { - } + template {}>> + class_instance(class_instance&& d) noexcept : o(std::move(d.o)) {} - class_instance& operator=(const class_instance &) = default; - class_instance& operator=(class_instance &&) noexcept = default; + class_instance& operator=(const class_instance&) = default; + class_instance& operator=(class_instance&&) noexcept = default; // prohibits creating a class_instance from int/char*/etc by implicit casting them to bool - template + template class_instance(T2) = delete; - template{}>> - class_instance& operator=(const class_instance &d) { + template {}>> + class_instance& operator=(const class_instance& d) { o = d.o; return *this; } - template{}>> - class_instance& operator=(class_instance &&d) noexcept { + template {}>> + class_instance& operator=(class_instance&& d) noexcept { o = std::move(d.o); return *this; } // prohibits assignment int/char*/etc to class_instance by implicit casting them to bool - template - class_instance &operator=(T2) = delete; + template + class_instance& operator=(T2) = delete; - inline class_instance &operator=(const Optional &null) noexcept; + inline class_instance& operator=(const Optional& null) noexcept; inline class_instance clone() const; - template - inline class_instance alloc(Args &&... args) __attribute__((always_inline)); + template + inline class_instance alloc(Args&&... args) __attribute__((always_inline)); inline class_instance empty_alloc() __attribute__((always_inline)); inline void destroy() { o.reset(); } int64_t get_reference_counter() const { return o ? o->get_refcnt() : 0; } @@ -83,24 +77,24 @@ public: bool is_reference_counter(ExtraRefCnt ref_cnt_value) const noexcept; void force_destroy(ExtraRefCnt expected_ref_cnt) noexcept; - template + template std::enable_if_t{}, size_t> estimate_memory_usage() const noexcept { static_assert(!std::is_empty{}, "class T may not be empty"); return sizeof(T); } - template + template std::enable_if_t{}, size_t> estimate_memory_usage() const noexcept { // TODO this is used only for job workers. Should we use this logic for other? return o->virtual_builtin_sizeof(); } - template + template std::enable_if_t{}, class_instance> virtual_builtin_clone() const noexcept { return clone(); } - template + template std::enable_if_t{}, class_instance> virtual_builtin_clone() const noexcept { // TODO this is used only for job workers. Should we use this logic for other? class_instance res; @@ -111,80 +105,78 @@ public: return res; } - template - std::enable_if_t{}, void *> get_base_raw_ptr() const noexcept { + template + std::enable_if_t{}, void*> get_base_raw_ptr() const noexcept { return get(); } - template - std::enable_if_t{}, void *> get_base_raw_ptr() const noexcept { + template + std::enable_if_t{}, void*> get_base_raw_ptr() const noexcept { // all polymorphic instances inherit abstract_refcountable_php_interface // don't inline, we need an explicit conversion to abstract_refcountable_php_interface - abstract_refcountable_php_interface *interface = get(); + abstract_refcountable_php_interface* interface = get(); return interface; } - template - static std::enable_if_t{}, class_instance> create_from_base_raw_ptr(void *raw_ptr) noexcept { + template + static std::enable_if_t{}, class_instance> create_from_base_raw_ptr(void* raw_ptr) noexcept { class_instance res; - res.o = vk::intrusive_ptr{static_cast(raw_ptr)}; + res.o = vk::intrusive_ptr{static_cast(raw_ptr)}; return res; } - template - static std::enable_if_t{}, class_instance> create_from_base_raw_ptr(void *raw_ptr) noexcept { + template + static std::enable_if_t{}, class_instance> create_from_base_raw_ptr(void* raw_ptr) noexcept { class_instance res; - auto *interface = static_cast(raw_ptr); - auto *object = dynamic_cast(interface); + auto* interface = static_cast(raw_ptr); + auto* object = dynamic_cast(interface); php_assert(object); res.o = vk::intrusive_ptr{object}; return res; } - template - static std::enable_if_t{}, class_instance> create_from_polymorphic(T *object) noexcept { + template + static std::enable_if_t{}, class_instance> create_from_polymorphic(T* object) noexcept { class_instance res; php_assert(object); res.o = vk::intrusive_ptr{object}; return res; } - inline T *operator->() __attribute__ ((always_inline)); - inline T *operator->() const __attribute__ ((always_inline)); + inline T* operator->() __attribute__((always_inline)); + inline T* operator->() const __attribute__((always_inline)); - inline T *get() const __attribute__ ((always_inline)); + inline T* get() const __attribute__((always_inline)); bool is_null() const { return !static_cast(o); } - const char *get_class() const { return o ? o->get_class() : "null"; } + const char* get_class() const { return o ? o->get_class() : "null"; } int64_t get_hash() const { return o ? o->get_hash() : 0; } - template + template bool is_a() const { return is_a_helper(); } - template{}, D>, class dummy = void> + template {}, D>, class dummy = void> bool is_a_helper() const { - return dynamic_cast(o.get()); + return dynamic_cast(o.get()); } - template{}, D>> + template {}, D>> bool is_a_helper() const { return o && std::is_same{}; } - template + template class_instance cast_to() const { class_instance res; res.o = vk::dynamic_pointer_cast(o); return res; } - inline bool operator==(const class_instance &rhs) const { - return o == rhs.o; - } + inline bool operator==(const class_instance& rhs) const { return o == rhs.o; } - template + template friend class class_instance; private: @@ -192,8 +184,8 @@ private: class_instance clone_impl(std::false_type /*is empty*/) const; }; -template -class_instance make_instance(Args &&...args) noexcept { +template +class_instance make_instance(Args&&... args) noexcept { class_instance instance; instance.alloc(std::forward(args)...); return instance; diff --git a/runtime-common/core/class-instance/class-instance.inl b/runtime-common/core/class-instance/class-instance.inl index 02d8bf3a32..b8c428ceec 100644 --- a/runtime-common/core/class-instance/class-instance.inl +++ b/runtime-common/core/class-instance/class-instance.inl @@ -1,22 +1,22 @@ #pragma once #ifndef INCLUDED_FROM_KPHP_CORE - #error "this file must be included only from runtime-core.h" +#error "this file must be included only from runtime-core.h" #endif -template -class_instance &class_instance::operator=(const Optional &null) noexcept { +template +class_instance& class_instance::operator=(const Optional& null) noexcept { php_assert(null.value_state() == OptionalState::null_value); o.reset(); return *this; } -template +template class_instance class_instance::clone_impl(std::true_type /*is empty*/) const { return class_instance{}.empty_alloc(); } -template +template class_instance class_instance::clone_impl(std::false_type /*is empty*/) const { class_instance res; if (o) { @@ -26,21 +26,21 @@ class_instance class_instance::clone_impl(std::false_type /*is empty*/) co return res; } -template +template class_instance class_instance::clone() const { return clone_impl(std::is_empty{}); } -template -template -class_instance class_instance::alloc(Args &&... args) { +template +template +class_instance class_instance::alloc(Args&&... args) { static_assert(!std::is_empty{}, "class T may not be empty"); php_assert(!o); new (&o) vk::intrusive_ptr(new T{std::forward(args)...}); return *this; } -template +template inline class_instance class_instance::empty_alloc() { static_assert(std::is_empty{}, "class T must be empty"); uint32_t obj = ++RuntimeContext::get().empty_obj_count; @@ -48,8 +48,8 @@ inline class_instance class_instance::empty_alloc() { return *this; } -template -T *class_instance::operator->() { +template +T* class_instance::operator->() { if (unlikely(!o)) { warn_on_access_null(); } @@ -57,8 +57,8 @@ T *class_instance::operator->() { return get(); }; -template -T *class_instance::operator->() const { +template +T* class_instance::operator->() const { if (unlikely(!o)) { warn_on_access_null(); } @@ -66,30 +66,30 @@ T *class_instance::operator->() const { return get(); }; -template -T *class_instance::get() const { +template +T* class_instance::get() const { static_assert(!std::is_empty{}, "class T may not be empty"); return o.get(); } -template +template void class_instance::warn_on_access_null() const { php_warning("Trying to access property of null object"); - const_cast *>(this)->alloc(); + const_cast*>(this)->alloc(); } -template +template void class_instance::set_reference_counter_to(ExtraRefCnt ref_cnt_value) noexcept { php_assert(o->get_refcnt() == 1); o->set_refcnt(static_cast(static_cast(ref_cnt_value))); } -template +template bool class_instance::is_reference_counter(ExtraRefCnt ref_cnt_value) const noexcept { return static_cast(o->get_refcnt()) == ref_cnt_value; } -template +template void class_instance::force_destroy(ExtraRefCnt expected_ref_cnt) noexcept { if (o) { php_assert(static_cast(o->get_refcnt()) == expected_ref_cnt); diff --git a/runtime-common/core/class-instance/refcountable-php-classes.h b/runtime-common/core/class-instance/refcountable-php-classes.h index 3d919255ac..485e62d177 100644 --- a/runtime-common/core/class-instance/refcountable-php-classes.h +++ b/runtime-common/core/class-instance/refcountable-php-classes.h @@ -18,10 +18,10 @@ class abstract_refcountable_php_interface : public ScriptAllocatorManaged { virtual uint32_t get_refcnt() const noexcept = 0; virtual void set_refcnt(uint32_t new_refcnt) noexcept = 0; - virtual void *get_instance_data_raw_ptr() noexcept = 0; + virtual void* get_instance_data_raw_ptr() noexcept = 0; }; -template +template class refcountable_polymorphic_php_classes : public Bases... { public: void add_ref() noexcept final { @@ -30,9 +30,7 @@ class refcountable_polymorphic_php_classes : public Bases... { } } - uint32_t get_refcnt() const noexcept final { - return refcnt; - } + uint32_t get_refcnt() const noexcept final { return refcnt; } void release() noexcept final __attribute__((always_inline)) { if (refcnt < ExtraRefCnt::for_global_const) { @@ -43,25 +41,21 @@ class refcountable_polymorphic_php_classes : public Bases... { } } - void set_refcnt(uint32_t new_refcnt) noexcept final { - refcnt = new_refcnt; - } + void set_refcnt(uint32_t new_refcnt) noexcept final { refcnt = new_refcnt; } - void *get_instance_data_raw_ptr() noexcept final { - return this; - } + void* get_instance_data_raw_ptr() noexcept final { return this; } private: uint32_t refcnt{0}; }; -template +template class refcountable_polymorphic_php_classes_virt : public virtual abstract_refcountable_php_interface, public Interfaces... { public: refcountable_polymorphic_php_classes_virt() __attribute__((always_inline)) = default; }; -template<> +template <> class refcountable_polymorphic_php_classes_virt<> : public virtual abstract_refcountable_php_interface { public: refcountable_polymorphic_php_classes_virt() __attribute__((always_inline)) = default; @@ -72,9 +66,7 @@ class refcountable_polymorphic_php_classes_virt<> : public virtual abstract_refc } } - uint32_t get_refcnt() const noexcept final { - return refcnt; - } + uint32_t get_refcnt() const noexcept final { return refcnt; } void release() noexcept final __attribute__((always_inline)) { if (refcnt < ExtraRefCnt::for_global_const) { @@ -85,19 +77,15 @@ class refcountable_polymorphic_php_classes_virt<> : public virtual abstract_refc } } - void set_refcnt(uint32_t new_refcnt) noexcept final { - refcnt = new_refcnt; - } + void set_refcnt(uint32_t new_refcnt) noexcept final { refcnt = new_refcnt; } - void *get_instance_data_raw_ptr() noexcept final { - return this; - } + void* get_instance_data_raw_ptr() noexcept final { return this; } private: uint32_t refcnt{0}; }; -template +template class refcountable_php_classes : public ScriptAllocatorManaged { public: void add_ref() noexcept { @@ -106,9 +94,7 @@ class refcountable_php_classes : public ScriptAllocatorManaged { } } - uint32_t get_refcnt() const noexcept { - return refcnt; - } + uint32_t get_refcnt() const noexcept { return refcnt; } void release() noexcept __attribute__((always_inline)) { if (refcnt < ExtraRefCnt::for_global_const) { @@ -122,17 +108,13 @@ class refcountable_php_classes : public ScriptAllocatorManaged { * we should have vptr for passing proper sizeof of Derived class, but we don't want to increase size of every class * therefore we use static_cast here */ - delete static_cast(this); + delete static_cast(this); } } - void set_refcnt(uint32_t new_refcnt) noexcept { - refcnt = new_refcnt; - } + void set_refcnt(uint32_t new_refcnt) noexcept { refcnt = new_refcnt; } - void *get_instance_data_raw_ptr() noexcept { - return this; - } + void* get_instance_data_raw_ptr() noexcept { return this; } private: uint32_t refcnt{0}; @@ -146,5 +128,5 @@ class refcountable_empty_php_classes { struct may_be_mixed_base : public virtual abstract_refcountable_php_interface { ~may_be_mixed_base() override = default; - virtual const char *get_class() const noexcept = 0; + virtual const char* get_class() const noexcept = 0; }; diff --git a/runtime-common/core/core-context.h b/runtime-common/core/core-context.h index 55dca24249..30137813fd 100644 --- a/runtime-common/core/core-context.h +++ b/runtime-common/core/core-context.h @@ -25,5 +25,5 @@ struct RuntimeContext final : vk::not_copyable { void init() noexcept; void free() noexcept; - static RuntimeContext &get() noexcept; + static RuntimeContext& get() noexcept; }; diff --git a/runtime-common/core/core-types/comparison_operators.inl b/runtime-common/core/core-types/comparison_operators.inl index ba5f748646..2bb8b66107 100644 --- a/runtime-common/core/core-types/comparison_operators.inl +++ b/runtime-common/core/core-types/comparison_operators.inl @@ -3,49 +3,40 @@ #include "runtime-common/core/utils/migration-php8.h" #ifndef INCLUDED_FROM_KPHP_CORE - #error "this file must be included only from runtime-core.h" +#error "this file must be included only from runtime-core.h" #endif namespace impl_ { -template -inline bool optional_eq2_impl(const Optional &lhs, const T2 &rhs); -template -inline bool optional_equals_impl(const Optional &lhs, const T2 &rhs); +template +inline bool optional_eq2_impl(const Optional& lhs, const T2& rhs); +template +inline bool optional_equals_impl(const Optional& lhs, const T2& rhs); -template -inline bool optional_lt_impl(const Optional &lhs, const T2 &rhs); -template -inline enable_if_t_is_not_optional optional_lt_impl(const T1 &lhs, const Optional &rhs); +template +inline bool optional_lt_impl(const Optional& lhs, const T2& rhs); +template +inline enable_if_t_is_not_optional optional_lt_impl(const T1& lhs, const Optional& rhs); } // namespace impl_ -template -inline decltype(auto) call_fun_on_optional_value(FunT && fun, const Optional &opt, Args &&... args); -template -inline decltype(auto) call_fun_on_optional_value(FunT && fun, Optional &&opt, Args &&... args); +template +inline decltype(auto) call_fun_on_optional_value(FunT&& fun, const Optional& opt, Args&&... args); +template +inline decltype(auto) call_fun_on_optional_value(FunT&& fun, Optional&& opt, Args&&... args); - -template -inline enable_if_one_of_types_is_unknown eq2(const T &, const U &) { - php_assert ("Comparison of Unknown" && 0); +template +inline enable_if_one_of_types_is_unknown eq2(const T&, const U&) { + php_assert("Comparison of Unknown" && 0); return false; } -inline bool eq2(bool lhs, bool rhs) { - return lhs == rhs; -} -inline bool eq2(int64_t lhs, int64_t rhs) { - return lhs == rhs; -} -inline bool eq2(double lhs, double rhs) { - return lhs == rhs; -} -inline bool eq2(const string &lhs, const string &rhs) { - return compare_strings_php_order(lhs, rhs) == 0; -} +inline bool eq2(bool lhs, bool rhs) { return lhs == rhs; } +inline bool eq2(int64_t lhs, int64_t rhs) { return lhs == rhs; } +inline bool eq2(double lhs, double rhs) { return lhs == rhs; } +inline bool eq2(const string& lhs, const string& rhs) { return compare_strings_php_order(lhs, rhs) == 0; } -inline bool eq2(const mixed &lhs, const mixed &rhs) { +inline bool eq2(const mixed& lhs, const mixed& rhs) { if (lhs.is_object() || rhs.is_object()) { php_warning("operators ==, != are not supported for %s and %s", lhs.get_type_or_class_name(), rhs.get_type_or_class_name()); return false; @@ -53,37 +44,21 @@ inline bool eq2(const mixed &lhs, const mixed &rhs) { return lhs.compare(rhs) == 0; } -inline bool eq2(bool lhs, int64_t rhs) { - return lhs != !rhs; -} -inline bool eq2(int64_t lhs, bool rhs) { - return eq2(rhs, lhs); -} +inline bool eq2(bool lhs, int64_t rhs) { return lhs != !rhs; } +inline bool eq2(int64_t lhs, bool rhs) { return eq2(rhs, lhs); } -inline bool eq2(bool lhs, double rhs) { - return lhs != (rhs == 0.0); -} -inline bool eq2(double lhs, bool rhs) { - return eq2(rhs, lhs); -} +inline bool eq2(bool lhs, double rhs) { return lhs != (rhs == 0.0); } +inline bool eq2(double lhs, bool rhs) { return eq2(rhs, lhs); } -inline bool eq2(int64_t lhs, double rhs) { - return static_cast(lhs) == rhs; -} -inline bool eq2(double lhs, int64_t rhs) { - return eq2(rhs, lhs); -} +inline bool eq2(int64_t lhs, double rhs) { return static_cast(lhs) == rhs; } +inline bool eq2(double lhs, int64_t rhs) { return eq2(rhs, lhs); } -inline bool eq2(bool lhs, const string &rhs) { - return lhs == rhs.to_bool(); -} -inline bool eq2(const string &lhs, bool rhs) { - return eq2(rhs, lhs); -} +inline bool eq2(bool lhs, const string& rhs) { return lhs == rhs.to_bool(); } +inline bool eq2(const string& lhs, bool rhs) { return eq2(rhs, lhs); } // see https://www.php.net/manual/en/migration80.incompatible.php#migration80.incompatible.core.string-number-comparision template -inline bool eq2_number_string_as_php8(T lhs, const string &rhs) { +inline bool eq2_number_string_as_php8(T lhs, const string& rhs) { auto rhs_float = 0.0; const auto rhs_is_string_number = rhs.try_to_float(&rhs_float); @@ -94,7 +69,7 @@ inline bool eq2_number_string_as_php8(T lhs, const string &rhs) { } } -inline bool eq2(int64_t lhs, const string &rhs) { +inline bool eq2(int64_t lhs, const string& rhs) { const auto php7_result = eq2(lhs, rhs.to_float()); if (RuntimeContext::get().show_migration_php8_warning & MIGRATION_PHP8_STRING_COMPARISON_FLAG) { const auto php8_result = eq2_number_string_as_php8(lhs, rhs); @@ -102,20 +77,15 @@ inline bool eq2(int64_t lhs, const string &rhs) { return php7_result; } - php_warning("Comparison (operator ==) results in PHP 7 and PHP 8 are different for %" PRIi64 " and \"%s\" (PHP7: %s, PHP8: %s)", - lhs, - rhs.c_str(), - php7_result ? "true" : "false", - php8_result ? "true" : "false"); + php_warning("Comparison (operator ==) results in PHP 7 and PHP 8 are different for %" PRIi64 " and \"%s\" (PHP7: %s, PHP8: %s)", lhs, rhs.c_str(), + php7_result ? "true" : "false", php8_result ? "true" : "false"); } return php7_result; } -inline bool eq2(const string &lhs, int64_t rhs) { - return eq2(rhs, lhs); -} +inline bool eq2(const string& lhs, int64_t rhs) { return eq2(rhs, lhs); } -inline bool eq2(double lhs, const string &rhs) { +inline bool eq2(double lhs, const string& rhs) { const auto php7_result = lhs == rhs.to_float(); if (RuntimeContext::get().show_migration_php8_warning & MIGRATION_PHP8_STRING_COMPARISON_FLAG) { const auto php8_result = eq2_number_string_as_php8(lhs, rhs); @@ -123,189 +93,172 @@ inline bool eq2(double lhs, const string &rhs) { return php7_result; } - php_warning("Comparison (operator ==) results in PHP 7 and PHP 8 are different for %lf and \"%s\" (PHP7: %s, PHP8: %s)", - lhs, - rhs.c_str(), - php7_result ? "true" : "false", - php8_result ? "true" : "false"); + php_warning("Comparison (operator ==) results in PHP 7 and PHP 8 are different for %lf and \"%s\" (PHP7: %s, PHP8: %s)", lhs, rhs.c_str(), + php7_result ? "true" : "false", php8_result ? "true" : "false"); } return php7_result; } -inline bool eq2(const string &lhs, double rhs) { - return eq2(rhs, lhs); -} +inline bool eq2(const string& lhs, double rhs) { return eq2(rhs, lhs); } -template -inline bool eq2(bool lhs, const array &rhs) { +template +inline bool eq2(bool lhs, const array& rhs) { return lhs == !rhs.empty(); } -template -inline bool eq2(const array &lhs, bool rhs) { +template +inline bool eq2(const array& lhs, bool rhs) { return eq2(rhs, lhs); } -template -inline bool eq2(int64_t, const array &) { +template +inline bool eq2(int64_t, const array&) { php_warning("Unsupported operand types for operator == (int and array)"); return false; } -template -inline bool eq2(const array &lhs, int64_t rhs) { +template +inline bool eq2(const array& lhs, int64_t rhs) { return eq2(rhs, lhs); } -template -inline bool eq2(double, const array &) { +template +inline bool eq2(double, const array&) { php_warning("Unsupported operand types for operator == (float and array)"); return false; } -template -inline bool eq2(const array &lhs, double rhs) { +template +inline bool eq2(const array& lhs, double rhs) { return eq2(rhs, lhs); } -template -inline bool eq2(const string &, const array &) { +template +inline bool eq2(const string&, const array&) { php_warning("Unsupported operand types for operator == (string and array)"); return false; } -template -inline bool eq2(const array &lhs, const string &rhs) { +template +inline bool eq2(const array& lhs, const string& rhs) { return eq2(rhs, lhs); } -template -inline bool eq2(const TupleLhsT &lhs, const TupleRhsT &rhs, std::index_sequence) { +template +inline bool eq2(const TupleLhsT& lhs, const TupleRhsT& rhs, std::index_sequence) { return vk::all_of_equal(true, eq2(std::get(lhs), std::get(rhs))...); } -template -inline bool eq2(const std::tuple &lhs, const std::tuple &rhs) { +template +inline bool eq2(const std::tuple& lhs, const std::tuple& rhs) { return eq2(lhs, rhs, std::make_index_sequence{}); } -template -inline std::enable_if_t eq2(const std::tuple &lhs, const std::tuple &rhs) { +template +inline std::enable_if_t eq2(const std::tuple& lhs, const std::tuple& rhs) { return eq2(lhs, rhs, std::make_index_sequence{}); } -template -inline std::enable_if_t eq2(const std::tuple &, const std::tuple &) { +template +inline std::enable_if_t eq2(const std::tuple&, const std::tuple&) { return false; } -template -inline bool eq2(const TupleT &lhs, const array &rhs, std::index_sequence) { +template +inline bool eq2(const TupleT& lhs, const array& rhs, std::index_sequence) { return vk::all_of_equal(true, eq2(std::get(lhs), rhs.get_value(Indices))...); } -template -inline bool eq2(const std::tuple &lhs, const array &rhs) { +template +inline bool eq2(const std::tuple& lhs, const array& rhs) { if (!rhs.is_vector() || sizeof...(Args) != rhs.size().size) { return false; } return eq2(lhs, rhs, std::make_index_sequence{}); } -template -inline bool eq2(const array &lhs, const std::tuple &rhs) { +template +inline bool eq2(const array& lhs, const std::tuple& rhs) { return eq2(rhs, lhs); } -template -inline bool eq2(bool lhs, const std::tuple &) { +template +inline bool eq2(bool lhs, const std::tuple&) { return lhs; } -template -inline bool eq2(const std::tuple &lhs, bool rhs) { +template +inline bool eq2(const std::tuple& lhs, bool rhs) { return eq2(rhs, lhs); } -template -inline bool eq2(const T &, const std::tuple &) { +template +inline bool eq2(const T&, const std::tuple&) { return false; } -template -inline bool eq2(const std::tuple &lhs, const T &rhs) { +template +inline bool eq2(const std::tuple& lhs, const T& rhs) { return eq2(rhs, lhs); } -template -inline bool eq2(const class_instance &lhs, const class_instance &rhs) { +template +inline bool eq2(const class_instance& lhs, const class_instance& rhs) { // can be called implicitly from in_array, for example return lhs == rhs; } -inline bool eq2(bool lhs, const mixed &rhs) { - return lhs == rhs.to_bool(); -} -inline bool eq2(const mixed &lhs, bool rhs) { - return eq2(rhs, lhs); -} +inline bool eq2(bool lhs, const mixed& rhs) { return lhs == rhs.to_bool(); } +inline bool eq2(const mixed& lhs, bool rhs) { return eq2(rhs, lhs); } -inline bool eq2(double lhs, const mixed &rhs) { +inline bool eq2(double lhs, const mixed& rhs) { switch (rhs.get_type()) { - case mixed::type::NUL: - return eq2(lhs, 0.0); - case mixed::type::BOOLEAN: - return eq2(lhs, rhs.as_bool()); - case mixed::type::INTEGER: - return eq2(lhs, rhs.as_int()); - case mixed::type::FLOAT: - return eq2(lhs, rhs.as_double()); - case mixed::type::STRING: - return eq2(lhs, rhs.as_string()); - case mixed::type::ARRAY: - php_warning("Unsupported operand types for operator == (float and array)"); - return false; - case mixed::type::OBJECT: - php_warning("Unsupported operand types for operator == (float and %s)", rhs.as_object()->get_class()); - return false; - default: - __builtin_unreachable(); + case mixed::type::NUL: + return eq2(lhs, 0.0); + case mixed::type::BOOLEAN: + return eq2(lhs, rhs.as_bool()); + case mixed::type::INTEGER: + return eq2(lhs, rhs.as_int()); + case mixed::type::FLOAT: + return eq2(lhs, rhs.as_double()); + case mixed::type::STRING: + return eq2(lhs, rhs.as_string()); + case mixed::type::ARRAY: + php_warning("Unsupported operand types for operator == (float and array)"); + return false; + case mixed::type::OBJECT: + php_warning("Unsupported operand types for operator == (float and %s)", rhs.as_object()->get_class()); + return false; + default: + __builtin_unreachable(); } } -inline bool eq2(const mixed &lhs, double rhs) { - return eq2(rhs, lhs); -} +inline bool eq2(const mixed& lhs, double rhs) { return eq2(rhs, lhs); } -inline bool eq2(int64_t lhs, const mixed &rhs) { +inline bool eq2(int64_t lhs, const mixed& rhs) { switch (rhs.get_type()) { - case mixed::type::NUL: - return eq2(lhs, int64_t{0}); - case mixed::type::BOOLEAN: - return eq2(lhs, rhs.as_bool()); - case mixed::type::INTEGER: - return eq2(lhs, rhs.as_int()); - case mixed::type::FLOAT: - return eq2(lhs, rhs.as_double()); - case mixed::type::STRING: - return eq2(lhs, rhs.as_string()); - case mixed::type::ARRAY: - php_warning("Unsupported operand types for operator == (int and array)"); - return false; - case mixed::type::OBJECT: - php_warning("Unsupported operand types for operator == (int and %s)", rhs.as_object()->get_class()); - return false; - default: - __builtin_unreachable(); + case mixed::type::NUL: + return eq2(lhs, int64_t{0}); + case mixed::type::BOOLEAN: + return eq2(lhs, rhs.as_bool()); + case mixed::type::INTEGER: + return eq2(lhs, rhs.as_int()); + case mixed::type::FLOAT: + return eq2(lhs, rhs.as_double()); + case mixed::type::STRING: + return eq2(lhs, rhs.as_string()); + case mixed::type::ARRAY: + php_warning("Unsupported operand types for operator == (int and array)"); + return false; + case mixed::type::OBJECT: + php_warning("Unsupported operand types for operator == (int and %s)", rhs.as_object()->get_class()); + return false; + default: + __builtin_unreachable(); } } -inline bool eq2(const mixed &lhs, int64_t rhs) { - return eq2(rhs, lhs); -} +inline bool eq2(const mixed& lhs, int64_t rhs) { return eq2(rhs, lhs); } -inline bool eq2(const string &lhs, const mixed &rhs) { - return eq2(mixed(lhs), rhs); -} -inline bool eq2(const mixed &lhs, const string &rhs) { - return eq2(rhs, lhs); -} +inline bool eq2(const string& lhs, const mixed& rhs) { return eq2(mixed(lhs), rhs); } +inline bool eq2(const mixed& lhs, const string& rhs) { return eq2(rhs, lhs); } -template -inline bool eq2(const array &lhs, const mixed &rhs) { - if (likely (rhs.is_array())) { +template +inline bool eq2(const array& lhs, const mixed& rhs) { + if (likely(rhs.is_array())) { return eq2(lhs, rhs.as_array()); } @@ -319,32 +272,32 @@ inline bool eq2(const array &lhs, const mixed &rhs) { php_warning("Unsupported operand types for operator == (array and %s)", rhs.get_type_c_str()); return false; } -template -inline bool eq2(const mixed &lhs, const array &rhs) { +template +inline bool eq2(const mixed& lhs, const array& rhs) { return eq2(rhs, lhs); } -template -inline bool eq2(const Optional &lhs, const T2 &rhs) { +template +inline bool eq2(const Optional& lhs, const T2& rhs) { return impl_::optional_eq2_impl(lhs, rhs); } -template -inline bool eq2(const T1 &lhs, const Optional &rhs) { +template +inline bool eq2(const T1& lhs, const Optional& rhs) { return eq2(rhs, lhs); } -template -inline bool eq2(const Optional &lhs, const Optional &rhs) { +template +inline bool eq2(const Optional& lhs, const Optional& rhs) { return impl_::optional_eq2_impl(lhs, rhs); } -template -inline bool eq2(const Optional &lhs, const Optional &rhs) { +template +inline bool eq2(const Optional& lhs, const Optional& rhs) { return impl_::optional_eq2_impl(lhs, rhs); } -template -inline bool eq2(const array &lhs, const array &rhs) { +template +inline bool eq2(const array& lhs, const array& rhs) { if (rhs.count() != lhs.count()) { return false; } @@ -359,38 +312,37 @@ inline bool eq2(const array &lhs, const array &rhs) { return true; } -template -inline bool eq2(const T &lhs, int32_t rhs); +template +inline bool eq2(const T& lhs, int32_t rhs); -template -inline bool eq2(int32_t lhs, const T &rhs); +template +inline bool eq2(int32_t lhs, const T& rhs); -template -inline bool eq2(const T &lhs, int32_t rhs) { +template +inline bool eq2(const T& lhs, int32_t rhs) { return eq2(lhs, int64_t{rhs}); } -template -inline bool eq2(int32_t lhs, const T &rhs) { +template +inline bool eq2(int32_t lhs, const T& rhs) { return eq2(int64_t{lhs}, rhs); } -template -inline enable_if_one_of_types_is_unknown equals(const T &lhs, const U &rhs) { +template +inline enable_if_one_of_types_is_unknown equals(const T& lhs, const U& rhs) { return eq2(lhs, rhs); } -template -inline disable_if_one_of_types_is_unknown equals(const T &, const U &) { +template +inline disable_if_one_of_types_is_unknown equals(const T&, const U&) { return false; } -template -inline disable_if_one_of_types_is_unknown equals(const T &lhs, const T &rhs) { +template +inline disable_if_one_of_types_is_unknown equals(const T& lhs, const T& rhs) { return lhs == rhs; } - -template -inline bool equals(const array &lhs, const array &rhs) { +template +inline bool equals(const array& lhs, const array& rhs) { if (lhs.count() != rhs.count()) { return false; } @@ -403,8 +355,8 @@ inline bool equals(const array &lhs, const array &rhs) { return true; } -template -inline bool equals(const array &lhs, const array &rhs) { +template +inline bool equals(const array& lhs, const array& rhs) { if (lhs.count() != rhs.count()) { return false; } @@ -419,201 +371,179 @@ inline bool equals(const array &lhs, const array &rhs) { return true; } -inline bool equals(const may_be_mixed_base *lhs, const may_be_mixed_base* rhs) { - return lhs == rhs; -} +inline bool equals(const may_be_mixed_base* lhs, const may_be_mixed_base* rhs) { return lhs == rhs; } -inline bool equals(bool lhs, const mixed &rhs) { - return rhs.is_bool() && equals(lhs, rhs.as_bool()); -} -inline bool equals(const mixed &lhs, bool rhs) { - return equals(rhs, lhs); -} +inline bool equals(bool lhs, const mixed& rhs) { return rhs.is_bool() && equals(lhs, rhs.as_bool()); } +inline bool equals(const mixed& lhs, bool rhs) { return equals(rhs, lhs); } -inline bool equals(int64_t lhs, const mixed &rhs) { - return rhs.is_int() && equals(lhs, rhs.as_int()); -} -inline bool equals(const mixed &lhs, int64_t rhs) { - return equals(rhs, lhs); -} +inline bool equals(int64_t lhs, const mixed& rhs) { return rhs.is_int() && equals(lhs, rhs.as_int()); } +inline bool equals(const mixed& lhs, int64_t rhs) { return equals(rhs, lhs); } -inline bool equals(double lhs, const mixed &rhs) { - return rhs.is_float() && equals(lhs, rhs.as_double()); -} -inline bool equals(const mixed &lhs, double rhs) { - return equals(rhs, lhs); -} +inline bool equals(double lhs, const mixed& rhs) { return rhs.is_float() && equals(lhs, rhs.as_double()); } +inline bool equals(const mixed& lhs, double rhs) { return equals(rhs, lhs); } -inline bool equals(const string &lhs, const mixed &rhs) { - return rhs.is_string() && equals(lhs, rhs.as_string()); -} -inline bool equals(const mixed &lhs, const string &rhs) { - return equals(rhs, lhs); -} +inline bool equals(const string& lhs, const mixed& rhs) { return rhs.is_string() && equals(lhs, rhs.as_string()); } +inline bool equals(const mixed& lhs, const string& rhs) { return equals(rhs, lhs); } -template -inline bool equals(const array &lhs, const mixed &rhs) { +template +inline bool equals(const array& lhs, const mixed& rhs) { return rhs.is_array() && equals(lhs, rhs.as_array()); } -template -inline bool equals(const mixed &lhs, const array &rhs) { +template +inline bool equals(const mixed& lhs, const array& rhs) { return equals(rhs, lhs); } -inline bool equals(const mixed &lhs, const mixed &rhs) { +inline bool equals(const mixed& lhs, const mixed& rhs) { if (lhs.get_type() != rhs.get_type()) { return false; } switch (lhs.get_type()) { - case mixed::type::NUL: - return true; - case mixed::type::BOOLEAN: - return equals(lhs.as_bool(), rhs.as_bool()); - case mixed::type::INTEGER: - return equals(lhs.as_int(), rhs.as_int()); - case mixed::type::FLOAT: - return equals(lhs.as_double(), rhs.as_double()); - case mixed::type::STRING: - return equals(lhs.as_string(), rhs.as_string()); - case mixed::type::ARRAY: - return equals(lhs.as_array(), rhs.as_array()); - case mixed::type::OBJECT: - return equals(lhs.as_object(), rhs.as_object()); - default: - __builtin_unreachable(); + case mixed::type::NUL: + return true; + case mixed::type::BOOLEAN: + return equals(lhs.as_bool(), rhs.as_bool()); + case mixed::type::INTEGER: + return equals(lhs.as_int(), rhs.as_int()); + case mixed::type::FLOAT: + return equals(lhs.as_double(), rhs.as_double()); + case mixed::type::STRING: + return equals(lhs.as_string(), rhs.as_string()); + case mixed::type::ARRAY: + return equals(lhs.as_array(), rhs.as_array()); + case mixed::type::OBJECT: + return equals(lhs.as_object(), rhs.as_object()); + default: + __builtin_unreachable(); } } -template -inline bool equals(const class_instance &lhs, const class_instance &rhs) { +template +inline bool equals(const class_instance& lhs, const class_instance& rhs) { return lhs == rhs; } -template -inline bool equals(const TupleLhsT &lhs, const TupleRhsT &rhs, std::index_sequence) { +template +inline bool equals(const TupleLhsT& lhs, const TupleRhsT& rhs, std::index_sequence) { return vk::all_of_equal(true, equals(std::get(lhs), std::get(rhs))...); } -template -inline bool equals(const std::tuple &lhs, const std::tuple &rhs) { +template +inline bool equals(const std::tuple& lhs, const std::tuple& rhs) { return equals(lhs, rhs, std::make_index_sequence{}); } -template -inline bool equals(const std::tuple &lhs, const std::tuple &rhs) { - return sizeof...(Args) == sizeof...(Args2) && - equals(lhs, rhs, std::make_index_sequence{}); +template +inline bool equals(const std::tuple& lhs, const std::tuple& rhs) { + return sizeof...(Args) == sizeof...(Args2) && equals(lhs, rhs, std::make_index_sequence{}); } -template -inline bool equals(const TupleT &lhs, const array &rhs, std::index_sequence) { +template +inline bool equals(const TupleT& lhs, const array& rhs, std::index_sequence) { return vk::all_of_equal(true, equals(std::get(lhs), rhs.get_value(Indices))...); } -template -inline bool equals(const std::tuple &lhs, const array &rhs) { +template +inline bool equals(const std::tuple& lhs, const array& rhs) { if (!rhs.is_vector() || sizeof...(Args) != rhs.size().size) { return false; } return equals(lhs, rhs, std::make_index_sequence{}); } -template -inline bool equals(const array &lhs, const std::tuple &rhs) { +template +inline bool equals(const array& lhs, const std::tuple& rhs) { return equals(rhs, lhs); } -template -inline std::enable_if_t{} || std::is_base_of{}, bool> equals(const class_instance &lhs, const class_instance &rhs) { - return dynamic_cast(lhs.get()) == dynamic_cast(rhs.get()); +template +inline std::enable_if_t{} || std::is_base_of{}, bool> equals(const class_instance& lhs, const class_instance& rhs) { + return dynamic_cast(lhs.get()) == dynamic_cast(rhs.get()); } -template -inline std::enable_if_t{} && !std::is_base_of{}, bool> equals(const class_instance &, const class_instance &) { +template +inline std::enable_if_t{} && !std::is_base_of{}, bool> equals(const class_instance&, const class_instance&) { return false; } - -template -inline bool equals(const Optional &lhs, const T2 &rhs) { +template +inline bool equals(const Optional& lhs, const T2& rhs) { return impl_::optional_equals_impl(lhs, rhs); } -template -inline bool equals(const T1 &lhs, const Optional &rhs) { +template +inline bool equals(const T1& lhs, const Optional& rhs) { return equals(rhs, lhs); } -template -inline bool equals(const Optional &lhs, const Optional &rhs) { +template +inline bool equals(const Optional& lhs, const Optional& rhs) { return impl_::optional_equals_impl(lhs, rhs); } -template -inline bool equals(const Optional &lhs, const Optional &rhs) { +template +inline bool equals(const Optional& lhs, const Optional& rhs) { return impl_::optional_equals_impl(lhs, rhs); } -template -inline bool equals(const T &lhs, int32_t rhs); +template +inline bool equals(const T& lhs, int32_t rhs); -template -inline bool equals(int32_t lhs, const T &rhs); +template +inline bool equals(int32_t lhs, const T& rhs); -template -inline bool equals(const T &lhs, int32_t rhs) { +template +inline bool equals(const T& lhs, int32_t rhs) { return equals(lhs, int64_t{rhs}); } -template -inline bool equals(int32_t lhs, const T &rhs) { +template +inline bool equals(int32_t lhs, const T& rhs) { return equals(int64_t{lhs}, rhs); } -inline bool lt(const bool &lhs, const bool &rhs) { - return lhs < rhs; -} -template -inline bool lt(const T1 &lhs, const T2 &rhs) { +inline bool lt(const bool& lhs, const bool& rhs) { return lhs < rhs; } +template +inline bool lt(const T1& lhs, const T2& rhs) { return lhs < rhs; } -template -inline bool lt(const bool &lhs, const T2 &rhs) { +template +inline bool lt(const bool& lhs, const T2& rhs) { return lhs < f$boolval(rhs); } -template -inline bool lt(const T1 &lhs, const bool &rhs) { +template +inline bool lt(const T1& lhs, const bool& rhs) { return f$boolval(lhs) < rhs; } -template -inline bool lt(const Optional &lhs, const T2 &rhs) { +template +inline bool lt(const Optional& lhs, const T2& rhs) { return impl_::optional_lt_impl(lhs, rhs); } -template -inline bool lt(const T1 &lhs, const Optional &rhs) { +template +inline bool lt(const T1& lhs, const Optional& rhs) { return impl_::optional_lt_impl(lhs, rhs); } -template -inline bool lt(const Optional &lhs, const Optional &rhs) { +template +inline bool lt(const Optional& lhs, const Optional& rhs) { return impl_::optional_lt_impl(lhs, rhs); } -template -inline bool lt(const Optional &lhs, const Optional &rhs) { +template +inline bool lt(const Optional& lhs, const Optional& rhs) { return impl_::optional_lt_impl(lhs, rhs); } -template -inline bool lt(const bool &lhs, const Optional &rhs) { +template +inline bool lt(const bool& lhs, const Optional& rhs) { return lt(lhs, f$boolval(rhs)); } -template -inline bool lt(const Optional &lhs, const bool &rhs) { +template +inline bool lt(const Optional& lhs, const bool& rhs) { return lt(f$boolval(lhs), rhs); } -template -inline bool lt(const array &lhs, const array &rhs) { +template +inline bool lt(const array& lhs, const array& rhs) { if (lhs.count() != rhs.count()) { return lhs.count() < rhs.count(); } @@ -635,70 +565,68 @@ inline bool lt(const array &lhs, const array &rhs) { return false; } -template -inline bool leq(const T1 &lhs, const T2 &rhs) { +template +inline bool leq(const T1& lhs, const T2& rhs) { // (lhs <= rhs) === (!(rhs < lhs)) return !lt(rhs, lhs); } namespace impl_ { -template -bool optional_eq2_impl(const Optional &lhs, const T2 &rhs) { - auto eq2_lambda = [](const auto &l, const auto &r) { return eq2(r, l); }; +template +bool optional_eq2_impl(const Optional& lhs, const T2& rhs) { + auto eq2_lambda = [](const auto& l, const auto& r) { return eq2(r, l); }; return call_fun_on_optional_value(eq2_lambda, lhs, rhs); } -template -bool optional_equals_impl(const Optional &lhs, const T2 &rhs) { - auto equals_lambda = [](const auto &l, const auto &r) { +template +bool optional_equals_impl(const Optional& lhs, const T2& rhs) { + auto equals_lambda = [](const auto& l, const auto& r) { // if (is_null(lhs)) { return is_null(r); } // else return equals(r, l); - parameters are swapped to cope with Optional on right side - return std::is_same{} ? - f$is_null(r) : - equals(r, l); + return std::is_same{} ? f$is_null(r) : equals(r, l); }; return call_fun_on_optional_value(equals_lambda, lhs, rhs); } -template -inline bool optional_lt_impl(const Optional &lhs, const T2 &rhs) { - auto lt_lambda = [](const auto &l, const auto &r) { return lt(l, r);}; +template +inline bool optional_lt_impl(const Optional& lhs, const T2& rhs) { + auto lt_lambda = [](const auto& l, const auto& r) { return lt(l, r); }; return call_fun_on_optional_value(lt_lambda, lhs, rhs); } -template -inline enable_if_t_is_not_optional optional_lt_impl(const T1 &lhs, const Optional &rhs) { - auto lt_reversed_args_lambda = [](const auto &l, const auto &r) { return lt(r, l);}; +template +inline enable_if_t_is_not_optional optional_lt_impl(const T1& lhs, const Optional& rhs) { + auto lt_reversed_args_lambda = [](const auto& l, const auto& r) { return lt(r, l); }; return call_fun_on_optional_value(lt_reversed_args_lambda, rhs, lhs); } } // namespace impl_ -template -decltype(auto) call_fun_on_optional_value(FunT && fun, const Optional &opt, Args &&... args) { +template +decltype(auto) call_fun_on_optional_value(FunT&& fun, const Optional& opt, Args&&... args) { switch (opt.value_state()) { - case OptionalState::has_value: - return fun(opt.val(), std::forward(args)...); - case OptionalState::false_value: - return fun(false, std::forward(args)...); - case OptionalState::null_value: - return fun(mixed{}, std::forward(args)...); - default: - __builtin_unreachable(); + case OptionalState::has_value: + return fun(opt.val(), std::forward(args)...); + case OptionalState::false_value: + return fun(false, std::forward(args)...); + case OptionalState::null_value: + return fun(mixed{}, std::forward(args)...); + default: + __builtin_unreachable(); } } -template -decltype(auto) call_fun_on_optional_value(FunT && fun, Optional &&opt, Args &&... args) { +template +decltype(auto) call_fun_on_optional_value(FunT&& fun, Optional&& opt, Args&&... args) { switch (opt.value_state()) { - case OptionalState::has_value: - return fun(std::move(opt.val()), std::forward(args)...); - case OptionalState::false_value: - return fun(false, std::forward(args)...); - case OptionalState::null_value: - return fun(mixed{}, std::forward(args)...); - default: - __builtin_unreachable(); + case OptionalState::has_value: + return fun(std::move(opt.val()), std::forward(args)...); + case OptionalState::false_value: + return fun(false, std::forward(args)...); + case OptionalState::null_value: + return fun(mixed{}, std::forward(args)...); + default: + __builtin_unreachable(); } } diff --git a/runtime-common/core/core-types/conversions_types.inl b/runtime-common/core/core-types/conversions_types.inl index a97f3e7296..7405f19206 100644 --- a/runtime-common/core/core-types/conversions_types.inl +++ b/runtime-common/core/core-types/conversions_types.inl @@ -1,64 +1,54 @@ #pragma once #ifndef INCLUDED_FROM_KPHP_CORE - #error "this file must be included only from runtime-core.h" +#error "this file must be included only from runtime-core.h" #endif -template> +template > inline bool f$boolval(T val) { return static_cast(val); } -inline bool f$boolval(tmp_string val) { - return val.to_bool(); -} +inline bool f$boolval(tmp_string val) { return val.to_bool(); } -inline bool f$boolval(const string &val) { - return val.to_bool(); -} +inline bool f$boolval(const string& val) { return val.to_bool(); } -template -inline bool f$boolval(const array &val) { +template +inline bool f$boolval(const array& val) { return !val.empty(); } -template -inline bool f$boolval(const class_instance &val) { +template +inline bool f$boolval(const class_instance& val) { return !val.is_null(); } -template -inline bool f$boolval(const std::tuple &) { +template +inline bool f$boolval(const std::tuple&) { return true; } -template -inline bool f$boolval(const Optional &val) { +template +inline bool f$boolval(const Optional& val) { return val.has_value() ? f$boolval(val.val()) : false; } -inline bool f$boolval(const mixed &val) { - return val.to_bool(); -} +inline bool f$boolval(const mixed& val) { return val.to_bool(); } -template> +template > inline int64_t f$intval(T val) ubsan_supp("float-cast-overflow"); -template +template inline int64_t f$intval(T val) { return static_cast(val); } -inline int64_t f$intval(const string &val) { - return val.to_int(); -} +inline int64_t f$intval(const string& val) { return val.to_int(); } -inline int64_t f$intval(const mixed &val) { - return val.to_int(); -} +inline int64_t f$intval(const mixed& val) { return val.to_int(); } -template -inline int64_t f$intval(const Optional &val) { +template +inline int64_t f$intval(const Optional& val) { return val.has_value() ? f$intval(val.val()) : 0; } @@ -69,14 +59,9 @@ inline int64_t f$intval(tmp_string s) { return string::to_int(s.data, s.size); } +inline int64_t f$safe_intval(bool val) { return val; } -inline int64_t f$safe_intval(bool val) { - return val; -} - -inline int64_t f$safe_intval(int64_t val) { - return val; -} +inline int64_t f$safe_intval(int64_t val) { return val; } inline int64_t f$safe_intval(double val) { constexpr auto max_int = static_cast(static_cast(std::numeric_limits::max()) + 1); @@ -86,104 +71,77 @@ inline int64_t f$safe_intval(double val) { return static_cast(val); } -inline int64_t f$safe_intval(const string &val) { - return val.safe_to_int(); -} +inline int64_t f$safe_intval(const string& val) { return val.safe_to_int(); } -inline int64_t f$safe_intval(const mixed &val) { - return val.safe_to_int(); -} +inline int64_t f$safe_intval(const mixed& val) { return val.safe_to_int(); } -template> +template > inline double f$floatval(T val) { return static_cast(val); } -inline double f$floatval(const string &val) { - return val.to_float(); -} +inline double f$floatval(const string& val) { return val.to_float(); } -inline double f$floatval(const mixed &val) { - return val.to_float(); -} +inline double f$floatval(const mixed& val) { return val.to_float(); } -template -inline double f$floatval(const Optional &val) { +template +inline double f$floatval(const Optional& val) { return val.has_value() ? f$floatval(val.val()) : 0; } +inline string f$strval(bool val) { return (val ? string("1", 1) : string()); } -inline string f$strval(bool val) { - return (val ? string("1", 1) : string()); -} +inline string f$strval(int64_t val) { return string(val); } -inline string f$strval(int64_t val) { - return string(val); -} +inline string f$strval(double val) { return string(val); } -inline string f$strval(double val) { - return string(val); -} +inline string f$strval(const string& val) { return val; } -inline string f$strval(const string &val) { - return val; -} - -inline string &&f$strval(string &&val) { - return std::move(val); -} +inline string&& f$strval(string&& val) { return std::move(val); } -template -inline string f$strval(const Optional &val) { +template +inline string f$strval(const Optional& val) { return val.has_value() ? f$strval(val.val()) : f$strval(false); } -template -inline string f$strval(Optional &&val) { +template +inline string f$strval(Optional&& val) { return val.has_value() ? f$strval(std::move(val.val())) : f$strval(false); } -inline string f$strval(const mixed &val) { - return val.to_string(); -} +inline string f$strval(const mixed& val) { return val.to_string(); } -inline string f$strval(mixed &&val) { - return val.is_string() ? std::move(val.as_string()) : val.to_string(); -} +inline string f$strval(mixed&& val) { return val.is_string() ? std::move(val.as_string()) : val.to_string(); } -template -inline array f$arrayval(const T &val) { +template +inline array f$arrayval(const T& val) { array res(array_size(1, true)); res.push_back(val); return res; } -template -inline const array &f$arrayval(const array &val) { +template +inline const array& f$arrayval(const array& val) { return val; } -template -inline array &&f$arrayval(array &&val) { +template +inline array&& f$arrayval(array&& val) { return std::move(val); } -inline array f$arrayval(const mixed &val) { - return val.to_array(); -} +inline array f$arrayval(const mixed& val) { return val.to_array(); } -inline array f$arrayval(mixed &&val) { - return val.is_array() ? std::move(val.as_array()) : val.to_array(); -} +inline array f$arrayval(mixed&& val) { return val.is_array() ? std::move(val.as_array()) : val.to_array(); } namespace impl_ { -template +template inline std::enable_if_t{}, array> false_cast_to_array() { return f$arrayval(T{false}); } -template +template inline std::enable_if_t{}, array> false_cast_to_array() { php_warning("Dangerous cast false to array, the result will be different from PHP"); return array{}; @@ -191,44 +149,44 @@ inline std::enable_if_t{}, array> false_ } // namespace impl_ -template -inline array f$arrayval(const Optional &val) { +template +inline array f$arrayval(const Optional& val) { switch (val.value_state()) { - case OptionalState::has_value: - return f$arrayval(val.val()); - case OptionalState::false_value: - return impl_::false_cast_to_array(); - case OptionalState::null_value: - return array{}; - default: - __builtin_unreachable(); + case OptionalState::has_value: + return f$arrayval(val.val()); + case OptionalState::false_value: + return impl_::false_cast_to_array(); + case OptionalState::null_value: + return array{}; + default: + __builtin_unreachable(); } } -template -inline array f$arrayval(Optional &&val) { +template +inline array f$arrayval(Optional&& val) { switch (val.value_state()) { - case OptionalState::has_value: - return f$arrayval(std::move(val.val())); - case OptionalState::false_value: - return impl_::false_cast_to_array(); - case OptionalState::null_value: - return array{}; - default: - __builtin_unreachable(); + case OptionalState::has_value: + return f$arrayval(std::move(val.val())); + case OptionalState::false_value: + return impl_::false_cast_to_array(); + case OptionalState::null_value: + return array{}; + default: + __builtin_unreachable(); } } -template -inline array f$arrayval(const Optional> &val) { +template +inline array f$arrayval(const Optional>& val) { if (val.is_false()) { return impl_::false_cast_to_array(); } return val.val(); } -template -inline array f$arrayval(Optional> &&val) { +template +inline array f$arrayval(Optional>&& val) { if (val.is_false()) { return impl_::false_cast_to_array(); } diff --git a/runtime-common/core/core-types/decl/array_decl.inl b/runtime-common/core/core-types/decl/array_decl.inl index 893616334e..9a286afc9e 100644 --- a/runtime-common/core/core-types/decl/array_decl.inl +++ b/runtime-common/core/core-types/decl/array_decl.inl @@ -8,7 +8,7 @@ #include "runtime-common/core/include.h" #ifndef INCLUDED_FROM_KPHP_CORE - #error "this file must be included only from runtime-core.h" +#error "this file must be included only from runtime-core.h" #endif struct array_size { @@ -19,17 +19,16 @@ struct array_size { inline array_size(int64_t int_size, bool is_vector) noexcept; - inline array_size operator+(const array_size &other) const noexcept; + inline array_size operator+(const array_size& other) const noexcept; - inline array_size &cut(int64_t length) noexcept; + inline array_size& cut(int64_t length) noexcept; - inline array_size &min(const array_size &other) noexcept; + inline array_size& min(const array_size& other) noexcept; }; - namespace dl { -template -void sort(TT *begin_init, TT *end_init, const T1 &compare); +template +void sort(TT* begin_init, TT* end_init, const T1& compare); } enum class overwrite_element { YES, NO }; @@ -43,7 +42,7 @@ struct array_list_hash_entry { list_entry_pointer_type prev; }; -struct ArrayBucketDummyStrTag{}; +struct ArrayBucketDummyStrTag {}; struct array_inner_control { bool is_vector_internal; @@ -54,7 +53,7 @@ struct array_inner_control { uint32_t buf_size; }; -template +template class array { public: // TODO why we need 2 value types? @@ -62,7 +61,7 @@ public: using value_type = T; using key_type = mixed; - inline static bool is_int_key(const key_type &key); + inline static bool is_int_key(const key_type& key); private: using entry_pointer_type = list_entry_pointer_type; @@ -90,82 +89,81 @@ private: struct alignas(array_bucket) array_inner : array_inner_control { static constexpr uint32_t MAX_HASHTABLE_SIZE = (1 << 26); - //empty hash_entry identified by (next == EMPTY_POINTER) + // empty hash_entry identified by (next == EMPTY_POINTER) static constexpr entry_pointer_type EMPTY_POINTER = 0; static constexpr size_t ENTRIES_OFFSET = sizeof(array_inner); - inline bool is_vector() const noexcept __attribute__ ((always_inline)); + inline bool is_vector() const noexcept __attribute__((always_inline)); - inline array_bucket* entries() noexcept __attribute__ ((always_inline)); - inline const array_bucket* entries() const noexcept __attribute__ ((always_inline)); + inline array_bucket* entries() noexcept __attribute__((always_inline)); + inline const array_bucket* entries() const noexcept __attribute__((always_inline)); - inline list_hash_entry *get_entry(entry_pointer_type pointer) const __attribute__ ((always_inline)); - inline entry_pointer_type get_pointer(list_hash_entry *entry) const __attribute__ ((always_inline)); + inline list_hash_entry* get_entry(entry_pointer_type pointer) const __attribute__((always_inline)); + inline entry_pointer_type get_pointer(list_hash_entry* entry) const __attribute__((always_inline)); - inline const array_bucket *begin() const __attribute__ ((always_inline)) ubsan_supp("alignment"); - inline const array_bucket *next(const array_bucket *ptr) const __attribute__ ((always_inline)) ubsan_supp("alignment"); - inline const array_bucket *prev(const array_bucket *ptr) const __attribute__ ((always_inline)) ubsan_supp("alignment"); - inline const array_bucket *end() const __attribute__ ((always_inline)) ubsan_supp("alignment"); - inline array_bucket *begin() __attribute__ ((always_inline)) ubsan_supp("alignment"); - inline array_bucket *next(array_bucket *ptr) __attribute__ ((always_inline)) ubsan_supp("alignment"); - inline array_bucket *prev(array_bucket *ptr) __attribute__ ((always_inline)) ubsan_supp("alignment"); - inline array_bucket *end() __attribute__ ((always_inline)) ubsan_supp("alignment"); + inline const array_bucket* begin() const __attribute__((always_inline)) ubsan_supp("alignment"); + inline const array_bucket* next(const array_bucket* ptr) const __attribute__((always_inline)) ubsan_supp("alignment"); + inline const array_bucket* prev(const array_bucket* ptr) const __attribute__((always_inline)) ubsan_supp("alignment"); + inline const array_bucket* end() const __attribute__((always_inline)) ubsan_supp("alignment"); + inline array_bucket* begin() __attribute__((always_inline)) ubsan_supp("alignment"); + inline array_bucket* next(array_bucket* ptr) __attribute__((always_inline)) ubsan_supp("alignment"); + inline array_bucket* prev(array_bucket* ptr) __attribute__((always_inline)) ubsan_supp("alignment"); + inline array_bucket* end() __attribute__((always_inline)) ubsan_supp("alignment"); - inline bool is_string_hash_entry(const array_bucket *ptr) const __attribute__ ((always_inline)); + inline bool is_string_hash_entry(const array_bucket* ptr) const __attribute__((always_inline)); - inline array_inner_fields_for_map &fields_for_map() __attribute__((always_inline)); - inline const array_inner_fields_for_map &fields_for_map() const __attribute__((always_inline)); + inline array_inner_fields_for_map& fields_for_map() __attribute__((always_inline)); + inline const array_inner_fields_for_map& fields_for_map() const __attribute__((always_inline)); - inline uint32_t choose_bucket(int64_t key) const noexcept __attribute__ ((always_inline)); - inline uint32_t choose_bucket(const array_inner_fields_for_map &fields, int64_t key) const noexcept __attribute__ ((always_inline)); + inline uint32_t choose_bucket(int64_t key) const noexcept __attribute__((always_inline)); + inline uint32_t choose_bucket(const array_inner_fields_for_map& fields, int64_t key) const noexcept __attribute__((always_inline)); inline static size_t sizeof_vector(uint32_t int_size) noexcept __attribute__((always_inline)); inline static size_t sizeof_map(uint32_t int_size) noexcept __attribute__((always_inline)); - inline static size_t estimate_size(int64_t &new_int_size, bool is_vector); - inline static array_inner *create(int64_t new_int_size, bool is_vector); + inline static size_t estimate_size(int64_t& new_int_size, bool is_vector); + inline static array_inner* create(int64_t new_int_size, bool is_vector); - inline static array_inner *empty_array() __attribute__ ((always_inline)); + inline static array_inner* empty_array() __attribute__((always_inline)); inline void dispose(); - inline array_inner *ref_copy() __attribute__ ((always_inline)); - + inline array_inner* ref_copy() __attribute__((always_inline)); - template - inline T &emplace_back_vector_value(Args &&... args) noexcept; - inline T &push_back_vector_value(const T &v); //unsafe + template + inline T& emplace_back_vector_value(Args&&... args) noexcept; + inline T& push_back_vector_value(const T& v); // unsafe - template - inline T &emplace_vector_value(int64_t int_key, Args &&... args) noexcept; - inline T &set_vector_value(int64_t int_key, const T &v); //unsafe + template + inline T& emplace_vector_value(int64_t int_key, Args&&... args) noexcept; + inline T& set_vector_value(int64_t int_key, const T& v); // unsafe - template - inline T &emplace_int_key_map_value(overwrite_element policy, int64_t int_key, Args &&... args) noexcept; - inline T &set_map_value(overwrite_element policy, int64_t int_key, const T &v); + template + inline T& emplace_int_key_map_value(overwrite_element policy, int64_t int_key, Args&&... args) noexcept; + inline T& set_map_value(overwrite_element policy, int64_t int_key, const T& v); - template - inline std::pair emplace_string_key_map_value(overwrite_element policy, int64_t int_key, STRING &&string_key, Args &&... args) noexcept; - inline T &set_map_value(overwrite_element policy, int64_t int_key, const string &string_key, const T &v); + template + inline std::pair emplace_string_key_map_value(overwrite_element policy, int64_t int_key, STRING&& string_key, Args&&... args) noexcept; + inline T& set_map_value(overwrite_element policy, int64_t int_key, const string& string_key, const T& v); inline T unset_vector_value(); inline T unset_map_value(int64_t int_key); // to avoid the const_cast, declare these functions as static with a template self parameter (this) - template - static auto &find_map_entry(S &self, int64_t int_key) noexcept; - template - static auto &find_map_entry(S &self, const string &string_key, int64_t precomputed_hash) noexcept; - template - static auto &find_map_entry(S &self, const char *key, string::size_type key_size, int64_t precomputed_hash) noexcept; - - template - inline const T *find_map_value(Key &&... key) const noexcept; - inline const T *find_vector_value(int64_t int_key) const noexcept; - inline T *find_vector_value(int64_t int_key) noexcept; - - inline const T &get_vector_value(int64_t int_key) const;//unsafe - inline T &get_vector_value(int64_t int_key);//unsafe - inline T unset_map_value(const string &string_key, int64_t precomputed_hash); + template + static auto& find_map_entry(S& self, int64_t int_key) noexcept; + template + static auto& find_map_entry(S& self, const string& string_key, int64_t precomputed_hash) noexcept; + template + static auto& find_map_entry(S& self, const char* key, string::size_type key_size, int64_t precomputed_hash) noexcept; + + template + inline const T* find_map_value(Key&&... key) const noexcept; + inline const T* find_vector_value(int64_t int_key) const noexcept; + inline T* find_vector_value(int64_t int_key) noexcept; + + inline const T& get_vector_value(int64_t int_key) const; // unsafe + inline T& get_vector_value(int64_t int_key); // unsafe + inline T unset_map_value(const string& string_key, int64_t precomputed_hash); bool is_vector_internal_or_last_index(int64_t key) const noexcept; bool has_no_string_keys() const noexcept; @@ -173,8 +171,8 @@ private: size_t estimate_memory_usage() const noexcept; size_t calculate_memory_for_copying() const noexcept; - inline array_inner(const array_inner &other) = delete; - inline array_inner &operator=(const array_inner &other) = delete; + inline array_inner(const array_inner& other) = delete; + inline array_inner& operator=(const array_inner& other) = delete; }; inline bool mutate_if_vector_shared(uint32_t mul = 1); @@ -187,11 +185,11 @@ private: inline void convert_to_map(); - template - inline void copy_from(const array &other); + template + inline void copy_from(const array& other); - template - inline void move_from(array &&other) noexcept; + template + inline void move_from(array&& other) noexcept; inline void destroy(); @@ -202,202 +200,196 @@ public: using iterator = array_iterator; using const_iterator = array_iterator; - inline array() __attribute__ ((always_inline)); + inline array() __attribute__((always_inline)); - inline explicit array(const array_size &s) __attribute__ ((always_inline)); + inline explicit array(const array_size& s) __attribute__((always_inline)); - template - inline array(const std::initializer_list> &list) __attribute__ ((always_inline)); + template + inline array(const std::initializer_list>& list) __attribute__((always_inline)); - inline array(const array &other) noexcept __attribute__ ((always_inline)); + inline array(const array& other) noexcept __attribute__((always_inline)); - inline array(array &&other) noexcept __attribute__ ((always_inline)); + inline array(array&& other) noexcept __attribute__((always_inline)); - template> - inline array(const array &other) noexcept __attribute__ ((always_inline)); + template > + inline array(const array& other) noexcept __attribute__((always_inline)); - template> - inline array(array &&other) noexcept __attribute__ ((always_inline)); + template > + inline array(array&& other) noexcept __attribute__((always_inline)); - template - inline static array create(Args &&... args) __attribute__ ((always_inline)); + template + inline static array create(Args&&... args) __attribute__((always_inline)); - inline array &operator=(const array &other) noexcept __attribute__ ((always_inline)); + inline array& operator=(const array& other) noexcept __attribute__((always_inline)); - inline array &operator=(array &&other) noexcept __attribute__ ((always_inline)); + inline array& operator=(array&& other) noexcept __attribute__((always_inline)); - template> - inline array &operator=(const array &other) noexcept; + template > + inline array& operator=(const array& other) noexcept; - template> - inline array &operator=(array &&other) noexcept; + template > + inline array& operator=(array&& other) noexcept; inline ~array(); - inline void clear() __attribute__ ((always_inline)); + inline void clear() __attribute__((always_inline)); // shows if internal storage is vector - inline bool is_vector() const __attribute__ ((always_inline)); + inline bool is_vector() const __attribute__((always_inline)); // internal storage may be map, but it still behaves exactly like vector - inline bool is_pseudo_vector() const __attribute__ ((always_inline)); + inline bool is_pseudo_vector() const __attribute__((always_inline)); // and one more level deep: shows if there are no string keys in storage; // it is useful in some specific cases like in shift() function, // there we drop all int indexes, and if there will be also no string indexes // we can create true vector bool has_no_string_keys() const noexcept; - static size_t estimate_size(int64_t n, bool is_vector) noexcept { - return array_inner::estimate_size(n, is_vector); - } - - T &operator[](int64_t int_key); - T &operator[](int32_t key) { return (*this)[int64_t{key}]; } - T &operator[](const string &s); - T &operator[](tmp_string s); - T &operator[](const mixed &v); - T &operator[](double double_key); - T &operator[](const const_iterator &it) noexcept; - T &operator[](const iterator &it) noexcept; - - template - void emplace_value(int64_t int_key, Args &&... args) noexcept; - void set_value(int64_t int_key, T &&v) noexcept; - void set_value(int64_t int_key, const T &v) noexcept; - void set_value(int32_t key, T &&v) noexcept { set_value(int64_t{key}, std::move(v)); } - void set_value(int32_t key, const T &v) noexcept { set_value(int64_t{key}, v); } - void set_value(double double_key, T &&v) noexcept; - void set_value(double double_key, const T &v) noexcept; - - template - void emplace_value(const string &string_key, Args &&... args) noexcept; - void set_value(const string &string_key, T &&v) noexcept; - void set_value(const string &string_key, const T &v) noexcept; - void set_value(tmp_string string_key, T &&v) noexcept; - void set_value(tmp_string string_key, const T &v) noexcept; - - void set_value(const string &string_key, T &&v, int64_t precomputed_hash) noexcept; - void set_value(const string &string_key, const T &v, int64_t precomputed_hash) noexcept; - - template - void emplace_value(const mixed &var_key, Args &&... args) noexcept; - void set_value(const mixed &v, T &&value) noexcept; - void set_value(const mixed &v, const T &value) noexcept; - - - template - void emplace_value(const Optional &key, Args &&... args) noexcept; - template - void set_value(const Optional &key, T &&value) noexcept; - template - void set_value(const Optional &key, const T &value) noexcept; - - void set_value(const const_iterator &it) noexcept; - void set_value(const iterator &it) noexcept; + static size_t estimate_size(int64_t n, bool is_vector) noexcept { return array_inner::estimate_size(n, is_vector); } + + T& operator[](int64_t int_key); + T& operator[](int32_t key) { return (*this)[int64_t{key}]; } + T& operator[](const string& s); + T& operator[](tmp_string s); + T& operator[](const mixed& v); + T& operator[](double double_key); + T& operator[](const const_iterator& it) noexcept; + T& operator[](const iterator& it) noexcept; + + template + void emplace_value(int64_t int_key, Args&&... args) noexcept; + void set_value(int64_t int_key, T&& v) noexcept; + void set_value(int64_t int_key, const T& v) noexcept; + void set_value(int32_t key, T&& v) noexcept { set_value(int64_t{key}, std::move(v)); } + void set_value(int32_t key, const T& v) noexcept { set_value(int64_t{key}, v); } + void set_value(double double_key, T&& v) noexcept; + void set_value(double double_key, const T& v) noexcept; + + template + void emplace_value(const string& string_key, Args&&... args) noexcept; + void set_value(const string& string_key, T&& v) noexcept; + void set_value(const string& string_key, const T& v) noexcept; + void set_value(tmp_string string_key, T&& v) noexcept; + void set_value(tmp_string string_key, const T& v) noexcept; + + void set_value(const string& string_key, T&& v, int64_t precomputed_hash) noexcept; + void set_value(const string& string_key, const T& v, int64_t precomputed_hash) noexcept; + + template + void emplace_value(const mixed& var_key, Args&&... args) noexcept; + void set_value(const mixed& v, T&& value) noexcept; + void set_value(const mixed& v, const T& value) noexcept; + + template + void emplace_value(const Optional& key, Args&&... args) noexcept; + template + void set_value(const Optional& key, T&& value) noexcept; + template + void set_value(const Optional& key, const T& value) noexcept; + + void set_value(const const_iterator& it) noexcept; + void set_value(const iterator& it) noexcept; // assign binary array_inner representation // can be used only on empty arrays to receive logically const array - void assign_raw(const char *s); - - const T *find_value(int64_t int_key) const noexcept; - const T *find_value(int32_t key) const noexcept { return find_value(int64_t{key}); } - const T *find_value(const char *s, string::size_type l) const noexcept; - const T *find_value(tmp_string s) const noexcept { return find_value(s.data, s.size); } - const T *find_value(const string &s) const noexcept { return find_value(s.c_str(), s.size()); } - const T *find_value(const string &s, int64_t precomputed_hash) const noexcept; - const T *find_value(const mixed &v) const noexcept; - const T *find_value(double double_key) const noexcept; - const T *find_value(const const_iterator &it) const noexcept; - const T *find_value(const iterator &it) const noexcept; + void assign_raw(const char* s); + + const T* find_value(int64_t int_key) const noexcept; + const T* find_value(int32_t key) const noexcept { return find_value(int64_t{key}); } + const T* find_value(const char* s, string::size_type l) const noexcept; + const T* find_value(tmp_string s) const noexcept { return find_value(s.data, s.size); } + const T* find_value(const string& s) const noexcept { return find_value(s.c_str(), s.size()); } + const T* find_value(const string& s, int64_t precomputed_hash) const noexcept; + const T* find_value(const mixed& v) const noexcept; + const T* find_value(double double_key) const noexcept; + const T* find_value(const const_iterator& it) const noexcept; + const T* find_value(const iterator& it) const noexcept; // All non-const methods find_no_mutate() do not lead to a copy iterator find_no_mutate(int64_t int_key) noexcept; - iterator find_no_mutate(const string &string_key) noexcept; - iterator find_no_mutate(const mixed &v) noexcept; + iterator find_no_mutate(const string& string_key) noexcept; + iterator find_no_mutate(const mixed& v) noexcept; - template - const mixed get_var(const K &key) const; + template + const mixed get_var(const K& key) const; - template - const T get_value(const K &key) const; - const T get_value(const string &string_key, int64_t precomputed_hash) const; + template + const T get_value(const K& key) const; + const T get_value(const string& string_key, int64_t precomputed_hash) const; - template - T &emplace_back(Args &&... args) noexcept; - void push_back(T &&v) noexcept; - void push_back(const T &v) noexcept; + template + T& emplace_back(Args&&... args) noexcept; + void push_back(T&& v) noexcept; + void push_back(const T& v) noexcept; - void push_back(const const_iterator &it) noexcept; - void push_back(const iterator &it) noexcept; + void push_back(const const_iterator& it) noexcept; + void push_back(const iterator& it) noexcept; - const T push_back_return(const T &v); - const T push_back_return(T &&v); + const T push_back_return(const T& v); + const T push_back_return(T&& v); void swap_int_keys(int64_t idx1, int64_t idx2) noexcept; - inline void fill_vector(int64_t num, const T &value); - inline void memcpy_vector(int64_t num, const void *src_buf); + inline void fill_vector(int64_t num, const T& value); + inline void memcpy_vector(int64_t num, const void* src_buf); - inline int64_t get_next_key() const __attribute__ ((always_inline)); + inline int64_t get_next_key() const __attribute__((always_inline)); - template - bool has_key(const K &key) const; + template + bool has_key(const K& key) const; - template - bool isset(const K &key) const noexcept; - bool isset(const string &key, int64_t precomputed_hash) const noexcept; + template + bool isset(const K& key) const noexcept; + bool isset(const string& key, int64_t precomputed_hash) const noexcept; T unset(int64_t int_key); T unset(int32_t key) { return unset(int64_t{key}); } T unset(double double_key) { return unset(static_cast(double_key)); } - T unset(const string &string_key); - T unset(const string &string_key, int64_t precomputed_hash); - T unset(const mixed &var_key); - - inline bool empty() const __attribute__ ((always_inline)); - inline int64_t count() const __attribute__ ((always_inline)); + T unset(const string& string_key); + T unset(const string& string_key, int64_t precomputed_hash); + T unset(const mixed& var_key); - inline array_size size() const __attribute__ ((always_inline)); + inline bool empty() const __attribute__((always_inline)); + inline int64_t count() const __attribute__((always_inline)); - template> - void merge_with(const array &other) noexcept; - template> - void merge_with_recursive(const array &other) noexcept; - void merge_with_recursive(const mixed &other) noexcept; + inline array_size size() const __attribute__((always_inline)); - const array operator+(const array &other) const; - array &operator+=(const array &other); + template > + void merge_with(const array& other) noexcept; + template > + void merge_with_recursive(const array& other) noexcept; + void merge_with_recursive(const mixed& other) noexcept; - inline const_iterator begin() const __attribute__ ((always_inline)); - inline const_iterator cbegin() const __attribute__ ((always_inline)); - inline const_iterator middle(int64_t n) const __attribute__ ((always_inline)); - inline const_iterator end() const __attribute__ ((always_inline)); - inline const_iterator cend() const __attribute__ ((always_inline)); + const array operator+(const array& other) const; + array& operator+=(const array& other); - inline iterator begin() __attribute__ ((always_inline)); - inline iterator middle(int64_t n) __attribute__ ((always_inline)); - inline iterator end() __attribute__ ((always_inline)); + inline const_iterator begin() const __attribute__((always_inline)); + inline const_iterator cbegin() const __attribute__((always_inline)); + inline const_iterator middle(int64_t n) const __attribute__((always_inline)); + inline const_iterator end() const __attribute__((always_inline)); + inline const_iterator cend() const __attribute__((always_inline)); - template - void sort(const T1 &compare, bool renumber); + inline iterator begin() __attribute__((always_inline)); + inline iterator middle(int64_t n) __attribute__((always_inline)); + inline iterator end() __attribute__((always_inline)); - template - void ksort(const T1 &compare); + template + void sort(const T1& compare, bool renumber); - inline void swap(array &other) __attribute__ ((always_inline)); + template + void ksort(const T1& compare); + inline void swap(array& other) __attribute__((always_inline)); T pop(); - T &back(); + T& back(); T shift(); - int64_t unshift(const T &val); - - - inline bool to_bool() const __attribute__ ((always_inline)); - inline int64_t to_int() const __attribute__ ((always_inline)); - inline double to_float() const __attribute__ ((always_inline)); + int64_t unshift(const T& val); + inline bool to_bool() const __attribute__((always_inline)); + inline int64_t to_int() const __attribute__((always_inline)); + inline double to_float() const __attribute__((always_inline)); int64_t get_reference_counter() const; bool is_reference_counter(ExtraRefCnt ref_cnt_value) const noexcept; @@ -409,40 +401,39 @@ public: void mutate_if_shared() noexcept; - const T *get_const_vector_pointer() const; // unsafe - T *get_vector_pointer(); // unsafe + const T* get_const_vector_pointer() const; // unsafe + T* get_vector_pointer(); // unsafe - bool is_equal_inner_pointer(const array &other) const noexcept; + bool is_equal_inner_pointer(const array& other) const noexcept; void reserve(int64_t int_size, bool make_vector_if_possible); size_t estimate_memory_usage() const noexcept; size_t calculate_memory_for_copying() const noexcept; - template - static array convert_from(const array &); + template + static array convert_from(const array&); private: - template - iterator find_iterator_in_map_no_mutate(const Key &... key) noexcept; + template + iterator find_iterator_in_map_no_mutate(const Key&... key) noexcept; - template - std::enable_if_t start_merge_recursive(T &value, bool was_inserted, const T &other_value) noexcept; - template - std::enable_if_t start_merge_recursive(T & /*value*/, bool /*was_inserted*/, const T & /*other_value*/) noexcept {} + template + std::enable_if_t start_merge_recursive(T& value, bool was_inserted, const T& other_value) noexcept; + template + std::enable_if_t start_merge_recursive(T& /*value*/, bool /*was_inserted*/, const T& /*other_value*/) noexcept {} - template - void push_back_iterator(const array_iterator &it) noexcept; + template + void push_back_iterator(const array_iterator& it) noexcept; - array_inner *p; + array_inner* p; - template + template friend class array; }; -template -inline void swap(array &lhs, array &rhs); - -template -inline const array array_add(array a1, const array &a2); +template +inline void swap(array& lhs, array& rhs); +template +inline const array array_add(array a1, const array& a2); diff --git a/runtime-common/core/core-types/decl/array_iterator.h b/runtime-common/core/core-types/decl/array_iterator.h index c7304eea3f..88c7e616b4 100644 --- a/runtime-common/core/core-types/decl/array_iterator.h +++ b/runtime-common/core/core-types/decl/array_iterator.h @@ -4,20 +4,20 @@ #pragma once -#include "common/type_traits/list_of_types.h" #include "common/sanitizer.h" +#include "common/type_traits/list_of_types.h" #include "runtime-common/core/core-types/decl/declarations.h" -template +template class array_iterator { private: - template + template friend class array; friend class array_iterator; - template + template using const_conditional_t = std::conditional_t::value, const S, S>; public: @@ -28,28 +28,23 @@ class array_iterator { using list_hash_type = const_conditional_t; using bucket_type = const_conditional_t; - inline constexpr array_iterator() noexcept __attribute__ ((always_inline)) = default; + inline constexpr array_iterator() noexcept __attribute__((always_inline)) = default; - inline array_iterator(inner_type *self, list_hash_type *entry) noexcept __attribute__ ((always_inline)): - self_(self), - entry_(entry) { - } + inline array_iterator(inner_type* self, list_hash_type* entry) noexcept __attribute__((always_inline)) : self_(self), entry_(entry) {} - inline operator array_iterator() noexcept __attribute__ ((always_inline)) { - return array_iterator(self_, entry_); - } + inline operator array_iterator() noexcept __attribute__((always_inline)) { return array_iterator(self_, entry_); } - inline value_type &get_value() noexcept __attribute__ ((always_inline)) { - return self_->is_vector() ? *reinterpret_cast(entry_) : static_cast(entry_)->value; + inline value_type& get_value() noexcept __attribute__((always_inline)) { + return self_->is_vector() ? *reinterpret_cast(entry_) : static_cast(entry_)->value; } - inline const value_type &get_value() const noexcept __attribute__ ((always_inline)) { - return self_->is_vector() ? *reinterpret_cast(entry_) : static_cast(entry_)->value; + inline const value_type& get_value() const noexcept __attribute__((always_inline)) { + return self_->is_vector() ? *reinterpret_cast(entry_) : static_cast(entry_)->value; } - inline key_type get_key() const noexcept __attribute__ ((always_inline)) { + inline key_type get_key() const noexcept __attribute__((always_inline)) { if (self_->is_vector()) { - return key_type{static_cast(reinterpret_cast(entry_) - reinterpret_cast(self_->entries()))}; + return key_type{static_cast(reinterpret_cast(entry_) - reinterpret_cast(self_->entries()))}; } if (is_string_key()) { @@ -59,64 +54,42 @@ class array_iterator { } } - inline int64_t get_int_key() noexcept __attribute__ ((always_inline)) { - return static_cast(entry_)->int_key; - } + inline int64_t get_int_key() noexcept __attribute__((always_inline)) { return static_cast(entry_)->int_key; } - inline int64_t get_int_key() const noexcept __attribute__ ((always_inline)) { - return static_cast(entry_)->int_key; - } + inline int64_t get_int_key() const noexcept __attribute__((always_inline)) { return static_cast(entry_)->int_key; } - inline bool is_string_key() const noexcept __attribute__ ((always_inline)) ubsan_supp("alignment") { - return !self_->is_vector() && self_->is_string_hash_entry(static_cast(entry_)); + inline bool is_string_key() const noexcept __attribute__((always_inline)) ubsan_supp("alignment") { + return !self_->is_vector() && self_->is_string_hash_entry(static_cast(entry_)); } - inline const_conditional_t &get_string_key() noexcept __attribute__ ((always_inline)) { - return static_cast(entry_)->string_key; - } + inline const_conditional_t& get_string_key() noexcept __attribute__((always_inline)) { return static_cast(entry_)->string_key; } - inline const string &get_string_key() const noexcept __attribute__ ((always_inline)) { - return static_cast(entry_)->string_key; - } + inline const string& get_string_key() const noexcept __attribute__((always_inline)) { return static_cast(entry_)->string_key; } - inline array_iterator &operator++() noexcept __attribute__ ((always_inline)) ubsan_supp("alignment") { - entry_ = self_->is_vector() - ? reinterpret_cast(reinterpret_cast(entry_) + 1) - : self_->next(static_cast(entry_)); + inline array_iterator& operator++() noexcept __attribute__((always_inline)) ubsan_supp("alignment") { + entry_ = self_->is_vector() ? reinterpret_cast(reinterpret_cast(entry_) + 1) : self_->next(static_cast(entry_)); return *this; } - inline array_iterator &operator--() noexcept __attribute__ ((always_inline)) ubsan_supp("alignment") { - entry_ = self_->is_vector() - ? reinterpret_cast(reinterpret_cast(entry_) - 1) - : self_->prev(static_cast(entry_)); + inline array_iterator& operator--() noexcept __attribute__((always_inline)) ubsan_supp("alignment") { + entry_ = self_->is_vector() ? reinterpret_cast(reinterpret_cast(entry_) - 1) : self_->prev(static_cast(entry_)); return *this; } - inline bool operator==(const array_iterator &other) const noexcept __attribute__ ((always_inline)) { - return entry_ == other.entry_; - } + inline bool operator==(const array_iterator& other) const noexcept __attribute__((always_inline)) { return entry_ == other.entry_; } - inline bool operator!=(const array_iterator &other) const noexcept __attribute__ ((always_inline)) { - return entry_ != other.entry_; - } + inline bool operator!=(const array_iterator& other) const noexcept __attribute__((always_inline)) { return entry_ != other.entry_; } - inline array_iterator &operator*() noexcept __attribute__ ((always_inline)) { - return *this; - } + inline array_iterator& operator*() noexcept __attribute__((always_inline)) { return *this; } - inline const array_iterator &operator*() const noexcept __attribute__ ((always_inline)) { - return *this; - } + inline const array_iterator& operator*() const noexcept __attribute__((always_inline)) { return *this; } - static inline array_iterator make_begin(std::add_const_t &arr) noexcept __attribute__ ((always_inline)) { + static inline array_iterator make_begin(std::add_const_t& arr) noexcept __attribute__((always_inline)) { static_assert(std::is_const{}, "expected to be const"); - return arr.is_vector() - ? array_iterator{arr.p, arr.p->entries()} - : array_iterator{arr.p, arr.p->begin()}; + return arr.is_vector() ? array_iterator{arr.p, arr.p->entries()} : array_iterator{arr.p, arr.p->begin()}; } - static inline array_iterator make_begin(std::remove_const_t &arr) noexcept __attribute__ ((always_inline)) { + static inline array_iterator make_begin(std::remove_const_t& arr) noexcept __attribute__((always_inline)) { static_assert(!std::is_const{}, "expected to be mutable"); if (arr.is_vector()) { arr.mutate_if_vector_shared(); @@ -127,13 +100,12 @@ class array_iterator { return array_iterator{arr.p, arr.p->begin()}; } - static inline array_iterator make_end(array_type &arr) noexcept __attribute__ ((always_inline)) { - return arr.is_vector() - ? array_iterator{arr.p, reinterpret_cast(reinterpret_cast(arr.p->entries()) + arr.p->size)} - : array_iterator{arr.p, arr.p->end()}; + static inline array_iterator make_end(array_type& arr) noexcept __attribute__((always_inline)) { + return arr.is_vector() ? array_iterator{arr.p, reinterpret_cast(reinterpret_cast(arr.p->entries()) + arr.p->size)} + : array_iterator{arr.p, arr.p->end()}; } - static inline array_iterator make_middle(array_type &arr, int64_t n) noexcept { + static inline array_iterator make_middle(array_type& arr, int64_t n) noexcept { int64_t l = arr.count(); if (arr.is_vector()) { @@ -147,7 +119,7 @@ class array_iterator { return make_end(arr); } - return array_iterator{arr.p, reinterpret_cast(reinterpret_cast(arr.p->entries()) + n)}; + return array_iterator{arr.p, reinterpret_cast(reinterpret_cast(arr.p->entries()) + n)}; } if (n < -l / 2) { @@ -164,7 +136,7 @@ class array_iterator { } } - bucket_type *result = nullptr; + bucket_type* result = nullptr; if (n < 0) { result = arr.p->end(); while (n < 0) { @@ -182,6 +154,6 @@ class array_iterator { } private: - inner_type *self_{nullptr}; - list_hash_type *entry_{nullptr}; + inner_type* self_{nullptr}; + list_hash_type* entry_{nullptr}; }; diff --git a/runtime-common/core/core-types/decl/declarations.h b/runtime-common/core/core-types/decl/declarations.h index 6089d8734d..224009d194 100644 --- a/runtime-common/core/core-types/decl/declarations.h +++ b/runtime-common/core/core-types/decl/declarations.h @@ -6,22 +6,21 @@ struct array_size; -template +template class array; -template +template class class_instance; class mixed; -class Unknown { -}; +class Unknown {}; class string; class string_buffer; -template +template class Optional; struct C$RpcConnection; diff --git a/runtime-common/core/core-types/decl/mixed_decl.inl b/runtime-common/core/core-types/decl/mixed_decl.inl index 26fb3ef24a..851021d614 100644 --- a/runtime-common/core/core-types/decl/mixed_decl.inl +++ b/runtime-common/core/core-types/decl/mixed_decl.inl @@ -12,43 +12,34 @@ #include "runtime-common/core/class-instance/refcountable-php-classes.h" #ifndef INCLUDED_FROM_KPHP_CORE - #error "this file must be included only from runtime-core.h" +#error "this file must be included only from runtime-core.h" #endif -template -struct is_type_acceptable_for_mixed : vk::is_type_in_list { -}; +template +struct is_type_acceptable_for_mixed : vk::is_type_in_list {}; -template -struct is_type_acceptable_for_mixed> : is_constructible_or_unknown { -}; +template +struct is_type_acceptable_for_mixed> : is_constructible_or_unknown {}; -template -struct is_type_acceptable_for_mixed> : std::is_base_of { -}; +template +struct is_type_acceptable_for_mixed> : std::is_base_of {}; -template +template class Materialized final { - using MixRef = Mix &; - std::variant slot_; + using MixRef = Mix&; + std::variant slot_; - Materialized(Mix *ptr) noexcept - : slot_{ptr} {} + Materialized(Mix* ptr) noexcept : slot_{ptr} {} - Materialized(Mix &&value) noexcept - : slot_(std::move(value)) {} + Materialized(Mix&& value) noexcept : slot_(std::move(value)) {} public: - static Materialized WithRef(Mix &ref) noexcept { - return Materialized(&ref); - } + static Materialized WithRef(Mix& ref) noexcept { return Materialized(&ref); } - static Materialized WithValue(Mix &&val) noexcept { - return Materialized(std::move(val)); - } + static Materialized WithValue(Mix&& val) noexcept { return Materialized(std::move(val)); } - template - Materialized operator[](T &&arg) && { + template + Materialized operator[](T&& arg) && { return this->operator MixRef()[std::forward(arg)]; } @@ -56,19 +47,19 @@ public: if (likely(std::holds_alternative(slot_))) { return std::get(slot_); } - return *std::get(slot_); + return *std::get(slot_); } // methods below are used in runtime sources // in codegen Materizalied is casted to mixed& - template - Materialized operator=(T &&arg) && noexcept { + template + Materialized operator=(T&& arg) && noexcept { return Materialized::WithRef(this->operator MixRef() = std::forward(arg)); } - template - void push_back(T &&arg) && { + template + void push_back(T&& arg) && { this->operator MixRef().push_back(std::forward(arg)); } }; @@ -85,68 +76,68 @@ public: OBJECT, }; - mixed(const void *) = delete; // deprecate conversion from pointer to boolean + mixed(const void*) = delete; // deprecate conversion from pointer to boolean mixed() = default; - mixed(const Unknown &u) noexcept; - mixed(const char *s, string::size_type len) noexcept; - mixed(const mixed &v) noexcept; - mixed(mixed &&v) noexcept; - - template>::value>> - mixed(T &&v) noexcept; - template::value>> - mixed(const Optional &v) noexcept; - template::value>> - mixed(Optional &&v) noexcept; - - mixed &operator=(const mixed &other) noexcept; - mixed &operator=(mixed &&other) noexcept; - - template>::value>> - mixed &operator=(T &&v) noexcept; - template::value>> - mixed &operator=(const Optional &v) noexcept; - template::value>> - mixed &operator=(Optional &&v) noexcept; - - mixed &assign(const char *other, string::size_type len); + mixed(const Unknown& u) noexcept; + mixed(const char* s, string::size_type len) noexcept; + mixed(const mixed& v) noexcept; + mixed(mixed&& v) noexcept; + + template >::value>> + mixed(T&& v) noexcept; + template ::value>> + mixed(const Optional& v) noexcept; + template ::value>> + mixed(Optional&& v) noexcept; + + mixed& operator=(const mixed& other) noexcept; + mixed& operator=(mixed&& other) noexcept; + + template >::value>> + mixed& operator=(T&& v) noexcept; + template ::value>> + mixed& operator=(const Optional& v) noexcept; + template ::value>> + mixed& operator=(Optional&& v) noexcept; + + mixed& assign(const char* other, string::size_type len); const mixed operator-() const; const mixed operator+() const; int64_t operator~() const; - mixed &operator+=(const mixed &other); - mixed &operator-=(const mixed &other); - mixed &operator*=(const mixed &other); - mixed &operator/=(const mixed &other); - mixed &operator%=(const mixed &other); + mixed& operator+=(const mixed& other); + mixed& operator-=(const mixed& other); + mixed& operator*=(const mixed& other); + mixed& operator/=(const mixed& other); + mixed& operator%=(const mixed& other); - mixed &operator&=(const mixed &other); - mixed &operator|=(const mixed &other); - mixed &operator^=(const mixed &other); - mixed &operator<<=(const mixed &other); - mixed &operator>>=(const mixed &other); + mixed& operator&=(const mixed& other); + mixed& operator|=(const mixed& other); + mixed& operator^=(const mixed& other); + mixed& operator<<=(const mixed& other); + mixed& operator>>=(const mixed& other); - mixed &operator++(); + mixed& operator++(); const mixed operator++(int); - mixed &operator--(); + mixed& operator--(); const mixed operator--(int); bool operator!() const; - mixed &append(const string &v); - mixed &append(tmp_string v); + mixed& append(const string& v); + mixed& append(tmp_string v); Materialized operator[](int64_t int_key); Materialized operator[](int32_t key) { return (*this)[int64_t{key}]; } - Materialized operator[](const string &string_key); + Materialized operator[](const string& string_key); Materialized operator[](tmp_string string_key); - Materialized operator[](const mixed &v); + Materialized operator[](const mixed& v); Materialized operator[](double double_key); - Materialized operator[](const array::const_iterator &it); - Materialized operator[](const array::iterator &it); + Materialized operator[](const array::const_iterator& it); + Materialized operator[](const array::iterator& it); /* * The `set_value_return()` method is used in assignment chains like `$mix[0] = $mix[1] = foo();`. @@ -156,48 +147,48 @@ public: * Since returning by reference is not supported, we call `offsetSet($offset, $value)` and return `$value`. */ - template - mixed set_value_return(T key, const mixed &val); - mixed set_value_return(const mixed &key, const mixed &val); - mixed set_value_return(const string &key, const mixed &val); - mixed set_value_return(const array::iterator &key, const mixed &val); - mixed set_value_return(const array::const_iterator &key, const mixed &val); - - void set_value(int64_t int_key, const mixed &v); - void set_value(int32_t key, const mixed &value) { set_value(int64_t{key}, value); } - void set_value(const string &string_key, const mixed &v); - void set_value(const string &string_key, const mixed &v, int64_t precomuted_hash); - void set_value(tmp_string string_key, const mixed &v); - void set_value(const mixed &v, const mixed &value); - void set_value(double double_key, const mixed &value); - void set_value(const array::const_iterator &it); - void set_value(const array::iterator &it); + template + mixed set_value_return(T key, const mixed& val); + mixed set_value_return(const mixed& key, const mixed& val); + mixed set_value_return(const string& key, const mixed& val); + mixed set_value_return(const array::iterator& key, const mixed& val); + mixed set_value_return(const array::const_iterator& key, const mixed& val); + + void set_value(int64_t int_key, const mixed& v); + void set_value(int32_t key, const mixed& value) { set_value(int64_t{key}, value); } + void set_value(const string& string_key, const mixed& v); + void set_value(const string& string_key, const mixed& v, int64_t precomuted_hash); + void set_value(tmp_string string_key, const mixed& v); + void set_value(const mixed& v, const mixed& value); + void set_value(double double_key, const mixed& value); + void set_value(const array::const_iterator& it); + void set_value(const array::iterator& it); const mixed get_value(int64_t int_key) const; const mixed get_value(int32_t key) const { return get_value(int64_t{key}); } - const mixed get_value(const string &string_key) const; - const mixed get_value(const string &string_key, int64_t precomuted_hash) const; + const mixed get_value(const string& string_key) const; + const mixed get_value(const string& string_key, int64_t precomuted_hash) const; const mixed get_value(tmp_string string_key) const; - const mixed get_value(const mixed &v) const; + const mixed get_value(const mixed& v) const; const mixed get_value(double double_key) const; - const mixed get_value(const array::const_iterator &it) const; - const mixed get_value(const array::iterator &it) const; + const mixed get_value(const array::const_iterator& it) const; + const mixed get_value(const array::iterator& it) const; - void push_back(const mixed &v); - const mixed push_back_return(const mixed &v); + void push_back(const mixed& v); + const mixed push_back_return(const mixed& v); bool isset(int64_t int_key) const; bool isset(int32_t key) const { return isset(int64_t{key}); } - template - bool isset(const string &string_key, MaybeHash ...maybe_hash) const; - bool isset(const mixed &v) const; + template + bool isset(const string& string_key, MaybeHash... maybe_hash) const; + bool isset(const mixed& v) const; bool isset(double double_key) const; void unset(int64_t int_key); void unset(int32_t key) { unset(int64_t{key}); } - template - void unset(const string &string_key, MaybeHash ...maybe_hash); - void unset(const mixed &v); + template + void unset(const string& string_key, MaybeHash... maybe_hash); + void unset(const mixed& v); void unset(double double_key); void destroy() noexcept; @@ -212,31 +203,34 @@ public: const string to_string() const; const array to_array() const; - bool &as_bool() __attribute__((always_inline)) { return *reinterpret_cast(&storage_); } - const bool &as_bool() const __attribute__((always_inline)) { return *reinterpret_cast(&storage_); } + bool& as_bool() __attribute__((always_inline)) { return *reinterpret_cast(&storage_); } + const bool& as_bool() const __attribute__((always_inline)) { return *reinterpret_cast(&storage_); } - int64_t &as_int() __attribute__((always_inline)) { return *reinterpret_cast(&storage_); } - const int64_t &as_int() const __attribute__((always_inline)) { return *reinterpret_cast(&storage_); } + int64_t& as_int() __attribute__((always_inline)) { return *reinterpret_cast(&storage_); } + const int64_t& as_int() const __attribute__((always_inline)) { return *reinterpret_cast(&storage_); } - double &as_double() __attribute__((always_inline)) { return *reinterpret_cast(&storage_); } - const double &as_double() const __attribute__((always_inline)) { return *reinterpret_cast(&storage_); } + double& as_double() __attribute__((always_inline)) { return *reinterpret_cast(&storage_); } + const double& as_double() const __attribute__((always_inline)) { return *reinterpret_cast(&storage_); } - string &as_string() __attribute__((always_inline)) { return *reinterpret_cast(&storage_); } - const string &as_string() const __attribute__((always_inline)) { return *reinterpret_cast(&storage_); } + string& as_string() __attribute__((always_inline)) { return *reinterpret_cast(&storage_); } + const string& as_string() const __attribute__((always_inline)) { return *reinterpret_cast(&storage_); } - array &as_array() __attribute__((always_inline)) { return *reinterpret_cast *>(&storage_); } - const array &as_array() const __attribute__((always_inline)) { return *reinterpret_cast *>(&storage_); } - - vk::intrusive_ptr as_object() __attribute__((always_inline)) { return *reinterpret_cast*>(&storage_); } - const vk::intrusive_ptr as_object() const __attribute__((always_inline)) { return *reinterpret_cast*>(&storage_); } + array& as_array() __attribute__((always_inline)) { return *reinterpret_cast*>(&storage_); } + const array& as_array() const __attribute__((always_inline)) { return *reinterpret_cast*>(&storage_); } + vk::intrusive_ptr as_object() __attribute__((always_inline)) { + return *reinterpret_cast*>(&storage_); + } + const vk::intrusive_ptr as_object() const __attribute__((always_inline)) { + return *reinterpret_cast*>(&storage_); + } // TODO is it ok to return pointer to mutable from const method? // I need it just to pass such a pointer into class_instance. Mutability is needed because // class_instance do ref-counting template - T *as_object_ptr() const { - auto ptr_to_object = vk::dynamic_pointer_cast(*reinterpret_cast *>(&storage_)); + T* as_object_ptr() const { + auto ptr_to_object = vk::dynamic_pointer_cast(*reinterpret_cast*>(&storage_)); return ptr_to_object.get(); } @@ -258,17 +252,17 @@ public: void convert_to_float(); void convert_to_string(); - const bool &as_bool(const char *function) const; - const int64_t &as_int(const char *function) const; - const double &as_float(const char *function) const; - const string &as_string(const char *function) const; - const array &as_array(const char *function) const; + const bool& as_bool(const char* function) const; + const int64_t& as_int(const char* function) const; + const double& as_float(const char* function) const; + const string& as_string(const char* function) const; + const array& as_array(const char* function) const; - bool &as_bool(const char *function); - int64_t &as_int(const char *function); - double &as_float(const char *function); - string &as_string(const char *function); - array &as_array(const char *function); + bool& as_bool(const char* function); + int64_t& as_int(const char* function); + double& as_float(const char* function); + string& as_string(const char* function); + array& as_array(const char* function); bool is_numeric() const; bool is_scalar() const; @@ -283,21 +277,20 @@ public: inline bool is_object() const; const string get_type_str() const; - const char *get_type_c_str() const; - const char *get_type_or_class_name() const; - + const char* get_type_c_str() const; + const char* get_type_or_class_name() const; - template + template bool empty_at(T key) const; - bool empty_at(const mixed &key) const; - bool empty_at(const string &key) const; - bool empty_at(const string &key, int64_t precomputed_hash) const; - bool empty_at(const array::iterator &key) const; - bool empty_at(const array::const_iterator &key) const; + bool empty_at(const mixed& key) const; + bool empty_at(const string& key) const; + bool empty_at(const string& key, int64_t precomputed_hash) const; + bool empty_at(const array::iterator& key) const; + bool empty_at(const array::const_iterator& key) const; bool empty() const; int64_t count() const; - int64_t compare(const mixed &rhs) const; + int64_t compare(const mixed& rhs) const; array::const_iterator begin() const; array::const_iterator end() const; @@ -305,7 +298,7 @@ public: array::iterator begin(); array::iterator end(); - inline void swap(mixed &other); + inline void swap(mixed& other); int64_t get_reference_counter() const; @@ -318,63 +311,66 @@ public: static inline void reset_empty_values() noexcept; private: - void copy_from(const mixed &other); - void copy_from(mixed &&other); + void copy_from(const mixed& other); + void copy_from(mixed&& other); - template - inline void init_from(T &&v); + template + inline void init_from(T&& v); void init_from(mixed v) { copy_from(std::move(v)); } - template - inline mixed &assign_from(T &&v); - mixed &assign_from(mixed v) { return (*this = std::move(v)); } + template + inline mixed& assign_from(T&& v); + mixed& assign_from(mixed v) { return (*this = std::move(v)); } - template - auto get_type_and_value_ptr(const array &) { return std::make_pair(type::ARRAY , &as_array()); } - auto get_type_and_value_ptr(const bool &) { return std::make_pair(type::BOOLEAN, &as_bool()); } - auto get_type_and_value_ptr(const long &) { return std::make_pair(type::INTEGER, &as_int()); } - auto get_type_and_value_ptr(const long long &) { return std::make_pair(type::INTEGER, &as_int()); } - auto get_type_and_value_ptr(const int &) { return std::make_pair(type::INTEGER, &as_int()); } - auto get_type_and_value_ptr(const double &) { return std::make_pair(type::FLOAT , &as_double()); } - auto get_type_and_value_ptr(const string &) { return std::make_pair(type::STRING , &as_string()); } - template - auto get_type_and_value_ptr(const InstanceClass &) {return std::make_pair(type::OBJECT, as_object_ptr()); } + template + auto get_type_and_value_ptr(const array&) { + return std::make_pair(type::ARRAY, &as_array()); + } + auto get_type_and_value_ptr(const bool&) { return std::make_pair(type::BOOLEAN, &as_bool()); } + auto get_type_and_value_ptr(const long&) { return std::make_pair(type::INTEGER, &as_int()); } + auto get_type_and_value_ptr(const long long&) { return std::make_pair(type::INTEGER, &as_int()); } + auto get_type_and_value_ptr(const int&) { return std::make_pair(type::INTEGER, &as_int()); } + auto get_type_and_value_ptr(const double&) { return std::make_pair(type::FLOAT, &as_double()); } + auto get_type_and_value_ptr(const string&) { return std::make_pair(type::STRING, &as_string()); } + template + auto get_type_and_value_ptr(const InstanceClass&) { + return std::make_pair(type::OBJECT, as_object_ptr()); + } - template - static T &empty_value() noexcept; + template + static T& empty_value() noexcept; type type_{type::NUL}; uint64_t storage_{0}; }; - -mixed operator+(const mixed &lhs, const mixed &rhs); -mixed operator-(const mixed &lhs, const mixed &rhs); -mixed operator*(const mixed &lhs, const mixed &rhs); -mixed operator-(const string &lhs); -mixed operator+(const string &lhs); -int64_t operator&(const mixed &lhs, const mixed &rhs); -int64_t operator|(const mixed &lhs, const mixed &rhs); -int64_t operator^(const mixed &lhs, const mixed &rhs); -int64_t operator<<(const mixed &lhs, const mixed &rhs); -int64_t operator>>(const mixed &lhs, const mixed &rhs); -bool operator<(const mixed &lhs, const mixed &rhs); -bool operator<=(const mixed &lhs, const mixed &rhs); -void swap(mixed &lhs, mixed &rhs); - -string_buffer &operator<<(string_buffer &sb, const mixed &v); +mixed operator+(const mixed& lhs, const mixed& rhs); +mixed operator-(const mixed& lhs, const mixed& rhs); +mixed operator*(const mixed& lhs, const mixed& rhs); +mixed operator-(const string& lhs); +mixed operator+(const string& lhs); +int64_t operator&(const mixed& lhs, const mixed& rhs); +int64_t operator|(const mixed& lhs, const mixed& rhs); +int64_t operator^(const mixed& lhs, const mixed& rhs); +int64_t operator<<(const mixed& lhs, const mixed& rhs); +int64_t operator>>(const mixed& lhs, const mixed& rhs); +bool operator<(const mixed& lhs, const mixed& rhs); +bool operator<=(const mixed& lhs, const mixed& rhs); +void swap(mixed& lhs, mixed& rhs); + +string_buffer& operator<<(string_buffer& sb, const mixed& v); template -bool less_number_string_as_php8_impl(T lhs, const string &rhs); +bool less_number_string_as_php8_impl(T lhs, const string& rhs); template -bool less_string_number_as_php8_impl(const string &lhs, T rhs); +bool less_string_number_as_php8_impl(const string& lhs, T rhs); template -bool less_number_string_as_php8(bool php7_result, T lhs, const string &rhs); +bool less_number_string_as_php8(bool php7_result, T lhs, const string& rhs); template -inline bool less_string_number_as_php8(bool php7_result, const string &lhs, T rhs); +inline bool less_string_number_as_php8(bool php7_result, const string& lhs, T rhs); -template -mixed f$to_mixed(const class_instance &instance) noexcept; -template -ResultClass from_mixed(const mixed &m, const string &) noexcept; -std::optional> try_as_array_access(const mixed &) noexcept; +template +mixed f$to_mixed(const class_instance& instance) noexcept; +template +ResultClass from_mixed(const mixed& m, const string&) noexcept; +std::optional> try_as_array_access(const mixed&) noexcept; diff --git a/runtime-common/core/core-types/decl/optional.h b/runtime-common/core/core-types/decl/optional.h index 5bb88a927c..e30fdfa346 100644 --- a/runtime-common/core/core-types/decl/optional.h +++ b/runtime-common/core/core-types/decl/optional.h @@ -10,79 +10,53 @@ #include "common/type_traits/is_constructible.h" #include "common/type_traits/list_of_types.h" -#include "runtime-common/core/utils/kphp-assert-core.h" #include "runtime-common/core/core-types/decl/declarations.h" +#include "runtime-common/core/utils/kphp-assert-core.h" -template +template class Optional; -template -struct is_optional : std::false_type { -}; +template +struct is_optional : std::false_type {}; -template -struct is_optional> : std::true_type { -}; +template +struct is_optional> : std::true_type {}; +template +struct is_conversion_in_optional_allowed : std::is_constructible {}; -template -struct is_conversion_in_optional_allowed : std::is_constructible { -}; - -template -struct is_conversion_in_optional_allowed : std::true_type { -}; +template +struct is_conversion_in_optional_allowed : std::true_type {}; -enum class OptionalState : uint8_t { - has_value = 0, - false_value = 1, - null_value = 2 -}; +enum class OptionalState : uint8_t { has_value = 0, false_value = 1, null_value = 2 }; -template +template class OptionalBase { public: static_assert(!std::is_same{}, "int is forbidden"); - T &ref() noexcept { + T& ref() noexcept { value_state_ = OptionalState::has_value; return value_; } - T &val() noexcept { - return value_; - } + T& val() noexcept { return value_; } - const T &val() const noexcept { - return value_; - } + const T& val() const noexcept { return value_; } - bool has_value() const noexcept { - return value_state_ == OptionalState::has_value; - } + bool has_value() const noexcept { return value_state_ == OptionalState::has_value; } - bool is_null() const noexcept { - return value_state_ == OptionalState::null_value; - } + bool is_null() const noexcept { return value_state_ == OptionalState::null_value; } - bool is_false() const noexcept { - return value_state_ == OptionalState::false_value; - } + bool is_false() const noexcept { return value_state_ == OptionalState::false_value; } - OptionalState value_state() const noexcept { - return value_state_; - } + OptionalState value_state() const noexcept { return value_state_; } protected: - template - OptionalBase(T1 &&value, OptionalState value_state) noexcept : - value_(std::forward(value)), - value_state_(value_state) { - } + template + OptionalBase(T1&& value, OptionalState value_state) noexcept : value_(std::forward(value)), value_state_(value_state) {} - explicit OptionalBase(OptionalState value_state) noexcept : - value_state_(value_state) { - } + explicit OptionalBase(OptionalState value_state) noexcept : value_state_(value_state) {} OptionalBase() = default; ~OptionalBase() = default; @@ -91,10 +65,10 @@ class OptionalBase { OptionalState value_state_{OptionalState::null_value}; }; -template +template class Optional : public OptionalBase { private: - template + template using enable_if_allowed = std::enable_if_t{}>; static_assert(!std::is_same{}, "Usage Optional is forbidden"); @@ -107,71 +81,56 @@ class Optional : public OptionalBase { Optional() = default; - Optional(bool value) noexcept : - Optional(value, OptionalState::false_value) { - } + Optional(bool value) noexcept : Optional(value, OptionalState::false_value) {} - template> - Optional(T1 &&value) noexcept : - Optional(std::forward(value), OptionalState::has_value) { - } + template > + Optional(T1&& value) noexcept : Optional(std::forward(value), OptionalState::has_value) {} - template> - Optional(const Optional &other) noexcept : - Optional(other.val(), other.value_state()) { - } + template > + Optional(const Optional& other) noexcept : Optional(other.val(), other.value_state()) {} - template> - Optional(Optional &&other) noexcept : - Optional(std::move(other.val()), other.value_state()) { - } + template > + Optional(Optional&& other) noexcept : Optional(std::move(other.val()), other.value_state()) {} - Optional &operator=(bool x) noexcept { - return assign(x, OptionalState::false_value); - } + Optional& operator=(bool x) noexcept { return assign(x, OptionalState::false_value); } - template> - Optional &operator=(const Optional &other) noexcept { + template > + Optional& operator=(const Optional& other) noexcept { return assign(other.val(), other.value_state()); } - template> - Optional &operator=(Optional &&other) noexcept { + template > + Optional& operator=(Optional&& other) noexcept { return assign(std::move(other.val()), other.value_state()); } - template> - Optional &operator=(T1 &&value) noexcept { + template > + Optional& operator=(T1&& value) noexcept { return assign(std::forward(value), OptionalState::has_value); } private: - Optional(bool value, OptionalState value_state) noexcept : - Base(value_state) { - php_assert(!value); - } + Optional(bool value, OptionalState value_state) noexcept : Base(value_state) { php_assert(!value); } - template> - Optional(T1 &&value, OptionalState value_state) noexcept : - Base(std::forward(value), value_state) { - } + template > + Optional(T1&& value, OptionalState value_state) noexcept : Base(std::forward(value), value_state) {} - Optional &assign(bool value, OptionalState value_state) noexcept { + Optional& assign(bool value, OptionalState value_state) noexcept { php_assert(!value); Base::value_ = T(); Base::value_state_ = value_state; return *this; } - template> - Optional &assign(T1 &&value, OptionalState value_state) noexcept { + template > + Optional& assign(T1&& value, OptionalState value_state) noexcept { Base::value_ = std::forward(value); Base::value_state_ = value_state; return *this; } }; -template<> +template <> class Optional : public OptionalBase { private: using Base = OptionalBase; @@ -181,38 +140,36 @@ class Optional : public OptionalBase { Optional() = default; - Optional(bool value) noexcept: - Base(value, value ? OptionalState::has_value : OptionalState::false_value) { - } + Optional(bool value) noexcept : Base(value, value ? OptionalState::has_value : OptionalState::false_value) {} - Optional &operator=(bool value) noexcept { + Optional& operator=(bool value) noexcept { Base::value_ = value; Base::value_state_ = value ? OptionalState::has_value : OptionalState::false_value; return *this; } }; -template +template using enable_if_t_is_optional = std::enable_if_t>::value, ResT>; -template +template using enable_if_t_is_not_optional = std::enable_if_t>{}, ResT>; -template +template using enable_if_t_is_optional_t2 = std::enable_if_t>::value>; -template +template using enable_if_t_is_optional_string = enable_if_t_is_optional_t2; -template +template struct InternalOptionalType { using type = T; }; -template +template struct InternalOptionalType> { using type = T; }; -template +template using internal_optional_type_t = typename InternalOptionalType::type; diff --git a/runtime-common/core/core-types/decl/shape.h b/runtime-common/core/core-types/decl/shape.h index 094d77c879..ceaad2803b 100644 --- a/runtime-common/core/core-types/decl/shape.h +++ b/runtime-common/core/core-types/decl/shape.h @@ -11,107 +11,111 @@ #include "common/algorithms/find.h" -template +template class shape_node { public: static_assert(!std::is_same{}, "int is forbidden"); T value{}; shape_node() = default; - shape_node(const shape_node &) = default; - shape_node(shape_node &&) noexcept = default; - shape_node &operator=(const shape_node &) = default; - shape_node &operator=(shape_node &&) noexcept = default; - - template> - explicit shape_node(T1 value) : - value(std::move(value)) {} + shape_node(const shape_node&) = default; + shape_node(shape_node&&) noexcept = default; + shape_node& operator=(const shape_node&) = default; + shape_node& operator=(shape_node&&) noexcept = default; + + template > + explicit shape_node(T1 value) : value(std::move(value)) {} }; -template +template class shape { static_assert(std::is_same{}, "Bad one mapped"); }; struct shape_variadic_constructor_stub {}; -template -class shape, T...> : public shape_node ... { - template - static decltype(auto) get_node_impl(shape_node *t) { return *t; } - template - static decltype(auto) get_node_impl(const shape_node *t) { return *t; } - template - decltype(auto) get_node() { return get_node_impl(this); } - template - decltype(auto) get_node() const { return get_node_impl(this); } - - template - void set(const shape_node &other) { +template +class shape, T...> : public shape_node... { + template + static decltype(auto) get_node_impl(shape_node* t) { + return *t; + } + template + static decltype(auto) get_node_impl(const shape_node* t) { + return *t; + } + template + decltype(auto) get_node() { + return get_node_impl(this); + } + template + decltype(auto) get_node() const { + return get_node_impl(this); + } + + template + void set(const shape_node& other) { get_node().value = other.value; } - template - void set(shape_node &&other) { + template + void set(shape_node&& other) { get_node().value = std::move(other.value); } - template + template class is_constructible_helper; - template - class is_constructible_helper : public std::integral_constant{}...)> { - }; + template + class is_constructible_helper : public std::integral_constant{}...)> {}; - template - class is_constructible_helper : public std::false_type { - }; + template + class is_constructible_helper : public std::false_type {}; - template - class is_constructible : public is_constructible_helper { - }; + template + class is_constructible : public is_constructible_helper {}; - template + template using enable_if_sequence_is_subset = std::enable_if_t; public: + template {}>> + explicit shape(shape_variadic_constructor_stub, Args&&... args) : shape_node(std::forward(args))... {} - template{}>> - explicit shape(shape_variadic_constructor_stub, Args &&...args) : - shape_node(std::forward(args))... {} - - template - auto &get() { return get_node().value; } - template - const auto &get() const { return get_node().value; } + template + auto& get() { + return get_node().value; + } + template + const auto& get() const { + return get_node().value; + } shape() = default; - shape(const shape &) = default; - shape(shape &&) noexcept = default; - shape &operator=(const shape &) = default; - shape &operator=(shape &&) noexcept = default; + shape(const shape&) = default; + shape(shape&&) noexcept = default; + shape& operator=(const shape&) = default; + shape& operator=(shape&&) noexcept = default; // TODO: not SFINAE-friendly - template> - explicit shape(shape, T2...> &&other) noexcept : - shape_node()... { + template > + explicit shape(shape, T2...>&& other) noexcept : shape_node()... { (set(std::forward>(other)), ...); } - template> - shape(const shape, T2...> &other) noexcept : - shape_node()... { - (set(static_cast &>(other)), ...); + template > + shape(const shape, T2...>& other) noexcept : shape_node()... { + (set(static_cast&>(other)), ...); } - template> - shape &operator=(shape, T2...> other) { + template > + shape& operator=(shape, T2...> other) { shape nv(std::move(other)); std::swap(nv, *this); return *this; } }; -template -inline bool f$boolval(const shape, T...> &) { +template +inline bool f$boolval(const shape, T...>&) { return true; } diff --git a/runtime-common/core/core-types/decl/string_buffer_decl.inl b/runtime-common/core/core-types/decl/string_buffer_decl.inl index 5a589162e2..2c7ca1e66c 100644 --- a/runtime-common/core/core-types/decl/string_buffer_decl.inl +++ b/runtime-common/core/core-types/decl/string_buffer_decl.inl @@ -1,7 +1,7 @@ #pragma once #ifndef INCLUDED_FROM_KPHP_CORE - #error "this file must be included only from runtime-core.h" +#error "this file must be included only from runtime-core.h" #endif #define STRING_BUFFER_ERROR_FLAG_ON -1 @@ -9,44 +9,44 @@ #define STRING_BUFFER_ERROR_FLAG_FAILED 1 class string_buffer { - char *buffer_end; - char *buffer_begin; + char* buffer_end; + char* buffer_begin; string::size_type buffer_len; inline void resize(string::size_type new_buffer_len) noexcept; inline void reserve_at_least(string::size_type new_buffer_len) noexcept; - string_buffer(const string_buffer &other) = delete; - string_buffer &operator=(const string_buffer &other) = delete; + string_buffer(const string_buffer& other) = delete; + string_buffer& operator=(const string_buffer& other) = delete; public: explicit string_buffer(string::size_type buffer_len = 4000) noexcept; - inline string_buffer &clean() noexcept; + inline string_buffer& clean() noexcept; - friend inline string_buffer &operator<<(string_buffer &sb, char c); - friend inline string_buffer &operator<<(string_buffer &sb, const char *s); - friend inline string_buffer &operator<<(string_buffer &sb, double f); - friend inline string_buffer &operator<<(string_buffer &sb, const string &s); - friend inline string_buffer &operator<<(string_buffer &sb, bool x); - friend inline string_buffer &operator<<(string_buffer &sb, int32_t x); - friend inline string_buffer &operator<<(string_buffer &sb, uint32_t x); - friend inline string_buffer &operator<<(string_buffer &sb, int64_t x); + friend inline string_buffer& operator<<(string_buffer& sb, char c); + friend inline string_buffer& operator<<(string_buffer& sb, const char* s); + friend inline string_buffer& operator<<(string_buffer& sb, double f); + friend inline string_buffer& operator<<(string_buffer& sb, const string& s); + friend inline string_buffer& operator<<(string_buffer& sb, bool x); + friend inline string_buffer& operator<<(string_buffer& sb, int32_t x); + friend inline string_buffer& operator<<(string_buffer& sb, uint32_t x); + friend inline string_buffer& operator<<(string_buffer& sb, int64_t x); - inline string_buffer &append(const char *str, size_t len) noexcept; - inline void write(const char *str, int len) noexcept; + inline string_buffer& append(const char* str, size_t len) noexcept; + inline void write(const char* str, int len) noexcept; - inline void append_unsafe(const char *str, int len); + inline void append_unsafe(const char* str, int len); - inline void append_char(char c) __attribute__ ((always_inline));//unsafe + inline void append_char(char c) __attribute__((always_inline)); // unsafe inline void reserve(int len); inline string::size_type size() const noexcept; - inline char *buffer(); - inline const char *buffer() const; + inline char* buffer(); + inline const char* buffer() const; - inline const char *c_str(); + inline const char* c_str(); inline string str() const; inline bool set_pos(int64_t pos); @@ -57,13 +57,12 @@ public: inline void debug_print() const; - inline void copy_raw_data(const string_buffer &other); + inline void copy_raw_data(const string_buffer& other); - friend inline bool operator==(const string_buffer &lhs, const string_buffer &rhs); - friend inline bool operator!=(const string_buffer &lhs, const string_buffer &rhs); + friend inline bool operator==(const string_buffer& lhs, const string_buffer& rhs); + friend inline bool operator!=(const string_buffer& lhs, const string_buffer& rhs); }; - struct string_buffer_lib_context { string::size_type MIN_BUFFER_LEN = 266175; string::size_type MAX_BUFFER_LEN = (1 << 24); diff --git a/runtime-common/core/core-types/decl/string_decl.inl b/runtime-common/core/core-types/decl/string_decl.inl index 5a2bb01d40..09b2e3e295 100644 --- a/runtime-common/core/core-types/decl/string_decl.inl +++ b/runtime-common/core/core-types/decl/string_decl.inl @@ -1,14 +1,12 @@ #pragma once #ifndef INCLUDED_FROM_KPHP_CORE - #error "this file must be included only from runtime-core.h" +#error "this file must be included only from runtime-core.h" #endif using string_size_type = uint32_t; -inline bool string_to_bool(const char *s, string_size_type size) { - return size >= 2 || (size == 1 && s[0] != '0'); -} +inline bool string_to_bool(const char* s, string_size_type size) { return size >= 2 || (size == 1 && s[0] != '0'); } // tmp_string is not a real string: it can't be used in a place where string types are expected; // it can be a result of compiler-inserted evaluation that should be then recognized by the @@ -16,16 +14,14 @@ inline bool string_to_bool(const char *s, string_size_type size) { // // in a sense, it's like a string view, but only valid for a single expression evaluation struct tmp_string { - const char *data = nullptr; + const char* data = nullptr; string_size_type size = 0; tmp_string() = default; - inline tmp_string(const char *data, string_size_type size); - explicit inline tmp_string(const string &s); + inline tmp_string(const char* data, string_size_type size); + explicit inline tmp_string(const string& s); - bool to_bool() const noexcept { - return data && string_to_bool(data, size); - } + bool to_bool() const noexcept { return data && string_to_bool(data, size); } bool has_value() const noexcept { return data != nullptr; } bool empty() const noexcept { return size == 0; } @@ -39,7 +35,7 @@ public: static constexpr size_type npos = (size_type)-1; private: - char *p; + char* p; private: struct string_inner { @@ -50,12 +46,12 @@ private: inline bool is_shared() const; inline void set_length_and_sharable(size_type n); - inline char *ref_data() const; + inline char* ref_data() const; inline static size_type new_capacity(size_type requested_capacity, size_type old_capacity); - inline static string_inner *create(size_type requested_capacity, size_type old_capacity); + inline static string_inner* create(size_type requested_capacity, size_type old_capacity); - inline char *reserve(size_type requested_capacity); + inline char* reserve(size_type requested_capacity); inline void dispose(); @@ -63,48 +59,46 @@ private: inline size_type get_memory_usage() const; - inline char *ref_copy(); + inline char* ref_copy(); - inline char *clone(size_type requested_cap); + inline char* clone(size_type requested_cap); }; - inline string_inner *inner() const; + inline string_inner* inner() const; - inline bool disjunct(const char *s) const; + inline bool disjunct(const char* s) const; inline void set_size(size_type new_size); - inline static char *create(const char *beg, const char *end); + inline static char* create(const char* beg, const char* end); // IMPORTANT: this function may return read-only strings for n == 0 and n == 1. // Use it unless you have to manually write something into the buffer. - inline static char *create(size_type req, char c); - inline static char *create(size_type req, bool b); + inline static char* create(size_type req, char c); + inline static char* create(size_type req, bool b); friend class string_cache; public: - static constexpr size_type max_size() noexcept { - return ((size_type)-1 - sizeof(string_inner) - 1) / 4; - } + static constexpr size_type max_size() noexcept { return ((size_type)-1 - sizeof(string_inner) - 1) / 4; } static size_type unsafe_cast_to_size_type(int64_t size) noexcept { php_assert(size >= 0); if (unlikely(size > max_size())) { - php_critical_error ("Trying to make too big string of size %" PRId64, size); + php_critical_error("Trying to make too big string of size %" PRId64, size); } return static_cast(size); } inline string(); - inline string(const string &str) noexcept; - inline string(string &&str) noexcept; - inline string(const char *s, size_type n); - inline explicit string(const char *s); + inline string(const string& str) noexcept; + inline string(string&& str) noexcept; + inline string(const char* s, size_type n); + inline explicit string(const char* s); // IMPORTANT: this constructor may return read-only strings for n == 0 and n == 1. // Use it unless you have to manually operate with string's internal buffer. inline string(size_type n, char c); inline string(size_type n, bool b); inline explicit string(int64_t i); - inline explicit string(int32_t i): string(static_cast(i)) {} + inline explicit string(int32_t i) : string(static_cast(i)) {} inline explicit string(double f); ~string() noexcept; @@ -115,8 +109,8 @@ public: inline explicit string(ArrayBucketDummyStrTag) noexcept; inline bool is_dummy_string() const noexcept; - inline string &operator=(const string &str) noexcept; - inline string &operator=(string &&str) noexcept; + inline string& operator=(const string& str) noexcept; + inline string& operator=(string&& str) noexcept; inline size_type size() const; @@ -129,80 +123,80 @@ public: inline string copy_and_make_not_shared() const; inline void force_reserve(size_type res); - inline string &reserve_at_least(size_type res); + inline string& reserve_at_least(size_type res); inline bool empty() const; - inline bool starts_with(const string &other) const noexcept; - inline bool ends_with(const string &other) const noexcept; - - inline const char &operator[](size_type pos) const; - inline char &operator[](size_type pos); - - inline string &append(const string &str) __attribute__ ((always_inline)); - inline string &append(const string &str, size_type pos2, size_type n2) __attribute__ ((always_inline)); - inline string &append(const char *s) __attribute__ ((always_inline)); - inline string &append(const char *s, size_type n) __attribute__ ((always_inline)); - inline string &append(size_type n, char c) __attribute__ ((always_inline)); - - inline string &append(bool b) __attribute__ ((always_inline)); - inline string &append(int64_t i) __attribute__ ((always_inline)); - inline string &append(int32_t v) {return append(int64_t{v});} - inline string &append(double d) __attribute__ ((always_inline)); - inline string &append(const mixed &v) __attribute__ ((always_inline)); - - inline string &append_unsafe(bool b) __attribute__((always_inline)); - inline string &append_unsafe(int64_t i) __attribute__((always_inline)); - inline string &append_unsafe(int32_t v) {return append(int64_t{v});} - inline string &append_unsafe(double d) __attribute__((always_inline)); - inline string &append_unsafe(const string &str) __attribute__((always_inline)); - inline string &append_unsafe(tmp_string str) __attribute__((always_inline)); - inline string &append_unsafe(const char *s, size_type n) __attribute__((always_inline)); - inline string &append_unsafe(const mixed &v) __attribute__((always_inline)); - inline string &finish_append() __attribute__((always_inline)); - - template - inline string &append_unsafe(const array &a) __attribute__((always_inline)); - - template - inline string &append_unsafe(const Optional &v) __attribute__((always_inline)); + inline bool starts_with(const string& other) const noexcept; + inline bool ends_with(const string& other) const noexcept; + + inline const char& operator[](size_type pos) const; + inline char& operator[](size_type pos); + + inline string& append(const string& str) __attribute__((always_inline)); + inline string& append(const string& str, size_type pos2, size_type n2) __attribute__((always_inline)); + inline string& append(const char* s) __attribute__((always_inline)); + inline string& append(const char* s, size_type n) __attribute__((always_inline)); + inline string& append(size_type n, char c) __attribute__((always_inline)); + + inline string& append(bool b) __attribute__((always_inline)); + inline string& append(int64_t i) __attribute__((always_inline)); + inline string& append(int32_t v) { return append(int64_t{v}); } + inline string& append(double d) __attribute__((always_inline)); + inline string& append(const mixed& v) __attribute__((always_inline)); + + inline string& append_unsafe(bool b) __attribute__((always_inline)); + inline string& append_unsafe(int64_t i) __attribute__((always_inline)); + inline string& append_unsafe(int32_t v) { return append(int64_t{v}); } + inline string& append_unsafe(double d) __attribute__((always_inline)); + inline string& append_unsafe(const string& str) __attribute__((always_inline)); + inline string& append_unsafe(tmp_string str) __attribute__((always_inline)); + inline string& append_unsafe(const char* s, size_type n) __attribute__((always_inline)); + inline string& append_unsafe(const mixed& v) __attribute__((always_inline)); + inline string& finish_append() __attribute__((always_inline)); + + template + inline string& append_unsafe(const array& a) __attribute__((always_inline)); + + template + inline string& append_unsafe(const Optional& v) __attribute__((always_inline)); inline void push_back(char c); - inline string &assign(const string &str); - inline string &assign(const string &str, size_type pos, size_type n); - inline string &assign(const char *s); - inline string &assign(const char *s, size_type n); - inline string &assign(size_type n, char c); - inline string &assign(size_type n, bool b);//do not initialize. if b == true - just reserve + inline string& assign(const string& str); + inline string& assign(const string& str, size_type pos, size_type n); + inline string& assign(const char* s); + inline string& assign(const char* s, size_type n); + inline string& assign(size_type n, char c); + inline string& assign(size_type n, bool b); // do not initialize. if b == true - just reserve - //assign binary string_inner representation - //can be used only on empty string to receive logically const string - inline void assign_raw(const char *s); + // assign binary string_inner representation + // can be used only on empty string to receive logically const string + inline void assign_raw(const char* s); - inline void swap(string &s); + inline void swap(string& s); - inline char *buffer(); - inline const char *c_str() const; + inline char* buffer(); + inline const char* c_str() const; inline string substr(size_type pos, size_type n) const; - inline size_type find_first_of(const string &s, size_type pos = 0) const; - inline size_type find(const string &s, size_type pos = 0) const; + inline size_type find_first_of(const string& s, size_type pos = 0) const; + inline size_type find(const string& s, size_type pos = 0) const; inline void warn_on_float_conversion() const; - inline bool try_to_int(int64_t *val) const; - inline bool try_to_float(double *val, bool php8_warning = true) const; - inline bool try_to_float_as_php7(double *val) const; - inline bool try_to_float_as_php8(double *val) const; + inline bool try_to_int(int64_t* val) const; + inline bool try_to_float(double* val, bool php8_warning = true) const; + inline bool try_to_float_as_php7(double* val) const; + inline bool try_to_float_as_php8(double* val) const; inline mixed to_numeric() const; inline bool to_bool() const; - inline static int64_t to_int(const char *s, size_type l); + inline static int64_t to_int(const char* s, size_type l); inline int64_t to_int(int64_t start, int64_t l) const; inline int64_t to_int() const; inline double to_float() const; - inline const string &to_string() const; + inline const string& to_string() const; inline int64_t safe_to_int() const; @@ -213,8 +207,8 @@ public: inline int64_t hash() const; - static inline int64_t compare(const string &str, const char *other, size_type other_size); - inline int64_t compare(const string &str) const; + static inline int64_t compare(const string& str, const char* other, size_type other_size); + inline int64_t compare(const string& str) const; inline bool isset(int64_t index) const; static inline int64_t get_correct_offset(size_type size, int64_t offset); @@ -222,8 +216,8 @@ public: inline int64_t get_correct_offset(int64_t offset) const; inline int64_t get_correct_offset_clamped(int64_t offset) const; inline const string get_value(int64_t int_key) const; - inline const string get_value(const string &string_key) const; - inline const string get_value(const mixed &v) const; + inline const string get_value(const string& string_key) const; + inline const string get_value(const mixed& v) const; inline int64_t get_reference_counter() const; @@ -235,7 +229,7 @@ public: inline static size_type estimate_memory_usage(size_t len) noexcept; inline static constexpr size_t inner_sizeof() noexcept { return sizeof(string_inner); } - inline static string make_const_string_on_memory(const char *str, size_type len, void *memory, size_t memory_size); + inline static string make_const_string_on_memory(const char* str, size_type len, void* memory, size_t memory_size); inline void destroy() __attribute__((always_inline)); }; @@ -247,35 +241,34 @@ inline string materialize_tmp_string(tmp_string s) { return string{s.data, s.size}; } -inline bool operator==(const string &lhs, const string &rhs); +inline bool operator==(const string& lhs, const string& rhs); -#define CONST_STRING(const_str) string (const_str, sizeof (const_str) - 1) -#define STRING_EQUALS(str, const_str) (str.size() + 1 == sizeof (const_str) && !strcmp (str.c_str(), const_str)) +#define CONST_STRING(const_str) string(const_str, sizeof(const_str) - 1) +#define STRING_EQUALS(str, const_str) (str.size() + 1 == sizeof(const_str) && !strcmp(str.c_str(), const_str)) -inline bool operator!=(const string &lhs, const string &rhs); +inline bool operator!=(const string& lhs, const string& rhs); inline bool is_ok_float(double v); -inline int64_t compare_strings_php_order(const string &lhs, const string &rhs); - -inline void swap(string &lhs, string &rhs); +inline int64_t compare_strings_php_order(const string& lhs, const string& rhs); +inline void swap(string& lhs, string& rhs); inline string::size_type max_string_size(bool) __attribute__((always_inline)); inline string::size_type max_string_size(int64_t) __attribute__((always_inline)); inline string::size_type max_string_size(int32_t) __attribute__((always_inline)); inline string::size_type max_string_size(double) __attribute__((always_inline)); -inline string::size_type max_string_size(const string &s) __attribute__((always_inline)); +inline string::size_type max_string_size(const string& s) __attribute__((always_inline)); inline string::size_type max_string_size(tmp_string s) __attribute__((always_inline)); -inline string::size_type max_string_size(const mixed &v) __attribute__((always_inline)); +inline string::size_type max_string_size(const mixed& v) __attribute__((always_inline)); -template -inline string::size_type max_string_size(const array &) __attribute__((always_inline)); +template +inline string::size_type max_string_size(const array&) __attribute__((always_inline)); -template -inline string::size_type max_string_size(const Optional &v) __attribute__((always_inline)); +template +inline string::size_type max_string_size(const Optional& v) __attribute__((always_inline)); -inline bool wrap_substr_args(string::size_type str_len, int64_t &start, int64_t &length) { +inline bool wrap_substr_args(string::size_type str_len, int64_t& start, int64_t& length) { if (length < 0 && -length > str_len) { return false; } diff --git a/runtime-common/core/core-types/definition/array.inl b/runtime-common/core/core-types/definition/array.inl index 7bae3dbc9e..d7fb107aa0 100644 --- a/runtime-common/core/core-types/definition/array.inl +++ b/runtime-common/core/core-types/definition/array.inl @@ -9,25 +9,21 @@ #include "common/algorithms/fastmod.h" #ifndef INCLUDED_FROM_KPHP_CORE - #error "this file must be included only from runtime-core.h" +#error "this file must be included only from runtime-core.h" #endif -array_size::array_size(int64_t int_size, bool is_vector) noexcept - : size(int_size) - , is_vector(is_vector) {} +array_size::array_size(int64_t int_size, bool is_vector) noexcept : size(int_size), is_vector(is_vector) {} -array_size array_size::operator+(const array_size &other) const noexcept { - return {size + other.size, is_vector && other.is_vector}; -} +array_size array_size::operator+(const array_size& other) const noexcept { return {size + other.size, is_vector && other.is_vector}; } -array_size &array_size::cut(int64_t length) noexcept { +array_size& array_size::cut(int64_t length) noexcept { if (size > length) { size = length; } return *this; } -array_size &array_size::min(const array_size &other) noexcept { +array_size& array_size::min(const array_size& other) noexcept { if (size > other.size) { size = other.size; } @@ -38,17 +34,17 @@ array_size &array_size::min(const array_size &other) noexcept { namespace dl { -template -void sort(T *begin_init, T *end_init, const T1 &compare) { - T *begin_stack[32]; - T *end_stack[32]; +template +void sort(T* begin_init, T* end_init, const T1& compare) { + T* begin_stack[32]; + T* end_stack[32]; begin_stack[0] = begin_init; end_stack[0] = end_init - 1; for (int depth = 0; depth >= 0; --depth) { - T *begin = begin_stack[depth]; - T *end = end_stack[depth]; + T* begin = begin_stack[depth]; + T* end = end_stack[depth]; while (begin < end) { const auto offset = (end - begin) >> 1; @@ -93,147 +89,144 @@ void sort(T *begin_init, T *end_init, const T1 &compare) { } // namespace dl -template +template typename array::key_type array::array_bucket::get_key() const { return string_key.is_dummy_string() ? key_type{int_key} : key_type{string_key}; } -template -bool array::is_int_key(const typename array::key_type &key) { +template +bool array::is_int_key(const typename array::key_type& key) { return key.is_int(); } -template<> -inline typename array::array_inner *array::array_inner::empty_array() { +template <> +inline typename array::array_inner* array::array_inner::empty_array() { // need this hack because gcc10 and newer complains about // "array subscript is outside array bounds of array::array_inner" static array_inner_control empty_array[1]{{ - true, ExtraRefCnt::for_global_const, - -1, - {0, 0}, - 0, - 2, + true, + ExtraRefCnt::for_global_const, + -1, + {0, 0}, + 0, + 2, }}; - return static_cast::array_inner *>(&empty_array[0]); + return static_cast::array_inner*>(&empty_array[0]); } -template -typename array::array_inner *array::array_inner::empty_array() { - return reinterpret_cast(array::array_inner::empty_array()); +template +typename array::array_inner* array::array_inner::empty_array() { + return reinterpret_cast(array::array_inner::empty_array()); } -template +template uint32_t array::array_inner::choose_bucket(int64_t key) const noexcept { return choose_bucket(fields_for_map(), key); } -template -uint32_t array::array_inner::choose_bucket(const array_inner_fields_for_map &fields, int64_t key) const noexcept { +template +uint32_t array::array_inner::choose_bucket(const array_inner_fields_for_map& fields, int64_t key) const noexcept { return fastmod::fastmod_u32(static_cast(key << 2), fields.modulo_helper_buf_size, buf_size); } -template +template bool array::array_inner::is_vector() const noexcept { return is_vector_internal; } -template -typename array::array_bucket *array::array_inner::entries() noexcept { - return reinterpret_cast(reinterpret_cast(this) + ENTRIES_OFFSET); +template +typename array::array_bucket* array::array_inner::entries() noexcept { + return reinterpret_cast(reinterpret_cast(this) + ENTRIES_OFFSET); } -template -const typename array::array_bucket *array::array_inner::entries() const noexcept { - return reinterpret_cast(reinterpret_cast(this) + ENTRIES_OFFSET); +template +const typename array::array_bucket* array::array_inner::entries() const noexcept { + return reinterpret_cast(reinterpret_cast(this) + ENTRIES_OFFSET); } -template -typename array::list_hash_entry *array::array_inner::get_entry(entry_pointer_type pointer) const { - return (list_hash_entry * )((char *)this + pointer); -// return pointer; +template +typename array::list_hash_entry* array::array_inner::get_entry(entry_pointer_type pointer) const { + return (list_hash_entry*)((char*)this + pointer); + // return pointer; } -template -typename array::entry_pointer_type array::array_inner::get_pointer(list_hash_entry *entry) const { - return (entry_pointer_type)((char *)entry - (char *)this); -// return entry; +template +typename array::entry_pointer_type array::array_inner::get_pointer(list_hash_entry* entry) const { + return (entry_pointer_type)((char*)entry - (char*)this); + // return entry; } - -template -const typename array::array_bucket *array::array_inner::begin() const { - return (const array_bucket *)get_entry(last.next); +template +const typename array::array_bucket* array::array_inner::begin() const { + return (const array_bucket*)get_entry(last.next); } -template -const typename array::array_bucket *array::array_inner::next(const array_bucket *ptr) const { - return (const array_bucket *)get_entry(ptr->next); +template +const typename array::array_bucket* array::array_inner::next(const array_bucket* ptr) const { + return (const array_bucket*)get_entry(ptr->next); } -template -const typename array::array_bucket *array::array_inner::prev(const array_bucket *ptr) const { - return (const array_bucket *)get_entry(ptr->prev); +template +const typename array::array_bucket* array::array_inner::prev(const array_bucket* ptr) const { + return (const array_bucket*)get_entry(ptr->prev); } -template -const typename array::array_bucket *array::array_inner::end() const { - return const_cast::array_inner *>(this)->end(); +template +const typename array::array_bucket* array::array_inner::end() const { + return const_cast::array_inner*>(this)->end(); } -template -typename array::array_bucket *array::array_inner::begin() { - return (array_bucket *)get_entry(end()->next); +template +typename array::array_bucket* array::array_inner::begin() { + return (array_bucket*)get_entry(end()->next); } -template -typename array::array_bucket *array::array_inner::next(array_bucket *ptr) { - return (array_bucket *)get_entry(ptr->next); +template +typename array::array_bucket* array::array_inner::next(array_bucket* ptr) { + return (array_bucket*)get_entry(ptr->next); } -template -typename array::array_bucket *array::array_inner::prev(array_bucket *ptr) { - return (array_bucket *)get_entry(ptr->prev); +template +typename array::array_bucket* array::array_inner::prev(array_bucket* ptr) { + return (array_bucket*)get_entry(ptr->prev); } -template -typename array::array_bucket *array::array_inner::end() { - return (array_bucket * ) &last; +template +typename array::array_bucket* array::array_inner::end() { + return (array_bucket*)&last; } -template -bool array::array_inner::is_string_hash_entry(const array_bucket *ptr) const { +template +bool array::array_inner::is_string_hash_entry(const array_bucket* ptr) const { return !ptr->string_key.is_dummy_string(); } -template -typename array::array_inner_fields_for_map &array::array_inner::fields_for_map() { - return *reinterpret_cast(reinterpret_cast(this) - sizeof(array_inner_fields_for_map)); +template +typename array::array_inner_fields_for_map& array::array_inner::fields_for_map() { + return *reinterpret_cast(reinterpret_cast(this) - sizeof(array_inner_fields_for_map)); } -template -const typename array::array_inner_fields_for_map &array::array_inner::fields_for_map() const { - return const_cast(this)->fields_for_map(); +template +const typename array::array_inner_fields_for_map& array::array_inner::fields_for_map() const { + return const_cast(this)->fields_for_map(); } -template +template size_t array::array_inner::sizeof_vector(uint32_t int_size) noexcept { - return sizeof(array_inner) - + int_size * sizeof(T); + return sizeof(array_inner) + int_size * sizeof(T); } -template +template size_t array::array_inner::sizeof_map(uint32_t int_size) noexcept { - return sizeof(array_inner_fields_for_map) - + sizeof(array_inner) - + int_size * sizeof(array_bucket); + return sizeof(array_inner_fields_for_map) + sizeof(array_inner) + int_size * sizeof(array_bucket); } -template -size_t array::array_inner::estimate_size(int64_t &new_int_size, bool is_vector) { +template +size_t array::array_inner::estimate_size(int64_t& new_int_size, bool is_vector) { new_int_size = std::max(new_int_size, int64_t{0}); if (new_int_size > MAX_HASHTABLE_SIZE) { - php_critical_error ("max array size exceeded: int_size = %" PRIi64, new_int_size); + php_critical_error("max array size exceeded: int_size = %" PRIi64, new_int_size); } if (is_vector) { @@ -249,11 +242,11 @@ size_t array::array_inner::estimate_size(int64_t &new_int_size, bool is_vecto return sizeof_map(static_cast(new_int_size)); } -template -typename array::array_inner *array::array_inner::create(int64_t new_int_size, bool is_vector) { +template +typename array::array_inner* array::array_inner::create(int64_t new_int_size, bool is_vector) { const size_t mem_size = estimate_size(new_int_size, is_vector); if (is_vector) { - auto p = reinterpret_cast(RuntimeAllocator::get().alloc_script_memory(mem_size)); + auto p = reinterpret_cast(RuntimeAllocator::get().alloc_script_memory(mem_size)); p->is_vector_internal = true; p->ref_cnt = 0; p->max_key = -1; @@ -262,11 +255,9 @@ typename array::array_inner *array::array_inner::create(int64_t new_int_si return p; } - auto shift_pointer_to_array_inner = [](void *mem) { - return reinterpret_cast(static_cast(mem) + sizeof(array_inner_fields_for_map)); - }; + auto shift_pointer_to_array_inner = [](void* mem) { return reinterpret_cast(static_cast(mem) + sizeof(array_inner_fields_for_map)); }; - array_inner *p = shift_pointer_to_array_inner(RuntimeAllocator::get().alloc0_script_memory(mem_size)); + array_inner* p = shift_pointer_to_array_inner(RuntimeAllocator::get().alloc0_script_memory(mem_size)); p->is_vector_internal = false; p->ref_cnt = 0; p->max_key = -1; @@ -281,21 +272,21 @@ typename array::array_inner *array::array_inner::create(int64_t new_int_si return p; } -template +template void array::array_inner::dispose() { if (ref_cnt < ExtraRefCnt::for_global_const) { ref_cnt--; if (ref_cnt <= -1) { if (is_vector()) { for (uint32_t i = 0; i < size; i++) { - ((T *)entries())[i].~T(); + ((T*)entries())[i].~T(); } - RuntimeAllocator::get().free_script_memory((void *)this, sizeof_vector(buf_size)); + RuntimeAllocator::get().free_script_memory((void*)this, sizeof_vector(buf_size)); return; } - for (const array_bucket *it = begin(); it != end(); it = next(it)) { + for (const array_bucket* it = begin(); it != end(); it = next(it)) { it->value.~T(); if (is_string_hash_entry(it)) { it->string_key.~string(); @@ -303,67 +294,65 @@ void array::array_inner::dispose() { } php_assert(this != empty_array()); - auto shifted_this = std::launder(reinterpret_cast(this)) - sizeof(array_inner_fields_for_map); + auto shifted_this = std::launder(reinterpret_cast(this)) - sizeof(array_inner_fields_for_map); RuntimeAllocator::get().free_script_memory(shifted_this, sizeof_map(buf_size)); } } } - -template -typename array::array_inner *array::array_inner::ref_copy() { +template +typename array::array_inner* array::array_inner::ref_copy() { if (ref_cnt < ExtraRefCnt::for_global_const) { ref_cnt++; } return this; } -template -template -inline T &array::array_inner::emplace_back_vector_value(Args &&... args) noexcept { +template +template +inline T& array::array_inner::emplace_back_vector_value(Args&&... args) noexcept { static_assert(std::is_constructible{}, "should be constructible"); - php_assert (size < buf_size); - new(&((T *)entries())[size]) T(std::forward(args)...); + php_assert(size < buf_size); + new (&((T*)entries())[size]) T(std::forward(args)...); max_key++; size++; - return reinterpret_cast(entries())[max_key]; + return reinterpret_cast(entries())[max_key]; } -template -T &array::array_inner::push_back_vector_value(const T &v) { +template +T& array::array_inner::push_back_vector_value(const T& v) { return emplace_back_vector_value(v); } -template -T &array::array_inner::get_vector_value(int64_t int_key) { - return reinterpret_cast(entries())[int_key]; +template +T& array::array_inner::get_vector_value(int64_t int_key) { + return reinterpret_cast(entries())[int_key]; } -template -const T &array::array_inner::get_vector_value(int64_t int_key) const { - return reinterpret_cast(entries())[int_key]; +template +const T& array::array_inner::get_vector_value(int64_t int_key) const { + return reinterpret_cast(entries())[int_key]; } -template -template -T &array::array_inner::emplace_vector_value(int64_t int_key, Args &&... args) noexcept { +template +template +T& array::array_inner::emplace_vector_value(int64_t int_key, Args&&... args) noexcept { static_assert(std::is_constructible{}, "should be constructible"); - reinterpret_cast(entries())[int_key] = T(std::forward(args)...); + reinterpret_cast(entries())[int_key] = T(std::forward(args)...); return get_vector_value(int_key); } -template -T &array::array_inner::set_vector_value(int64_t int_key, const T &v) { +template +T& array::array_inner::set_vector_value(int64_t int_key, const T& v) { return emplace_vector_value(int_key, v); } -template -template -T &array::array_inner::emplace_int_key_map_value(overwrite_element policy, int64_t int_key, Args &&... args) noexcept { +template +template +T& array::array_inner::emplace_int_key_map_value(overwrite_element policy, int64_t int_key, Args&&... args) noexcept { static_assert(std::is_constructible{}, "should be constructible"); uint32_t bucket = choose_bucket(int_key); - while (entries()[bucket].next != EMPTY_POINTER && - (entries()[bucket].int_key != int_key || !entries()[bucket].string_key.is_dummy_string())) { + while (entries()[bucket].next != EMPTY_POINTER && (entries()[bucket].int_key != int_key || !entries()[bucket].string_key.is_dummy_string())) { if (unlikely(++bucket == buf_size)) { bucket = 0; } @@ -371,7 +360,7 @@ T &array::array_inner::emplace_int_key_map_value(overwrite_element policy, in if (entries()[bucket].next == EMPTY_POINTER) { entries()[bucket].int_key = int_key; - new(&entries()[bucket].string_key) string{ArrayBucketDummyStrTag{}}; + new (&entries()[bucket].string_key) string{ArrayBucketDummyStrTag{}}; entries()[bucket].prev = end()->prev; get_entry(end()->prev)->next = get_pointer(&entries()[bucket]); @@ -379,7 +368,7 @@ T &array::array_inner::emplace_int_key_map_value(overwrite_element policy, in entries()[bucket].next = get_pointer(end()); end()->prev = get_pointer(&entries()[bucket]); - new(&entries()[bucket].value) T(std::forward(args)...); + new (&entries()[bucket].value) T(std::forward(args)...); size++; @@ -393,24 +382,23 @@ T &array::array_inner::emplace_int_key_map_value(overwrite_element policy, in return entries()[bucket].value; } -template -T &array::array_inner::set_map_value(overwrite_element policy, int64_t int_key, const T &v) { +template +T& array::array_inner::set_map_value(overwrite_element policy, int64_t int_key, const T& v) { return emplace_int_key_map_value(policy, int_key, v); } -template +template T array::array_inner::unset_vector_value() { --size; - T res = std::move(reinterpret_cast(entries())[max_key--]); + T res = std::move(reinterpret_cast(entries())[max_key--]); return res; } -template +template T array::array_inner::unset_map_value(int64_t int_key) { uint32_t bucket = choose_bucket(int_key); - while (entries()[bucket].next != EMPTY_POINTER && - (entries()[bucket].int_key != int_key || !entries()[bucket].string_key.is_dummy_string())) { - if (unlikely (++bucket == buf_size)) { + while (entries()[bucket].next != EMPTY_POINTER && (entries()[bucket].int_key != int_key || !entries()[bucket].string_key.is_dummy_string())) { + if (unlikely(++bucket == buf_size)) { bucket = 0; } } @@ -459,13 +447,12 @@ T array::array_inner::unset_map_value(int64_t int_key) { return {}; } -template -template -auto &array::array_inner::find_map_entry(S &self, int64_t int_key) noexcept { +template +template +auto& array::array_inner::find_map_entry(S& self, int64_t int_key) noexcept { uint32_t bucket = self.choose_bucket(int_key); - while (self.entries()[bucket].next != EMPTY_POINTER && - (self.entries()[bucket].int_key != int_key || !self.entries()[bucket].string_key.is_dummy_string())) { - if (unlikely (++bucket == self.buf_size)) { + while (self.entries()[bucket].next != EMPTY_POINTER && (self.entries()[bucket].int_key != int_key || !self.entries()[bucket].string_key.is_dummy_string())) { + if (unlikely(++bucket == self.buf_size)) { bucket = 0; } } @@ -473,23 +460,24 @@ auto &array::array_inner::find_map_entry(S &self, int64_t int_key) noexcept { return self.entries()[bucket]; } -template -template -auto &array::array_inner::find_map_entry(S &self, const string &string_key, int64_t precomputed_hash) noexcept { +template +template +auto& array::array_inner::find_map_entry(S& self, const string& string_key, int64_t precomputed_hash) noexcept { return find_map_entry(self, string_key.c_str(), string_key.size(), precomputed_hash); } -template -template -auto &array::array_inner::find_map_entry(S &self, const char *key, string::size_type key_size, int64_t precomputed_hash) noexcept { - static const auto str_not_eq = [](const string &lhs, const char *rhs, string::size_type rhs_size) { +template +template +auto& array::array_inner::find_map_entry(S& self, const char* key, string::size_type key_size, int64_t precomputed_hash) noexcept { + static const auto str_not_eq = [](const string& lhs, const char* rhs, string::size_type rhs_size) { return lhs.size() != rhs_size || string::compare(lhs, rhs, rhs_size) != 0; }; - auto *string_entries = self.entries(); + auto* string_entries = self.entries(); uint32_t bucket = self.choose_bucket(precomputed_hash); while (string_entries[bucket].next != EMPTY_POINTER && - (string_entries[bucket].int_key != precomputed_hash || string_entries[bucket].string_key.is_dummy_string() || str_not_eq(string_entries[bucket].string_key, key, key_size))) { - if (unlikely (++bucket == self.buf_size)) { + (string_entries[bucket].int_key != precomputed_hash || string_entries[bucket].string_key.is_dummy_string() || + str_not_eq(string_entries[bucket].string_key, key, key_size))) { + if (unlikely(++bucket == self.buf_size)) { bucket = 0; } } @@ -497,34 +485,35 @@ auto &array::array_inner::find_map_entry(S &self, const char *key, string::si return string_entries[bucket]; } -template -template -const T *array::array_inner::find_map_value(Key &&... key) const noexcept { - const auto &entry = find_map_entry(*this, std::forward(key)...); +template +template +const T* array::array_inner::find_map_value(Key&&... key) const noexcept { + const auto& entry = find_map_entry(*this, std::forward(key)...); return entry.next != EMPTY_POINTER ? &entry.value : nullptr; } -template -const T *array::array_inner::find_vector_value(int64_t int_key) const noexcept { +template +const T* array::array_inner::find_vector_value(int64_t int_key) const noexcept { return int_key >= 0 && int_key < size ? &get_vector_value(int_key) : nullptr; } -template -T *array::array_inner::find_vector_value(int64_t int_key) noexcept { +template +T* array::array_inner::find_vector_value(int64_t int_key) noexcept { return int_key >= 0 && int_key < size ? &get_vector_value(int_key) : nullptr; } -template -template -std::pair array::array_inner::emplace_string_key_map_value(overwrite_element policy, int64_t int_key, STRING &&string_key, Args &&... args) noexcept { +template +template +std::pair array::array_inner::emplace_string_key_map_value(overwrite_element policy, int64_t int_key, STRING&& string_key, + Args&&... args) noexcept { static_assert(std::is_same, string>::value, "string_key should be string"); - array_bucket *string_entries = entries(); - auto &fields = fields_for_map(); + array_bucket* string_entries = entries(); + auto& fields = fields_for_map(); uint32_t bucket = choose_bucket(fields, int_key); - while (string_entries[bucket].next != EMPTY_POINTER && - (string_entries[bucket].int_key != int_key || string_entries[bucket].string_key.is_dummy_string() || string_entries[bucket].string_key != string_key)) { - if (unlikely (++bucket == buf_size)) { + while (string_entries[bucket].next != EMPTY_POINTER && (string_entries[bucket].int_key != int_key || string_entries[bucket].string_key.is_dummy_string() || + string_entries[bucket].string_key != string_key)) { + if (unlikely(++bucket == buf_size)) { bucket = 0; } } @@ -532,7 +521,7 @@ std::pair array::array_inner::emplace_string_key_map_value(overwri bool inserted = false; if (string_entries[bucket].next == EMPTY_POINTER) { string_entries[bucket].int_key = int_key; - new(&string_entries[bucket].string_key) string{std::forward(string_key)}; + new (&string_entries[bucket].string_key) string{std::forward(string_key)}; string_entries[bucket].prev = end()->prev; get_entry(end()->prev)->next = get_pointer(&string_entries[bucket]); @@ -540,7 +529,7 @@ std::pair array::array_inner::emplace_string_key_map_value(overwri string_entries[bucket].next = get_pointer(end()); end()->prev = get_pointer(&string_entries[bucket]); - new(&string_entries[bucket].value) T(std::forward(args)...); + new (&string_entries[bucket].value) T(std::forward(args)...); ++size; ++fields.string_size; @@ -553,19 +542,20 @@ std::pair array::array_inner::emplace_string_key_map_value(overwri return {string_entries[bucket].value, inserted}; } -template -T &array::array_inner::set_map_value(overwrite_element policy, int64_t int_key, const string &string_key, const T &v) { +template +T& array::array_inner::set_map_value(overwrite_element policy, int64_t int_key, const string& string_key, const T& v) { return emplace_string_key_map_value(policy, int_key, string_key, v).first; } -template -T array::array_inner::unset_map_value(const string &string_key, int64_t precomputed_hash) { - array_bucket *string_entries = entries(); - auto &fields = fields_for_map(); +template +T array::array_inner::unset_map_value(const string& string_key, int64_t precomputed_hash) { + array_bucket* string_entries = entries(); + auto& fields = fields_for_map(); uint32_t bucket = choose_bucket(fields, precomputed_hash); while (string_entries[bucket].next != EMPTY_POINTER && - (string_entries[bucket].int_key != precomputed_hash || string_entries[bucket].string_key.is_dummy_string() || string_entries[bucket].string_key != string_key)) { - if (unlikely (++bucket == buf_size)) { + (string_entries[bucket].int_key != precomputed_hash || string_entries[bucket].string_key.is_dummy_string() || + string_entries[bucket].string_key != string_key)) { + if (unlikely(++bucket == buf_size)) { bucket = 0; } } @@ -616,22 +606,22 @@ T array::array_inner::unset_map_value(const string &string_key, int64_t preco return {}; } -template +template bool array::array_inner::is_vector_internal_or_last_index(int64_t key) const noexcept { return key >= 0 && key <= size; } -template +template bool array::array_inner::has_no_string_keys() const noexcept { return is_vector_internal ? true : fields_for_map().string_size == 0; } -template +template size_t array::array_inner::estimate_memory_usage() const noexcept { return is_vector() ? sizeof_vector(buf_size) : sizeof_map(buf_size); } -template +template size_t array::array_inner::calculate_memory_for_copying() const noexcept { int64_t int_elements = size; const bool vector_structure = is_vector(); @@ -641,12 +631,12 @@ size_t array::array_inner::calculate_memory_for_copying() const noexcept { return estimate_size(++int_elements, vector_structure); } -template +template bool array::is_vector() const { return p->is_vector(); } -template +template bool array::is_pseudo_vector() const { if (p->is_vector_internal) { return true; @@ -663,23 +653,23 @@ bool array::is_pseudo_vector() const { return n == count(); } -template +template bool array::has_no_string_keys() const noexcept { return p->has_no_string_keys(); } -template +template bool array::mutate_if_vector_shared(uint32_t mul) { return mutate_to_size_if_vector_shared(mul * int64_t{p->size}); } -template +template bool array::mutate_to_size_if_vector_shared(int64_t int_size) { if (p->ref_cnt > 0) { - array_inner *new_array = array_inner::create(int_size, true); + array_inner* new_array = array_inner::create(int_size, true); const auto size = static_cast(p->size); - T *it = (T *)p->entries(); + T* it = (T*)p->entries(); for (uint32_t i = 0; i < size; i++) { new_array->push_back_vector_value(it[i]); @@ -692,12 +682,12 @@ bool array::mutate_to_size_if_vector_shared(int64_t int_size) { return false; } -template +template bool array::mutate_if_map_shared(uint32_t mul) { if (p->ref_cnt > 0) { - array_inner *new_array = array_inner::create(p->size * mul + 1, false); + array_inner* new_array = array_inner::create(p->size * mul + 1, false); - for (const array_bucket *it = p->begin(); it != p->end(); it = p->next(it)) { + for (const array_bucket* it = p->begin(); it != p->end(); it = p->next(it)) { if (p->is_string_hash_entry(it)) { new_array->set_map_value(overwrite_element::YES, it->int_key, it->string_key, it->value); } else { @@ -712,7 +702,7 @@ bool array::mutate_if_map_shared(uint32_t mul) { return false; } -template +template void array::mutate_if_vector_needs_space() { if (mutate_if_vector_shared(2)) { return; @@ -723,20 +713,20 @@ void array::mutate_if_vector_needs_space() { } } -template +template void array::mutate_to_size(int64_t int_size) { if (mutate_to_size_if_vector_shared(int_size)) { return; } if (unlikely(int_size > array_inner::MAX_HASHTABLE_SIZE)) { - php_critical_error ("max array size exceeded: int_size = %" PRIi64, int_size); + php_critical_error("max array size exceeded: int_size = %" PRIi64, int_size); } const auto new_int_buff_size = static_cast(int_size); - p = static_cast(RuntimeAllocator::get().realloc_script_memory(p, p->sizeof_vector(new_int_buff_size), p->sizeof_vector(p->buf_size))); + p = static_cast(RuntimeAllocator::get().realloc_script_memory(p, p->sizeof_vector(new_int_buff_size), p->sizeof_vector(p->buf_size))); p->buf_size = new_int_buff_size; } -template +template void array::mutate_if_map_needs_space() { if (mutate_if_map_shared(2)) { return; @@ -745,15 +735,13 @@ void array::mutate_if_map_needs_space() { // not shared (ref_cnt == 0) if (p->size * 5 > 3 * p->buf_size) { int64_t new_int_size = p->size * 2 + 1; - array_inner *new_array = array_inner::create(new_int_size, false); + array_inner* new_array = array_inner::create(new_int_size, false); - for (array_bucket *it = p->begin(); it != p->end(); it = p->next(it)) { + for (array_bucket* it = p->begin(); it != p->end(); it = p->next(it)) { if (p->is_string_hash_entry(it)) { - new_array->emplace_string_key_map_value(overwrite_element::YES, - it->int_key, std::move(it->string_key), std::move(it->value)); + new_array->emplace_string_key_map_value(overwrite_element::YES, it->int_key, std::move(it->string_key), std::move(it->value)); } else { - new_array->emplace_int_key_map_value(overwrite_element::YES, - it->int_key, std::move(it->value)); + new_array->emplace_int_key_map_value(overwrite_element::YES, it->int_key, std::move(it->value)); } } @@ -762,7 +750,7 @@ void array::mutate_if_map_needs_space() { } } -template +template void array::mutate_to_map_if_vector_or_map_need_space() { if (is_vector()) { convert_to_map(); @@ -771,22 +759,22 @@ void array::mutate_to_map_if_vector_or_map_need_space() { } } -template +template void array::reserve(int64_t int_size, bool make_vector_if_possible) { if (int_size > int64_t{p->buf_size}) { if (is_vector() && make_vector_if_possible) { mutate_to_size(int_size); } else { const int64_t new_int_size = std::max(int_size, int64_t{p->buf_size}); - array_inner *new_array = array_inner::create(new_int_size, false); + array_inner* new_array = array_inner::create(new_int_size, false); if (is_vector()) { for (uint32_t it = 0; it != p->size; it++) { - new_array->set_map_value(overwrite_element::YES, it, ((T *)p->entries())[it]); + new_array->set_map_value(overwrite_element::YES, it, ((T*)p->entries())[it]); } - php_assert (new_array->max_key == p->max_key); + php_assert(new_array->max_key == p->max_key); } else { - for (const array_bucket *it = p->begin(); it != p->end(); it = p->next(it)) { + for (const array_bucket* it = p->begin(); it != p->end(); it = p->next(it)) { if (p->is_string_hash_entry(it)) { new_array->set_map_value(overwrite_element::YES, it->int_key, it->string_key, it->value); } else { @@ -801,62 +789,61 @@ void array::reserve(int64_t int_size, bool make_vector_if_possible) { } } -template +template size_t array::estimate_memory_usage() const noexcept { return p->estimate_memory_usage(); } -template +template size_t array::calculate_memory_for_copying() const noexcept { return p->calculate_memory_for_copying(); } -template +template typename array::const_iterator array::cbegin() const { return const_iterator::make_begin(*this); } -template +template typename array::const_iterator array::begin() const { return const_iterator::make_begin(*this); } -template +template typename array::const_iterator array::middle(int64_t n) const { return const_iterator::make_middle(*this, n); } -template +template typename array::const_iterator array::cend() const { return const_iterator::make_end(*this); } -template +template typename array::const_iterator array::end() const { return cend(); } -template +template typename array::iterator array::begin() { return iterator::make_begin(*this); } -template +template typename array::iterator array::middle(int64_t n) { return iterator::make_middle(*this, n); } -template +template typename array::iterator array::end() { return iterator::make_end(*this); } - -template +template void array::convert_to_map() { - array_inner *new_array = array_inner::create(p->size + 4, false); + array_inner* new_array = array_inner::create(p->size + 4, false); - T *elements = reinterpret_cast(p->entries()); + T* elements = reinterpret_cast(p->entries()); const bool move_values = p->ref_cnt == 0; if (move_values) { for (uint32_t it = 0; it != p->size; it++) { @@ -868,30 +855,30 @@ void array::convert_to_map() { } } - php_assert (new_array->max_key == p->max_key); + php_assert(new_array->max_key == p->max_key); p->dispose(); p = new_array; } -template -template -void array::copy_from(const array &other) { +template +template +void array::copy_from(const array& other) { if (other.empty()) { p = array_inner::empty_array(); return; } - array_inner *new_array = array_inner::create(other.p->size, other.is_vector()); + array_inner* new_array = array_inner::create(other.p->size, other.is_vector()); if (new_array->is_vector()) { uint32_t size = other.p->size; - T1 *it = reinterpret_cast(other.p->entries()); + T1* it = reinterpret_cast(other.p->entries()); for (uint32_t i = 0; i < size; i++) { new_array->push_back_vector_value(convert_to::convert(it[i])); } } else { - for (const typename array::array_bucket *it = other.p->begin(); it != other.p->end(); it = other.p->next(it)) { + for (const typename array::array_bucket* it = other.p->begin(); it != other.p->end(); it = other.p->next(it)) { if (other.p->is_string_hash_entry(it)) { new_array->set_map_value(overwrite_element::YES, it->int_key, it->string_key, convert_to::convert(it->value)); } else { @@ -902,12 +889,12 @@ void array::copy_from(const array &other) { p = new_array; - php_assert (new_array->size == other.p->size); + php_assert(new_array->size == other.p->size); } -template -template -void array::move_from(array &&other) noexcept { +template +template +void array::move_from(array&& other) noexcept { if (other.empty()) { p = array_inner::empty_array(); return; @@ -919,86 +906,75 @@ void array::move_from(array &&other) noexcept { return; } - array_inner *new_array = array_inner::create(other.p->size, other.is_vector()); + array_inner* new_array = array_inner::create(other.p->size, other.is_vector()); if (new_array->is_vector()) { uint32_t size = other.p->size; - T1 *it = reinterpret_cast(other.p->entries()); + T1* it = reinterpret_cast(other.p->entries()); for (uint32_t i = 0; i < size; i++) { new_array->emplace_back_vector_value(convert_to::convert(std::move(it[i]))); } } else { for (auto it = other.p->begin(); it != other.p->end(); it = other.p->next(it)) { if (other.p->is_string_hash_entry(it)) { - new_array->emplace_string_key_map_value(overwrite_element::YES, it->int_key, - std::move(it->string_key), convert_to::convert(std::move(it->value))); + new_array->emplace_string_key_map_value(overwrite_element::YES, it->int_key, std::move(it->string_key), convert_to::convert(std::move(it->value))); } else { - new_array->emplace_int_key_map_value(overwrite_element::YES, - it->int_key, convert_to::convert(std::move(it->value))); + new_array->emplace_int_key_map_value(overwrite_element::YES, it->int_key, convert_to::convert(std::move(it->value))); } } } p = new_array; - php_assert (new_array->size == other.p->size); + php_assert(new_array->size == other.p->size); other = array{}; } -template -template -array array::convert_from(const array &other) { +template +template +array array::convert_from(const array& other) { array res; res.copy_from(other); return res; } -template -array::array(): - p(array_inner::empty_array()) { -} - +template +array::array() : p(array_inner::empty_array()) {} -template -array::array(const array_size &s) : - p(array_inner::create(s.size, s.is_vector)) { -} +template +array::array(const array_size& s) : p(array_inner::create(s.size, s.is_vector)) {} -template -template -inline array::array(const std::initializer_list> &list) : - array() { - for (const auto &kv: list) { +template +template +inline array::array(const std::initializer_list>& list) : array() { + for (const auto& kv : list) { set_value(kv.first, kv.second); } } +template +array::array(const array& other) noexcept : p(other.p->ref_copy()) {} -template -array::array(const array &other) noexcept : - p(other.p->ref_copy()) {} - -template -array::array(array &&other) noexcept : - p(other.p) { +template +array::array(array&& other) noexcept : p(other.p) { other.p = array_inner::empty_array(); } -template -template -array::array(const array &other) noexcept { +template +template +array::array(const array& other) noexcept { copy_from(other); } -template -template -array::array(array &&other) noexcept { +template +template +array::array(array&& other) noexcept { move_from(std::move(other)); } -template -template -inline array array::create(Args &&... args) { +template +template +inline array array::create(Args&&... args) { static_assert((std::is_convertible, T>::value && ...), "Args type must be convertible to T"); array res{array_size{sizeof...(args), true}}; @@ -1006,16 +982,16 @@ inline array array::create(Args &&... args) { return res; } -template -array &array::operator=(const array &other) noexcept { +template +array& array::operator=(const array& other) noexcept { auto other_copy = other.p->ref_copy(); destroy(); p = other_copy; return *this; } -template -array &array::operator=(array &&other) noexcept { +template +array& array::operator=(array&& other) noexcept { if (this != &other) { destroy(); p = other.p; @@ -1024,44 +1000,42 @@ array &array::operator=(array &&other) noexcept { return *this; } -template -template -array &array::operator=(const array &other) noexcept { +template +template +array& array::operator=(const array& other) noexcept { destroy(); copy_from(other); return *this; } -template -template -array &array::operator=(array &&other) noexcept { +template +template +array& array::operator=(array&& other) noexcept { destroy(); move_from(std::move(other)); return *this; } -template +template void array::destroy() { if (p) { p->dispose(); } } -template +template array::~array() { destroy(); } - -template +template void array::clear() { destroy(); p = array_inner::empty_array(); } - -template -T &array::operator[](int64_t int_key) { +template +T& array::operator[](int64_t int_key) { if (is_vector()) { if (p->is_vector_internal_or_last_index(int_key)) { if (int_key == p->size) { @@ -1081,8 +1055,8 @@ T &array::operator[](int64_t int_key) { return p->emplace_int_key_map_value(overwrite_element::NO, int_key); } -template -T &array::operator[](const string &string_key) { +template +T& array::operator[](const string& string_key) { int64_t int_val = 0; if (string_key.try_to_int(&int_val)) { return (*this)[int_val]; @@ -1092,48 +1066,48 @@ T &array::operator[](const string &string_key) { return p->emplace_string_key_map_value(overwrite_element::NO, string_key.hash(), string_key).first; } -template -T &array::operator[](tmp_string string_key) { +template +T& array::operator[](tmp_string string_key) { // TODO: try not to allocate here too return (*this)[materialize_tmp_string(string_key)]; } -template -T &array::operator[](const mixed &v) { +template +T& array::operator[](const mixed& v) { switch (v.get_type()) { - case mixed::type::NUL: - return (*this)[string()]; - case mixed::type::BOOLEAN: - return (*this)[static_cast(v.as_bool())]; - case mixed::type::INTEGER: - return (*this)[v.as_int()]; - case mixed::type::FLOAT: - return (*this)[static_cast(v.as_double())]; - case mixed::type::STRING: - return (*this)[v.as_string()]; - case mixed::type::ARRAY: - php_warning("Illegal offset type array"); - return (*this)[v.as_array().to_int()]; - case mixed::type::OBJECT: - php_warning("Illegal offset type %s", v.get_type_or_class_name()); - return (*this)[string()]; - default: - __builtin_unreachable(); - } -} - -template -T &array::operator[](double double_key) { + case mixed::type::NUL: + return (*this)[string()]; + case mixed::type::BOOLEAN: + return (*this)[static_cast(v.as_bool())]; + case mixed::type::INTEGER: + return (*this)[v.as_int()]; + case mixed::type::FLOAT: + return (*this)[static_cast(v.as_double())]; + case mixed::type::STRING: + return (*this)[v.as_string()]; + case mixed::type::ARRAY: + php_warning("Illegal offset type array"); + return (*this)[v.as_array().to_int()]; + case mixed::type::OBJECT: + php_warning("Illegal offset type %s", v.get_type_or_class_name()); + return (*this)[string()]; + default: + __builtin_unreachable(); + } +} + +template +T& array::operator[](double double_key) { return (*this)[static_cast(double_key)]; } -template -T &array::operator[](const const_iterator &it) noexcept { +template +T& array::operator[](const const_iterator& it) noexcept { if (it.self_->is_vector()) { - const auto key = static_cast(reinterpret_cast(it.entry_) - reinterpret_cast(it.self_->entries())); + const auto key = static_cast(reinterpret_cast(it.entry_) - reinterpret_cast(it.self_->entries())); return operator[](key); } - auto *entry = reinterpret_cast(it.entry_); + auto* entry = reinterpret_cast(it.entry_); if (it.self_->is_string_hash_entry(entry)) { mutate_to_map_if_vector_or_map_need_space(); return p->emplace_string_key_map_value(overwrite_element::NO, entry->int_key, entry->string_key).first; @@ -1141,14 +1115,14 @@ T &array::operator[](const const_iterator &it) noexcept { return operator[](entry->int_key); } -template -T &array::operator[](const iterator &it) noexcept { +template +T& array::operator[](const iterator& it) noexcept { return operator[](const_iterator{it.self_, it.entry_}); } -template -template -void array::emplace_value(int64_t int_key, Args &&... args) noexcept { +template +template +void array::emplace_value(int64_t int_key, Args&&... args) noexcept { if (is_vector()) { if (p->is_vector_internal_or_last_index(int_key)) { if (int_key == p->size) { @@ -1169,29 +1143,29 @@ void array::emplace_value(int64_t int_key, Args &&... args) noexcept { p->emplace_int_key_map_value(overwrite_element::YES, int_key, std::forward(args)...); } -template -void array::set_value(int64_t int_key, T &&v) noexcept { +template +void array::set_value(int64_t int_key, T&& v) noexcept { emplace_value(int_key, std::move(v)); } -template -void array::set_value(int64_t int_key, const T &v) noexcept { +template +void array::set_value(int64_t int_key, const T& v) noexcept { emplace_value(int_key, v); } -template -void array::set_value(double double_key, T &&v) noexcept { +template +void array::set_value(double double_key, T&& v) noexcept { emplace_value(static_cast(double_key), std::move(v)); } -template -void array::set_value(double double_key, const T &v) noexcept { +template +void array::set_value(double double_key, const T& v) noexcept { emplace_value(static_cast(double_key), v); } -template -template -void array::emplace_value(const string &string_key, Args &&... args) noexcept { +template +template +void array::emplace_value(const string& string_key, Args&&... args) noexcept { int64_t int_val = 0; if (string_key.try_to_int(&int_val)) { emplace_value(int_val, std::forward(args)...); @@ -1199,109 +1173,107 @@ void array::emplace_value(const string &string_key, Args &&... args) noexcept } mutate_to_map_if_vector_or_map_need_space(); - p->emplace_string_key_map_value(overwrite_element::YES, - string_key.hash(), string_key, std::forward(args)...); + p->emplace_string_key_map_value(overwrite_element::YES, string_key.hash(), string_key, std::forward(args)...); } -template -void array::set_value(const string &string_key, T &&v) noexcept { +template +void array::set_value(const string& string_key, T&& v) noexcept { emplace_value(string_key, std::move(v)); } -template -void array::set_value(const string &string_key, const T &v) noexcept { +template +void array::set_value(const string& string_key, const T& v) noexcept { emplace_value(string_key, v); } -template -void array::set_value(tmp_string string_key, T &&v) noexcept { +template +void array::set_value(tmp_string string_key, T&& v) noexcept { // TODO: rework value insertion, so tmp_string is converted to a real string // only when new insertion happens emplace_value(materialize_tmp_string(string_key), std::move(v)); } -template -void array::set_value(tmp_string string_key, const T &v) noexcept { +template +void array::set_value(tmp_string string_key, const T& v) noexcept { // TODO: rework value insertion, so tmp_string is converted to a real string // only when new insertion happens emplace_value(materialize_tmp_string(string_key), v); } -template -void array::set_value(const string &string_key, const T &v, int64_t precomputed_hash) noexcept { +template +void array::set_value(const string& string_key, const T& v, int64_t precomputed_hash) noexcept { mutate_to_map_if_vector_or_map_need_space(); p->emplace_string_key_map_value(overwrite_element::YES, precomputed_hash, string_key, v); } -template -void array::set_value(const string &string_key, T &&v, int64_t precomputed_hash) noexcept { +template +void array::set_value(const string& string_key, T&& v, int64_t precomputed_hash) noexcept { mutate_to_map_if_vector_or_map_need_space(); p->emplace_string_key_map_value(overwrite_element::YES, precomputed_hash, string_key, std::move(v)); } - -template -template -void array::emplace_value(const mixed &var_key, Args &&... args) noexcept { +template +template +void array::emplace_value(const mixed& var_key, Args&&... args) noexcept { switch (var_key.get_type()) { - case mixed::type::NUL: - return emplace_value(string(), std::forward(args)...); - case mixed::type::BOOLEAN: - return emplace_value(static_cast(var_key.as_bool()), std::forward(args)...); - case mixed::type::INTEGER: - return emplace_value(var_key.as_int(), std::forward(args)...); - case mixed::type::FLOAT: - return emplace_value(static_cast(var_key.as_double()), std::forward(args)...); - case mixed::type::STRING: - return emplace_value(var_key.as_string(), std::forward(args)...); - case mixed::type::ARRAY: - php_warning("Illegal offset type array"); - return emplace_value(var_key.as_array().to_int(), std::forward(args)...); - case mixed::type::OBJECT: - php_warning("Illegal offset type %s", var_key.get_type_or_class_name()); - return emplace_value(string(), std::forward(args)...); - default: - __builtin_unreachable(); - } -} - -template -void array::set_value(const mixed &v, T &&value) noexcept { + case mixed::type::NUL: + return emplace_value(string(), std::forward(args)...); + case mixed::type::BOOLEAN: + return emplace_value(static_cast(var_key.as_bool()), std::forward(args)...); + case mixed::type::INTEGER: + return emplace_value(var_key.as_int(), std::forward(args)...); + case mixed::type::FLOAT: + return emplace_value(static_cast(var_key.as_double()), std::forward(args)...); + case mixed::type::STRING: + return emplace_value(var_key.as_string(), std::forward(args)...); + case mixed::type::ARRAY: + php_warning("Illegal offset type array"); + return emplace_value(var_key.as_array().to_int(), std::forward(args)...); + case mixed::type::OBJECT: + php_warning("Illegal offset type %s", var_key.get_type_or_class_name()); + return emplace_value(string(), std::forward(args)...); + default: + __builtin_unreachable(); + } +} + +template +void array::set_value(const mixed& v, T&& value) noexcept { emplace_value(v, std::move(value)); } -template -void array::set_value(const mixed &v, const T &value) noexcept { +template +void array::set_value(const mixed& v, const T& value) noexcept { emplace_value(v, value); } -template -template -void array::emplace_value(const Optional &key, Args &&... args) noexcept { - auto set_value_lambda = [this](auto &&... args) { return this->set_value(std::forward(args)...);}; +template +template +void array::emplace_value(const Optional& key, Args&&... args) noexcept { + auto set_value_lambda = [this](auto&&... args) { return this->set_value(std::forward(args)...); }; return call_fun_on_optional_value(set_value_lambda, key, std::forward(args)...); } -template -template -void array::set_value(const Optional &key, T &&value) noexcept { +template +template +void array::set_value(const Optional& key, T&& value) noexcept { emplace_value(key, std::move(value)); } -template -template -void array::set_value(const Optional &key, const T &value) noexcept { +template +template +void array::set_value(const Optional& key, const T& value) noexcept { emplace_value(key, value); } -template -void array::set_value(const const_iterator &it) noexcept { +template +void array::set_value(const const_iterator& it) noexcept { if (it.self_->is_vector()) { - const auto key = static_cast(reinterpret_cast(it.entry_) - reinterpret_cast(it.self_->entries())); - emplace_value(key, *reinterpret_cast(it.entry_)); + const auto key = static_cast(reinterpret_cast(it.entry_) - reinterpret_cast(it.self_->entries())); + emplace_value(key, *reinterpret_cast(it.entry_)); return; } - auto *entry = reinterpret_cast(it.entry_); + auto* entry = reinterpret_cast(it.entry_); if (it.self_->is_string_hash_entry(entry)) { mutate_to_map_if_vector_or_map_need_space(); p->emplace_string_key_map_value(overwrite_element::YES, entry->int_key, entry->string_key, entry->value); @@ -1310,25 +1282,23 @@ void array::set_value(const const_iterator &it) noexcept { } } -template -void array::set_value(const iterator &it) noexcept { +template +void array::set_value(const iterator& it) noexcept { set_value(const_iterator{it.self_, it.entry_}); } -template -void array::assign_raw(const char *s) { - p = reinterpret_cast(const_cast(s)); +template +void array::assign_raw(const char* s) { + p = reinterpret_cast(const_cast(s)); } -template -const T *array::find_value(int64_t int_key) const noexcept { - return p->is_vector() - ? p->find_vector_value(int_key) - : p->find_map_value(int_key); +template +const T* array::find_value(int64_t int_key) const noexcept { + return p->is_vector() ? p->find_vector_value(int_key) : p->find_map_value(int_key); } -template -const T *array::find_value(const char *s, string::size_type l) const noexcept { +template +const T* array::find_value(const char* s, string::size_type l) const noexcept { int64_t int_val = 0; const bool is_key_int = php_try_to_int(s, l, &int_val); if (p->is_vector()) { @@ -1337,71 +1307,69 @@ const T *array::find_value(const char *s, string::size_type l) const noexcept return is_key_int ? p->find_map_value(int_val) : p->find_map_value(s, l, string_hash(s, l)); } -template -const T *array::find_value(const string &string_key, int64_t precomputed_hash) const noexcept { +template +const T* array::find_value(const string& string_key, int64_t precomputed_hash) const noexcept { return p->is_vector() ? nullptr : p->find_map_value(string_key, precomputed_hash); } -template -const T *array::find_value(const mixed &v) const noexcept { +template +const T* array::find_value(const mixed& v) const noexcept { switch (v.get_type()) { - case mixed::type::NUL: - return find_value(string()); - case mixed::type::BOOLEAN: - return find_value(static_cast(v.as_bool())); - case mixed::type::INTEGER: - return find_value(v.as_int()); - case mixed::type::FLOAT: - return find_value(static_cast(v.as_double())); - case mixed::type::STRING: - return find_value(v.as_string()); - case mixed::type::ARRAY: - php_warning("Illegal offset type array"); - return find_value(v.as_array().to_int()); - case mixed::type::OBJECT: - php_warning("Illegal offset type %s", v.get_type_or_class_name()); - return find_value(string()); - default: - __builtin_unreachable(); - } -} - -template -const T *array::find_value(double double_key) const noexcept { + case mixed::type::NUL: + return find_value(string()); + case mixed::type::BOOLEAN: + return find_value(static_cast(v.as_bool())); + case mixed::type::INTEGER: + return find_value(v.as_int()); + case mixed::type::FLOAT: + return find_value(static_cast(v.as_double())); + case mixed::type::STRING: + return find_value(v.as_string()); + case mixed::type::ARRAY: + php_warning("Illegal offset type array"); + return find_value(v.as_array().to_int()); + case mixed::type::OBJECT: + php_warning("Illegal offset type %s", v.get_type_or_class_name()); + return find_value(string()); + default: + __builtin_unreachable(); + } +} + +template +const T* array::find_value(double double_key) const noexcept { return find_value(static_cast(double_key)); } -template -const T *array::find_value(const const_iterator &it) const noexcept { +template +const T* array::find_value(const const_iterator& it) const noexcept { if (it.self_->is_vector()) { - const auto key = static_cast(reinterpret_cast(it.entry_) - reinterpret_cast(it.self_->entries())); + const auto key = static_cast(reinterpret_cast(it.entry_) - reinterpret_cast(it.self_->entries())); return find_value(key); } else { - auto *entry = reinterpret_cast(it.entry_); - return it.self_->is_string_hash_entry(entry) - ? find_value(entry->string_key, entry->int_key) - : find_value(entry->int_key); + auto* entry = reinterpret_cast(it.entry_); + return it.self_->is_string_hash_entry(entry) ? find_value(entry->string_key, entry->int_key) : find_value(entry->int_key); } } -template -const T *array::find_value(const iterator &it) const noexcept { +template +const T* array::find_value(const iterator& it) const noexcept { return find_value(const_iterator{it.self_, it.entry_}); } -template +template typename array::iterator array::find_no_mutate(int64_t int_key) noexcept { if (p->is_vector()) { - if (auto *vector_entry = p->find_vector_value(int_key)) { - return iterator{p, reinterpret_cast(vector_entry)}; + if (auto* vector_entry = p->find_vector_value(int_key)) { + return iterator{p, reinterpret_cast(vector_entry)}; } return end_no_mutate(); } return find_iterator_in_map_no_mutate(int_key); } -template -typename array::iterator array::find_no_mutate(const string &string_key) noexcept { +template +typename array::iterator array::find_no_mutate(const string& string_key) noexcept { int64_t int_key = 0; if (string_key.try_to_int(&int_key)) { return find_no_mutate(int_key); @@ -1412,80 +1380,80 @@ typename array::iterator array::find_no_mutate(const string &string_key) n return find_iterator_in_map_no_mutate(string_key, string_key.hash()); } -template -template -typename array::iterator array::find_iterator_in_map_no_mutate(const Key &... key) noexcept { - list_hash_entry &map_entry = array_inner::find_map_entry(*p, key...); +template +template +typename array::iterator array::find_iterator_in_map_no_mutate(const Key&... key) noexcept { + list_hash_entry& map_entry = array_inner::find_map_entry(*p, key...); if (map_entry.next != array_inner::EMPTY_POINTER) { return iterator{p, &map_entry}; } return end_no_mutate(); } -template -typename array::iterator array::find_no_mutate(const mixed &v) noexcept { +template +typename array::iterator array::find_no_mutate(const mixed& v) noexcept { switch (v.get_type()) { - case mixed::type::NUL: - return find_no_mutate(string()); - case mixed::type::BOOLEAN: - return find_no_mutate(static_cast(v.as_bool())); - case mixed::type::INTEGER: - return find_no_mutate(v.as_int()); - case mixed::type::FLOAT: - return find_no_mutate(static_cast(v.as_double())); - case mixed::type::STRING: - return find_no_mutate(v.as_string()); - case mixed::type::ARRAY: - php_warning("Illegal offset type array"); - return find_no_mutate(v.as_array().to_int()); - case mixed::type::OBJECT: - php_warning("Illegal offset type %s", v.get_type_or_class_name()); - return find_no_mutate(string()); - default: - __builtin_unreachable(); - } -} - -template -template -const mixed array::get_var(const K &key) const { - auto *value = find_value(key); + case mixed::type::NUL: + return find_no_mutate(string()); + case mixed::type::BOOLEAN: + return find_no_mutate(static_cast(v.as_bool())); + case mixed::type::INTEGER: + return find_no_mutate(v.as_int()); + case mixed::type::FLOAT: + return find_no_mutate(static_cast(v.as_double())); + case mixed::type::STRING: + return find_no_mutate(v.as_string()); + case mixed::type::ARRAY: + php_warning("Illegal offset type array"); + return find_no_mutate(v.as_array().to_int()); + case mixed::type::OBJECT: + php_warning("Illegal offset type %s", v.get_type_or_class_name()); + return find_no_mutate(string()); + default: + __builtin_unreachable(); + } +} + +template +template +const mixed array::get_var(const K& key) const { + auto* value = find_value(key); return value ? mixed{*value} : mixed{}; } -template -template -const T array::get_value(const K &key) const { - auto *value = find_value(key); +template +template +const T array::get_value(const K& key) const { + auto* value = find_value(key); return value ? *value : T{}; } -template -const T array::get_value(const string &string_key, int64_t precomputed_hash) const { - auto *value = find_value(string_key, precomputed_hash); +template +const T array::get_value(const string& string_key, int64_t precomputed_hash) const { + auto* value = find_value(string_key, precomputed_hash); return value ? *value : T{}; } -template -template -bool array::has_key(const K &key) const { +template +template +bool array::has_key(const K& key) const { return find_value(key) != nullptr; } -template -template -bool array::isset(const K &key) const noexcept { - auto *value = find_value(key); +template +template +bool array::isset(const K& key) const noexcept { + auto* value = find_value(key); return value && !f$is_null(*value); } -template -bool array::isset(const string &key, int64_t precomputed_hash) const noexcept { - auto *value = find_value(key, precomputed_hash); +template +bool array::isset(const string& key, int64_t precomputed_hash) const noexcept { + auto* value = find_value(key, precomputed_hash); return value && !f$is_null(*value); } -template +template T array::unset(int64_t int_key) { if (is_vector()) { if (int_key < 0 || int_key >= p->size) { @@ -1503,8 +1471,8 @@ T array::unset(int64_t int_key) { return p->unset_map_value(int_key); } -template -T array::unset(const string &string_key) { +template +T array::unset(const string& string_key) { int64_t int_val = 0; if (string_key.try_to_int(&int_val)) { return unset(int_val); @@ -1517,8 +1485,8 @@ T array::unset(const string &string_key) { return unset(string_key, string_key.hash()); } -template -T array::unset(const string &string_key, int64_t precomputed_hash) { +template +T array::unset(const string& string_key, int64_t precomputed_hash) { if (is_vector()) { return {}; } @@ -1527,63 +1495,63 @@ T array::unset(const string &string_key, int64_t precomputed_hash) { return p->unset_map_value(string_key, precomputed_hash); } -template -T array::unset(const mixed &v) { +template +T array::unset(const mixed& v) { switch (v.get_type()) { - case mixed::type::NUL: - return unset(string()); - case mixed::type::BOOLEAN: - return unset(static_cast(v.as_bool())); - case mixed::type::INTEGER: - return unset(v.as_int()); - case mixed::type::FLOAT: - return unset(static_cast(v.as_double())); - case mixed::type::STRING: - return unset(v.as_string()); - case mixed::type::ARRAY: - php_warning("Illegal offset type array"); - return unset(v.as_array().to_int()); - case mixed::type::OBJECT: - php_warning("Illegal offset type %s", v.get_type_or_class_name()); - return unset(string()); - default: - __builtin_unreachable(); - } -} - -template + case mixed::type::NUL: + return unset(string()); + case mixed::type::BOOLEAN: + return unset(static_cast(v.as_bool())); + case mixed::type::INTEGER: + return unset(v.as_int()); + case mixed::type::FLOAT: + return unset(static_cast(v.as_double())); + case mixed::type::STRING: + return unset(v.as_string()); + case mixed::type::ARRAY: + php_warning("Illegal offset type array"); + return unset(v.as_array().to_int()); + case mixed::type::OBJECT: + php_warning("Illegal offset type %s", v.get_type_or_class_name()); + return unset(string()); + default: + __builtin_unreachable(); + } +} + +template bool array::empty() const { return count() == 0; } -template +template int64_t array::count() const { return p->size; } -template +template array_size array::size() const { return {p->size, is_vector()}; } -template -template -void array::merge_with(const array &other) noexcept { +template +template +void array::merge_with(const array& other) noexcept { for (auto it : other) { push_back_iterator(it); } } -template -template -void array::merge_with_recursive(const array &other) noexcept { +template +template +void array::merge_with_recursive(const array& other) noexcept { for (auto it : other) { push_back_iterator(it); } } -template -void array::merge_with_recursive(const mixed &other) noexcept { +template +void array::merge_with_recursive(const mixed& other) noexcept { if (other.is_array()) { return merge_with_recursive(other.as_array()); } @@ -1594,23 +1562,27 @@ void array::merge_with_recursive(const mixed &other) noexcept { } } -template -const array array::operator+(const array &other) const { +template +const array array::operator+(const array& other) const { bool this_empty{this->empty()}; bool other_empty{other.empty()}; // short path in case at least one array is empty if (this_empty || other_empty) { - if (this_empty && other_empty) { return {}; } - else if (other_empty) { return *this; } - else { return other; } + if (this_empty && other_empty) { + return {}; + } else if (other_empty) { + return *this; + } else { + return other; + } } array result(size() + other.size()); if (is_vector()) { uint32_t size = p->size; - T *it = (T *)p->entries(); + T* it = (T*)p->entries(); if (result.is_vector()) { for (uint32_t i = 0; i < size; i++) { @@ -1622,7 +1594,7 @@ const array array::operator+(const array &other) const { } } } else { - for (const array_bucket *it = p->begin(); it != p->end(); it = p->next(it)) { + for (const array_bucket* it = p->begin(); it != p->end(); it = p->next(it)) { if (p->is_string_hash_entry(it)) { result.p->set_map_value(overwrite_element::YES, it->int_key, it->string_key, it->value); } else { @@ -1633,7 +1605,7 @@ const array array::operator+(const array &other) const { if (other.is_vector()) { uint32_t size = other.p->size; - T *it = (T *)other.p->entries(); + T* it = (T*)other.p->entries(); if (result.is_vector()) { for (uint32_t i = p->size; i < size; i++) { @@ -1645,7 +1617,7 @@ const array array::operator+(const array &other) const { } } } else { - for (const array_bucket *it = other.p->begin(); it != other.p->end(); it = other.p->next(it)) { + for (const array_bucket* it = other.p->begin(); it != other.p->end(); it = other.p->next(it)) { if (other.p->is_string_hash_entry(it)) { result.p->set_map_value(overwrite_element::NO, it->int_key, it->string_key, it->value); } else { @@ -1657,21 +1629,21 @@ const array array::operator+(const array &other) const { return result; } -template -array &array::operator+=(const array &other) { +template +array& array::operator+=(const array& other) { if (other.empty()) { return *this; } if (is_vector()) { if (other.is_vector()) { uint32_t size = other.p->size; - T *it = (T *)other.p->entries(); + T* it = (T*)other.p->entries(); if (p->ref_cnt > 0) { uint32_t my_size = p->size; - T *my_it = (T *)p->entries(); + T* my_it = (T*)p->entries(); - array_inner *new_array = array_inner::create(max(size, my_size), true); + array_inner* new_array = array_inner::create(max(size, my_size), true); for (uint32_t i = 0; i < my_size; i++) { new_array->push_back_vector_value(my_it[i]); @@ -1681,7 +1653,7 @@ array &array::operator+=(const array &other) { p = new_array; } else if (p->buf_size < size + 2) { uint32_t new_size = max(size + 2, p->buf_size * 2); - p = (array_inner *)RuntimeAllocator::get().realloc_script_memory((void *)p, p->sizeof_vector(new_size), p->sizeof_vector(p->buf_size)); + p = (array_inner*)RuntimeAllocator::get().realloc_script_memory((void*)p, p->sizeof_vector(new_size), p->sizeof_vector(p->buf_size)); p->buf_size = new_size; } @@ -1695,8 +1667,8 @@ array &array::operator+=(const array &other) { return *this; } else { - array_inner *new_array = array_inner::create(p->size + other.p->size + 4, false); - T *it = (T *)p->entries(); + array_inner* new_array = array_inner::create(p->size + other.p->size + 4, false); + T* it = (T*)p->entries(); for (uint32_t i = 0; i != p->size; i++) { new_array->set_map_value(overwrite_element::YES, i, it[i]); @@ -1713,9 +1685,9 @@ array &array::operator+=(const array &other) { uint32_t new_int_size = p->size + other.p->size; if (new_int_size * 5 > 3 * p->buf_size || p->ref_cnt > 0) { - array_inner *new_array = array_inner::create(max(new_int_size, 2 * p->size) + 1, false); + array_inner* new_array = array_inner::create(max(new_int_size, 2 * p->size) + 1, false); - for (const array_bucket *it = p->begin(); it != p->end(); it = p->next(it)) { + for (const array_bucket* it = p->begin(); it != p->end(); it = p->next(it)) { if (p->is_string_hash_entry(it)) { new_array->set_map_value(overwrite_element::YES, it->int_key, it->string_key, it->value); } else { @@ -1730,13 +1702,13 @@ array &array::operator+=(const array &other) { if (other.is_vector()) { uint32_t size = other.p->size; - T *it = (T *)other.p->entries(); + T* it = (T*)other.p->entries(); for (uint32_t i = 0; i < size; i++) { p->set_map_value(overwrite_element::NO, i, it[i]); } } else { - for (array_bucket *it = other.p->begin(); it != other.p->end(); it = other.p->next(it)) { + for (array_bucket* it = other.p->begin(); it != other.p->end(); it = other.p->next(it)) { if (other.p->is_string_hash_entry(it)) { p->set_map_value(overwrite_element::NO, it->int_key, it->string_key, it->value); } else { @@ -1748,9 +1720,9 @@ array &array::operator+=(const array &other) { return *this; } -template -template -T &array::emplace_back(Args &&... args) noexcept { +template +template +T& array::emplace_back(Args&&... args) noexcept { if (is_vector()) { mutate_if_vector_needs_space(); return p->emplace_back_vector_value(std::forward(args)...); @@ -1760,19 +1732,19 @@ T &array::emplace_back(Args &&... args) noexcept { } } -template -void array::push_back(T &&v) noexcept { +template +void array::push_back(T&& v) noexcept { emplace_back(std::move(v)); } -template -void array::push_back(const T &v) noexcept { +template +void array::push_back(const T& v) noexcept { emplace_back(v); } -template -template -std::enable_if_t array::start_merge_recursive(T &value, bool was_inserted, const T &other_value) noexcept { +template +template +std::enable_if_t array::start_merge_recursive(T& value, bool was_inserted, const T& other_value) noexcept { static_assert(std::is_same_v); if (!was_inserted) { if (!value.is_array()) { @@ -1782,23 +1754,22 @@ std::enable_if_t array::start_merge_recurs } } -template -template -void array::push_back_iterator(const array_iterator &it) noexcept { +template +template +void array::push_back_iterator(const array_iterator& it) noexcept { if (it.self_->is_vector()) { - emplace_back(*reinterpret_cast(it.entry_)); + emplace_back(*reinterpret_cast(it.entry_)); } else { - auto *entry = reinterpret_cast::bucket_type *>(it.entry_); + auto* entry = reinterpret_cast::bucket_type*>(it.entry_); if (it.self_->is_string_hash_entry(entry)) { mutate_to_map_if_vector_or_map_need_space(); // don't overwrite existing element if we are in merge_recursive::YES mode, // this case will be handled further - auto [value_ref, inserted] = p->emplace_string_key_map_value( - recursive == merge_recursive::YES ? overwrite_element::NO : overwrite_element::YES, - entry->int_key, entry->string_key, entry->value); + auto [value_ref, inserted] = p->emplace_string_key_map_value(recursive == merge_recursive::YES ? overwrite_element::NO : overwrite_element::YES, + entry->int_key, entry->string_key, entry->value); - static_assert(std::is_same_v, "value_ref should be reference type"); + static_assert(std::is_same_v, "value_ref should be reference type"); start_merge_recursive(value_ref, inserted, entry->value); } else { @@ -1813,27 +1784,27 @@ void array::push_back_iterator(const array_iterator &it) noexcept { } } -template -void array::push_back(const const_iterator &it) noexcept { +template +void array::push_back(const const_iterator& it) noexcept { push_back_iterator(it); } -template -void array::push_back(const iterator &it) noexcept { +template +void array::push_back(const iterator& it) noexcept { push_back_iterator(it); } -template -const T array::push_back_return(const T &v) { +template +const T array::push_back_return(const T& v) { return emplace_back(v); } -template -const T array::push_back_return(T &&v) { +template +const T array::push_back_return(T&& v) { return emplace_back(std::move(v)); } -template +template void array::swap_int_keys(int64_t idx1, int64_t idx2) noexcept { if (idx1 == idx2) { return; @@ -1842,10 +1813,10 @@ void array::swap_int_keys(int64_t idx1, int64_t idx2) noexcept { // this function is supposed to be used for vector optimization, else branch is just to be on the safe side if (is_vector() && idx1 >= 0 && idx2 >= 0 && idx1 < p->size && idx2 < p->size) { mutate_if_vector_shared(); - std::swap(reinterpret_cast(p->entries())[idx1], reinterpret_cast(p->entries())[idx2]); + std::swap(reinterpret_cast(p->entries())[idx1], reinterpret_cast(p->entries())[idx2]); } else { - if (auto *v1 = find_value(idx1)) { - if (auto *v2 = find_value(idx2)) { + if (auto* v1 = find_value(idx1)) { + if (auto* v2 = find_value(idx2)) { T tmp = std::move(*v1); set_value(idx1, std::move(*v2)); set_value(idx2, std::move(tmp)); @@ -1854,22 +1825,22 @@ void array::swap_int_keys(int64_t idx1, int64_t idx2) noexcept { } } -template -void array::fill_vector(int64_t num, const T &value) { +template +void array::fill_vector(int64_t num, const T& value) { php_assert(is_vector() && p->size == 0 && num <= p->buf_size); - std::uninitialized_fill((T *)p->entries(), (T *)p->entries() + num, value); + std::uninitialized_fill((T*)p->entries(), (T*)p->entries() + num, value); p->max_key = num - 1; p->size = static_cast(num); } -template -void array::memcpy_vector(int64_t num __attribute__((unused)), const void *src_buf __attribute__((unused))) { +template +void array::memcpy_vector(int64_t num __attribute__((unused)), const void* src_buf __attribute__((unused))) { if constexpr (std::is_trivially_copyable_v) { php_assert(is_vector() && p->size == 0 && num <= p->buf_size); mutate_if_vector_shared(); - memcpy(reinterpret_cast(p->entries()), src_buf, num * sizeof(T)); + memcpy(reinterpret_cast(p->entries()), src_buf, num * sizeof(T)); p->max_key = num - 1; p->size = static_cast(num); } else { @@ -1877,16 +1848,14 @@ void array::memcpy_vector(int64_t num __attribute__((unused)), const void *sr } } - -template +template int64_t array::get_next_key() const { return p->max_key + 1; } - -template -template -void array::sort(const T1 &compare, bool renumber) { +template +template +void array::sort(const T1& compare, bool renumber) { int64_t n = count(); if (renumber) { @@ -1895,8 +1864,8 @@ void array::sort(const T1 &compare, bool renumber) { } if (!is_vector()) { - array_inner *res = array_inner::create(n, true); - for (array_bucket *it = p->begin(); it != p->end(); it = p->next(it)) { + array_inner* res = array_inner::create(n, true); + for (array_bucket* it = p->begin(); it != p->end(); it = p->next(it)) { res->push_back_vector_value(it->value); } @@ -1906,11 +1875,8 @@ void array::sort(const T1 &compare, bool renumber) { mutate_if_vector_shared(); } - const auto elements_cmp = - [&compare](const T &lhs, const T &rhs) { - return compare(lhs, rhs) > 0; - }; - T *begin = reinterpret_cast(p->entries()); + const auto elements_cmp = [&compare](const T& lhs, const T& rhs) { return compare(lhs, rhs) > 0; }; + T* begin = reinterpret_cast(p->entries()); dl::sort(begin, begin + n, elements_cmp); return; } @@ -1925,18 +1891,15 @@ void array::sort(const T1 &compare, bool renumber) { mutate_if_map_shared(); } - array_bucket **arTmp = (array_bucket **)RuntimeAllocator::get().alloc_script_memory(n * sizeof(array_bucket * )); + array_bucket** arTmp = (array_bucket**)RuntimeAllocator::get().alloc_script_memory(n * sizeof(array_bucket*)); uint32_t i = 0; - for (array_bucket *it = p->begin(); it != p->end(); it = p->next(it)) { + for (array_bucket* it = p->begin(); it != p->end(); it = p->next(it)) { arTmp[i++] = it; } - php_assert (i == n); + php_assert(i == n); - const auto hash_entry_cmp = - [&compare](const array_bucket *lhs, const array_bucket *rhs) { - return compare(lhs->value, rhs->value) > 0; - }; - dl::sort(arTmp, arTmp + n, hash_entry_cmp); + const auto hash_entry_cmp = [&compare](const array_bucket* lhs, const array_bucket* rhs) { return compare(lhs->value, rhs->value) > 0; }; + dl::sort(arTmp, arTmp + n, hash_entry_cmp); arTmp[0]->prev = p->get_pointer(p->end()); p->end()->next = p->get_pointer(arTmp[0]); @@ -1947,13 +1910,12 @@ void array::sort(const T1 &compare, bool renumber) { arTmp[n - 1]->next = p->get_pointer(p->end()); p->end()->prev = p->get_pointer(arTmp[n - 1]); - RuntimeAllocator::get().free_script_memory(arTmp, n * sizeof(array_bucket * )); + RuntimeAllocator::get().free_script_memory(arTmp, n * sizeof(array_bucket*)); } - -template -template -void array::ksort(const T1 &compare) { +template +template +void array::ksort(const T1& compare) { int64_t n = count(); if (n <= 1) { return; @@ -1966,36 +1928,37 @@ void array::ksort(const T1 &compare) { } array keys(array_size(n, true)); - for (auto *it = p->begin(); it != p->end(); it = p->next(it)) { + for (auto* it = p->begin(); it != p->end(); it = p->next(it)) { keys.p->push_back_vector_value(it->get_key()); } - key_type *keysp = (key_type *)keys.p->entries(); + key_type* keysp = (key_type*)keys.p->entries(); dl::sort(keysp, keysp + n, compare); - list_hash_entry *prev = (list_hash_entry *)p->end(); + list_hash_entry* prev = (list_hash_entry*)p->end(); for (uint32_t j = 0; j < n; j++) { - list_hash_entry *cur; + list_hash_entry* cur; if (is_int_key(keysp[j])) { int64_t int_key = keysp[j].to_int(); uint32_t bucket = p->choose_bucket(int_key); while (p->entries()[bucket].int_key != int_key || !p->entries()[bucket].string_key.is_dummy_string()) { - if (unlikely (++bucket == p->buf_size)) { + if (unlikely(++bucket == p->buf_size)) { bucket = 0; } } - cur = (list_hash_entry * ) &p->entries()[bucket]; + cur = (list_hash_entry*)&p->entries()[bucket]; } else { string string_key = keysp[j].to_string(); int64_t int_key = string_key.hash(); - array_bucket *string_entries = p->entries(); + array_bucket* string_entries = p->entries(); uint32_t bucket = p->choose_bucket(int_key); - while ((string_entries[bucket].int_key != int_key || string_entries[bucket].string_key.is_dummy_string() || string_entries[bucket].string_key != string_key)) { - if (unlikely (++bucket == p->buf_size)) { + while ((string_entries[bucket].int_key != int_key || string_entries[bucket].string_key.is_dummy_string() || + string_entries[bucket].string_key != string_key)) { + if (unlikely(++bucket == p->buf_size)) { bucket = 0; } } - cur = (list_hash_entry * ) & string_entries[bucket]; + cur = (list_hash_entry*)&string_entries[bucket]; } cur->prev = p->get_pointer(prev); @@ -2007,15 +1970,14 @@ void array::ksort(const T1 &compare) { p->end()->prev = p->get_pointer(prev); } - -template -void array::swap(array &other) { - array_inner *tmp = p; +template +void array::swap(array& other) { + array_inner* tmp = p; p = other.p; other.p = tmp; } -template +template T array::pop() { if (empty()) { return {}; @@ -2027,19 +1989,17 @@ T array::pop() { } mutate_if_map_shared(); - array_bucket *it = p->prev(p->end()); + array_bucket* it = p->prev(p->end()); - return p->is_string_hash_entry(it) ? - p->unset_map_value(it->string_key, it->int_key) : - p->unset_map_value(it->int_key); + return p->is_string_hash_entry(it) ? p->unset_map_value(it->string_key, it->int_key) : p->unset_map_value(it->int_key); } -template -T &array::back() { +template +T& array::back() { return (--end()).get_value(); } -template +template T array::shift() { if (count() == 0) { php_warning("Cannot use array_shift on empty array"); @@ -2049,11 +2009,11 @@ T array::shift() { if (is_vector()) { mutate_if_vector_shared(); - T *it = (T *)p->entries(); + T* it = (T*)p->entries(); T res = *it; it->~T(); - memmove((void *)it, it + 1, --p->size * sizeof(T)); + memmove((void*)it, it + 1, --p->size * sizeof(T)); p->max_key--; return res; @@ -2061,8 +2021,8 @@ T array::shift() { array_size new_size = size().cut(count() - 1); const bool is_v = p->has_no_string_keys(); - array_inner *new_array = array_inner::create(new_size.size, is_v); - array_bucket *it = p->begin(); + array_inner* new_array = array_inner::create(new_size.size, is_v); + array_bucket* it = p->begin(); T res = it->value; it = p->next(it); @@ -2087,21 +2047,21 @@ T array::shift() { } } -template -int64_t array::unshift(const T &val) { +template +int64_t array::unshift(const T& val) { if (is_vector()) { mutate_if_vector_needs_space(); - T *it = (T *)p->entries(); - memmove((void *)(it + 1), it, p->size++ * sizeof(T)); + T* it = (T*)p->entries(); + memmove((void*)(it + 1), it, p->size++ * sizeof(T)); p->max_key++; - new(it) T(val); + new (it) T(val); } else { array_size new_size = size(); const bool is_v = p->has_no_string_keys(); - array_inner *new_array = array_inner::create(new_size.size + 1, is_v); - array_bucket *it = p->begin(); + array_inner* new_array = array_inner::create(new_size.size + 1, is_v); + array_bucket* it = p->begin(); if (is_v) { new_array->push_back_vector_value(val); @@ -2130,33 +2090,32 @@ int64_t array::unshift(const T &val) { return count(); } - -template +template bool array::to_bool() const { return static_cast(count()); } -template +template int64_t array::to_int() const { return count(); } -template +template double array::to_float() const { return static_cast(count()); } -template +template int64_t array::get_reference_counter() const { return p->ref_cnt + 1; } -template +template bool array::is_reference_counter(ExtraRefCnt ref_cnt_value) const noexcept { return p->ref_cnt == ref_cnt_value; } -template +template void array::set_reference_counter_to(ExtraRefCnt ref_cnt_value) noexcept { // some const arrays are placed in read only memory and can't be modified if (p->ref_cnt != ref_cnt_value) { @@ -2164,7 +2123,7 @@ void array::set_reference_counter_to(ExtraRefCnt ref_cnt_value) noexcept { } } -template +template void array::force_destroy(ExtraRefCnt expected_ref_cnt) noexcept { php_assert(expected_ref_cnt != ExtraRefCnt::for_global_const); if (p) { @@ -2175,7 +2134,7 @@ void array::force_destroy(ExtraRefCnt expected_ref_cnt) noexcept { } } -template +template typename array::iterator array::begin_no_mutate() { if (is_vector()) { return typename array::iterator(p, p->entries()); @@ -2183,12 +2142,12 @@ typename array::iterator array::begin_no_mutate() { return typename array::iterator(p, p->begin()); } -template +template typename array::iterator array::end_no_mutate() { return end(); } -template +template void array::mutate_if_shared() noexcept { if (is_vector()) { mutate_if_vector_shared(); @@ -2197,29 +2156,29 @@ void array::mutate_if_shared() noexcept { } } -template -const T *array::get_const_vector_pointer() const { - php_assert (is_vector()); +template +const T* array::get_const_vector_pointer() const { + php_assert(is_vector()); return &(p->get_vector_value(0)); } -template -T *array::get_vector_pointer() { - php_assert (is_vector()); +template +T* array::get_vector_pointer() { + php_assert(is_vector()); return &(p->get_vector_value(0)); } -template -bool array::is_equal_inner_pointer(const array &other) const noexcept { +template +bool array::is_equal_inner_pointer(const array& other) const noexcept { return p == other.p; } -template -void swap(array &lhs, array &rhs) { +template +void swap(array& lhs, array& rhs) { lhs.swap(rhs); } -template -const array array_add(array a1, const array &a2) { +template +const array array_add(array a1, const array& a2) { return a1 += a2; } diff --git a/runtime-common/core/core-types/definition/mixed.cpp b/runtime-common/core/core-types/definition/mixed.cpp index 7a3f78dc25..c99cd87efc 100644 --- a/runtime-common/core/core-types/definition/mixed.cpp +++ b/runtime-common/core/core-types/definition/mixed.cpp @@ -11,92 +11,83 @@ namespace { -string to_string_without_warning(const mixed &m) { +string to_string_without_warning(const mixed& m) { switch (m.get_type()) { - case mixed::type::NUL: - return string(); - case mixed::type::BOOLEAN: - return (m.as_bool() ? string("1", 1) : string()); - case mixed::type::INTEGER: - return string(m.as_int()); - case mixed::type::FLOAT: - return string(m.as_double()); - case mixed::type::STRING: - return m.as_string(); - case mixed::type::ARRAY: - return string("Array", 5); - case mixed::type::OBJECT: { - const char *s = m.get_type_or_class_name(); - return string(s, strlen(s)); - } - default: - __builtin_unreachable(); + case mixed::type::NUL: + return string(); + case mixed::type::BOOLEAN: + return (m.as_bool() ? string("1", 1) : string()); + case mixed::type::INTEGER: + return string(m.as_int()); + case mixed::type::FLOAT: + return string(m.as_double()); + case mixed::type::STRING: + return m.as_string(); + case mixed::type::ARRAY: + return string("Array", 5); + case mixed::type::OBJECT: { + const char* s = m.get_type_or_class_name(); + return string(s, strlen(s)); + } + default: + __builtin_unreachable(); } } } // namespace -void mixed::copy_from(const mixed &other) { +void mixed::copy_from(const mixed& other) { switch (other.get_type()) { - case type::STRING: - new(&as_string()) string(other.as_string()); - break; - case type::ARRAY: - new(&as_array()) array(other.as_array()); - break; - case type::OBJECT: { - new (&storage_) vk::intrusive_ptr(*reinterpret_cast *>(&other.storage_)); - break; - } - default: - storage_ = other.storage_; + case type::STRING: + new (&as_string()) string(other.as_string()); + break; + case type::ARRAY: + new (&as_array()) array(other.as_array()); + break; + case type::OBJECT: { + new (&storage_) vk::intrusive_ptr(*reinterpret_cast*>(&other.storage_)); + break; + } + default: + storage_ = other.storage_; } type_ = other.get_type(); } -void mixed::copy_from(mixed &&other) { +void mixed::copy_from(mixed&& other) { switch (other.get_type()) { - case type::STRING: - new(&as_string()) string(std::move(other.as_string())); - break; - case type::ARRAY: - new(&as_array()) array(std::move(other.as_array())); - break; - case type::OBJECT: { - storage_ = other.storage_; - other.storage_ = 0; - break; - } - default: - storage_ = other.storage_; + case type::STRING: + new (&as_string()) string(std::move(other.as_string())); + break; + case type::ARRAY: + new (&as_array()) array(std::move(other.as_array())); + break; + case type::OBJECT: { + storage_ = other.storage_; + other.storage_ = 0; + break; + } + default: + storage_ = other.storage_; } type_ = other.get_type(); } -mixed::mixed(const mixed &v) noexcept { - copy_from(v); -} +mixed::mixed(const mixed& v) noexcept { copy_from(v); } -mixed::mixed(mixed &&v) noexcept { - copy_from(std::move(v)); -} +mixed::mixed(mixed&& v) noexcept { copy_from(std::move(v)); } -mixed::mixed(const Unknown &u __attribute__((unused))) noexcept { - php_assert ("Unknown used!!!" && 0); -} - -mixed::mixed(const char *s, string::size_type len) noexcept : - mixed(string{s, len}){ -} +mixed::mixed(const Unknown& u __attribute__((unused))) noexcept { php_assert("Unknown used!!!" && 0); } +mixed::mixed(const char* s, string::size_type len) noexcept : mixed(string{s, len}) {} -mixed &mixed::assign(const char *other, string::size_type len) { +mixed& mixed::assign(const char* other, string::size_type len) { if (get_type() == type::STRING) { as_string().assign(other, len); } else { destroy(); type_ = type::STRING; - new(&as_string()) string(other, len); + new (&as_string()) string(other, len); } return *this; } @@ -112,23 +103,17 @@ const mixed mixed::operator-() const { return arg1; } -const mixed mixed::operator+() const { - return to_numeric(); -} +const mixed mixed::operator+() const { return to_numeric(); } +int64_t mixed::operator~() const { return ~to_int(); } -int64_t mixed::operator~() const { - return ~to_int(); -} - - -mixed &mixed::operator+=(const mixed &other) { - if (likely (get_type() == type::INTEGER && other.get_type() == type::INTEGER)) { +mixed& mixed::operator+=(const mixed& other) { + if (likely(get_type() == type::INTEGER && other.get_type() == type::INTEGER)) { as_int() += other.as_int(); return *this; } - if (unlikely (get_type() == type::ARRAY || other.get_type() == type::ARRAY)) { + if (unlikely(get_type() == type::ARRAY || other.get_type() == type::ARRAY)) { if (get_type() == type::ARRAY && other.get_type() == type::ARRAY) { as_array() += other.as_array(); } else { @@ -158,8 +143,8 @@ mixed &mixed::operator+=(const mixed &other) { return *this; } -mixed &mixed::operator-=(const mixed &other) { - if (likely (get_type() == type::INTEGER && other.get_type() == type::INTEGER)) { +mixed& mixed::operator-=(const mixed& other) { + if (likely(get_type() == type::INTEGER && other.get_type() == type::INTEGER)) { as_int() -= other.as_int(); return *this; } @@ -185,8 +170,8 @@ mixed &mixed::operator-=(const mixed &other) { return *this; } -mixed &mixed::operator*=(const mixed &other) { - if (likely (get_type() == type::INTEGER && other.get_type() == type::INTEGER)) { +mixed& mixed::operator*=(const mixed& other) { + if (likely(get_type() == type::INTEGER && other.get_type() == type::INTEGER)) { as_int() *= other.as_int(); return *this; } @@ -212,8 +197,8 @@ mixed &mixed::operator*=(const mixed &other) { return *this; } -mixed &mixed::operator/=(const mixed &other) { - if (likely (get_type() == type::INTEGER && other.get_type() == type::INTEGER)) { +mixed& mixed::operator/=(const mixed& other) { + if (likely(get_type() == type::INTEGER && other.get_type() == type::INTEGER)) { if (as_int() % other.as_int() == 0) { as_int() /= other.as_int(); } else { @@ -263,7 +248,7 @@ mixed &mixed::operator/=(const mixed &other) { return *this; } -mixed &mixed::operator%=(const mixed &other) { +mixed& mixed::operator%=(const mixed& other) { int64_t div = other.to_int(); if (div == 0) { php_warning("Modulo by zero"); @@ -276,193 +261,187 @@ mixed &mixed::operator%=(const mixed &other) { return *this; } - -mixed &mixed::operator&=(const mixed &other) { +mixed& mixed::operator&=(const mixed& other) { convert_to_int(); as_int() &= other.to_int(); return *this; } -mixed &mixed::operator|=(const mixed &other) { +mixed& mixed::operator|=(const mixed& other) { convert_to_int(); as_int() |= other.to_int(); return *this; } -mixed &mixed::operator^=(const mixed &other) { +mixed& mixed::operator^=(const mixed& other) { convert_to_int(); as_int() ^= other.to_int(); return *this; } -mixed &mixed::operator<<=(const mixed &other) { +mixed& mixed::operator<<=(const mixed& other) { convert_to_int(); as_int() <<= other.to_int(); return *this; } -mixed &mixed::operator>>=(const mixed &other) { +mixed& mixed::operator>>=(const mixed& other) { convert_to_int(); as_int() >>= other.to_int(); return *this; } - -mixed &mixed::operator++() { +mixed& mixed::operator++() { switch (get_type()) { - case type::NUL: - type_ = type::INTEGER; - as_int() = 1; - return *this; - case type::BOOLEAN: - php_warning("Can't apply operator ++ to boolean"); - return *this; - case type::INTEGER: - ++as_int(); - return *this; - case type::FLOAT: - as_double() += 1; - return *this; - case type::STRING: - *this = as_string().to_numeric(); - return ++(*this); - case type::ARRAY: - php_warning("Can't apply operator ++ to array"); - return *this; - case type::OBJECT: - php_warning("Can't apply operator ++ to %s", get_type_or_class_name()); - return *this; - default: - __builtin_unreachable(); + case type::NUL: + type_ = type::INTEGER; + as_int() = 1; + return *this; + case type::BOOLEAN: + php_warning("Can't apply operator ++ to boolean"); + return *this; + case type::INTEGER: + ++as_int(); + return *this; + case type::FLOAT: + as_double() += 1; + return *this; + case type::STRING: + *this = as_string().to_numeric(); + return ++(*this); + case type::ARRAY: + php_warning("Can't apply operator ++ to array"); + return *this; + case type::OBJECT: + php_warning("Can't apply operator ++ to %s", get_type_or_class_name()); + return *this; + default: + __builtin_unreachable(); } } const mixed mixed::operator++(int) { switch (get_type()) { - case type::NUL: - type_ = type::INTEGER; - as_int() = 1; - return mixed(); - case type::BOOLEAN: - php_warning("Can't apply operator ++ to boolean"); - return as_bool(); - case type::INTEGER: { - mixed res(as_int()); - ++as_int(); - return res; - } - case type::FLOAT: { - mixed res(as_double()); - as_double() += 1; - return res; - } - case type::STRING: { - mixed res(as_string()); - *this = as_string().to_numeric(); - (*this)++; - return res; - } - case type::ARRAY: - php_warning("Can't apply operator ++ to array"); - return as_array(); - case type::OBJECT: - php_warning("Can't apply operator ++ to %s", get_type_or_class_name()); - return *this; - default: - __builtin_unreachable(); + case type::NUL: + type_ = type::INTEGER; + as_int() = 1; + return mixed(); + case type::BOOLEAN: + php_warning("Can't apply operator ++ to boolean"); + return as_bool(); + case type::INTEGER: { + mixed res(as_int()); + ++as_int(); + return res; + } + case type::FLOAT: { + mixed res(as_double()); + as_double() += 1; + return res; + } + case type::STRING: { + mixed res(as_string()); + *this = as_string().to_numeric(); + (*this)++; + return res; + } + case type::ARRAY: + php_warning("Can't apply operator ++ to array"); + return as_array(); + case type::OBJECT: + php_warning("Can't apply operator ++ to %s", get_type_or_class_name()); + return *this; + default: + __builtin_unreachable(); } } -mixed &mixed::operator--() { - if (likely (get_type() == type::INTEGER)) { +mixed& mixed::operator--() { + if (likely(get_type() == type::INTEGER)) { --as_int(); return *this; } switch (get_type()) { - case type::NUL: - php_warning("Can't apply operator -- to null"); - return *this; - case type::BOOLEAN: - php_warning("Can't apply operator -- to boolean"); - return *this; - case type::INTEGER: - --as_int(); - return *this; - case type::FLOAT: - as_double() -= 1; - return *this; - case type::STRING: - *this = as_string().to_numeric(); - return --(*this); - case type::ARRAY: - php_warning("Can't apply operator -- to array"); - return *this; - case type::OBJECT: - php_warning("Can't apply operator -- to %s", get_type_or_class_name()); - return *this; - default: - __builtin_unreachable(); + case type::NUL: + php_warning("Can't apply operator -- to null"); + return *this; + case type::BOOLEAN: + php_warning("Can't apply operator -- to boolean"); + return *this; + case type::INTEGER: + --as_int(); + return *this; + case type::FLOAT: + as_double() -= 1; + return *this; + case type::STRING: + *this = as_string().to_numeric(); + return --(*this); + case type::ARRAY: + php_warning("Can't apply operator -- to array"); + return *this; + case type::OBJECT: + php_warning("Can't apply operator -- to %s", get_type_or_class_name()); + return *this; + default: + __builtin_unreachable(); } } const mixed mixed::operator--(int) { - if (likely (get_type() == type::INTEGER)) { + if (likely(get_type() == type::INTEGER)) { mixed res(as_int()); --as_int(); return res; } switch (get_type()) { - case type::NUL: - php_warning("Can't apply operator -- to null"); - return mixed(); - case type::BOOLEAN: - php_warning("Can't apply operator -- to boolean"); - return as_bool(); - case type::INTEGER: { - mixed res(as_int()); - --as_int(); - return res; - } - case type::FLOAT: { - mixed res(as_double()); - as_double() -= 1; - return res; - } - case type::STRING: { - mixed res(as_string()); - *this = as_string().to_numeric(); - (*this)--; - return res; - } - case type::ARRAY: - php_warning("Can't apply operator -- to array"); - return as_array(); - case type::OBJECT: - php_warning("Can't apply operator -- to %s", get_type_or_class_name()); - return *this; - default: - __builtin_unreachable(); + case type::NUL: + php_warning("Can't apply operator -- to null"); + return mixed(); + case type::BOOLEAN: + php_warning("Can't apply operator -- to boolean"); + return as_bool(); + case type::INTEGER: { + mixed res(as_int()); + --as_int(); + return res; + } + case type::FLOAT: { + mixed res(as_double()); + as_double() -= 1; + return res; + } + case type::STRING: { + mixed res(as_string()); + *this = as_string().to_numeric(); + (*this)--; + return res; + } + case type::ARRAY: + php_warning("Can't apply operator -- to array"); + return as_array(); + case type::OBJECT: + php_warning("Can't apply operator -- to %s", get_type_or_class_name()); + return *this; + default: + __builtin_unreachable(); } } +bool mixed::operator!() const { return !to_bool(); } -bool mixed::operator!() const { - return !to_bool(); -} - - -mixed &mixed::append(const string &v) { - if (unlikely (get_type() != type::STRING)) { +mixed& mixed::append(const string& v) { + if (unlikely(get_type() != type::STRING)) { convert_to_string(); } as_string().append(v); return *this; } -mixed &mixed::append(tmp_string v) { - if (unlikely (get_type() != type::STRING)) { +mixed& mixed::append(tmp_string v) { + if (unlikely(get_type() != type::STRING)) { convert_to_string(); } as_string().append(v.data, v.size); @@ -471,564 +450,553 @@ mixed &mixed::append(tmp_string v) { const mixed mixed::to_numeric() const { switch (get_type()) { - case type::NUL: - return 0; - case type::BOOLEAN: - return (as_bool() ? 1 : 0); - case type::INTEGER: - return as_int(); - case type::FLOAT: - return as_double(); - case type::STRING: - return as_string().to_numeric(); - case type::ARRAY: - php_warning("Wrong conversion from array to number"); - return as_array().to_int(); - case type::OBJECT: - php_warning("Wrong conversion from %s to number", get_type_or_class_name()); - return (as_object() ? 1 : 0); - default: - __builtin_unreachable(); + case type::NUL: + return 0; + case type::BOOLEAN: + return (as_bool() ? 1 : 0); + case type::INTEGER: + return as_int(); + case type::FLOAT: + return as_double(); + case type::STRING: + return as_string().to_numeric(); + case type::ARRAY: + php_warning("Wrong conversion from array to number"); + return as_array().to_int(); + case type::OBJECT: + php_warning("Wrong conversion from %s to number", get_type_or_class_name()); + return (as_object() ? 1 : 0); + default: + __builtin_unreachable(); } } - bool mixed::to_bool() const { switch (get_type()) { - case type::NUL: - return false; - case type::BOOLEAN: - return as_bool(); - case type::INTEGER: - return (bool)as_int(); - case type::FLOAT: - return (bool)as_double(); - case type::STRING: - return as_string().to_bool(); - case type::ARRAY: - return !as_array().empty(); - case type::OBJECT: - return (bool)as_object(); - default: - __builtin_unreachable(); + case type::NUL: + return false; + case type::BOOLEAN: + return as_bool(); + case type::INTEGER: + return (bool)as_int(); + case type::FLOAT: + return (bool)as_double(); + case type::STRING: + return as_string().to_bool(); + case type::ARRAY: + return !as_array().empty(); + case type::OBJECT: + return (bool)as_object(); + default: + __builtin_unreachable(); } } int64_t mixed::to_int() const { switch (get_type()) { - case type::NUL: - return 0; - case type::BOOLEAN: - return static_cast(as_bool()); - case type::INTEGER: - return as_int(); - case type::FLOAT: - return static_cast(as_double()); - case type::STRING: - return as_string().to_int(); - case type::ARRAY: - php_warning("Wrong conversion from array to int"); - return as_array().to_int(); - case type::OBJECT: - php_warning("Wrong conversion from %s to int", get_type_or_class_name()); - return (as_object() ? 1 : 0); - default: - __builtin_unreachable(); + case type::NUL: + return 0; + case type::BOOLEAN: + return static_cast(as_bool()); + case type::INTEGER: + return as_int(); + case type::FLOAT: + return static_cast(as_double()); + case type::STRING: + return as_string().to_int(); + case type::ARRAY: + php_warning("Wrong conversion from array to int"); + return as_array().to_int(); + case type::OBJECT: + php_warning("Wrong conversion from %s to int", get_type_or_class_name()); + return (as_object() ? 1 : 0); + default: + __builtin_unreachable(); } } double mixed::to_float() const { switch (get_type()) { - case type::NUL: - return 0.0; - case type::BOOLEAN: - return (as_bool() ? 1.0 : 0.0); - case type::INTEGER: - return (double)as_int(); - case type::FLOAT: - return as_double(); - case type::STRING: - return as_string().to_float(); - case type::ARRAY: - php_warning("Wrong conversion from array to float"); - return as_array().to_float(); - case type::OBJECT: { - php_warning("Wrong conversion from %s to float", get_type_or_class_name()); - return (as_object() ? 1.0 : 0.0); - } - default: - __builtin_unreachable(); + case type::NUL: + return 0.0; + case type::BOOLEAN: + return (as_bool() ? 1.0 : 0.0); + case type::INTEGER: + return (double)as_int(); + case type::FLOAT: + return as_double(); + case type::STRING: + return as_string().to_float(); + case type::ARRAY: + php_warning("Wrong conversion from array to float"); + return as_array().to_float(); + case type::OBJECT: { + php_warning("Wrong conversion from %s to float", get_type_or_class_name()); + return (as_object() ? 1.0 : 0.0); + } + default: + __builtin_unreachable(); } } - const string mixed::to_string() const { switch (get_type()) { - case mixed::type::NUL: - case mixed::type::BOOLEAN: - case mixed::type::INTEGER: - case mixed::type::FLOAT: - case mixed::type::STRING: - break; - case type::ARRAY: - php_warning("Conversion from array to string"); - break; - case type::OBJECT: { - php_warning("Wrong conversion from %s to string", get_type_or_class_name()); - break; - } - default: - __builtin_unreachable(); + case mixed::type::NUL: + case mixed::type::BOOLEAN: + case mixed::type::INTEGER: + case mixed::type::FLOAT: + case mixed::type::STRING: + break; + case type::ARRAY: + php_warning("Conversion from array to string"); + break; + case type::OBJECT: { + php_warning("Wrong conversion from %s to string", get_type_or_class_name()); + break; + } + default: + __builtin_unreachable(); } return to_string_without_warning(*this); } const array mixed::to_array() const { switch (get_type()) { - case type::NUL: - return array(); - case type::BOOLEAN: - case type::INTEGER: - case type::FLOAT: - case type::STRING: - case type::OBJECT: { - array res(array_size(1, true)); - res.push_back(*this); - return res; - } - case type::ARRAY: - return as_array(); - default: - __builtin_unreachable(); + case type::NUL: + return array(); + case type::BOOLEAN: + case type::INTEGER: + case type::FLOAT: + case type::STRING: + case type::OBJECT: { + array res(array_size(1, true)); + res.push_back(*this); + return res; + } + case type::ARRAY: + return as_array(); + default: + __builtin_unreachable(); } } int64_t mixed::safe_to_int() const { switch (get_type()) { - case type::NUL: - return 0; - case type::BOOLEAN: - return static_cast(as_bool()); - case type::INTEGER: - return as_int(); - case type::FLOAT: { - constexpr auto max_int = static_cast(static_cast(std::numeric_limits::max()) + 1); - if (fabs(as_double()) > max_int) { - php_warning("Wrong conversion from double %.6lf to int", as_double()); - } - return static_cast(as_double()); + case type::NUL: + return 0; + case type::BOOLEAN: + return static_cast(as_bool()); + case type::INTEGER: + return as_int(); + case type::FLOAT: { + constexpr auto max_int = static_cast(static_cast(std::numeric_limits::max()) + 1); + if (fabs(as_double()) > max_int) { + php_warning("Wrong conversion from double %.6lf to int", as_double()); } - case type::STRING: - return as_string().safe_to_int(); - case type::ARRAY: - php_warning("Wrong conversion from array to int"); - return as_array().to_int(); - case type::OBJECT: { - php_warning("Wrong conversion from %s to int", get_type_or_class_name()); - return (as_object() ? 1 : 0); - } - default: - __builtin_unreachable(); + return static_cast(as_double()); + } + case type::STRING: + return as_string().safe_to_int(); + case type::ARRAY: + php_warning("Wrong conversion from array to int"); + return as_array().to_int(); + case type::OBJECT: { + php_warning("Wrong conversion from %s to int", get_type_or_class_name()); + return (as_object() ? 1 : 0); + } + default: + __builtin_unreachable(); } } - void mixed::convert_to_numeric() { switch (get_type()) { - case type::NUL: - type_ = type::INTEGER; - as_int() = 0; - return; - case type::BOOLEAN: - type_ = type::INTEGER; - as_int() = as_bool(); - return; - case type::INTEGER: - case type::FLOAT: - return; - case type::STRING: - *this = as_string().to_numeric(); - return; - case type::ARRAY: { - php_warning("Wrong conversion from array to number"); - const int64_t int_val = as_array().to_int(); - as_array().~array(); - type_ = type::INTEGER; - as_int() = int_val; - return; - } - case type::OBJECT: { - php_warning("Wrong conversion from %s to number", get_type_or_class_name()); - const int64_t int_val = (as_object() ? 1 : 0); - destroy(); - type_ = type::INTEGER; - as_int() = int_val; - return; - } - default: - __builtin_unreachable(); + case type::NUL: + type_ = type::INTEGER; + as_int() = 0; + return; + case type::BOOLEAN: + type_ = type::INTEGER; + as_int() = as_bool(); + return; + case type::INTEGER: + case type::FLOAT: + return; + case type::STRING: + *this = as_string().to_numeric(); + return; + case type::ARRAY: { + php_warning("Wrong conversion from array to number"); + const int64_t int_val = as_array().to_int(); + as_array().~array(); + type_ = type::INTEGER; + as_int() = int_val; + return; + } + case type::OBJECT: { + php_warning("Wrong conversion from %s to number", get_type_or_class_name()); + const int64_t int_val = (as_object() ? 1 : 0); + destroy(); + type_ = type::INTEGER; + as_int() = int_val; + return; + } + default: + __builtin_unreachable(); } } void mixed::convert_to_bool() { switch (get_type()) { - case type::NUL: - type_ = type::BOOLEAN; - as_bool() = 0; - return; - case type::BOOLEAN: - return; - case type::INTEGER: - type_ = type::BOOLEAN; - as_bool() = (bool)as_int(); - return; - case type::FLOAT: - type_ = type::BOOLEAN; - as_bool() = (bool)as_double(); - return; - case type::STRING: { - const bool bool_val = as_string().to_bool(); - as_string().~string(); - type_ = type::BOOLEAN; - as_bool() = bool_val; - return; - } - case type::ARRAY: { - const bool bool_val = as_array().to_bool(); - as_array().~array(); - type_ = type::BOOLEAN; - as_bool() = bool_val; - return; - } - case type::OBJECT: { - const bool bool_val = static_cast(as_object()); - destroy(); - type_ = type::BOOLEAN; - as_bool() = bool_val; - return; - } - default: - __builtin_unreachable(); + case type::NUL: + type_ = type::BOOLEAN; + as_bool() = 0; + return; + case type::BOOLEAN: + return; + case type::INTEGER: + type_ = type::BOOLEAN; + as_bool() = (bool)as_int(); + return; + case type::FLOAT: + type_ = type::BOOLEAN; + as_bool() = (bool)as_double(); + return; + case type::STRING: { + const bool bool_val = as_string().to_bool(); + as_string().~string(); + type_ = type::BOOLEAN; + as_bool() = bool_val; + return; + } + case type::ARRAY: { + const bool bool_val = as_array().to_bool(); + as_array().~array(); + type_ = type::BOOLEAN; + as_bool() = bool_val; + return; + } + case type::OBJECT: { + const bool bool_val = static_cast(as_object()); + destroy(); + type_ = type::BOOLEAN; + as_bool() = bool_val; + return; + } + default: + __builtin_unreachable(); } } void mixed::convert_to_int() { switch (get_type()) { - case type::NUL: - type_ = type::INTEGER; - as_int() = 0; - return; - case type::BOOLEAN: - type_ = type::INTEGER; - as_int() = as_bool(); - return; - case type::INTEGER: - return; - case type::FLOAT: - type_ = type::INTEGER; - as_int() = static_cast(as_double()); - return; - case type::STRING: { - const int64_t int_val = as_string().to_int(); - as_string().~string(); - type_ = type::INTEGER; - as_int() = int_val; - return; - } - case type::ARRAY: { - php_warning("Wrong conversion from array to int"); - const int64_t int_val = as_array().to_int(); - as_array().~array(); - type_ = type::INTEGER; - as_int() = int_val; - return; - } - case type::OBJECT: { - php_warning("Wrong conversion from %s to int", get_type_or_class_name()); - const int64_t int_val = (as_object() ? 1 : 0); - destroy(); - type_ = type::INTEGER; - as_int() = int_val; - return; - } - default: - __builtin_unreachable(); + case type::NUL: + type_ = type::INTEGER; + as_int() = 0; + return; + case type::BOOLEAN: + type_ = type::INTEGER; + as_int() = as_bool(); + return; + case type::INTEGER: + return; + case type::FLOAT: + type_ = type::INTEGER; + as_int() = static_cast(as_double()); + return; + case type::STRING: { + const int64_t int_val = as_string().to_int(); + as_string().~string(); + type_ = type::INTEGER; + as_int() = int_val; + return; + } + case type::ARRAY: { + php_warning("Wrong conversion from array to int"); + const int64_t int_val = as_array().to_int(); + as_array().~array(); + type_ = type::INTEGER; + as_int() = int_val; + return; + } + case type::OBJECT: { + php_warning("Wrong conversion from %s to int", get_type_or_class_name()); + const int64_t int_val = (as_object() ? 1 : 0); + destroy(); + type_ = type::INTEGER; + as_int() = int_val; + return; + } + default: + __builtin_unreachable(); } } void mixed::convert_to_float() { switch (get_type()) { - case type::NUL: - type_ = type::FLOAT; - as_double() = 0.0; - return; - case type::BOOLEAN: - type_ = type::FLOAT; - as_double() = as_bool(); - return; - case type::INTEGER: - type_ = type::FLOAT; - as_double() = (double)as_int(); - return; - case type::FLOAT: - return; - case type::STRING: { - const double float_val = as_string().to_float(); - as_string().~string(); - type_ = type::FLOAT; - as_double() = float_val; - return; - } - case type::ARRAY: { - php_warning("Wrong conversion from array to float"); - const double float_val = as_array().to_float(); - as_array().~array(); - type_ = type::FLOAT; - as_double() = float_val; - return; - } - case type::OBJECT: { - php_warning("Wrong conversion from %s to float", get_type_or_class_name()); - const double float_val = (as_object() ? 1.0 : 0.0); - destroy(); - type_ = type::FLOAT; - as_double() = float_val; - return; - } - default: - __builtin_unreachable(); + case type::NUL: + type_ = type::FLOAT; + as_double() = 0.0; + return; + case type::BOOLEAN: + type_ = type::FLOAT; + as_double() = as_bool(); + return; + case type::INTEGER: + type_ = type::FLOAT; + as_double() = (double)as_int(); + return; + case type::FLOAT: + return; + case type::STRING: { + const double float_val = as_string().to_float(); + as_string().~string(); + type_ = type::FLOAT; + as_double() = float_val; + return; + } + case type::ARRAY: { + php_warning("Wrong conversion from array to float"); + const double float_val = as_array().to_float(); + as_array().~array(); + type_ = type::FLOAT; + as_double() = float_val; + return; + } + case type::OBJECT: { + php_warning("Wrong conversion from %s to float", get_type_or_class_name()); + const double float_val = (as_object() ? 1.0 : 0.0); + destroy(); + type_ = type::FLOAT; + as_double() = float_val; + return; + } + default: + __builtin_unreachable(); } } void mixed::convert_to_string() { switch (get_type()) { - case type::NUL: - type_ = type::STRING; - new(&as_string()) string(); - return; - case type::BOOLEAN: - type_ = type::STRING; - if (as_bool()) { - new(&as_string()) string("1", 1); - } else { - new(&as_string()) string(); - } - return; - case type::INTEGER: - type_ = type::STRING; - new(&as_string()) string(as_int()); - return; - case type::FLOAT: - type_ = type::STRING; - new(&as_string()) string(as_double()); - return; - case type::STRING: - return; - case type::ARRAY: - php_warning("Converting from array to string"); - as_array().~array(); - type_ = type::STRING; - new(&as_string()) string("Array", 5); - return; - case type::OBJECT: { - php_warning("Wrong conversion from %s to string", get_type_or_class_name()); - string s = string(get_type_or_class_name(), strlen(get_type_or_class_name())); - destroy(); - type_ = type::STRING; - new (&as_string()) string(std::move(s)); - return; + case type::NUL: + type_ = type::STRING; + new (&as_string()) string(); + return; + case type::BOOLEAN: + type_ = type::STRING; + if (as_bool()) { + new (&as_string()) string("1", 1); + } else { + new (&as_string()) string(); } - default: - __builtin_unreachable(); + return; + case type::INTEGER: + type_ = type::STRING; + new (&as_string()) string(as_int()); + return; + case type::FLOAT: + type_ = type::STRING; + new (&as_string()) string(as_double()); + return; + case type::STRING: + return; + case type::ARRAY: + php_warning("Converting from array to string"); + as_array().~array(); + type_ = type::STRING; + new (&as_string()) string("Array", 5); + return; + case type::OBJECT: { + php_warning("Wrong conversion from %s to string", get_type_or_class_name()); + string s = string(get_type_or_class_name(), strlen(get_type_or_class_name())); + destroy(); + type_ = type::STRING; + new (&as_string()) string(std::move(s)); + return; + } + default: + __builtin_unreachable(); } } -const bool &mixed::as_bool(const char *function) const { +const bool& mixed::as_bool(const char* function) const { switch (get_type()) { - case type::BOOLEAN: - return as_bool(); - default: - php_warning("%s() expects parameter to be boolean, %s is given", function, get_type_or_class_name()); - return empty_value(); + case type::BOOLEAN: + return as_bool(); + default: + php_warning("%s() expects parameter to be boolean, %s is given", function, get_type_or_class_name()); + return empty_value(); } } -const int64_t &mixed::as_int(const char *function) const { +const int64_t& mixed::as_int(const char* function) const { switch (get_type()) { - case type::INTEGER: - return as_int(); - default: - php_warning("%s() expects parameter to be int, %s is given", function, get_type_or_class_name()); - return empty_value(); + case type::INTEGER: + return as_int(); + default: + php_warning("%s() expects parameter to be int, %s is given", function, get_type_or_class_name()); + return empty_value(); } } -const double &mixed::as_float(const char *function) const { +const double& mixed::as_float(const char* function) const { switch (get_type()) { - case type::FLOAT: - return as_double(); - default: - php_warning("%s() expects parameter to be float, %s is given", function, get_type_or_class_name()); - return empty_value(); + case type::FLOAT: + return as_double(); + default: + php_warning("%s() expects parameter to be float, %s is given", function, get_type_or_class_name()); + return empty_value(); } } -const string &mixed::as_string(const char *function) const { +const string& mixed::as_string(const char* function) const { switch (get_type()) { - case type::STRING: - return as_string(); - default: - php_warning("%s() expects parameter to be string, %s is given", function, get_type_or_class_name()); - return empty_value(); + case type::STRING: + return as_string(); + default: + php_warning("%s() expects parameter to be string, %s is given", function, get_type_or_class_name()); + return empty_value(); } } -const array &mixed::as_array(const char *function) const { +const array& mixed::as_array(const char* function) const { switch (get_type()) { - case type::ARRAY: - return as_array(); - default: - php_warning("%s() expects parameter to be array, %s is given", function, get_type_or_class_name()); - return empty_value>(); + case type::ARRAY: + return as_array(); + default: + php_warning("%s() expects parameter to be array, %s is given", function, get_type_or_class_name()); + return empty_value>(); } } - -bool &mixed::as_bool(const char *function) { +bool& mixed::as_bool(const char* function) { switch (get_type()) { - case type::NUL: - convert_to_bool(); - [[fallthrough]]; - case type::BOOLEAN: - return as_bool(); - default: - php_warning("%s() expects parameter to be boolean, %s is given", function, get_type_or_class_name()); - return empty_value(); + case type::NUL: + convert_to_bool(); + [[fallthrough]]; + case type::BOOLEAN: + return as_bool(); + default: + php_warning("%s() expects parameter to be boolean, %s is given", function, get_type_or_class_name()); + return empty_value(); } } -int64_t &mixed::as_int(const char *function) { - switch (get_type()) { - case type::NUL: - [[fallthrough]]; - case type::BOOLEAN: - [[fallthrough]]; - case type::FLOAT: - [[fallthrough]]; - case type::STRING: - convert_to_int(); - [[fallthrough]]; - case type::INTEGER: - return as_int(); - default: - php_warning("%s() expects parameter to be int, %s is given", function, get_type_or_class_name()); - return empty_value(); - } -} - -double &mixed::as_float(const char *function) { +int64_t& mixed::as_int(const char* function) { switch (get_type()) { - case type::NUL: - [[fallthrough]]; - case type::BOOLEAN: - [[fallthrough]]; - case type::INTEGER: - [[fallthrough]]; - case type::STRING: - convert_to_float(); - [[fallthrough]]; - case type::FLOAT: - return as_double(); - default: - php_warning("%s() expects parameter to be float, %s is given", function, get_type_or_class_name()); - return empty_value(); - } -} - -string &mixed::as_string(const char *function) { + case type::NUL: + [[fallthrough]]; + case type::BOOLEAN: + [[fallthrough]]; + case type::FLOAT: + [[fallthrough]]; + case type::STRING: + convert_to_int(); + [[fallthrough]]; + case type::INTEGER: + return as_int(); + default: + php_warning("%s() expects parameter to be int, %s is given", function, get_type_or_class_name()); + return empty_value(); + } +} + +double& mixed::as_float(const char* function) { switch (get_type()) { - case type::NUL: - [[fallthrough]]; - case type::BOOLEAN: - [[fallthrough]]; - case type::INTEGER: - [[fallthrough]]; - case type::FLOAT: - convert_to_string(); - [[fallthrough]]; - case type::STRING: - return as_string(); - default: - php_warning("%s() expects parameter to be string, %s is given", function, get_type_or_class_name()); - return empty_value(); - } -} - -array &mixed::as_array(const char *function) { + case type::NUL: + [[fallthrough]]; + case type::BOOLEAN: + [[fallthrough]]; + case type::INTEGER: + [[fallthrough]]; + case type::STRING: + convert_to_float(); + [[fallthrough]]; + case type::FLOAT: + return as_double(); + default: + php_warning("%s() expects parameter to be float, %s is given", function, get_type_or_class_name()); + return empty_value(); + } +} + +string& mixed::as_string(const char* function) { switch (get_type()) { - case type::ARRAY: - return as_array(); - default: - php_warning("%s() expects parameter to be array, %s is given", function, get_type_or_class_name()); - return empty_value>(); + case type::NUL: + [[fallthrough]]; + case type::BOOLEAN: + [[fallthrough]]; + case type::INTEGER: + [[fallthrough]]; + case type::FLOAT: + convert_to_string(); + [[fallthrough]]; + case type::STRING: + return as_string(); + default: + php_warning("%s() expects parameter to be string, %s is given", function, get_type_or_class_name()); + return empty_value(); } } - -bool mixed::is_numeric() const { +array& mixed::as_array(const char* function) { switch (get_type()) { - case type::INTEGER: - [[fallthrough]]; - case type::FLOAT: - return true; - case type::STRING: - return as_string().is_numeric(); - default: - return false; + case type::ARRAY: + return as_array(); + default: + php_warning("%s() expects parameter to be array, %s is given", function, get_type_or_class_name()); + return empty_value>(); } } -bool mixed::is_scalar() const { - return get_type() != type::NUL && get_type() != type::ARRAY && get_type() != type::OBJECT; +bool mixed::is_numeric() const { + switch (get_type()) { + case type::INTEGER: + [[fallthrough]]; + case type::FLOAT: + return true; + case type::STRING: + return as_string().is_numeric(); + default: + return false; + } } +bool mixed::is_scalar() const { return get_type() != type::NUL && get_type() != type::ARRAY && get_type() != type::OBJECT; } - -const char *mixed::get_type_c_str() const { +const char* mixed::get_type_c_str() const { switch (get_type()) { - case type::NUL: - return "NULL"; - case type::BOOLEAN: - return "boolean"; - case type::INTEGER: - return "integer"; - case type::FLOAT: - return "double"; - case type::STRING: - return "string"; - case type::ARRAY: - return "array"; - case type::OBJECT: - return "object"; - default: - __builtin_unreachable(); - } -} - -const char *mixed::get_type_or_class_name() const { + case type::NUL: + return "NULL"; + case type::BOOLEAN: + return "boolean"; + case type::INTEGER: + return "integer"; + case type::FLOAT: + return "double"; + case type::STRING: + return "string"; + case type::ARRAY: + return "array"; + case type::OBJECT: + return "object"; + default: + __builtin_unreachable(); + } +} + +const char* mixed::get_type_or_class_name() const { switch (get_type()) { - case type::OBJECT: - return as_object()->get_class(); - default: - return get_type_c_str(); + case type::OBJECT: + return as_object()->get_class(); + default: + return get_type_c_str(); } } -const string mixed::get_type_str() const { - return string(get_type_c_str()); -} +const string mixed::get_type_str() const { return string(get_type_c_str()); } -std::optional> try_as_array_access(const mixed &m) noexcept { +std::optional> try_as_array_access(const mixed& m) noexcept { using T = class_instance; if (!m.is_object()) { return std::nullopt; @@ -1043,7 +1011,7 @@ std::optional> try_as_array_access(const mixed &m) return std::nullopt; } -bool mixed::empty_at(const mixed &key) const { +bool mixed::empty_at(const mixed& key) const { if (type_ == type::OBJECT) { if (auto as_aa = try_as_array_access(*this)) { return !f$ArrayAccess$$offsetExists(*as_aa, key) || f$ArrayAccess$$offsetGet(*as_aa, key).empty(); @@ -1053,7 +1021,7 @@ bool mixed::empty_at(const mixed &key) const { return get_value(key).empty(); } -bool mixed::empty_at(const string &key) const { +bool mixed::empty_at(const string& key) const { if (type_ == type::OBJECT) { if (auto as_aa = try_as_array_access(*this)) { return !f$ArrayAccess$$offsetExists(*as_aa, key) || f$ArrayAccess$$offsetGet(*as_aa, key).empty(); @@ -1063,7 +1031,7 @@ bool mixed::empty_at(const string &key) const { return get_value(key).empty(); } -bool mixed::empty_at(const string &key, int64_t precomputed_hash) const { +bool mixed::empty_at(const string& key, int64_t precomputed_hash) const { if (type_ == type::OBJECT) { if (auto as_aa = try_as_array_access(*this)) { return !f$ArrayAccess$$offsetExists(*as_aa, key) || f$ArrayAccess$$offsetGet(*as_aa, key).empty(); @@ -1073,40 +1041,34 @@ bool mixed::empty_at(const string &key, int64_t precomputed_hash) const { return get_value(key, precomputed_hash).empty(); } -bool mixed::empty_at(const array::iterator &key) const { - return get_value(key).empty(); -} +bool mixed::empty_at(const array::iterator& key) const { return get_value(key).empty(); } -bool mixed::empty_at(const array::const_iterator &key) const { - return get_value(key).empty(); -} +bool mixed::empty_at(const array::const_iterator& key) const { return get_value(key).empty(); } -bool mixed::empty() const { - return !to_bool(); -} +bool mixed::empty() const { return !to_bool(); } int64_t mixed::count() const { switch (get_type()) { - case type::NUL: - php_warning("count(): Parameter is null, but an array expected"); - return 0; - case type::BOOLEAN: - case type::INTEGER: - case type::FLOAT: - case type::STRING: - php_warning("count(): Parameter is %s, but an array expected", get_type_c_str()); - return 1; - case type::ARRAY: - return as_array().count(); - case type::OBJECT: - php_warning("count(): Parameter is %s, but an array expected", get_type_or_class_name()); - return (as_object() ? 1 : 0); - default: - __builtin_unreachable(); - } -} - -mixed &mixed::operator=(const mixed &other) noexcept { + case type::NUL: + php_warning("count(): Parameter is null, but an array expected"); + return 0; + case type::BOOLEAN: + case type::INTEGER: + case type::FLOAT: + case type::STRING: + php_warning("count(): Parameter is %s, but an array expected", get_type_c_str()); + return 1; + case type::ARRAY: + return as_array().count(); + case type::OBJECT: + php_warning("count(): Parameter is %s, but an array expected", get_type_or_class_name()); + return (as_object() ? 1 : 0); + default: + __builtin_unreachable(); + } +} + +mixed& mixed::operator=(const mixed& other) noexcept { if (this != &other) { destroy(); copy_from(other); @@ -1114,7 +1076,7 @@ mixed &mixed::operator=(const mixed &other) noexcept { return *this; } -mixed &mixed::operator=(mixed &&other) noexcept { +mixed& mixed::operator=(mixed&& other) noexcept { if (this != &other) { destroy(); copy_from(std::move(other)); @@ -1122,8 +1084,7 @@ mixed &mixed::operator=(mixed &&other) noexcept { return *this; } - -int64_t mixed::compare(const mixed &rhs) const { +int64_t mixed::compare(const mixed& rhs) const { if (unlikely(is_string())) { if (likely(rhs.is_string())) { return compare_strings_php_order(as_string(), rhs.as_string()); @@ -1156,7 +1117,7 @@ int64_t mixed::compare(const mixed &rhs) const { } Materialized mixed::operator[](int64_t int_key) { - if (unlikely (get_type() != type::ARRAY)) { + if (unlikely(get_type() != type::ARRAY)) { if (get_type() == type::STRING) { php_warning("Writing to string by offset isn't supported"); return Materialized::WithRef(empty_value()); @@ -1164,7 +1125,7 @@ Materialized mixed::operator[](int64_t int_key) { if (get_type() == type::NUL || (get_type() == type::BOOLEAN && !as_bool())) { type_ = type::ARRAY; - new(&as_array()) array(); + new (&as_array()) array(); } else if (get_type() == type::OBJECT) { if (auto as_aa = try_as_array_access(*this)) { return Materialized::WithValue(f$ArrayAccess$$offsetGet(*as_aa, int_key)); @@ -1172,15 +1133,16 @@ Materialized mixed::operator[](int64_t int_key) { php_notice("Indirect modification of overloaded element of %s has no effect", get_type_or_class_name()); return Materialized::WithRef(empty_value()); } else { - php_warning("Cannot use a value \"%s\" of type %s as an array, index = %" PRIi64, to_string_without_warning(*this).c_str(), get_type_or_class_name(), int_key); + php_warning("Cannot use a value \"%s\" of type %s as an array, index = %" PRIi64, to_string_without_warning(*this).c_str(), get_type_or_class_name(), + int_key); return Materialized::WithRef(empty_value()); } } return Materialized::WithRef(as_array()[int_key]); } -Materialized mixed::operator[](const string &string_key) { - if (unlikely (get_type() != type::ARRAY)) { +Materialized mixed::operator[](const string& string_key) { + if (unlikely(get_type() != type::ARRAY)) { if (get_type() == type::STRING) { php_warning("Writing to string by offset is't supported"); return Materialized::WithRef(empty_value()); @@ -1188,7 +1150,7 @@ Materialized mixed::operator[](const string &string_key) { if (get_type() == type::NUL || (get_type() == type::BOOLEAN && !as_bool())) { type_ = type::ARRAY; - new(&as_array()) array(); + new (&as_array()) array(); } else if (get_type() == type::OBJECT) { if (auto as_aa = try_as_array_access(*this)) { return Materialized::WithValue(f$ArrayAccess$$offsetGet(*as_aa, string_key)); @@ -1196,7 +1158,8 @@ Materialized mixed::operator[](const string &string_key) { php_notice("Indirect modification of overloaded element of %s has no effect", get_type_or_class_name()); return Materialized::WithRef(empty_value()); } else { - php_warning("Cannot use a value \"%s\" of type %s as an array, index = %s", to_string_without_warning(*this).c_str(), get_type_or_class_name(), string_key.c_str()); + php_warning("Cannot use a value \"%s\" of type %s as an array, index = %s", to_string_without_warning(*this).c_str(), get_type_or_class_name(), + string_key.c_str()); return Materialized::WithRef(empty_value()); } } @@ -1211,42 +1174,36 @@ Materialized mixed::operator[](tmp_string string_key) { return (*this)[materialize_tmp_string(string_key)]; } -Materialized mixed::operator[](const mixed &v) { +Materialized mixed::operator[](const mixed& v) { switch (v.get_type()) { - case type::NUL: - return (*this)[string()]; - case type::BOOLEAN: - return (*this)[v.as_bool()]; - case type::INTEGER: - return (*this)[v.as_int()]; - case type::FLOAT: - return (*this)[static_cast(v.as_double())]; - case type::STRING: - return (*this)[v.as_string()]; - case type::ARRAY: - php_warning("Illegal offset type %s", v.get_type_c_str()); - return (*this)[v.as_array().to_int()]; - case type::OBJECT: - php_warning("Illegal offset type %s", v.get_type_or_class_name()); - return (*this)[(as_object() ? 1 : 0)]; - default: - __builtin_unreachable(); - } -} - -Materialized mixed::operator[](double double_key) { - return (*this)[static_cast(double_key)]; -} - -Materialized mixed::operator[](const array::const_iterator &it) { - return Materialized::WithRef(as_array()[it]); -} - -Materialized mixed::operator[](const array::iterator &it) { - return Materialized::WithRef(as_array()[it]); -} - -mixed mixed::set_value_return(const mixed &key, const mixed &val) { + case type::NUL: + return (*this)[string()]; + case type::BOOLEAN: + return (*this)[v.as_bool()]; + case type::INTEGER: + return (*this)[v.as_int()]; + case type::FLOAT: + return (*this)[static_cast(v.as_double())]; + case type::STRING: + return (*this)[v.as_string()]; + case type::ARRAY: + php_warning("Illegal offset type %s", v.get_type_c_str()); + return (*this)[v.as_array().to_int()]; + case type::OBJECT: + php_warning("Illegal offset type %s", v.get_type_or_class_name()); + return (*this)[(as_object() ? 1 : 0)]; + default: + __builtin_unreachable(); + } +} + +Materialized mixed::operator[](double double_key) { return (*this)[static_cast(double_key)]; } + +Materialized mixed::operator[](const array::const_iterator& it) { return Materialized::WithRef(as_array()[it]); } + +Materialized mixed::operator[](const array::iterator& it) { return Materialized::WithRef(as_array()[it]); } + +mixed mixed::set_value_return(const mixed& key, const mixed& val) { if (get_type() == type::OBJECT) { set_value(key, val); return val; @@ -1254,7 +1211,7 @@ mixed mixed::set_value_return(const mixed &key, const mixed &val) { return (*this)[key] = val; } -mixed mixed::set_value_return(const string &key, const mixed &val) { +mixed mixed::set_value_return(const string& key, const mixed& val) { if (get_type() == type::OBJECT) { set_value(key, val); return val; @@ -1262,16 +1219,12 @@ mixed mixed::set_value_return(const string &key, const mixed &val) { return (*this)[key] = val; } -mixed mixed::set_value_return(const array::iterator &key, const mixed &val) { - return (*this)[key] = val; -} +mixed mixed::set_value_return(const array::iterator& key, const mixed& val) { return (*this)[key] = val; } -mixed mixed::set_value_return(const array::const_iterator &key, const mixed &val) { - return (*this)[key] = val; -} +mixed mixed::set_value_return(const array::const_iterator& key, const mixed& val) { return (*this)[key] = val; } -void mixed::set_value(int64_t int_key, const mixed &v) { - if (unlikely (get_type() != type::ARRAY)) { +void mixed::set_value(int64_t int_key, const mixed& v) { + if (unlikely(get_type() != type::ARRAY)) { if (get_type() == type::STRING) { auto rhs_string = v.to_string(); if (rhs_string.empty()) { @@ -1307,17 +1260,18 @@ void mixed::set_value(int64_t int_key, const mixed &v) { if (get_type() == type::NUL || (get_type() == type::BOOLEAN && !as_bool())) { type_ = type::ARRAY; - new(&as_array()) array(); + new (&as_array()) array(); } else { - php_warning("Cannot use a value \"%s\" of type %s as an array, index = %" PRIi64, to_string_without_warning(*this).c_str(), get_type_or_class_name(), int_key); + php_warning("Cannot use a value \"%s\" of type %s as an array, index = %" PRIi64, to_string_without_warning(*this).c_str(), get_type_or_class_name(), + int_key); return; } } return as_array().set_value(int_key, v); } -void mixed::set_value(const string &string_key, const mixed &v) { - if (unlikely (get_type() != type::ARRAY)) { +void mixed::set_value(const string& string_key, const mixed& v) { + if (unlikely(get_type() != type::ARRAY)) { if (get_type() == type::STRING) { int64_t int_val = 0; if (!string_key.try_to_int(&int_val)) { @@ -1351,9 +1305,10 @@ void mixed::set_value(const string &string_key, const mixed &v) { } if (get_type() == type::NUL || (get_type() == type::BOOLEAN && !as_bool())) { type_ = type::ARRAY; - new(&as_array()) array(); + new (&as_array()) array(); } else { - php_warning("Cannot use a value \"%s\" of type %s as an array, index = %s", to_string_without_warning(*this).c_str(), get_type_or_class_name(), string_key.c_str()); + php_warning("Cannot use a value \"%s\" of type %s as an array, index = %s", to_string_without_warning(*this).c_str(), get_type_or_class_name(), + string_key.c_str()); return; } } @@ -1361,53 +1316,46 @@ void mixed::set_value(const string &string_key, const mixed &v) { return as_array().set_value(string_key, v); } -void mixed::set_value(const string &string_key, const mixed &v, int64_t precomuted_hash) { +void mixed::set_value(const string& string_key, const mixed& v, int64_t precomuted_hash) { return get_type() == type::ARRAY ? as_array().set_value(string_key, v, precomuted_hash) : set_value(string_key, v); } -void mixed::set_value(tmp_string string_key, const mixed &v) { +void mixed::set_value(tmp_string string_key, const mixed& v) { // TODO: as with arrays, avoid eager tmp_string->string conversion set_value(materialize_tmp_string(string_key), v); } -void mixed::set_value(const mixed &v, const mixed &value) { +void mixed::set_value(const mixed& v, const mixed& value) { switch (v.get_type()) { - case type::NUL: - return set_value(string(), value); - case type::BOOLEAN: - return set_value(static_cast(v.as_bool()), value); - case type::INTEGER: - return set_value(v.as_int(), value); - case type::FLOAT: - return set_value(static_cast(v.as_double()), value); - case type::STRING: - return set_value(v.as_string(), value); - case type::ARRAY: - php_warning("Illegal offset type array"); - return; - case type::OBJECT: - php_warning("Illegal offset type %s", v.get_type_or_class_name()); - return; - default: - __builtin_unreachable(); + case type::NUL: + return set_value(string(), value); + case type::BOOLEAN: + return set_value(static_cast(v.as_bool()), value); + case type::INTEGER: + return set_value(v.as_int(), value); + case type::FLOAT: + return set_value(static_cast(v.as_double()), value); + case type::STRING: + return set_value(v.as_string(), value); + case type::ARRAY: + php_warning("Illegal offset type array"); + return; + case type::OBJECT: + php_warning("Illegal offset type %s", v.get_type_or_class_name()); + return; + default: + __builtin_unreachable(); } } -void mixed::set_value(double double_key, const mixed &value) { - set_value(static_cast(double_key), value); -} +void mixed::set_value(double double_key, const mixed& value) { set_value(static_cast(double_key), value); } -void mixed::set_value(const array::const_iterator &it) { - return as_array().set_value(it); -} - -void mixed::set_value(const array::iterator &it) { - return as_array().set_value(it); -} +void mixed::set_value(const array::const_iterator& it) { return as_array().set_value(it); } +void mixed::set_value(const array::iterator& it) { return as_array().set_value(it); } const mixed mixed::get_value(int64_t int_key) const { - if (unlikely (get_type() != type::ARRAY)) { + if (unlikely(get_type() != type::ARRAY)) { if (get_type() == type::STRING) { if (int_key < 0 || int_key >= as_string().size()) { return string(); @@ -1425,7 +1373,8 @@ const mixed mixed::get_value(int64_t int_key) const { } if (get_type() != type::NUL && (get_type() != type::BOOLEAN || as_bool())) { - php_warning("Cannot use a value \"%s\" of type %s as an array, index = %" PRIi64, to_string_without_warning(*this).c_str(), get_type_or_class_name(), int_key); + php_warning("Cannot use a value \"%s\" of type %s as an array, index = %" PRIi64, to_string_without_warning(*this).c_str(), get_type_or_class_name(), + int_key); } return mixed(); } @@ -1433,8 +1382,8 @@ const mixed mixed::get_value(int64_t int_key) const { return as_array().get_value(int_key); } -const mixed mixed::get_value(const string &string_key) const { - if (unlikely (get_type() != type::ARRAY)) { +const mixed mixed::get_value(const string& string_key) const { + if (unlikely(get_type() != type::ARRAY)) { if (get_type() == type::STRING) { int64_t int_val = 0; if (!string_key.try_to_int(&int_val)) { @@ -1457,7 +1406,8 @@ const mixed mixed::get_value(const string &string_key) const { } if (get_type() != type::NUL && (get_type() != type::BOOLEAN || as_bool())) { - php_warning("Cannot use a value \"%s\" of type %s as an array, index = %s", to_string_without_warning(*this).c_str(), get_type_or_class_name(), string_key.c_str()); + php_warning("Cannot use a value \"%s\" of type %s as an array, index = %s", to_string_without_warning(*this).c_str(), get_type_or_class_name(), + string_key.c_str()); } return mixed(); } @@ -1465,7 +1415,7 @@ const mixed mixed::get_value(const string &string_key) const { return as_array().get_value(string_key); } -const mixed mixed::get_value(const string &string_key, int64_t precomuted_hash) const { +const mixed mixed::get_value(const string& string_key, int64_t precomuted_hash) const { return get_type() == type::ARRAY ? as_array().get_value(string_key, precomuted_hash) : get_value(string_key); } @@ -1478,43 +1428,37 @@ const mixed mixed::get_value(tmp_string string_key) const { return get_value(materialize_tmp_string(string_key)); } -const mixed mixed::get_value(const mixed &v) const { +const mixed mixed::get_value(const mixed& v) const { switch (v.get_type()) { - case type::NUL: - return get_value(string()); - case type::BOOLEAN: - return get_value(static_cast(v.as_bool())); - case type::INTEGER: - return get_value(v.as_int()); - case type::FLOAT: - return get_value(static_cast(v.as_double())); - case type::STRING: - return get_value(v.as_string()); - case type::ARRAY: - php_warning("Illegal offset type %s", v.get_type_c_str()); - return mixed(); - case type::OBJECT: - php_warning("Illegal offset type %s", v.get_type_or_class_name()); - return mixed(); - default: - __builtin_unreachable(); + case type::NUL: + return get_value(string()); + case type::BOOLEAN: + return get_value(static_cast(v.as_bool())); + case type::INTEGER: + return get_value(v.as_int()); + case type::FLOAT: + return get_value(static_cast(v.as_double())); + case type::STRING: + return get_value(v.as_string()); + case type::ARRAY: + php_warning("Illegal offset type %s", v.get_type_c_str()); + return mixed(); + case type::OBJECT: + php_warning("Illegal offset type %s", v.get_type_or_class_name()); + return mixed(); + default: + __builtin_unreachable(); } } -const mixed mixed::get_value(double double_key) const { - return get_value(static_cast(double_key)); -} +const mixed mixed::get_value(double double_key) const { return get_value(static_cast(double_key)); } -const mixed mixed::get_value(const array::const_iterator &it) const { - return as_array().get_value(it); -} +const mixed mixed::get_value(const array::const_iterator& it) const { return as_array().get_value(it); } -const mixed mixed::get_value(const array::iterator &it) const { - return as_array().get_value(it); -} +const mixed mixed::get_value(const array::iterator& it) const { return as_array().get_value(it); } -void mixed::push_back(const mixed &v) { - if (unlikely (get_type() != type::ARRAY)) { +void mixed::push_back(const mixed& v) { + if (unlikely(get_type() != type::ARRAY)) { if (get_type() == type::OBJECT) { if (auto as_aa = try_as_array_access(*this)) { f$ArrayAccess$$offsetSet(*as_aa, Optional{}, v); @@ -1522,7 +1466,7 @@ void mixed::push_back(const mixed &v) { } } else if (get_type() == type::NUL || (get_type() == type::BOOLEAN && !as_bool())) { type_ = type::ARRAY; - new(&as_array()) array(); + new (&as_array()) array(); } else { php_warning("[] operator not supported for type %s", get_type_or_class_name()); return; @@ -1532,8 +1476,8 @@ void mixed::push_back(const mixed &v) { return as_array().push_back(v); } -const mixed mixed::push_back_return(const mixed &v) { - if (unlikely (get_type() != type::ARRAY)) { +const mixed mixed::push_back_return(const mixed& v) { + if (unlikely(get_type() != type::ARRAY)) { if (get_type() == type::OBJECT) { if (auto as_aa = try_as_array_access(*this)) { f$ArrayAccess$$offsetSet(*as_aa, Optional{}, v); @@ -1541,7 +1485,7 @@ const mixed mixed::push_back_return(const mixed &v) { } } else if (get_type() == type::NUL || (get_type() == type::BOOLEAN && !as_bool())) { type_ = type::ARRAY; - new(&as_array()) array(); + new (&as_array()) array(); } else { php_warning("[] operator not supported for type %s", get_type_or_class_name()); return empty_value(); @@ -1552,7 +1496,7 @@ const mixed mixed::push_back_return(const mixed &v) { } bool mixed::isset(int64_t int_key) const { - if (unlikely (get_type() != type::ARRAY)) { + if (unlikely(get_type() != type::ARRAY)) { if (get_type() == type::OBJECT) { if (auto as_aa = try_as_array_access(*this)) { return f$ArrayAccess$$offsetExists(*as_aa, int_key); @@ -1575,36 +1519,33 @@ bool mixed::isset(int64_t int_key) const { return as_array().isset(int_key); } - -bool mixed::isset(const mixed &v) const { +bool mixed::isset(const mixed& v) const { switch (v.get_type()) { - case type::NUL: - return isset(string()); - case type::BOOLEAN: - return isset(static_cast(v.as_bool())); - case type::INTEGER: - return isset(v.as_int()); - case type::FLOAT: - return isset(static_cast(v.as_double())); - case type::STRING: - return isset(v.as_string()); - case type::ARRAY: - php_warning("Illegal offset type array"); - return false; - case type::OBJECT: - php_warning("Illegal offset type %s", get_type_or_class_name()); - return false; - default: - __builtin_unreachable(); - } -} - -bool mixed::isset(double double_key) const { - return isset(static_cast(double_key)); + case type::NUL: + return isset(string()); + case type::BOOLEAN: + return isset(static_cast(v.as_bool())); + case type::INTEGER: + return isset(v.as_int()); + case type::FLOAT: + return isset(static_cast(v.as_double())); + case type::STRING: + return isset(v.as_string()); + case type::ARRAY: + php_warning("Illegal offset type array"); + return false; + case type::OBJECT: + php_warning("Illegal offset type %s", get_type_or_class_name()); + return false; + default: + __builtin_unreachable(); + } } +bool mixed::isset(double double_key) const { return isset(static_cast(double_key)); } + void mixed::unset(int64_t int_key) { - if (unlikely (get_type() != type::ARRAY)) { + if (unlikely(get_type() != type::ARRAY)) { if (get_type() == type::OBJECT) { if (auto as_aa = try_as_array_access(*this)) { f$ArrayAccess$$offsetUnset(*as_aa, int_key); @@ -1623,9 +1564,8 @@ void mixed::unset(int64_t int_key) { as_array().unset(int_key); } - -void mixed::unset(const mixed &v) { - if (unlikely (get_type() != type::ARRAY)) { +void mixed::unset(const mixed& v) { + if (unlikely(get_type() != type::ARRAY)) { if (get_type() == type::OBJECT) { if (auto as_aa = try_as_array_access(*this)) { f$ArrayAccess$$offsetUnset(*as_aa, v); @@ -1642,164 +1582,162 @@ void mixed::unset(const mixed &v) { } switch (v.get_type()) { - case type::NUL: - as_array().unset(string()); - break; - case type::BOOLEAN: - as_array().unset(static_cast(v.as_bool())); - break; - case type::INTEGER: - as_array().unset(v.as_int()); - break; - case type::FLOAT: - as_array().unset(static_cast(v.as_double())); - break; - case type::STRING: - as_array().unset(v.as_string()); - break; - case type::ARRAY: - php_warning("Illegal offset type array"); - break; - case type::OBJECT: - php_warning("Illegal offset type %s", v.get_type_or_class_name()); - break; - default: - __builtin_unreachable(); - } -} - -void mixed::unset(double double_key) { - unset(static_cast(double_key)); -} + case type::NUL: + as_array().unset(string()); + break; + case type::BOOLEAN: + as_array().unset(static_cast(v.as_bool())); + break; + case type::INTEGER: + as_array().unset(v.as_int()); + break; + case type::FLOAT: + as_array().unset(static_cast(v.as_double())); + break; + case type::STRING: + as_array().unset(v.as_string()); + break; + case type::ARRAY: + php_warning("Illegal offset type array"); + break; + case type::OBJECT: + php_warning("Illegal offset type %s", v.get_type_or_class_name()); + break; + default: + __builtin_unreachable(); + } +} + +void mixed::unset(double double_key) { unset(static_cast(double_key)); } array::const_iterator mixed::begin() const { - if (likely (get_type() == type::ARRAY)) { + if (likely(get_type() == type::ARRAY)) { return as_array().begin(); } - php_warning("Invalid argument supplied for foreach(), %s (string representation - \"%s\") is given", get_type_or_class_name(), to_string_without_warning(*this).c_str()); + php_warning("Invalid argument supplied for foreach(), %s (string representation - \"%s\") is given", get_type_or_class_name(), + to_string_without_warning(*this).c_str()); return array::const_iterator(); } array::const_iterator mixed::end() const { - if (likely (get_type() == type::ARRAY)) { + if (likely(get_type() == type::ARRAY)) { return as_array().end(); } return array::const_iterator(); } - array::iterator mixed::begin() { - if (likely (get_type() == type::ARRAY)) { + if (likely(get_type() == type::ARRAY)) { return as_array().begin(); } - php_warning("Invalid argument supplied for foreach(), %s (string representation - \"%s\") is given", get_type_or_class_name(), to_string_without_warning(*this).c_str()); + php_warning("Invalid argument supplied for foreach(), %s (string representation - \"%s\") is given", get_type_or_class_name(), + to_string_without_warning(*this).c_str()); return array::iterator(); } array::iterator mixed::end() { - if (likely (get_type() == type::ARRAY)) { + if (likely(get_type() == type::ARRAY)) { return as_array().end(); } return array::iterator(); } - int64_t mixed::get_reference_counter() const { switch (get_type()) { - case type::NUL: - return -1; - case type::BOOLEAN: - return -2; - case type::INTEGER: - return -3; - case type::FLOAT: - return -4; - case type::STRING: - return as_string().get_reference_counter(); - case type::ARRAY: - return as_array().get_reference_counter(); - case type::OBJECT: - return as_object()->get_refcnt(); - default: - __builtin_unreachable(); + case type::NUL: + return -1; + case type::BOOLEAN: + return -2; + case type::INTEGER: + return -3; + case type::FLOAT: + return -4; + case type::STRING: + return as_string().get_reference_counter(); + case type::ARRAY: + return as_array().get_reference_counter(); + case type::OBJECT: + return as_object()->get_refcnt(); + default: + __builtin_unreachable(); } } void mixed::set_reference_counter_to(ExtraRefCnt ref_cnt_value) noexcept { switch (get_type()) { - case type::NUL: - case type::BOOLEAN: - case type::INTEGER: - case type::FLOAT: - return; - case type::STRING: - return as_string().set_reference_counter_to(ref_cnt_value); - case type::ARRAY: - return as_array().set_reference_counter_to(ref_cnt_value); - case type::OBJECT: - return as_object()->set_refcnt(ref_cnt_value); - default: - __builtin_unreachable(); + case type::NUL: + case type::BOOLEAN: + case type::INTEGER: + case type::FLOAT: + return; + case type::STRING: + return as_string().set_reference_counter_to(ref_cnt_value); + case type::ARRAY: + return as_array().set_reference_counter_to(ref_cnt_value); + case type::OBJECT: + return as_object()->set_refcnt(ref_cnt_value); + default: + __builtin_unreachable(); } } bool mixed::is_reference_counter(ExtraRefCnt ref_cnt_value) const noexcept { switch (get_type()) { - case type::NUL: - case type::BOOLEAN: - case type::INTEGER: - case type::FLOAT: - return false; - case type::STRING: - return as_string().is_reference_counter(ref_cnt_value); - case type::ARRAY: - return as_array().is_reference_counter(ref_cnt_value); - case type::OBJECT: - return static_cast(as_object()->get_refcnt()) == ref_cnt_value; - default: - __builtin_unreachable(); + case type::NUL: + case type::BOOLEAN: + case type::INTEGER: + case type::FLOAT: + return false; + case type::STRING: + return as_string().is_reference_counter(ref_cnt_value); + case type::ARRAY: + return as_array().is_reference_counter(ref_cnt_value); + case type::OBJECT: + return static_cast(as_object()->get_refcnt()) == ref_cnt_value; + default: + __builtin_unreachable(); } } void mixed::force_destroy(ExtraRefCnt expected_ref_cnt) noexcept { switch (get_type()) { - case type::STRING: - as_string().force_destroy(expected_ref_cnt); - break; - case type::ARRAY: - as_array().force_destroy(expected_ref_cnt); - break; - case type::OBJECT: - php_warning("Objects (%s) are not supported in confdata", get_type_or_class_name()); - break; - default: - __builtin_unreachable(); + case type::STRING: + as_string().force_destroy(expected_ref_cnt); + break; + case type::ARRAY: + as_array().force_destroy(expected_ref_cnt); + break; + case type::OBJECT: + php_warning("Objects (%s) are not supported in confdata", get_type_or_class_name()); + break; + default: + __builtin_unreachable(); } } size_t mixed::estimate_memory_usage() const { switch (get_type()) { - case type::NUL: - case type::BOOLEAN: - case type::INTEGER: - case type::FLOAT: - return 0; - case type::STRING: - return as_string().estimate_memory_usage(); - case type::ARRAY: - return as_array().estimate_memory_usage(); - case type::OBJECT: - php_warning("Objects (%s) are not supported in confdata", get_type_or_class_name()); - return 0; - default: - __builtin_unreachable(); + case type::NUL: + case type::BOOLEAN: + case type::INTEGER: + case type::FLOAT: + return 0; + case type::STRING: + return as_string().estimate_memory_usage(); + case type::ARRAY: + return as_array().estimate_memory_usage(); + case type::OBJECT: + php_warning("Objects (%s) are not supported in confdata", get_type_or_class_name()); + return 0; + default: + __builtin_unreachable(); } } namespace impl_ { -template -mixed do_math_op_on_vars(const mixed &lhs, const mixed &rhs, MathOperation &&math_op) { +template +mixed do_math_op_on_vars(const mixed& lhs, const mixed& rhs, MathOperation&& math_op) { if (likely(lhs.is_int() && rhs.is_int())) { return math_op(lhs.as_int(), rhs.as_int()); } @@ -1824,23 +1762,23 @@ mixed do_math_op_on_vars(const mixed &lhs, const mixed &rhs, MathOperation &&mat } // namespace impl_ -mixed operator+(const mixed &lhs, const mixed &rhs) { +mixed operator+(const mixed& lhs, const mixed& rhs) { if (lhs.is_array() && rhs.is_array()) { return lhs.as_array() + rhs.as_array(); } - return impl_::do_math_op_on_vars(lhs, rhs, [](const auto &arg1, const auto &arg2) { return arg1 + arg2; }); + return impl_::do_math_op_on_vars(lhs, rhs, [](const auto& arg1, const auto& arg2) { return arg1 + arg2; }); } -mixed operator-(const mixed &lhs, const mixed &rhs) { - return impl_::do_math_op_on_vars(lhs, rhs, [](const auto &arg1, const auto &arg2) { return arg1 - arg2; }); +mixed operator-(const mixed& lhs, const mixed& rhs) { + return impl_::do_math_op_on_vars(lhs, rhs, [](const auto& arg1, const auto& arg2) { return arg1 - arg2; }); } -mixed operator*(const mixed &lhs, const mixed &rhs) { - return impl_::do_math_op_on_vars(lhs, rhs, [](const auto &arg1, const auto &arg2) { return arg1 * arg2; }); +mixed operator*(const mixed& lhs, const mixed& rhs) { + return impl_::do_math_op_on_vars(lhs, rhs, [](const auto& arg1, const auto& arg2) { return arg1 * arg2; }); } -mixed operator-(const string &lhs) { +mixed operator-(const string& lhs) { mixed arg1 = lhs.to_numeric(); if (arg1.is_int()) { @@ -1851,32 +1789,19 @@ mixed operator-(const string &lhs) { return arg1; } -mixed operator+(const string &lhs) { - return lhs.to_numeric(); -} - -int64_t operator&(const mixed &lhs, const mixed &rhs) { - return lhs.to_int() & rhs.to_int(); -} +mixed operator+(const string& lhs) { return lhs.to_numeric(); } -int64_t operator|(const mixed &lhs, const mixed &rhs) { - return lhs.to_int() | rhs.to_int(); -} +int64_t operator&(const mixed& lhs, const mixed& rhs) { return lhs.to_int() & rhs.to_int(); } -int64_t operator^(const mixed &lhs, const mixed &rhs) { - return lhs.to_int() ^ rhs.to_int(); -} +int64_t operator|(const mixed& lhs, const mixed& rhs) { return lhs.to_int() | rhs.to_int(); } -int64_t operator<<(const mixed &lhs, const mixed &rhs) { - return lhs.to_int() << rhs.to_int(); -} +int64_t operator^(const mixed& lhs, const mixed& rhs) { return lhs.to_int() ^ rhs.to_int(); } -int64_t operator>>(const mixed &lhs, const mixed &rhs) { - return lhs.to_int() >> rhs.to_int(); -} +int64_t operator<<(const mixed& lhs, const mixed& rhs) { return lhs.to_int() << rhs.to_int(); } +int64_t operator>>(const mixed& lhs, const mixed& rhs) { return lhs.to_int() >> rhs.to_int(); } -bool operator<(const mixed &lhs, const mixed &rhs) { +bool operator<(const mixed& lhs, const mixed& rhs) { const auto res = lhs.compare(rhs) < 0; if (rhs.is_string()) { @@ -1896,50 +1821,48 @@ bool operator<(const mixed &lhs, const mixed &rhs) { return res; } -bool operator<=(const mixed &lhs, const mixed &rhs) { - return !(rhs < lhs); -} +bool operator<=(const mixed& lhs, const mixed& rhs) { return !(rhs < lhs); } -string_buffer &operator<<(string_buffer &sb, const mixed &v) { +string_buffer& operator<<(string_buffer& sb, const mixed& v) { switch (v.get_type()) { - case mixed::type::NUL: - return sb; - case mixed::type::BOOLEAN: - return sb << v.as_bool(); - case mixed::type::INTEGER: - return sb << v.as_int(); - case mixed::type::FLOAT: - return sb << string(v.as_double()); - case mixed::type::STRING: - return sb << v.as_string(); - case mixed::type::ARRAY: - php_warning("Conversion from array to string"); - return sb.append("Array", 5); - case mixed::type::OBJECT: { - const char *s = v.get_type_or_class_name(); - php_warning("Conversion from %s to string", s); - return sb.append(s, strlen(s)); - } - default: - __builtin_unreachable(); + case mixed::type::NUL: + return sb; + case mixed::type::BOOLEAN: + return sb << v.as_bool(); + case mixed::type::INTEGER: + return sb << v.as_int(); + case mixed::type::FLOAT: + return sb << string(v.as_double()); + case mixed::type::STRING: + return sb << v.as_string(); + case mixed::type::ARRAY: + php_warning("Conversion from array to string"); + return sb.append("Array", 5); + case mixed::type::OBJECT: { + const char* s = v.get_type_or_class_name(); + php_warning("Conversion from %s to string", s); + return sb.append(s, strlen(s)); + } + default: + __builtin_unreachable(); } } void mixed::destroy() noexcept { switch (get_type()) { - case type::STRING: - as_string().~string(); - break; - case type::ARRAY: - as_array().~array(); - break; - case type::OBJECT: { - reinterpret_cast*>(&storage_)->~intrusive_ptr(); - storage_ = 0; - break; - } - default: { - } + case type::STRING: + as_string().~string(); + break; + case type::ARRAY: + as_array().~array(); + break; + case type::OBJECT: { + reinterpret_cast*>(&storage_)->~intrusive_ptr(); + storage_ = 0; + break; + } + default: { + } } } @@ -1949,9 +1872,7 @@ void mixed::clear() noexcept { } // Don't move this destructor to the headers, it spoils addr2line traces -mixed::~mixed() noexcept { - clear(); -} +mixed::~mixed() noexcept { clear(); } static_assert(sizeof(mixed) == SIZEOF_MIXED, "sizeof(mixed) at runtime doesn't match compile-time"); static_assert(sizeof(Unknown) == SIZEOF_UNKNOWN, "sizeof(Unknown) at runtime doesn't match compile-time"); diff --git a/runtime-common/core/core-types/definition/mixed.inl b/runtime-common/core/core-types/definition/mixed.inl index 81ad05012c..f855d72e99 100644 --- a/runtime-common/core/core-types/definition/mixed.inl +++ b/runtime-common/core/core-types/definition/mixed.inl @@ -11,16 +11,16 @@ #include "runtime-common/core/utils/migration-php8.h" #ifndef INCLUDED_FROM_KPHP_CORE - #error "this file must be included only from runtime-core.h" +#error "this file must be included only from runtime-core.h" #endif static_assert(vk::all_of_equal(sizeof(string), sizeof(double), sizeof(array)), "sizeof of array, string and double must be equal"); -template -void mixed::init_from(T &&v) { +template +void mixed::init_from(T&& v) { if constexpr (is_class_instance_v>) { static_assert(sizeof(storage_) >= sizeof(vk::intrusive_ptr)); - auto ptr_to_obj = new(&storage_) vk::intrusive_ptr(dynamic_cast(v.get())); + auto ptr_to_obj = new (&storage_) vk::intrusive_ptr(dynamic_cast(v.get())); if (unlikely(!ptr_to_obj)) { php_error("Internal error. Trying to set invalid object to mixed"); } @@ -28,15 +28,15 @@ void mixed::init_from(T &&v) { } else { auto type_and_value_ref = get_type_and_value_ptr(v); type_ = type_and_value_ref.first; - auto *value_ptr = type_and_value_ref.second; + auto* value_ptr = type_and_value_ref.second; using ValueType = std::decay_t; - new(value_ptr) ValueType(std::forward(v)); + new (value_ptr) ValueType(std::forward(v)); } } -template -mixed &mixed::assign_from(T &&v) { - if constexpr(is_class_instance_v>) { +template +mixed& mixed::assign_from(T&& v) { + if constexpr (is_class_instance_v>) { static_assert(std::is_base_of_v::ClassType>); destroy(); init_from(std::forward(v)); @@ -53,46 +53,46 @@ mixed &mixed::assign_from(T &&v) { return *this; } -template -mixed::mixed(T &&v) noexcept { +template +mixed::mixed(T&& v) noexcept { init_from(std::forward(v)); } -template -mixed::mixed(const Optional &v) noexcept { - auto init_from_lambda = [this](const auto &v) { this->init_from(v); }; +template +mixed::mixed(const Optional& v) noexcept { + auto init_from_lambda = [this](const auto& v) { this->init_from(v); }; call_fun_on_optional_value(init_from_lambda, v); } -template -mixed::mixed(Optional &&v) noexcept { - auto init_from_lambda = [this](auto &&v) { this->init_from(std::move(v)); }; - call_fun_on_optional_value(init_from_lambda, std::move(v)); +template +mixed::mixed(Optional&& v) noexcept { + auto init_from_lambda = [this](auto&& v) { this->init_from(std::move(v)); }; + call_fun_on_optional_value(init_from_lambda, std::move(v)); } -template -mixed &mixed::operator=(T &&v) noexcept { +template +mixed& mixed::operator=(T&& v) noexcept { return assign_from(std::forward(v)); } -template -mixed &mixed::operator=(const Optional &v) noexcept { - auto assign_from_lambda = [this](const auto &v) -> mixed& { return this->assign_from(v); }; +template +mixed& mixed::operator=(const Optional& v) noexcept { + auto assign_from_lambda = [this](const auto& v) -> mixed& { return this->assign_from(v); }; return call_fun_on_optional_value(assign_from_lambda, v); } -template -mixed &mixed::operator=(Optional &&v) noexcept { - auto assign_from_lambda = [this](auto &&v) -> mixed& { return this->assign_from(std::move(v)); }; +template +mixed& mixed::operator=(Optional&& v) noexcept { + auto assign_from_lambda = [this](auto&& v) -> mixed& { return this->assign_from(std::move(v)); }; return call_fun_on_optional_value(assign_from_lambda, std::move(v)); } -template -int64_t spaceship(const T1 &lhs, const T2 &rhs); +template +int64_t spaceship(const T1& lhs, const T2& rhs); -template -bool mixed::isset(const string &string_key, MaybeHash ...maybe_hash) const { - if (unlikely (get_type() != type::ARRAY)) { +template +bool mixed::isset(const string& string_key, MaybeHash... maybe_hash) const { + if (unlikely(get_type() != type::ARRAY)) { if (get_type() == type::OBJECT) { if (auto as_aa = try_as_array_access(*this)) { return f$ArrayAccess$$offsetExists(*as_aa, string_key); @@ -113,9 +113,9 @@ bool mixed::isset(const string &string_key, MaybeHash ...maybe_hash) const { return as_array().isset(string_key, maybe_hash...); } -template -void mixed::unset(const string &string_key, MaybeHash ...maybe_hash) { - if (unlikely (get_type() != type::ARRAY)) { +template +void mixed::unset(const string& string_key, MaybeHash... maybe_hash) { + if (unlikely(get_type() != type::ARRAY)) { if (get_type() == type::OBJECT) { if (auto as_aa = try_as_array_access(*this)) { f$ArrayAccess$$offsetUnset(*as_aa, string_key); @@ -132,49 +132,31 @@ void mixed::unset(const string &string_key, MaybeHash ...maybe_hash) { as_array().unset(string_key, maybe_hash...); } -inline mixed::type mixed::get_type() const { - return type_; -} +inline mixed::type mixed::get_type() const { return type_; } -inline bool mixed::is_null() const { - return get_type() == type::NUL; -} +inline bool mixed::is_null() const { return get_type() == type::NUL; } -inline bool mixed::is_bool() const { - return get_type() == type::BOOLEAN; -} +inline bool mixed::is_bool() const { return get_type() == type::BOOLEAN; } -inline bool mixed::is_int() const { - return get_type() == type::INTEGER; -} +inline bool mixed::is_int() const { return get_type() == type::INTEGER; } -inline bool mixed::is_float() const { - return get_type() == type::FLOAT; -} +inline bool mixed::is_float() const { return get_type() == type::FLOAT; } -inline bool mixed::is_string() const { - return get_type() == type::STRING; -} +inline bool mixed::is_string() const { return get_type() == type::STRING; } -inline bool mixed::is_array() const { - return get_type() == type::ARRAY; -} +inline bool mixed::is_array() const { return get_type() == type::ARRAY; } -inline bool mixed::is_object() const { - return get_type() == type::OBJECT; -} +inline bool mixed::is_object() const { return get_type() == type::OBJECT; } -inline void mixed::swap(mixed &other) { +inline void mixed::swap(mixed& other) { ::swap(type_, other.type_); ::swap(as_double(), other.as_double()); } -inline void swap(mixed &lhs, mixed &rhs) { - lhs.swap(rhs); -} +inline void swap(mixed& lhs, mixed& rhs) { lhs.swap(rhs); } -template -T &mixed::empty_value() noexcept { +template +T& mixed::empty_value() noexcept { static_assert(vk::is_type_in_list>{} || is_type_acceptable_for_mixed::value, "unsupported type"); static T value; @@ -191,40 +173,39 @@ inline void mixed::reset_empty_values() noexcept { empty_value>(); } -template -string_buffer &operator<<(string_buffer &sb, const Optional &v) { - auto write_lambda = [&sb](const auto &v) -> string_buffer& { return sb << v; }; +template +string_buffer& operator<<(string_buffer& sb, const Optional& v) { + auto write_lambda = [&sb](const auto& v) -> string_buffer& { return sb << v; }; return call_fun_on_optional_value(write_lambda, v); } - template -const char *conversion_php_warning_string() { +const char* conversion_php_warning_string() { return ""; } -template<> -inline const char *conversion_php_warning_string() { +template <> +inline const char* conversion_php_warning_string() { return "Comparison (operator <) results in PHP 7 and PHP 8 are different for %" PRIi64 " and \"%s\" (PHP7: %s, PHP8: %s)"; } -template<> -inline const char *conversion_php_warning_string() { +template <> +inline const char* conversion_php_warning_string() { return "Comparison (operator <) results in PHP 7 and PHP 8 are different for %lf and \"%s\" (PHP7: %s, PHP8: %s)"; } -template<> -inline const char *conversion_php_warning_string() { +template <> +inline const char* conversion_php_warning_string() { return "Comparison (operator <) results in PHP 7 and PHP 8 are different for \"%s\" and %" PRIi64 " (PHP7: %s, PHP8: %s)"; } -template<> -inline const char *conversion_php_warning_string() { +template <> +inline const char* conversion_php_warning_string() { return "Comparison (operator <) results in PHP 7 and PHP 8 are different for \"%s\" and %lf (PHP7: %s, PHP8: %s)"; } template -bool less_number_string_as_php8_impl(T lhs, const string &rhs) { +bool less_number_string_as_php8_impl(T lhs, const string& rhs) { auto rhs_float = 0.0; const auto rhs_is_string_number = rhs.try_to_float(&rhs_float); @@ -236,7 +217,7 @@ bool less_number_string_as_php8_impl(T lhs, const string &rhs) { } template -bool less_string_number_as_php8_impl(const string &lhs, T rhs) { +bool less_string_number_as_php8_impl(const string& lhs, T rhs) { auto lhs_float = 0.0; const auto lhs_is_string_number = lhs.try_to_float(&lhs_float); @@ -248,61 +229,55 @@ bool less_string_number_as_php8_impl(const string &lhs, T rhs) { } template -bool less_number_string_as_php8(bool php7_result, T lhs, const string &rhs) { +bool less_number_string_as_php8(bool php7_result, T lhs, const string& rhs) { if (RuntimeContext::get().show_migration_php8_warning & MIGRATION_PHP8_STRING_COMPARISON_FLAG) { const auto php8_result = less_number_string_as_php8_impl(lhs, rhs); if (php7_result == php8_result) { return php7_result; } - php_warning(conversion_php_warning_string::type, typename std::decay::type>(), - lhs, - rhs.c_str(), - php7_result ? "true" : "false", - php8_result ? "true" : "false"); + php_warning(conversion_php_warning_string::type, typename std::decay::type>(), lhs, rhs.c_str(), + php7_result ? "true" : "false", php8_result ? "true" : "false"); } return php7_result; } template -bool less_string_number_as_php8(bool php7_result, const string &lhs, T rhs) { +bool less_string_number_as_php8(bool php7_result, const string& lhs, T rhs) { if (RuntimeContext::get().show_migration_php8_warning & MIGRATION_PHP8_STRING_COMPARISON_FLAG) { const auto php8_result = less_string_number_as_php8_impl(lhs, rhs); if (php7_result == php8_result) { return php7_result; } - php_warning(conversion_php_warning_string::type, typename std::decay::type>(), - lhs.c_str(), - rhs, - php7_result ? "true" : "false", - php8_result ? "true" : "false"); + php_warning(conversion_php_warning_string::type, typename std::decay::type>(), lhs.c_str(), rhs, + php7_result ? "true" : "false", php8_result ? "true" : "false"); } return php7_result; } -template -mixed f$to_mixed(const class_instance &instance) noexcept { +template +mixed f$to_mixed(const class_instance& instance) noexcept { mixed m; m = instance; return m; } -template -ResultClass from_mixed(const mixed &m, const string &) noexcept { +template +ResultClass from_mixed(const mixed& m, const string&) noexcept { if constexpr (!std::is_polymorphic_v) { php_error("Internal error. Class inside a mixed is not polymorphic"); return {}; } else { - return m.is_object() ? ResultClass::create_from_base_raw_ptr(dynamic_cast(m.as_object_ptr())) + return m.is_object() ? ResultClass::create_from_base_raw_ptr(dynamic_cast(m.as_object_ptr())) : ResultClass{}; } } -template -mixed mixed::set_value_return(T key, const mixed &val) { +template +mixed mixed::set_value_return(T key, const mixed& val) { if (get_type() == type::OBJECT) { set_value(key, val); return val; @@ -310,7 +285,7 @@ mixed mixed::set_value_return(T key, const mixed &val) { return (*this)[key] = val; } -template +template bool mixed::empty_at(T key) const { if (type_ == type::OBJECT) { if (auto as_aa = try_as_array_access(*this)) { diff --git a/runtime-common/core/core-types/definition/string.cpp b/runtime-common/core/core-types/definition/string.cpp index 1503d3bcfc..6a801b79bf 100644 --- a/runtime-common/core/core-types/definition/string.cpp +++ b/runtime-common/core/core-types/definition/string.cpp @@ -5,8 +5,6 @@ #include "runtime-common/core/runtime-core.h" // Don't move this destructor to the headers, it spoils addr2line traces -string::~string() noexcept { - destroy(); -} +string::~string() noexcept { destroy(); } static_assert(sizeof(string) == SIZEOF_STRING, "sizeof(string) at runtime doesn't match compile-time"); diff --git a/runtime-common/core/core-types/definition/string.inl b/runtime-common/core/core-types/definition/string.inl index 3f84c1feee..d8d83ce412 100644 --- a/runtime-common/core/core-types/definition/string.inl +++ b/runtime-common/core/core-types/definition/string.inl @@ -8,35 +8,31 @@ #include "common/algorithms/simd-int-to-string.h" -#include "runtime-common/core/utils/migration-php8.h" #include "runtime-common/core/core-types/definition/string_cache.h" +#include "runtime-common/core/utils/migration-php8.h" #ifndef INCLUDED_FROM_KPHP_CORE - #error "this file must be included only from runtime-core.h" +#error "this file must be included only from runtime-core.h" #endif -tmp_string::tmp_string(const char *data, string_size_type size) : data{data}, size{size} {} +tmp_string::tmp_string(const char* data, string_size_type size) : data{data}, size{size} {} -tmp_string::tmp_string(const string &s) : data{s.c_str()}, size{s.size()} {} +tmp_string::tmp_string(const string& s) : data{s.c_str()}, size{s.size()} {} -bool string::string_inner::is_shared() const { - return ref_count > 0; -} +bool string::string_inner::is_shared() const { return ref_count > 0; } void string::string_inner::set_length_and_sharable(size_type n) { -// fprintf (stderr, "inc ref cnt %d %s\n", 0, ref_data()); + // fprintf (stderr, "inc ref cnt %d %s\n", 0, ref_data()); ref_count = 0; size = n; ref_data()[n] = '\0'; } -char *string::string_inner::ref_data() const { - return (char *)(this + 1); -} +char* string::string_inner::ref_data() const { return (char*)(this + 1); } string::size_type string::string_inner::new_capacity(size_type requested_capacity, size_type old_capacity) { if (requested_capacity > max_size()) { - php_critical_error ("tried to allocate too big string of size %lld", (long long)requested_capacity); + php_critical_error("tried to allocate too big string of size %lld", (long long)requested_capacity); } if (requested_capacity > old_capacity && requested_capacity < 2 * old_capacity) { @@ -53,27 +49,26 @@ string::size_type string::string_inner::new_capacity(size_type requested_capacit return requested_capacity; } - -string::string_inner *string::string_inner::create(size_type requested_capacity, size_type old_capacity) { +string::string_inner* string::string_inner::create(size_type requested_capacity, size_type old_capacity) { size_type capacity = new_capacity(requested_capacity, old_capacity); size_type new_size = (size_type)(sizeof(string_inner) + (capacity + 1)); - string_inner *p = (string_inner *)RuntimeAllocator::get().alloc_script_memory(new_size); + string_inner* p = (string_inner*)RuntimeAllocator::get().alloc_script_memory(new_size); p->capacity = capacity; return p; } -char *string::string_inner::reserve(size_type requested_capacity) { +char* string::string_inner::reserve(size_type requested_capacity) { size_type new_cap = new_capacity(requested_capacity, capacity); size_type old_size = (size_type)(sizeof(string_inner) + (capacity + 1)); size_type new_size = (size_type)(sizeof(string_inner) + (new_cap + 1)); - string_inner *p = (string_inner *)RuntimeAllocator::get().realloc_script_memory((void *)this, new_size, old_size); + string_inner* p = (string_inner*)RuntimeAllocator::get().realloc_script_memory((void*)this, new_size, old_size); p->capacity = new_cap; return p->ref_data(); } void string::string_inner::dispose() { -// fprintf (stderr, "dec ref cnt %d %s\n", ref_count - 1, ref_data()); + // fprintf (stderr, "dec ref cnt %d %s\n", ref_count - 1, ref_data()); if (ref_count < ExtraRefCnt::for_global_const) { ref_count--; if (ref_count <= -1) { @@ -82,24 +77,20 @@ void string::string_inner::dispose() { } } -void string::string_inner::destroy() { - RuntimeAllocator::get().free_script_memory(this, get_memory_usage()); -} +void string::string_inner::destroy() { RuntimeAllocator::get().free_script_memory(this, get_memory_usage()); } -inline string::size_type string::string_inner::get_memory_usage() const { - return static_cast(sizeof(string_inner) + (capacity + 1)); -} +inline string::size_type string::string_inner::get_memory_usage() const { return static_cast(sizeof(string_inner) + (capacity + 1)); } -char *string::string_inner::ref_copy() { -// fprintf (stderr, "inc ref cnt %d, %s\n", ref_count + 1, ref_data()); +char* string::string_inner::ref_copy() { + // fprintf (stderr, "inc ref cnt %d, %s\n", ref_count + 1, ref_data()); if (ref_count < ExtraRefCnt::for_global_const) { ref_count++; } return ref_data(); } -char *string::string_inner::clone(size_type requested_cap) { - string_inner *r = string_inner::create(requested_cap, capacity); +char* string::string_inner::clone(size_type requested_cap) { + string_inner* r = string_inner::create(requested_cap, capacity); if (size) { memcpy(r->ref_data(), ref_data(), size); } @@ -108,18 +99,13 @@ char *string::string_inner::clone(size_type requested_cap) { return r->ref_data(); } +string::string_inner* string::inner() const { return (string::string_inner*)p - 1; } -string::string_inner *string::inner() const { - return (string::string_inner *)p - 1; -} - -bool string::disjunct(const char *s) const { - return (s < p || p + size() < s); -} +bool string::disjunct(const char* s) const { return (s < p || p + size() < s); } void string::set_size(size_type new_size) { if (inner()->is_shared()) { - string_inner *r = string_inner::create(new_size, capacity()); + string_inner* r = string_inner::create(new_size, capacity()); inner()->dispose(); p = r->ref_data(); @@ -129,7 +115,7 @@ void string::set_size(size_type new_size) { inner()->set_length_and_sharable(new_size); } -char *string::create(const char *beg, const char *end) { +char* string::create(const char* beg, const char* end) { const size_type dnew = static_cast(end - beg); if (dnew == 0) { return string_cache::empty_string().ref_data(); @@ -138,8 +124,8 @@ char *string::create(const char *beg, const char *end) { return string_cache::cached_char(*beg).ref_data(); } - string_inner *r = string_inner::create(dnew, 0); - char *s = r->ref_data(); + string_inner* r = string_inner::create(dnew, 0); + char* s = r->ref_data(); memcpy(s, beg, dnew); r->ref_count = 0; @@ -148,7 +134,7 @@ char *string::create(const char *beg, const char *end) { return s; } -char *string::create(size_type n, char c) { +char* string::create(size_type n, char c) { if (n == 0) { return string_cache::empty_string().ref_data(); } @@ -156,15 +142,15 @@ char *string::create(size_type n, char c) { return string_cache::cached_char(c).ref_data(); } - string_inner *r = string_inner::create(n, 0); - char *s = r->ref_data(); + string_inner* r = string_inner::create(n, 0); + char* s = r->ref_data(); memset(s, c, n); r->set_length_and_sharable(n); return s; } -char *string::create(size_type n, bool b) { - string_inner *r = string_inner::create(n, 0); +char* string::create(size_type n, bool b) { + string_inner* r = string_inner::create(n, 0); if (b) { r->ref_count = 0; @@ -175,33 +161,19 @@ char *string::create(size_type n, bool b) { return r->ref_data(); } -string::string() : - p(string_cache::empty_string().ref_data()) { -} +string::string() : p(string_cache::empty_string().ref_data()) {} -string::string(const string &str) noexcept: - p(str.inner()->ref_copy()) { -} +string::string(const string& str) noexcept : p(str.inner()->ref_copy()) {} -string::string(string &&str) noexcept: - p(str.p) { - str.p = string_cache::empty_string().ref_data(); -} +string::string(string&& str) noexcept : p(str.p) { str.p = string_cache::empty_string().ref_data(); } -string::string(const char *s, size_type n) : - p(create(s, s + n)) { -} +string::string(const char* s, size_type n) : p(create(s, s + n)) {} -string::string(const char *s) : - string(s, static_cast(strlen(s))) {} +string::string(const char* s) : string(s, static_cast(strlen(s))) {} -string::string(size_type n, char c) : - p(create(n, c)) { -} +string::string(size_type n, char c) : p(create(n, c)) {} -string::string(size_type n, bool b) : - p(create(n, b)) { -} +string::string(size_type n, bool b) : p(create(n, b)) {} string::string(int64_t i) { if (i >= 0 && i < string_cache::cached_int_max()) { @@ -209,7 +181,7 @@ string::string(int64_t i) { return; } if (i < 0 && i > -string_cache::cached_int_max()) { - const auto &cached_int_positive = string_cache::cached_int(-i); + const auto& cached_int_positive = string_cache::cached_int(-i); p = create(cached_int_positive.size + 1, true); p[0] = '-'; // copy with \0 @@ -219,7 +191,7 @@ string::string(int64_t i) { } const auto i32 = static_cast(i); - const char *end = nullptr; + const char* end = nullptr; if (static_cast(i32) == i) { p = create(STRLEN_INT32, true); end = simd_int32_to_string(i32, p); @@ -237,11 +209,11 @@ string::string(double f) { result[0] = '\0'; result[1] = '\0'; - char *begin = result + 2; + char* begin = result + 2; if (std::isnan(f)) { // to prevent printing `-NAN` by snprintf f = std::abs(f); - } + } int len = snprintf(begin, MAX_LEN, "%.14G", f); if (static_cast(len) < MAX_LEN) { if (static_cast(begin[len - 1] - '5') < 5 && begin[len - 2] == '0' && begin[len - 3] == '-') { @@ -262,7 +234,7 @@ string::string(double f) { begin = result; len += 2; } - php_assert (len <= STRLEN_FLOAT); + php_assert(len <= STRLEN_FLOAT); p = create(begin, begin + len); } else { php_warning("Maximum length of float (%d) exceeded", MAX_LEN); @@ -270,18 +242,13 @@ string::string(double f) { } } -string::string(ArrayBucketDummyStrTag) noexcept - : p(nullptr) {} +string::string(ArrayBucketDummyStrTag) noexcept : p(nullptr) {} -bool string::is_dummy_string() const noexcept { - return p == nullptr; -} +bool string::is_dummy_string() const noexcept { return p == nullptr; } -string &string::operator=(const string &str) noexcept { - return assign(str); -} +string& string::operator=(const string& str) noexcept { return assign(str); } -string &string::operator=(string &&str) noexcept { +string& string::operator=(string&& str) noexcept { if (this != &str) { destroy(); p = str.p; @@ -290,16 +257,14 @@ string &string::operator=(string &&str) noexcept { return *this; } -string::size_type string::size() const { - return inner()->size; -} +string::size_type string::size() const { return inner()->size; } void string::shrink(size_type n) { const size_type old_size = size(); if (n < old_size) { if (inner()->is_shared()) { - string_inner *r = string_inner::create(n, capacity()); + string_inner* r = string_inner::create(n, capacity()); if (n) { memcpy(r->ref_data(), p, n); @@ -312,9 +277,7 @@ void string::shrink(size_type n) { } } -string::size_type string::capacity() const { - return inner()->capacity; -} +string::size_type string::capacity() const { return inner()->capacity; } void string::make_not_shared() { if (inner()->is_shared()) { @@ -329,12 +292,12 @@ string string::copy_and_make_not_shared() const { } void string::force_reserve(size_type res) { - char *new_p = inner()->clone(res); + char* new_p = inner()->clone(res); inner()->dispose(); p = new_p; } -string &string::reserve_at_least(size_type res) { +string& string::reserve_at_least(size_type res) { if (inner()->is_shared()) { force_reserve(res); } else if (res > capacity()) { @@ -343,28 +306,19 @@ string &string::reserve_at_least(size_type res) { return *this; } -bool string::empty() const { - return size() == 0; -} +bool string::empty() const { return size() == 0; } -bool string::starts_with(const string &other) const noexcept { - return other.size() > size() ? false : !memcmp(c_str(), other.c_str(), other.size()); -} +bool string::starts_with(const string& other) const noexcept { return other.size() > size() ? false : !memcmp(c_str(), other.c_str(), other.size()); } -bool string::ends_with(const string &other) const noexcept { +bool string::ends_with(const string& other) const noexcept { return other.size() > size() ? false : !memcmp(c_str() + (size() - other.size()), other.c_str(), other.size()); } -const char &string::operator[](size_type pos) const { - return p[pos]; -} - -char &string::operator[](size_type pos) { - return p[pos]; -} +const char& string::operator[](size_type pos) const { return p[pos]; } +char& string::operator[](size_type pos) { return p[pos]; } -string &string::append(const string &str) { +string& string::append(const string& str) { const size_type n2 = str.size(); if (n2) { const size_type len = n2 + size(); @@ -376,7 +330,7 @@ string &string::append(const string &str) { return *this; } -string &string::append(const string &str, size_type pos2, size_type n2) { +string& string::append(const string& str, size_type pos2, size_type n2) { if (pos2 > str.size()) { pos2 = str.size(); } @@ -393,14 +347,12 @@ string &string::append(const string &str, size_type pos2, size_type n2) { return *this; } -string &string::append(const char *s) { - return append(s, static_cast(strlen(s))); -} +string& string::append(const char* s) { return append(s, static_cast(strlen(s))); } -string &string::append(const char *s, size_type n) { +string& string::append(const char* s, size_type n) { if (n) { if (max_size() - size() < n) { - php_critical_error ("tried to allocate too big string of size %lld", (long long)size() + n); + php_critical_error("tried to allocate too big string of size %lld", (long long)size() + n); } const size_type len = n + size(); if (len > capacity() || inner()->is_shared()) { @@ -419,10 +371,10 @@ string &string::append(const char *s, size_type n) { return *this; } -string &string::append(size_type n, char c) { +string& string::append(size_type n, char c) { if (n) { if (max_size() - size() < n) { - php_critical_error ("tried to allocate too big string of size %lld", (long long)size() + n); + php_critical_error("tried to allocate too big string of size %lld", (long long)size() + n); } const size_type len = n + size(); reserve_at_least(len); @@ -433,7 +385,7 @@ string &string::append(size_type n, char c) { return *this; } -string &string::append(bool b) { +string& string::append(bool b) { if (b) { push_back('1'); } @@ -441,13 +393,13 @@ string &string::append(bool b) { return *this; } -string &string::append(int64_t i) { +string& string::append(int64_t i) { if (i >= 0 && i < string_cache::cached_int_max()) { - const auto &cached_int = string_cache::cached_int(i); + const auto& cached_int = string_cache::cached_int(i); return append(cached_int.ref_data(), cached_int.size); } if (i < 0 && i > -string_cache::cached_int_max()) { - const auto &cached_int_positive = string_cache::cached_int(-i); + const auto& cached_int_positive = string_cache::cached_int(-i); reserve_at_least(size() + cached_int_positive.size + 1); p[inner()->size++] = '-'; append_unsafe(cached_int_positive.ref_data(), cached_int_positive.size); @@ -455,38 +407,36 @@ string &string::append(int64_t i) { } reserve_at_least(size() + STRLEN_INT64); - const char *end = simd_int64_to_string(i, p + size()); + const char* end = simd_int64_to_string(i, p + size()); inner()->size = static_cast(end - p); return *this; } -string &string::append(double d) { - return append(string(d)); -} +string& string::append(double d) { return append(string(d)); } -string &string::append(const mixed &v) { +string& string::append(const mixed& v) { switch (v.get_type()) { - case mixed::type::NUL: - return *this; - case mixed::type::BOOLEAN: - if (v.as_bool()) { - push_back('1'); - } - return *this; - case mixed::type::INTEGER: - return append(v.as_int()); - case mixed::type::FLOAT: - return append(string(v.as_double())); - case mixed::type::STRING: - return append(v.as_string()); - case mixed::type::ARRAY: - php_warning("Conversion from array to string"); - return append("Array", 5); - case mixed::type::OBJECT: - php_warning("Conversion from %s to string", v.get_type_or_class_name()); - return append(v.get_type_or_class_name(), strlen(v.get_type_or_class_name())); - default: - __builtin_unreachable(); + case mixed::type::NUL: + return *this; + case mixed::type::BOOLEAN: + if (v.as_bool()) { + push_back('1'); + } + return *this; + case mixed::type::INTEGER: + return append(v.as_int()); + case mixed::type::FLOAT: + return append(string(v.as_double())); + case mixed::type::STRING: + return append(v.as_string()); + case mixed::type::ARRAY: + php_warning("Conversion from array to string"); + return append("Array", 5); + case mixed::type::OBJECT: + php_warning("Conversion from %s to string", v.get_type_or_class_name()); + return append(v.get_type_or_class_name(), strlen(v.get_type_or_class_name())); + default: + __builtin_unreachable(); } } @@ -497,35 +447,34 @@ void string::push_back(char c) { inner()->set_length_and_sharable(len); } - -string &string::append_unsafe(bool b) { +string& string::append_unsafe(bool b) { if (b) { p[inner()->size++] = '1'; } return *this; } -string &string::append_unsafe(int64_t i) { +string& string::append_unsafe(int64_t i) { if (i >= 0 && i < string_cache::cached_int_max()) { - const auto &cached_int = string_cache::cached_int(i); + const auto& cached_int = string_cache::cached_int(i); return append_unsafe(cached_int.ref_data(), cached_int.size); } if (i < 0 && i > -string_cache::cached_int_max()) { - const auto &cached_int_positive = string_cache::cached_int(-i); + const auto& cached_int_positive = string_cache::cached_int(-i); p[inner()->size++] = '-'; return append_unsafe(cached_int_positive.ref_data(), cached_int_positive.size); } - const char *end = simd_int64_to_string(i, p + size()); + const char* end = simd_int64_to_string(i, p + size()); inner()->size = static_cast(end - p); return *this; } -string &string::append_unsafe(double d) { - return append_unsafe(string(d));//TODO can be optimized +string& string::append_unsafe(double d) { + return append_unsafe(string(d)); // TODO can be optimized } -string &string::append_unsafe(const string &str) { +string& string::append_unsafe(const string& str) { const size_type n2 = str.size(); memcpy(p + size(), str.p, n2); inner()->size += n2; @@ -533,71 +482,70 @@ string &string::append_unsafe(const string &str) { return *this; } -string &string::append_unsafe(tmp_string str) { +string& string::append_unsafe(tmp_string str) { if (!str.has_value()) { return *this; } return append_unsafe(str.data, str.size); } -string &string::append_unsafe(const char *s, size_type n) { +string& string::append_unsafe(const char* s, size_type n) { memcpy(p + size(), s, n); inner()->size += n; return *this; } -template -string &string::append_unsafe(const array &a __attribute__((unused))) { +template +string& string::append_unsafe(const array& a __attribute__((unused))) { php_warning("Conversion from array to string"); return append_unsafe("Array", 5); } -string &string::append_unsafe(const mixed &v) { +string& string::append_unsafe(const mixed& v) { switch (v.get_type()) { - case mixed::type::NUL: - return *this; - case mixed::type::BOOLEAN: - return append_unsafe(v.as_bool()); - case mixed::type::INTEGER: - return append_unsafe(v.as_int()); - case mixed::type::FLOAT: - return append_unsafe(v.as_double()); - case mixed::type::STRING: - return append_unsafe(v.as_string()); - case mixed::type::ARRAY: - return append_unsafe(v.as_array()); - case mixed::type::OBJECT: - php_warning("Conversion from %s to string", v.get_type_or_class_name()); - return append(v.get_type_or_class_name(), strlen(v.get_type_or_class_name())); - default: - __builtin_unreachable(); - } -} - -string &string::finish_append() { - php_assert (inner()->size <= inner()->capacity); + case mixed::type::NUL: + return *this; + case mixed::type::BOOLEAN: + return append_unsafe(v.as_bool()); + case mixed::type::INTEGER: + return append_unsafe(v.as_int()); + case mixed::type::FLOAT: + return append_unsafe(v.as_double()); + case mixed::type::STRING: + return append_unsafe(v.as_string()); + case mixed::type::ARRAY: + return append_unsafe(v.as_array()); + case mixed::type::OBJECT: + php_warning("Conversion from %s to string", v.get_type_or_class_name()); + return append(v.get_type_or_class_name(), strlen(v.get_type_or_class_name())); + default: + __builtin_unreachable(); + } +} + +string& string::finish_append() { + php_assert(inner()->size <= inner()->capacity); p[inner()->size] = '\0'; return *this; } -template -string &string::append_unsafe(const Optional &v) { +template +string& string::append_unsafe(const Optional& v) { if (v.has_value()) { return append_unsafe(v.val()); } return *this; } - -string &string::assign(const string &str) { - char *str_copy = str.inner()->ref_copy(); +string& string::assign(const string& str) { + char* str_copy = str.inner()->ref_copy(); destroy(); p = str_copy; return *this; } -string &string::assign(const string &str, size_type pos, size_type n) { +string& string::assign(const string& str, size_type pos, size_type n) { if (pos > str.size()) { pos = str.size(); } @@ -607,13 +555,11 @@ string &string::assign(const string &str, size_type pos, size_type n) { return assign(str.p + pos, n); } -string &string::assign(const char *s) { - return assign(s, static_cast(strlen(s))); -} +string& string::assign(const char* s) { return assign(s, static_cast(strlen(s))); } -string &string::assign(const char *s, size_type n) { +string& string::assign(const char* s, size_type n) { if (max_size() < n) { - php_critical_error ("tried to allocate too big string of size %lld", (long long)n); + php_critical_error("tried to allocate too big string of size %lld", (long long)n); } if (disjunct(s) || inner()->is_shared()) { @@ -631,9 +577,9 @@ string &string::assign(const char *s, size_type n) { return *this; } -string &string::assign(size_type n, char c) { +string& string::assign(size_type n, char c) { if (max_size() < n) { - php_critical_error ("tried to allocate too big string of size %lld", (long long)n); + php_critical_error("tried to allocate too big string of size %lld", (long long)n); } set_size(n); @@ -642,9 +588,9 @@ string &string::assign(size_type n, char c) { return *this; } -string &string::assign(size_type n, bool b __attribute__((unused))) { +string& string::assign(size_type n, bool b __attribute__((unused))) { if (max_size() < n) { - php_critical_error ("tried to allocate too big string of size %lld", (long long)n); + php_critical_error("tried to allocate too big string of size %lld", (long long)n); } set_size(n); @@ -652,30 +598,23 @@ string &string::assign(size_type n, bool b __attribute__((unused))) { return *this; } - -void string::assign_raw(const char *s) { - static_assert (sizeof(string_inner) == 12u, "need 12 bytes"); - p = const_cast (s + sizeof(string_inner)); +void string::assign_raw(const char* s) { + static_assert(sizeof(string_inner) == 12u, "need 12 bytes"); + p = const_cast(s + sizeof(string_inner)); } - -void string::swap(string &s) { - char *tmp = p; +void string::swap(string& s) { + char* tmp = p; p = s.p; s.p = tmp; } -char *string::buffer() { - return p; -} - -const char *string::c_str() const { - return p; -} +char* string::buffer() { return p; } +const char* string::c_str() const { return p; } inline void string::warn_on_float_conversion() const { - const char *s = c_str(); + const char* s = c_str(); while (isspace(*s)) { s++; } @@ -721,15 +660,13 @@ inline void string::warn_on_float_conversion() const { php_warning("Possible loss of precision on converting string \"%s\" to float", c_str()); } -inline bool string::try_to_int(int64_t *val) const { - return php_try_to_int(p, size(), val); -} +inline bool string::try_to_int(int64_t* val) const { return php_try_to_int(p, size(), val); } -bool string::try_to_float_as_php8(double *val) const { +bool string::try_to_float_as_php8(double* val) const { if (empty() || (size() >= 2 && p[0] == '0' && vk::any_of_equal(p[1], 'x', 'X'))) { return false; } - char *end_ptr = nullptr; + char* end_ptr = nullptr; *val = strtod(p, &end_ptr); // If end_ptr == p then this means that strtod could not perform @@ -738,16 +675,16 @@ bool string::try_to_float_as_php8(double *val) const { return end_ptr != p && std::all_of(end_ptr, p + size(), [](char c) { return isspace(static_cast(c)); }); } -bool string::try_to_float_as_php7(double *val) const { +bool string::try_to_float_as_php7(double* val) const { if (empty() || (size() >= 2 && p[0] == '0' && vk::any_of_equal(p[1], 'x', 'X'))) { return false; } - char *end_ptr{nullptr}; + char* end_ptr{nullptr}; *val = strtod(p, &end_ptr); return (end_ptr == p + size()); } -bool string::try_to_float(double *val, bool php8_warning) const { +bool string::try_to_float(double* val, bool php8_warning) const { const bool is_float_php7 = try_to_float_as_php7(val); if ((RuntimeContext::get().show_migration_php8_warning & MIGRATION_PHP8_STRING_TO_FLOAT_FLAG) && php8_warning) { @@ -758,9 +695,7 @@ bool string::try_to_float(double *val, bool php8_warning) const { "Why does the warning appear:\n" "- string-string comparison\n" "- string-number comparison", - p, - is_float_php7 ? "true" : "false", - is_float_php8 ? "true" : "false"); + p, is_float_php7 ? "true" : "false", is_float_php8 ? "true" : "false"); } } @@ -782,7 +717,7 @@ mixed string::to_numeric() const { bool string::to_bool() const { return string_to_bool(p, size()); } -int64_t string::to_int(const char *s, size_type l) { +int64_t string::to_int(const char* s, size_type l) { while (isspace(*s) && l > 0) { s++; l--; @@ -804,14 +739,9 @@ int64_t string::to_int(const char *s, size_type l) { return val * mul; } +int64_t string::to_int() const { return to_int(p, size()); } -int64_t string::to_int() const { - return to_int(p, size()); -} - -int64_t string::to_int(int64_t start, int64_t l) const { - return to_int(p + start, l); -} +int64_t string::to_int(int64_t start, int64_t l) const { return to_int(p + start, l); } double string::to_float() const { double res{0}; @@ -819,10 +749,7 @@ double string::to_float() const { return res; } -const string &string::to_string() const { - return *this; -} - +const string& string::to_string() const { return *this; } int64_t string::safe_to_int() const { int64_t mul = 1; @@ -850,13 +777,10 @@ int64_t string::safe_to_int() const { return static_cast(val) * mul; } - -bool string::is_int() const { - return php_is_int(p, size()); -} +bool string::is_int() const { return php_is_int(p, size()); } bool string::is_numeric_as_php8() const { - const char *s = c_str(); + const char* s = c_str(); while (isspace(*s)) { s++; } @@ -914,9 +838,7 @@ bool string::is_numeric() const { const bool php8_result = is_numeric_as_php8(); if (php7_result != php8_result) { - php_warning("is_numeric('%s') result in PHP 7 and PHP 8 are different (PHP7: %s, PHP8: %s)", - p, - php7_result ? "true" : "false", + php_warning("is_numeric('%s') result in PHP 7 and PHP 8 are different (PHP7: %s, PHP8: %s)", p, php7_result ? "true" : "false", php8_result ? "true" : "false"); } } @@ -924,16 +846,11 @@ bool string::is_numeric() const { return php7_result; } -int64_t string::hash() const { - return string_hash(p, size()); -} - +int64_t string::hash() const { return string_hash(p, size()); } -string string::substr(size_type pos, size_type n) const { - return string(p + pos, n); -} +string string::substr(size_type pos, size_type n) const { return string(p + pos, n); } -string::size_type string::find(const string &s, size_type pos) const { +string::size_type string::find(const string& s, size_type pos) const { for (size_type i = pos; i + s.size() <= size(); i++) { bool equal = true; for (size_type j = 0; j < s.size(); j++) { @@ -949,7 +866,7 @@ string::size_type string::find(const string &s, size_type pos) const { return string::npos; } -string::size_type string::find_first_of(const string &s, size_type pos) const { +string::size_type string::find_first_of(const string& s, size_type pos) const { for (size_type i = pos; i < size(); i++) { for (size_type j = 0; j < s.size(); j++) { if (p[i] == s.p[j]) { @@ -960,24 +877,17 @@ string::size_type string::find_first_of(const string &s, size_type pos) const { return string::npos; } -int64_t string::compare(const string &str, const char *other, size_type other_size) { +int64_t string::compare(const string& str, const char* other, size_type other_size) { const size_type my_size = str.size(); const int res = memcmp(str.p, other, std::min(my_size, other_size)); return res ? res : static_cast(my_size) - static_cast(other_size); } -int64_t string::compare(const string &str) const { - return compare(*this, str.c_str(), str.size()); -} - -bool string::isset(int64_t index) const { - return index >= 0 && index < size(); -} +int64_t string::compare(const string& str) const { return compare(*this, str.c_str(), str.size()); } +bool string::isset(int64_t index) const { return index >= 0 && index < size(); } -int64_t string::get_correct_index(int64_t index) const { - return index >= 0 ? index : index + int64_t{size()}; -} +int64_t string::get_correct_index(int64_t index) const { return index >= 0 ? index : index + int64_t{size()}; } int64_t string::get_correct_offset(size_type size, int64_t offset) { if (offset < 0) { @@ -989,9 +899,7 @@ int64_t string::get_correct_offset(size_type size, int64_t offset) { return offset; } -int64_t string::get_correct_offset(int64_t offset) const { - return get_correct_offset(size(), offset); -} +int64_t string::get_correct_offset(int64_t offset) const { return get_correct_offset(size(), offset); } int64_t string::get_correct_offset_clamped(int64_t offset) const { if (offset < 0) { @@ -1013,7 +921,7 @@ const string string::get_value(int64_t int_key) const { return string(1, p[true_key]); } -const string string::get_value(const string &string_key) const { +const string string::get_value(const string& string_key) const { int64_t int_val = 0; if (!string_key.try_to_int(&int_val)) { php_warning("\"%s\" is illegal offset for string", string_key.c_str()); @@ -1022,37 +930,32 @@ const string string::get_value(const string &string_key) const { return get_value(int_val); } -const string string::get_value(const mixed &v) const { +const string string::get_value(const mixed& v) const { switch (v.get_type()) { - case mixed::type::NUL: - return get_value(0); - case mixed::type::BOOLEAN: - return get_value(static_cast(v.as_bool())); - case mixed::type::INTEGER: - return get_value(v.as_int()); - case mixed::type::FLOAT: - return get_value(static_cast(v.as_double())); - case mixed::type::STRING: - return get_value(v.as_string()); - case mixed::type::ARRAY: - php_warning("Illegal offset type %s", v.get_type_c_str()); - return string(); - case mixed::type::OBJECT: - php_warning("Illegal offset type %s", v.get_type_or_class_name()); - return string(); - default: - __builtin_unreachable(); - } -} - - -int64_t string::get_reference_counter() const { - return inner()->ref_count + 1; -} - -bool string::is_reference_counter(ExtraRefCnt ref_cnt_value) const noexcept { - return inner()->ref_count == ref_cnt_value; -} + case mixed::type::NUL: + return get_value(0); + case mixed::type::BOOLEAN: + return get_value(static_cast(v.as_bool())); + case mixed::type::INTEGER: + return get_value(v.as_int()); + case mixed::type::FLOAT: + return get_value(static_cast(v.as_double())); + case mixed::type::STRING: + return get_value(v.as_string()); + case mixed::type::ARRAY: + php_warning("Illegal offset type %s", v.get_type_c_str()); + return string(); + case mixed::type::OBJECT: + php_warning("Illegal offset type %s", v.get_type_or_class_name()); + return string(); + default: + __builtin_unreachable(); + } +} + +int64_t string::get_reference_counter() const { return inner()->ref_count + 1; } + +bool string::is_reference_counter(ExtraRefCnt ref_cnt_value) const noexcept { return inner()->ref_count == ref_cnt_value; } void string::set_reference_counter_to(ExtraRefCnt ref_cnt_value) noexcept { // some const arrays are placed in read only memory and can't be modified @@ -1071,17 +974,15 @@ void string::force_destroy(ExtraRefCnt expected_ref_cnt) noexcept { } } -inline string::size_type string::estimate_memory_usage() const { - return inner()->get_memory_usage(); -} +inline string::size_type string::estimate_memory_usage() const { return inner()->get_memory_usage(); } inline string::size_type string::estimate_memory_usage(size_t len) noexcept { return static_cast(sizeof(string_inner)) + string_inner::new_capacity(len, 0); } -inline string string::make_const_string_on_memory(const char *str, size_type len, void *memory, size_t memory_size) { +inline string string::make_const_string_on_memory(const char* str, size_type len, void* memory, size_t memory_size) { php_assert(len + inner_sizeof() + 1 <= memory_size); - auto *inner = new (memory) string_inner {len, len, ExtraRefCnt::for_global_const}; + auto* inner = new (memory) string_inner{len, len, ExtraRefCnt::for_global_const}; memcpy(inner->ref_data(), str, len); inner->ref_data()[len] = '\0'; string result; @@ -1095,20 +996,13 @@ inline void string::destroy() { } } +bool operator==(const string& lhs, const string& rhs) { return lhs.size() == rhs.size() && lhs.compare(rhs) == 0; } -bool operator==(const string &lhs, const string &rhs) { - return lhs.size() == rhs.size() && lhs.compare(rhs) == 0; -} +bool operator!=(const string& lhs, const string& rhs) { return lhs.size() != rhs.size() || lhs.compare(rhs) != 0; } -bool operator!=(const string &lhs, const string &rhs) { - return lhs.size() != rhs.size() || lhs.compare(rhs) != 0; -} - -bool is_ok_float(double v) { - return v == 0.0 || (std::fpclassify(v) == FP_NORMAL && v < 1e100 && v > -1e100); -} +bool is_ok_float(double v) { return v == 0.0 || (std::fpclassify(v) == FP_NORMAL && v < 1e100 && v > -1e100); } -inline bool is_all_digits(const string &s) { +inline bool is_all_digits(const string& s) { for (string::size_type i = 0; i < s.size(); ++i) { if (!('0' <= s[i] && s[i] <= '9')) { return false; @@ -1118,7 +1012,7 @@ inline bool is_all_digits(const string &s) { return true; } -int64_t compare_strings_php_order(const string &lhs, const string &rhs) { +int64_t compare_strings_php_order(const string& lhs, const string& rhs) { if (lhs.size() == rhs.size() && is_all_digits(lhs) && is_all_digits(rhs)) { return lhs.compare(rhs); } @@ -1146,71 +1040,53 @@ int64_t compare_strings_php_order(const string &lhs, const string &rhs) { return lhs.compare(rhs); } -void swap(string &lhs, string &rhs) { - lhs.swap(rhs); -} - +void swap(string& lhs, string& rhs) { lhs.swap(rhs); } -string::size_type max_string_size(bool) { - return static_cast(STRLEN_BOOL); -} - -string::size_type max_string_size(int32_t) { - return static_cast(STRLEN_INT); -} +string::size_type max_string_size(bool) { return static_cast(STRLEN_BOOL); } -string::size_type max_string_size(int64_t) { - return static_cast(STRLEN_INT); -} +string::size_type max_string_size(int32_t) { return static_cast(STRLEN_INT); } +string::size_type max_string_size(int64_t) { return static_cast(STRLEN_INT); } -string::size_type max_string_size(double) { - return static_cast(STRLEN_FLOAT); -} +string::size_type max_string_size(double) { return static_cast(STRLEN_FLOAT); } -string::size_type max_string_size(const string &s) { - return s.size(); -} +string::size_type max_string_size(const string& s) { return s.size(); } -string::size_type max_string_size(tmp_string s) { - return s.size; -} +string::size_type max_string_size(tmp_string s) { return s.size; } -string::size_type max_string_size(const mixed &v) { +string::size_type max_string_size(const mixed& v) { switch (v.get_type()) { - case mixed::type::NUL: - return 0; - case mixed::type::BOOLEAN: - return max_string_size(v.as_bool()); - case mixed::type::INTEGER: - return max_string_size(v.as_int()); - case mixed::type::FLOAT: - return max_string_size(v.as_double()); - case mixed::type::STRING: - return max_string_size(v.as_string()); - case mixed::type::ARRAY: - return max_string_size(v.as_array()); - case mixed::type::OBJECT: - php_warning("Cannot use objects (%s) in string builder", v.get_type_or_class_name()); - default: - __builtin_unreachable(); - } -} - -template -string::size_type max_string_size(const array &) { + case mixed::type::NUL: + return 0; + case mixed::type::BOOLEAN: + return max_string_size(v.as_bool()); + case mixed::type::INTEGER: + return max_string_size(v.as_int()); + case mixed::type::FLOAT: + return max_string_size(v.as_double()); + case mixed::type::STRING: + return max_string_size(v.as_string()); + case mixed::type::ARRAY: + return max_string_size(v.as_array()); + case mixed::type::OBJECT: + php_warning("Cannot use objects (%s) in string builder", v.get_type_or_class_name()); + default: + __builtin_unreachable(); + } +} + +template +string::size_type max_string_size(const array&) { return static_cast(STRLEN_ARRAY); } -template -string::size_type max_string_size(const Optional &v) { +template +string::size_type max_string_size(const Optional& v) { return v.has_value() ? max_string_size(v.val()) : 0; } // in PHP, the '<' operator when applied to strings tries to compare strings as numbers, // therefore stl trees with keys of type string run really slow struct stl_string_less { - bool operator()(const string &lhs, const string &rhs) const noexcept { - return lhs.compare(rhs) < 0; - } + bool operator()(const string& lhs, const string& rhs) const noexcept { return lhs.compare(rhs) < 0; } }; diff --git a/runtime-common/core/core-types/definition/string_buffer.cpp b/runtime-common/core/core-types/definition/string_buffer.cpp index 98d4231a26..0ca2fa66d4 100644 --- a/runtime-common/core/core-types/definition/string_buffer.cpp +++ b/runtime-common/core/core-types/definition/string_buffer.cpp @@ -4,12 +4,7 @@ #include "runtime-common/core/runtime-core.h" -string_buffer::string_buffer(string::size_type buffer_len) noexcept: - buffer_end(static_cast(RuntimeAllocator::get().alloc_global_memory(buffer_len))), - buffer_begin(buffer_end), - buffer_len(buffer_len) { -} +string_buffer::string_buffer(string::size_type buffer_len) noexcept + : buffer_end(static_cast(RuntimeAllocator::get().alloc_global_memory(buffer_len))), buffer_begin(buffer_end), buffer_len(buffer_len) {} -string_buffer::~string_buffer() noexcept { - RuntimeAllocator::get().free_global_memory(buffer_begin, buffer_len); -} +string_buffer::~string_buffer() noexcept { RuntimeAllocator::get().free_global_memory(buffer_begin, buffer_len); } diff --git a/runtime-common/core/core-types/definition/string_buffer.inl b/runtime-common/core/core-types/definition/string_buffer.inl index 7689e5214c..c18f452970 100644 --- a/runtime-common/core/core-types/definition/string_buffer.inl +++ b/runtime-common/core/core-types/definition/string_buffer.inl @@ -3,11 +3,11 @@ #include "common/algorithms/simd-int-to-string.h" #ifndef INCLUDED_FROM_KPHP_CORE - #error "this file must be included only from runtime-core.h" +#error "this file must be included only from runtime-core.h" #endif inline void string_buffer::resize(string::size_type new_buffer_len) noexcept { - string_buffer_lib_context &sb_context = RuntimeContext::get().sb_lib_context; + string_buffer_lib_context& sb_context = RuntimeContext::get().sb_lib_context; if (new_buffer_len < sb_context.MIN_BUFFER_LEN) { new_buffer_len = sb_context.MIN_BUFFER_LEN; } @@ -20,14 +20,14 @@ inline void string_buffer::resize(string::size_type new_buffer_len) noexcept { sb_context.error_flag = STRING_BUFFER_ERROR_FLAG_FAILED; return; } else { - php_critical_error ("maximum buffer size exceeded. buffer_len = %u, new_buffer_len = %u", buffer_len, new_buffer_len); + php_critical_error("maximum buffer size exceeded. buffer_len = %u, new_buffer_len = %u", buffer_len, new_buffer_len); } } } string::size_type current_len = size(); - if(void *new_mem = RuntimeAllocator::get().realloc_global_memory(buffer_begin, new_buffer_len, buffer_len)) { - buffer_begin = static_cast(new_mem); + if (void* new_mem = RuntimeAllocator::get().realloc_global_memory(buffer_begin, new_buffer_len, buffer_len)) { + buffer_begin = static_cast(new_mem); buffer_len = new_buffer_len; buffer_end = buffer_begin + current_len; } @@ -35,17 +35,17 @@ inline void string_buffer::resize(string::size_type new_buffer_len) noexcept { inline void string_buffer::reserve_at_least(string::size_type need) noexcept { string::size_type new_buffer_len = need + size(); - while (unlikely (buffer_len < new_buffer_len && RuntimeContext::get().sb_lib_context.error_flag != STRING_BUFFER_ERROR_FLAG_FAILED)) { + while (unlikely(buffer_len < new_buffer_len && RuntimeContext::get().sb_lib_context.error_flag != STRING_BUFFER_ERROR_FLAG_FAILED)) { resize(((new_buffer_len * 2 + 1 + 64) | 4095) - 64); } } -string_buffer &string_buffer::clean() noexcept { +string_buffer& string_buffer::clean() noexcept { buffer_end = buffer_begin; return *this; } -string_buffer &operator<<(string_buffer &sb, char c) { +string_buffer& operator<<(string_buffer& sb, char c) { sb.reserve_at_least(1); *sb.buffer_end++ = c; @@ -53,8 +53,7 @@ string_buffer &operator<<(string_buffer &sb, char c) { return sb; } - -string_buffer &operator<<(string_buffer &sb, const char *s) { +string_buffer& operator<<(string_buffer& sb, const char* s) { while (*s != 0) { sb.reserve_at_least(1); @@ -64,15 +63,13 @@ string_buffer &operator<<(string_buffer &sb, const char *s) { return sb; } -string_buffer &operator<<(string_buffer &sb, double f) { - return sb << string(f); -} +string_buffer& operator<<(string_buffer& sb, double f) { return sb << string(f); } -string_buffer &operator<<(string_buffer &sb, const string &s) { +string_buffer& operator<<(string_buffer& sb, const string& s) { string::size_type l = s.size(); sb.reserve_at_least(l); - if (unlikely (RuntimeContext::get().sb_lib_context.error_flag == STRING_BUFFER_ERROR_FLAG_FAILED)) { + if (unlikely(RuntimeContext::get().sb_lib_context.error_flag == STRING_BUFFER_ERROR_FLAG_FAILED)) { return sb; } @@ -82,7 +79,7 @@ string_buffer &operator<<(string_buffer &sb, const string &s) { return sb; } -string_buffer &operator<<(string_buffer &sb, bool x) { +string_buffer& operator<<(string_buffer& sb, bool x) { if (x) { sb.reserve_at_least(1); *sb.buffer_end++ = '1'; @@ -91,37 +88,31 @@ string_buffer &operator<<(string_buffer &sb, bool x) { return sb; } -string_buffer &operator<<(string_buffer &sb, int32_t x) { +string_buffer& operator<<(string_buffer& sb, int32_t x) { sb.reserve_at_least(11); sb.buffer_end = simd_int32_to_string(x, sb.buffer_end); return sb; } -string_buffer &operator<<(string_buffer &sb, uint32_t x) { +string_buffer& operator<<(string_buffer& sb, uint32_t x) { sb.reserve_at_least(10); sb.buffer_end = simd_uint32_to_string(x, sb.buffer_end); return sb; } -string_buffer &operator<<(string_buffer &sb, int64_t x) { +string_buffer& operator<<(string_buffer& sb, int64_t x) { sb.reserve_at_least(20); sb.buffer_end = simd_int64_to_string(x, sb.buffer_end); return sb; } -string::size_type string_buffer::size() const noexcept { - return static_cast(buffer_end - buffer_begin); -} +string::size_type string_buffer::size() const noexcept { return static_cast(buffer_end - buffer_begin); } -char *string_buffer::buffer() { - return buffer_begin; -} +char* string_buffer::buffer() { return buffer_begin; } -const char *string_buffer::buffer() const { - return buffer_begin; -} +const char* string_buffer::buffer() const { return buffer_begin; } -const char *string_buffer::c_str() { +const char* string_buffer::c_str() { reserve_at_least(1); *buffer_end = 0; @@ -129,20 +120,20 @@ const char *string_buffer::c_str() { } string string_buffer::str() const { - php_assert (size() <= buffer_len); + php_assert(size() <= buffer_len); return string(buffer_begin, size()); } bool string_buffer::set_pos(int64_t pos) { - php_assert (static_cast(pos) <= buffer_len); + php_assert(static_cast(pos) <= buffer_len); buffer_end = buffer_begin + pos; return true; } -string_buffer &string_buffer::append(const char *str, size_t len) noexcept { +string_buffer& string_buffer::append(const char* str, size_t len) noexcept { reserve_at_least(static_cast(len)); - if (unlikely (RuntimeContext::get().sb_lib_context.error_flag == STRING_BUFFER_ERROR_FLAG_FAILED)) { + if (unlikely(RuntimeContext::get().sb_lib_context.error_flag == STRING_BUFFER_ERROR_FLAG_FAILED)) { return *this; } memcpy(buffer_end, str, len); @@ -151,26 +142,19 @@ string_buffer &string_buffer::append(const char *str, size_t len) noexcept { return *this; } -void string_buffer::write(const char *str, int len) noexcept { - append(str, len); -} +void string_buffer::write(const char* str, int len) noexcept { append(str, len); } -void string_buffer::append_unsafe(const char *str, int len) { +void string_buffer::append_unsafe(const char* str, int len) { memcpy(buffer_end, str, len); buffer_end += len; } -void string_buffer::append_char(char c) { - *buffer_end++ = c; -} - +void string_buffer::append_char(char c) { *buffer_end++ = c; } -void string_buffer::reserve(int len) { - reserve_at_least(len + 1); -} +void string_buffer::reserve(int len) { reserve_at_least(len + 1); } inline void init_string_buffer_lib(string::size_type min_length, string::size_type max_length) { - string_buffer_lib_context &sb_context = RuntimeContext::get().sb_lib_context; + string_buffer_lib_context& sb_context = RuntimeContext::get().sb_lib_context; if (min_length > 0) { sb_context.MIN_BUFFER_LEN = min_length; } @@ -179,12 +163,12 @@ inline void init_string_buffer_lib(string::size_type min_length, string::size_ty } } -void string_buffer::copy_raw_data(const string_buffer &other) { +void string_buffer::copy_raw_data(const string_buffer& other) { clean(); append(other.str().c_str(), other.size()); } -bool operator==(const string_buffer &lhs, const string_buffer &rhs) { +bool operator==(const string_buffer& lhs, const string_buffer& rhs) { size_t len_l = lhs.buffer_end - lhs.buffer_begin; size_t len_r = rhs.buffer_end - rhs.buffer_begin; if (len_l != len_r) { @@ -193,13 +177,9 @@ bool operator==(const string_buffer &lhs, const string_buffer &rhs) { return std::equal(lhs.buffer_begin, lhs.buffer_end, rhs.buffer_begin); } -bool operator!=(string_buffer const &lhs, string_buffer const &rhs) { - return !(lhs == rhs); -} +bool operator!=(string_buffer const& lhs, string_buffer const& rhs) { return !(lhs == rhs); } void string_buffer::debug_print() const { - std::for_each(buffer_begin, buffer_end, [](char c) { - fprintf(stderr, "%02x ", (int)c); - }); + std::for_each(buffer_begin, buffer_end, [](char c) { fprintf(stderr, "%02x ", (int)c); }); fprintf(stderr, "\n"); } diff --git a/runtime-common/core/core-types/definition/string_cache.cpp b/runtime-common/core/core-types/definition/string_cache.cpp index b215200e7b..60b51c9e33 100644 --- a/runtime-common/core/core-types/definition/string_cache.cpp +++ b/runtime-common/core/core-types/definition/string_cache.cpp @@ -4,11 +4,9 @@ #include "runtime-common/core/runtime-core.h" -constexpr auto string_cache::constexpr_make_large_ints() noexcept { - return constexpr_make_ints(std::make_index_sequence{}); -} +constexpr auto string_cache::constexpr_make_large_ints() noexcept { return constexpr_make_ints(std::make_index_sequence{}); } -const string::string_inner &string_cache::cached_large_int(int64_t i) noexcept { +const string::string_inner& string_cache::cached_large_int(int64_t i) noexcept { static_assert(sizeof(string_8bytes) == sizeof(string::string_inner) + string_8bytes::TAIL_SIZE, "unexpected padding"); // to avoid a big compilation time impact, we implement numbers generation from 100 (small_int_max) to 9999 (cached_int_max - 1) here static constexpr auto large_int_cache = constexpr_make_large_ints(); diff --git a/runtime-common/core/core-types/definition/string_cache.h b/runtime-common/core/core-types/definition/string_cache.h index 6541a0ab05..49ae301851 100644 --- a/runtime-common/core/core-types/definition/string_cache.h +++ b/runtime-common/core/core-types/definition/string_cache.h @@ -4,8 +4,8 @@ #pragma once -#include #include +#include #include "common/php-functions.h" @@ -16,16 +16,11 @@ class string_cache { struct string_8bytes { static constexpr size_t TAIL_SIZE = 8u; - constexpr explicit string_8bytes(char c) : - inner{1, 1, ExtraRefCnt::for_global_const}, - data{c, '\0'} { - } + constexpr explicit string_8bytes(char c) : inner{1, 1, ExtraRefCnt::for_global_const}, data{c, '\0'} {} - template - constexpr explicit string_8bytes(std::index_sequence) : - inner{sizeof...(Digits), sizeof...(Digits), ExtraRefCnt::for_global_const}, - data{static_cast('0' + Digits)..., '\0'} { - } + template + constexpr explicit string_8bytes(std::index_sequence) + : inner{sizeof...(Digits), sizeof...(Digits), ExtraRefCnt::for_global_const}, data{static_cast('0' + Digits)..., '\0'} {} constexpr string_8bytes() = default; @@ -39,72 +34,54 @@ class string_cache { using single_char_storage = std::array; struct single_char_storage_hack : single_char_storage { private: - template - constexpr single_char_storage_hack(std::index_sequence) noexcept : - single_char_storage{ - { - string_cache::string_8bytes(static_cast(Chars))... - } - } {} + template + constexpr single_char_storage_hack(std::index_sequence) noexcept + : single_char_storage{{string_cache::string_8bytes(static_cast(Chars))...}} {} public: - constexpr single_char_storage_hack() noexcept : - single_char_storage_hack{std::make_index_sequence{}>{}} { - } + constexpr single_char_storage_hack() noexcept : single_char_storage_hack{std::make_index_sequence{}>{}} {} }; - template - struct constexpr_number_to_string : constexpr_number_to_string { - }; + template + struct constexpr_number_to_string : constexpr_number_to_string {}; - template + template struct constexpr_number_to_string<0, Digits...> { static constexpr string_8bytes create() noexcept { - return sizeof...(Digits) - ? string_8bytes{std::index_sequence{}} - : string_8bytes{std::index_sequence<0>{}}; + return sizeof...(Digits) ? string_8bytes{std::index_sequence{}} : string_8bytes{std::index_sequence<0>{}}; } }; - template + template static constexpr auto constexpr_make_ints(std::index_sequence) noexcept { // split into the 10 parts, otherwise it compiles too long return std::array{ - { - constexpr_number_to_string<0 * sizeof...(Ints) + Ints>::create()..., - constexpr_number_to_string<1 * sizeof...(Ints) + Ints>::create()..., - constexpr_number_to_string<2 * sizeof...(Ints) + Ints>::create()..., - constexpr_number_to_string<3 * sizeof...(Ints) + Ints>::create()..., - constexpr_number_to_string<4 * sizeof...(Ints) + Ints>::create()..., - constexpr_number_to_string<5 * sizeof...(Ints) + Ints>::create()..., - constexpr_number_to_string<6 * sizeof...(Ints) + Ints>::create()..., - constexpr_number_to_string<7 * sizeof...(Ints) + Ints>::create()..., - constexpr_number_to_string<8 * sizeof...(Ints) + Ints>::create()..., - constexpr_number_to_string<9 * sizeof...(Ints) + Ints>::create()... - }}; + {constexpr_number_to_string<0 * sizeof...(Ints) + Ints>::create()..., constexpr_number_to_string<1 * sizeof...(Ints) + Ints>::create()..., + constexpr_number_to_string<2 * sizeof...(Ints) + Ints>::create()..., constexpr_number_to_string<3 * sizeof...(Ints) + Ints>::create()..., + constexpr_number_to_string<4 * sizeof...(Ints) + Ints>::create()..., constexpr_number_to_string<5 * sizeof...(Ints) + Ints>::create()..., + constexpr_number_to_string<6 * sizeof...(Ints) + Ints>::create()..., constexpr_number_to_string<7 * sizeof...(Ints) + Ints>::create()..., + constexpr_number_to_string<8 * sizeof...(Ints) + Ints>::create()..., constexpr_number_to_string<9 * sizeof...(Ints) + Ints>::create()...}}; } static constexpr int64_t small_int_max() noexcept { return 100; } - static constexpr auto constexpr_make_small_ints() noexcept { - return constexpr_make_ints(std::make_index_sequence{}); - } + static constexpr auto constexpr_make_small_ints() noexcept { return constexpr_make_ints(std::make_index_sequence{}); } static constexpr auto constexpr_make_large_ints() noexcept; - static const string::string_inner &cached_large_int(int64_t i) noexcept; + static const string::string_inner& cached_large_int(int64_t i) noexcept; public: - static const string::string_inner &empty_string() noexcept { + static const string::string_inner& empty_string() noexcept { static constexpr string_8bytes empty_string; return empty_string.inner; } - static const string::string_inner &cached_char(char c) noexcept { + static const string::string_inner& cached_char(char c) noexcept { static constexpr single_char_storage_hack constexpr_char_cache; return constexpr_char_cache[static_cast(c)].inner; } - static const string::string_inner &cached_int(int64_t i) noexcept { + static const string::string_inner& cached_int(int64_t i) noexcept { // constexpr_make_small_ints generates numbers from 0 to 99 (small_int_max - 1), // it makes the compilation faster // numbers from 100 (small_int_max) to 9999 (cached_int_max - 1) live inside the cached_large_int diff --git a/runtime-common/core/core-types/kphp_type_traits.h b/runtime-common/core/core-types/kphp_type_traits.h index 8766c536dd..170d74a7bd 100644 --- a/runtime-common/core/core-types/kphp_type_traits.h +++ b/runtime-common/core/core-types/kphp_type_traits.h @@ -12,73 +12,57 @@ #include "runtime-common/core/core-types/decl/optional.h" #include "runtime-common/core/core-types/decl/shape.h" -template -struct is_array : std::false_type { -}; +template +struct is_array : std::false_type {}; -template -struct is_array> : std::true_type { -}; +template +struct is_array> : std::true_type {}; -template -struct is_constructible_or_unknown : std::is_constructible { -}; +template +struct is_constructible_or_unknown : std::is_constructible {}; -template -struct is_constructible_or_unknown : std::true_type { -}; +template +struct is_constructible_or_unknown : std::true_type {}; -template +template using enable_if_constructible_or_unknown = std::enable_if_t::value>; -template +template using enable_for_bool_int_double = vk::enable_if_in_list>; -template -struct is_class_instance : std::false_type { -}; +template +struct is_class_instance : std::false_type {}; -template -struct is_class_instance> : std::true_type { -}; +template +struct is_class_instance> : std::true_type {}; template inline constexpr bool is_class_instance_v = is_class_instance::value; -template -struct is_class_instance_inside : is_class_instance { -}; +template +struct is_class_instance_inside : is_class_instance {}; -template -struct is_class_instance_inside> : is_class_instance_inside { -}; +template +struct is_class_instance_inside> : is_class_instance_inside {}; -template -struct is_class_instance_inside> : is_class_instance_inside { -}; +template +struct is_class_instance_inside> : is_class_instance_inside {}; -template -struct is_class_instance_inside> : is_class_instance_inside { -}; +template +struct is_class_instance_inside> : is_class_instance_inside {}; -template -struct is_class_instance_inside> : - std::integral_constant::value || - is_class_instance_inside>::value> { -}; +template +struct is_class_instance_inside> + : std::integral_constant::value || is_class_instance_inside>::value> {}; -template -struct is_class_instance_inside, Ts...>> : - is_class_instance_inside> { -}; +template +struct is_class_instance_inside, Ts...>> : is_class_instance_inside> {}; -template -struct one_of_is_unknown : vk::is_type_in_list { -}; +template +struct one_of_is_unknown : vk::is_type_in_list {}; -template +template using enable_if_one_of_types_is_unknown = std::enable_if_t{}, bool>; -template +template using disable_if_one_of_types_is_unknown = std::enable_if_t{} && !(is_class_instance{} && is_class_instance{}), bool>; diff --git a/runtime-common/core/include.h b/runtime-common/core/include.h index 267cdc1f91..fdc6dc32b1 100644 --- a/runtime-common/core/include.h +++ b/runtime-common/core/include.h @@ -12,45 +12,44 @@ #include "common/php-functions.h" #include "runtime-common/core/core-types/decl/declarations.h" -#include "runtime-common/core/core-types/kphp_type_traits.h" #include "runtime-common/core/core-types/decl/optional.h" +#include "runtime-common/core/core-types/kphp_type_traits.h" #include "runtime-common/core/utils/kphp-assert-core.h" #define COMMA , - -template +template class convert_to { public: static_assert(!std::is_same{}, "int is forbidden"); - static inline const T &convert(const T &val); + static inline const T& convert(const T& val); - static inline T &&convert(T &&val); + static inline T&& convert(T&& val); - static inline T convert(const Unknown &val); + static inline T convert(const Unknown& val); - template, Unknown>::value>, - class = std::enable_if_t, T>::value> - > - static inline T convert(T1 &&val); + template , Unknown>::value>, + class = std::enable_if_t, T>::value>> + static inline T convert(T1&& val); }; -template -inline bool f$is_null(const T &v); -template -inline bool f$is_null(const class_instance &v); -template -inline bool f$is_null(const Optional &v); -inline bool f$is_null(const mixed &v); +template +inline bool f$is_null(const T& v); +template +inline bool f$is_null(const class_instance& v); +template +inline bool f$is_null(const Optional& v); +inline bool f$is_null(const mixed& v); -template +template struct CDataPtr; -template -bool f$is_null(CDataPtr ptr) { return ptr.is_php_null(); } +template +bool f$is_null(CDataPtr ptr) { + return ptr.is_php_null(); +} -using std::swap; -using std::min; using std::max; +using std::min; +using std::swap; diff --git a/runtime-common/core/memory-resource/details/memory_chunk_list.h b/runtime-common/core/memory-resource/details/memory_chunk_list.h index 566a8aae6c..e56bd11454 100644 --- a/runtime-common/core/memory-resource/details/memory_chunk_list.h +++ b/runtime-common/core/memory-resource/details/memory_chunk_list.h @@ -15,39 +15,29 @@ class memory_chunk_list { public: memory_chunk_list() = default; - void *get_mem() noexcept { - void *result = next_; + void* get_mem() noexcept { + void* result = next_; if (next_) { next_ = next_->next_; } return result; } - void put_mem(void *block) noexcept { - next_ = new(block) memory_chunk_list{next_}; - } + void put_mem(void* block) noexcept { next_ = new (block) memory_chunk_list{next_}; } private: - explicit memory_chunk_list(memory_chunk_list *next) noexcept : - next_(next) { - } + explicit memory_chunk_list(memory_chunk_list* next) noexcept : next_(next) {} - memory_chunk_list *next_{nullptr}; + memory_chunk_list* next_{nullptr}; }; static_assert(sizeof(memory_chunk_list) == 8, "sizeof memory_chunk_list should be 8"); -inline constexpr size_t align_for_chunk(size_t size) noexcept { - return static_cast((size + 7L) & -8L); -} +inline constexpr size_t align_for_chunk(size_t size) noexcept { return static_cast((size + 7L) & -8L); } -inline constexpr size_t get_chunk_id(size_t aligned_size) noexcept { - return aligned_size >> 3; -} +inline constexpr size_t get_chunk_id(size_t aligned_size) noexcept { return aligned_size >> 3; } -inline constexpr size_t get_chunk_size(size_t chunk_id) noexcept { - return chunk_id << 3; -} +inline constexpr size_t get_chunk_size(size_t chunk_id) noexcept { return chunk_id << 3; } } // namespace details } // namespace memory_resource diff --git a/runtime-common/core/memory-resource/details/memory_chunk_tree.cpp b/runtime-common/core/memory-resource/details/memory_chunk_tree.cpp index 3009600eed..ee7f19cc10 100644 --- a/runtime-common/core/memory-resource/details/memory_chunk_tree.cpp +++ b/runtime-common/core/memory-resource/details/memory_chunk_tree.cpp @@ -15,33 +15,26 @@ namespace details { class memory_chunk_tree::tree_node { public: - tree_node *left{nullptr}; - tree_node *right{nullptr}; - tree_node *parent{nullptr}; - enum { - RED, - BLACK - } color{RED}; + tree_node* left{nullptr}; + tree_node* right{nullptr}; + tree_node* parent{nullptr}; + enum { RED, BLACK } color{RED}; size_t chunk_size; - tree_node *same_size_chunk_list{nullptr}; + tree_node* same_size_chunk_list{nullptr}; - explicit tree_node(size_t size) noexcept : - chunk_size(size) { - } + explicit tree_node(size_t size) noexcept : chunk_size(size) {} - tree_node *uncle() const noexcept { + tree_node* uncle() const noexcept { if (!parent || !parent->parent) { return nullptr; } - auto *grandpa = parent->parent; + auto* grandpa = parent->parent; return parent->is_left() ? grandpa->right : grandpa->left; } - bool is_left() const noexcept { - return this == parent->left; - } + bool is_left() const noexcept { return this == parent->left; } - void replace_self_on_parent(tree_node *replacer) noexcept { + void replace_self_on_parent(tree_node* replacer) noexcept { if (is_left()) { parent->left = replacer; } else { @@ -49,14 +42,14 @@ class memory_chunk_tree::tree_node { } } - tree_node *sibling() const noexcept { + tree_node* sibling() const noexcept { if (!parent) { return nullptr; } return is_left() ? parent->right : parent->left; } - void move_down(tree_node *new_parent) noexcept { + void move_down(tree_node* new_parent) noexcept { if (parent) { replace_self_on_parent(new_parent); } @@ -64,19 +57,17 @@ class memory_chunk_tree::tree_node { parent = new_parent; } - bool has_red_child() const noexcept { - return (left && left->color == RED) || (right && right->color == RED); - } + bool has_red_child() const noexcept { return (left && left->color == RED) || (right && right->color == RED); } }; -void memory_chunk_tree::insert(void *mem, size_t size) noexcept { +void memory_chunk_tree::insert(void* mem, size_t size) noexcept { php_assert(sizeof(tree_node) <= size); - tree_node *newNode = new(mem) tree_node{size}; + tree_node* newNode = new (mem) tree_node{size}; if (!root_) { newNode->color = tree_node::BLACK; root_ = newNode; } else { - tree_node *temp = search(size, false); + tree_node* temp = search(size, false); if (temp->chunk_size == size) { newNode->same_size_chunk_list = temp->same_size_chunk_list; temp->same_size_chunk_list = newNode; @@ -94,10 +85,10 @@ void memory_chunk_tree::insert(void *mem, size_t size) noexcept { } } -memory_chunk_tree::tree_node *memory_chunk_tree::extract(size_t size) noexcept { - if (tree_node *v = search(size, true)) { +memory_chunk_tree::tree_node* memory_chunk_tree::extract(size_t size) noexcept { + if (tree_node* v = search(size, true)) { if (v->same_size_chunk_list) { - tree_node *result = v->same_size_chunk_list; + tree_node* result = v->same_size_chunk_list; v->same_size_chunk_list = result->same_size_chunk_list; return result; } @@ -107,14 +98,14 @@ memory_chunk_tree::tree_node *memory_chunk_tree::extract(size_t size) noexcept { return nullptr; } -memory_chunk_tree::tree_node *memory_chunk_tree::extract_smallest() noexcept { - tree_node *v = root_; +memory_chunk_tree::tree_node* memory_chunk_tree::extract_smallest() noexcept { + tree_node* v = root_; while (v && v->left) { v = v->left; } if (v) { if (v->same_size_chunk_list) { - tree_node *result = v->same_size_chunk_list; + tree_node* result = v->same_size_chunk_list; v->same_size_chunk_list = result->same_size_chunk_list; return result; } @@ -123,40 +114,36 @@ memory_chunk_tree::tree_node *memory_chunk_tree::extract_smallest() noexcept { return v; } -bool memory_chunk_tree::has_memory_for(size_t size) const noexcept { - return search(size, true); -} +bool memory_chunk_tree::has_memory_for(size_t size) const noexcept { return search(size, true); } -size_t memory_chunk_tree::get_chunk_size(tree_node *node) noexcept { - return node->chunk_size; -} +size_t memory_chunk_tree::get_chunk_size(tree_node* node) noexcept { return node->chunk_size; } -void memory_chunk_tree::flush_to(memory_ordered_chunk_list &mem_list) noexcept { +void memory_chunk_tree::flush_to(memory_ordered_chunk_list& mem_list) noexcept { flush_node_to(root_, mem_list); root_ = nullptr; } -void memory_chunk_tree::flush_node_to(tree_node *node, memory_ordered_chunk_list &mem_list) noexcept { +void memory_chunk_tree::flush_node_to(tree_node* node, memory_ordered_chunk_list& mem_list) noexcept { if (!node) { return; } - while(node->same_size_chunk_list) { - tree_node *next = node->same_size_chunk_list; + while (node->same_size_chunk_list) { + tree_node* next = node->same_size_chunk_list; node->same_size_chunk_list = next->same_size_chunk_list; mem_list.add_memory(next, next->chunk_size); } - tree_node *left = node->left; - tree_node *right = node->right; + tree_node* left = node->left; + tree_node* right = node->right; mem_list.add_memory(node, node->chunk_size); flush_node_to(left, mem_list); flush_node_to(right, mem_list); } -memory_chunk_tree::tree_node *memory_chunk_tree::search(size_t size, bool lower_bound) const noexcept { - tree_node *node = root_; - tree_node *lower_bound_node = nullptr; +memory_chunk_tree::tree_node* memory_chunk_tree::search(size_t size, bool lower_bound) const noexcept { + tree_node* node = root_; + tree_node* lower_bound_node = nullptr; while (node && size != node->chunk_size) { if (size < node->chunk_size) { lower_bound_node = node; @@ -179,8 +166,8 @@ memory_chunk_tree::tree_node *memory_chunk_tree::search(size_t size, bool lower_ return lower_bound ? lower_bound_node : node; } -void memory_chunk_tree::left_rotate(tree_node *node) noexcept { - tree_node *new_parent = node->right; +void memory_chunk_tree::left_rotate(tree_node* node) noexcept { + tree_node* new_parent = node->right; if (node == root_) { root_ = new_parent; } @@ -194,8 +181,8 @@ void memory_chunk_tree::left_rotate(tree_node *node) noexcept { new_parent->left = node; } -void memory_chunk_tree::right_rotate(tree_node *node) noexcept { - tree_node *new_parent = node->left; +void memory_chunk_tree::right_rotate(tree_node* node) noexcept { + tree_node* new_parent = node->left; if (node == root_) { root_ = new_parent; } @@ -209,15 +196,15 @@ void memory_chunk_tree::right_rotate(tree_node *node) noexcept { new_parent->right = node; } -void memory_chunk_tree::fix_red_red(tree_node *node) noexcept { +void memory_chunk_tree::fix_red_red(tree_node* node) noexcept { if (node == root_) { node->color = tree_node::BLACK; return; } - tree_node *parent = node->parent; - tree_node *grandparent = parent->parent; - tree_node *uncle = node->uncle(); + tree_node* parent = node->parent; + tree_node* grandparent = parent->parent; + tree_node* uncle = node->uncle(); if (parent->color != tree_node::BLACK) { if (uncle && uncle->color == tree_node::RED) { @@ -247,10 +234,10 @@ void memory_chunk_tree::fix_red_red(tree_node *node) noexcept { } } -memory_chunk_tree::tree_node *memory_chunk_tree::find_replacer(tree_node *node) noexcept { +memory_chunk_tree::tree_node* memory_chunk_tree::find_replacer(tree_node* node) noexcept { if (node->left && node->right) { // find node that do not have a left child - tree_node *replacer = node->right; + tree_node* replacer = node->right; while (replacer->left) { replacer = replacer->left; } @@ -259,7 +246,7 @@ memory_chunk_tree::tree_node *memory_chunk_tree::find_replacer(tree_node *node) return node->left ? node->left : node->right; } -void memory_chunk_tree::detach_leaf(tree_node *detaching_node) noexcept { +void memory_chunk_tree::detach_leaf(tree_node* detaching_node) noexcept { if (detaching_node == root_) { root_ = nullptr; return; @@ -269,7 +256,7 @@ void memory_chunk_tree::detach_leaf(tree_node *detaching_node) noexcept { fix_double_black(detaching_node); } else { // replacer or detaching_node is red - if (tree_node *sibling = detaching_node->sibling()) { + if (tree_node* sibling = detaching_node->sibling()) { sibling->color = tree_node::RED; } } @@ -277,7 +264,7 @@ void memory_chunk_tree::detach_leaf(tree_node *detaching_node) noexcept { detaching_node->replace_self_on_parent(nullptr); } -void memory_chunk_tree::detach_node_with_one_child(tree_node *detaching_node, tree_node *replacer) noexcept { +void memory_chunk_tree::detach_node_with_one_child(tree_node* detaching_node, tree_node* replacer) noexcept { if (detaching_node == root_) { php_assert(!replacer->left && !replacer->right); php_assert(replacer->parent == detaching_node); @@ -297,7 +284,7 @@ void memory_chunk_tree::detach_node_with_one_child(tree_node *detaching_node, tr } } -void memory_chunk_tree::swap_detaching_node_with_replacer(tree_node *detaching_node, tree_node *replacer) noexcept { +void memory_chunk_tree::swap_detaching_node_with_replacer(tree_node* detaching_node, tree_node* replacer) noexcept { if (detaching_node->parent) { detaching_node->replace_self_on_parent(replacer); } else { @@ -331,8 +318,8 @@ void memory_chunk_tree::swap_detaching_node_with_replacer(tree_node *detaching_n std::swap(replacer->color, detaching_node->color); } -void memory_chunk_tree::detach_node(tree_node *detaching_node) noexcept { - tree_node *replacer = find_replacer(detaching_node); +void memory_chunk_tree::detach_node(tree_node* detaching_node) noexcept { + tree_node* replacer = find_replacer(detaching_node); if (!replacer) { detach_leaf(detaching_node); return; @@ -347,13 +334,13 @@ void memory_chunk_tree::detach_node(tree_node *detaching_node) noexcept { detach_node(detaching_node); } -void memory_chunk_tree::fix_double_black(tree_node *node) noexcept { +void memory_chunk_tree::fix_double_black(tree_node* node) noexcept { if (node == root_) { return; } - tree_node *parent = node->parent; - if (tree_node *sibling = node->sibling()) { + tree_node* parent = node->parent; + if (tree_node* sibling = node->sibling()) { if (sibling->color == tree_node::RED) { parent->color = tree_node::RED; sibling->color = tree_node::BLACK; diff --git a/runtime-common/core/memory-resource/details/memory_chunk_tree.h b/runtime-common/core/memory-resource/details/memory_chunk_tree.h index c1a0ef1665..f09967564c 100644 --- a/runtime-common/core/memory-resource/details/memory_chunk_tree.h +++ b/runtime-common/core/memory-resource/details/memory_chunk_tree.h @@ -18,30 +18,30 @@ class memory_chunk_tree : vk::not_copyable { class tree_node; void hard_reset() noexcept { root_ = nullptr; } - void insert(void *mem, size_t size) noexcept; - tree_node *extract(size_t size) noexcept; - tree_node *extract_smallest() noexcept; + void insert(void* mem, size_t size) noexcept; + tree_node* extract(size_t size) noexcept; + tree_node* extract_smallest() noexcept; bool has_memory_for(size_t size) const noexcept; - static size_t get_chunk_size(tree_node *node) noexcept; + static size_t get_chunk_size(tree_node* node) noexcept; - void flush_to(memory_ordered_chunk_list &mem_list) noexcept; + void flush_to(memory_ordered_chunk_list& mem_list) noexcept; private: - void flush_node_to(tree_node *node, memory_ordered_chunk_list &mem_list) noexcept; - tree_node *search(size_t size, bool lower_bound) const noexcept; - - void left_rotate(tree_node *node) noexcept; - void right_rotate(tree_node *node) noexcept; - void fix_red_red(tree_node *node) noexcept; - tree_node *find_replacer(tree_node *node) noexcept; - void detach_leaf(tree_node *detaching_node) noexcept; - void detach_node_with_one_child(tree_node *detaching_node, tree_node *replacer) noexcept; - void swap_detaching_node_with_replacer(tree_node *detaching_node, tree_node *replacer) noexcept; - void detach_node(tree_node *detaching_node) noexcept; - void fix_double_black(tree_node *node) noexcept; - - tree_node *root_{nullptr}; + void flush_node_to(tree_node* node, memory_ordered_chunk_list& mem_list) noexcept; + tree_node* search(size_t size, bool lower_bound) const noexcept; + + void left_rotate(tree_node* node) noexcept; + void right_rotate(tree_node* node) noexcept; + void fix_red_red(tree_node* node) noexcept; + tree_node* find_replacer(tree_node* node) noexcept; + void detach_leaf(tree_node* detaching_node) noexcept; + void detach_node_with_one_child(tree_node* detaching_node, tree_node* replacer) noexcept; + void swap_detaching_node_with_replacer(tree_node* detaching_node, tree_node* replacer) noexcept; + void detach_node(tree_node* detaching_node) noexcept; + void fix_double_black(tree_node* node) noexcept; + + tree_node* root_{nullptr}; }; } // namespace details diff --git a/runtime-common/core/memory-resource/details/memory_ordered_chunk_list.cpp b/runtime-common/core/memory-resource/details/memory_ordered_chunk_list.cpp index d2988f2947..4db8b532b5 100644 --- a/runtime-common/core/memory-resource/details/memory_ordered_chunk_list.cpp +++ b/runtime-common/core/memory-resource/details/memory_ordered_chunk_list.cpp @@ -11,49 +11,48 @@ namespace memory_resource { namespace details { -memory_ordered_chunk_list::memory_ordered_chunk_list(char *memory_resource_begin, char *memory_resource_end) noexcept - : memory_resource_begin_(memory_resource_begin) - , memory_resource_end_(memory_resource_end) { +memory_ordered_chunk_list::memory_ordered_chunk_list(char* memory_resource_begin, char* memory_resource_end) noexcept + : memory_resource_begin_(memory_resource_begin), memory_resource_end_(memory_resource_end) { static_assert(sizeof(list_node) == 8, "8 bytes expected"); } -memory_ordered_chunk_list::list_node *memory_ordered_chunk_list::flush() noexcept { +memory_ordered_chunk_list::list_node* memory_ordered_chunk_list::flush() noexcept { add_from_array(tmp_buffer_.data(), tmp_buffer_.data() + tmp_buffer_size_); tmp_buffer_size_ = 0; - memory_ordered_chunk_list::list_node *ret = head_; + memory_ordered_chunk_list::list_node* ret = head_; head_ = nullptr; return ret; } -void memory_ordered_chunk_list::save_next(list_node *node, const list_node *next) const noexcept { - node->next_chunk_offset_ = static_cast(reinterpret_cast(next) - memory_resource_begin_); +void memory_ordered_chunk_list::save_next(list_node* node, const list_node* next) const noexcept { + node->next_chunk_offset_ = static_cast(reinterpret_cast(next) - memory_resource_begin_); } -void memory_ordered_chunk_list::add_from_array(list_node **first, list_node **last) noexcept { +void memory_ordered_chunk_list::add_from_array(list_node** first, list_node** last) noexcept { if (first == last) { return; } - last = std::partition(first, last, [this](const auto *mem) { - return reinterpret_cast(mem) >= reinterpret_cast(this->memory_resource_begin_) - && reinterpret_cast(mem) < reinterpret_cast(this->memory_resource_end_); + last = std::partition(first, last, [this](const auto* mem) { + return reinterpret_cast(mem) >= reinterpret_cast(this->memory_resource_begin_) && + reinterpret_cast(mem) < reinterpret_cast(this->memory_resource_end_); }); std::sort(first, last, std::greater<>{}); if (!head_) { head_ = *first++; - } else if (reinterpret_cast(head_) < reinterpret_cast(*first)) { - list_node *next = head_; + } else if (reinterpret_cast(head_) < reinterpret_cast(*first)) { + list_node* next = head_; head_ = *first++; save_next(head_, next); } // current is always greater than *first - list_node *current = head_; + list_node* current = head_; for (; first != last && current->has_next();) { - list_node *next = get_next(current); - if (reinterpret_cast(*first) < reinterpret_cast(next)) { + list_node* next = get_next(current); + if (reinterpret_cast(*first) < reinterpret_cast(next)) { current = next; } else { (*first)->next_chunk_offset_ = current->next_chunk_offset_; @@ -69,8 +68,8 @@ void memory_ordered_chunk_list::add_from_array(list_node **first, list_node **la } // merge adjacent nodes - for (list_node *next = get_next(head_); next; next = get_next(head_)) { - if (reinterpret_cast(head_) == reinterpret_cast(next) + next->chunk_size_) { + for (list_node* next = get_next(head_); next; next = get_next(head_)) { + if (reinterpret_cast(head_) == reinterpret_cast(next) + next->chunk_size_) { next->chunk_size_ += (head_)->chunk_size_; head_ = next; } else { @@ -78,10 +77,10 @@ void memory_ordered_chunk_list::add_from_array(list_node **first, list_node **la } } - list_node *prev = head_; - if (list_node *node = get_next(prev)) { - for (list_node *next = get_next(node); next; next = get_next(node)) { - if (reinterpret_cast(node) == reinterpret_cast(next) + next->chunk_size_) { + list_node* prev = head_; + if (list_node* node = get_next(prev)) { + for (list_node* next = get_next(node); next; next = get_next(node)) { + if (reinterpret_cast(node) == reinterpret_cast(next) + next->chunk_size_) { next->chunk_size_ += node->chunk_size_; } else { save_next(prev, node); @@ -94,4 +93,4 @@ void memory_ordered_chunk_list::add_from_array(list_node **first, list_node **la } } // namespace details -} //namespace memory_resource +} // namespace memory_resource diff --git a/runtime-common/core/memory-resource/details/memory_ordered_chunk_list.h b/runtime-common/core/memory-resource/details/memory_ordered_chunk_list.h index c2010089c7..521b9cddee 100644 --- a/runtime-common/core/memory-resource/details/memory_ordered_chunk_list.h +++ b/runtime-common/core/memory-resource/details/memory_ordered_chunk_list.h @@ -22,9 +22,7 @@ class memory_ordered_chunk_list : vk::not_copyable { public: friend class memory_ordered_chunk_list; - explicit list_node(uint32_t size = 0) noexcept : - chunk_size_(size) { - } + explicit list_node(uint32_t size = 0) noexcept : chunk_size_(size) {} uint32_t size() const noexcept { return chunk_size_; } bool has_next() const noexcept { return next_chunk_offset_ != std::numeric_limits::max(); } @@ -34,32 +32,32 @@ class memory_ordered_chunk_list : vk::not_copyable { uint32_t chunk_size_{0}; }; - explicit memory_ordered_chunk_list(char *memory_resource_begin, char *memory_resource_end) noexcept; + explicit memory_ordered_chunk_list(char* memory_resource_begin, char* memory_resource_end) noexcept; - list_node *get_next(const list_node *node) const noexcept { - return node->has_next() ? reinterpret_cast(memory_resource_begin_ + node->next_chunk_offset_) : nullptr; + list_node* get_next(const list_node* node) const noexcept { + return node->has_next() ? reinterpret_cast(memory_resource_begin_ + node->next_chunk_offset_) : nullptr; } - void add_memory(void *mem, size_t size) noexcept { + void add_memory(void* mem, size_t size) noexcept { php_assert(size >= sizeof(list_node) && size <= std::numeric_limits::max()); - tmp_buffer_[tmp_buffer_size_++] = new(mem) list_node{static_cast(size)}; + tmp_buffer_[tmp_buffer_size_++] = new (mem) list_node{static_cast(size)}; if (tmp_buffer_size_ == tmp_buffer_.size()) { add_from_array(tmp_buffer_.data(), tmp_buffer_.data() + tmp_buffer_size_); tmp_buffer_size_ = 0; } } - list_node *flush() noexcept; + list_node* flush() noexcept; private: - void save_next(list_node *node, const list_node *next) const noexcept; - void add_from_array(list_node **first, list_node **last) noexcept; + void save_next(list_node* node, const list_node* next) const noexcept; + void add_from_array(list_node** first, list_node** last) noexcept; - char *memory_resource_begin_{nullptr}; - char *memory_resource_end_{nullptr}; - list_node *head_{nullptr}; + char* memory_resource_begin_{nullptr}; + char* memory_resource_end_{nullptr}; + list_node* head_{nullptr}; size_t tmp_buffer_size_{0}; - std::array tmp_buffer_; + std::array tmp_buffer_; }; } // namespace details diff --git a/runtime-common/core/memory-resource/details/universal_reallocate.h b/runtime-common/core/memory-resource/details/universal_reallocate.h index d5dad8b917..e1cb5d3d06 100644 --- a/runtime-common/core/memory-resource/details/universal_reallocate.h +++ b/runtime-common/core/memory-resource/details/universal_reallocate.h @@ -11,14 +11,14 @@ namespace memory_resource { namespace details { -template -void *universal_reallocate(Allocator &alloc, void *mem, size_t new_size, size_t old_size) { - if (void *new_mem = alloc.try_expand(mem, new_size, old_size)) { +template +void* universal_reallocate(Allocator& alloc, void* mem, size_t new_size, size_t old_size) { + if (void* new_mem = alloc.try_expand(mem, new_size, old_size)) { memory_debug("reallocate %zu to %zu, reallocated address %p\n", old_size, new_size, new_mem); return new_mem; } - void *new_mem = alloc.allocate(new_size); + void* new_mem = alloc.allocate(new_size); if (new_mem != nullptr) { memcpy(new_mem, mem, old_size); alloc.deallocate(mem, old_size); diff --git a/runtime-common/core/memory-resource/extra-memory-pool.h b/runtime-common/core/memory-resource/extra-memory-pool.h index e9a6149b61..d07f21bbeb 100644 --- a/runtime-common/core/memory-resource/extra-memory-pool.h +++ b/runtime-common/core/memory-resource/extra-memory-pool.h @@ -15,32 +15,22 @@ namespace memory_resource { class alignas(8) extra_memory_pool : vk::not_copyable { public: - explicit extra_memory_pool(size_t buffer_size) : - buffer_size_(buffer_size) { - } + explicit extra_memory_pool(size_t buffer_size) : buffer_size_(buffer_size) {} - uint8_t *memory_begin() { - return reinterpret_cast(this + 1); - } + uint8_t* memory_begin() { return reinterpret_cast(this + 1); } - bool is_memory_from_this_pool(const void *mem, size_t mem_size) noexcept { - return reinterpret_cast(memory_begin()) <= reinterpret_cast(mem) - && reinterpret_cast(mem) + mem_size <= reinterpret_cast(memory_begin()) + get_pool_payload_size(); + bool is_memory_from_this_pool(const void* mem, size_t mem_size) noexcept { + return reinterpret_cast(memory_begin()) <= reinterpret_cast(mem) && + reinterpret_cast(mem) + mem_size <= reinterpret_cast(memory_begin()) + get_pool_payload_size(); } - static size_t get_pool_payload_size(size_t buffer_size) noexcept { - return buffer_size - sizeof(extra_memory_pool); - } + static size_t get_pool_payload_size(size_t buffer_size) noexcept { return buffer_size - sizeof(extra_memory_pool); } - size_t get_pool_payload_size() const noexcept { - return get_pool_payload_size(buffer_size_); - } + size_t get_pool_payload_size() const noexcept { return get_pool_payload_size(buffer_size_); } - size_t get_buffer_size() const noexcept { - return buffer_size_; - } + size_t get_buffer_size() const noexcept { return buffer_size_; } - extra_memory_pool *next_in_chain{nullptr}; + extra_memory_pool* next_in_chain{nullptr}; private: const size_t buffer_size_{0}; @@ -48,23 +38,21 @@ class alignas(8) extra_memory_pool : vk::not_copyable { class extra_memory_raw_bucket : vk::not_copyable { public: - void init(uint8_t *raw_memory, size_t buffers_count, size_t buffer_size) noexcept { + void init(uint8_t* raw_memory, size_t buffers_count, size_t buffer_size) noexcept { raw_memory_ = raw_memory; buffers_count_ = buffers_count; buffer_size_ = buffer_size; } - size_t buffers_count() const noexcept { - return buffers_count_; - } + size_t buffers_count() const noexcept { return buffers_count_; } - void *get_extra_pool_raw(size_t index) const noexcept { + void* get_extra_pool_raw(size_t index) const noexcept { assert(index < buffers_count_); return raw_memory_ + index * buffer_size_; } private: - uint8_t *raw_memory_{nullptr}; + uint8_t* raw_memory_{nullptr}; size_t buffers_count_{0}; size_t buffer_size_{0}; }; diff --git a/runtime-common/core/memory-resource/memory_resource.h b/runtime-common/core/memory-resource/memory_resource.h index f17d65e4c8..10243290ad 100644 --- a/runtime-common/core/memory-resource/memory_resource.h +++ b/runtime-common/core/memory-resource/memory_resource.h @@ -11,9 +11,9 @@ // #define DEBUG_MEMORY -inline void memory_debug(const char *format, ...) __attribute__ ((format (printf, 1, 2))); +inline void memory_debug(const char* format, ...) __attribute__((format(printf, 1, 2))); -inline void memory_debug(const char *format, ...) { +inline void memory_debug(const char* format, ...) { (void)format; #ifdef DEBUG_MEMORY va_list argptr; @@ -25,26 +25,24 @@ inline void memory_debug(const char *format, ...) { namespace memory_resource { -constexpr size_t memory_buffer_limit() noexcept { - return std::numeric_limits::max(); -} +constexpr size_t memory_buffer_limit() noexcept { return std::numeric_limits::max(); } class MemoryStats { public: size_t real_memory_used{0}; // currently used and dirty memory - size_t memory_used{0}; // currently used memory + size_t memory_used{0}; // currently used memory size_t max_real_memory_used{0}; // maximum used and dirty memory - size_t max_memory_used{0}; // maximum used memory + size_t max_memory_used{0}; // maximum used memory size_t memory_limit{0}; // size of memory arena size_t defragmentation_calls{0}; // the number of defragmentation process calls - size_t huge_memory_pieces{0}; // the number of huge memory pirces (in rb tree) + size_t huge_memory_pieces{0}; // the number of huge memory pirces (in rb tree) size_t small_memory_pieces{0}; // the number of small memory pieces (in lists) - size_t total_allocations{0}; // the total number of allocations + size_t total_allocations{0}; // the total number of allocations size_t total_memory_allocated{0}; // the total amount of the memory allocated (doesn't take the freed memory into the account) }; diff --git a/runtime-common/core/memory-resource/monotonic_buffer_resource.cpp b/runtime-common/core/memory-resource/monotonic_buffer_resource.cpp index 7a6792a171..a98263ab21 100644 --- a/runtime-common/core/memory-resource/monotonic_buffer_resource.cpp +++ b/runtime-common/core/memory-resource/monotonic_buffer_resource.cpp @@ -6,9 +6,9 @@ namespace memory_resource { -void monotonic_buffer::init(void *buffer, size_t buffer_size) noexcept { +void monotonic_buffer::init(void* buffer, size_t buffer_size) noexcept { php_assert(buffer_size <= memory_buffer_limit()); - memory_begin_ = static_cast(buffer); + memory_begin_ = static_cast(buffer); memory_current_ = memory_begin_; memory_end_ = memory_begin_ + buffer_size; diff --git a/runtime-common/core/memory-resource/monotonic_buffer_resource.h b/runtime-common/core/memory-resource/monotonic_buffer_resource.h index fb4f2b3089..132e6bfc30 100644 --- a/runtime-common/core/memory-resource/monotonic_buffer_resource.h +++ b/runtime-common/core/memory-resource/monotonic_buffer_resource.h @@ -18,14 +18,14 @@ namespace memory_resource { class monotonic_buffer : vk::not_copyable { protected: - void init(void *buffer, size_t buffer_size) noexcept; + void init(void* buffer, size_t buffer_size) noexcept; size_t size() const noexcept { return static_cast(memory_end_ - memory_current_); } - void *memory_begin() const noexcept { return memory_begin_; } - void *memory_current() const noexcept { return memory_current_; } - const MemoryStats &get_memory_stats() const noexcept { return stats_; } + void* memory_begin() const noexcept { return memory_begin_; } + void* memory_current() const noexcept { return memory_current_; } + const MemoryStats& get_memory_stats() const noexcept { return stats_; } - void register_allocation(void *mem, size_t size) noexcept { + void register_allocation(void* mem, size_t size) noexcept { if (mem) { stats_.memory_used += size; stats_.max_memory_used = std::max(stats_.max_memory_used, stats_.memory_used); @@ -41,44 +41,39 @@ class monotonic_buffer : vk::not_copyable { stats_.real_memory_used = static_cast(memory_current_ - memory_begin_); } - bool check_memory_piece_was_used(void *mem, size_t size) const noexcept { - return memory_begin_ <= static_cast(mem) && static_cast(mem) + size <= memory_current_; + bool check_memory_piece_was_used(void* mem, size_t size) const noexcept { + return memory_begin_ <= static_cast(mem) && static_cast(mem) + size <= memory_current_; } MemoryStats stats_; static_assert(sizeof(char) == 1, "sizeof char should be 1"); - char *memory_current_{nullptr}; - char *memory_begin_{nullptr}; - char *memory_end_{nullptr}; + char* memory_current_{nullptr}; + char* memory_begin_{nullptr}; + char* memory_end_{nullptr}; }; - class monotonic_buffer_resource : protected monotonic_buffer { public: - using monotonic_buffer::init; using monotonic_buffer::get_memory_stats; - using monotonic_buffer::size; + using monotonic_buffer::init; using monotonic_buffer::memory_begin; using monotonic_buffer::memory_current; + using monotonic_buffer::size; - void *allocate(size_t size) noexcept { - void *mem = get_from_pool(size); + void* allocate(size_t size) noexcept { + void* mem = get_from_pool(size); memory_debug("allocate %zu, allocated address from pool %p\n", size, mem); register_allocation(mem, size); return mem; } - void *allocate0(size_t size) noexcept { - return memset(allocate(size), 0x00, size); - } + void* allocate0(size_t size) noexcept { return memset(allocate(size), 0x00, size); } - void *reallocate(void *mem, size_t new_size, size_t old_size) noexcept { - return details::universal_reallocate(*this, mem, new_size, old_size); - } + void* reallocate(void* mem, size_t new_size, size_t old_size) noexcept { return details::universal_reallocate(*this, mem, new_size, old_size); } - void *try_expand(void *mem, size_t new_size, size_t old_size) noexcept { - if (static_cast(mem) + old_size == memory_current_) { + void* try_expand(void* mem, size_t new_size, size_t old_size) noexcept { + if (static_cast(mem) + old_size == memory_current_) { const auto additional_size = old_size - new_size; if (static_cast(memory_end_ - memory_current_) >= additional_size) { memory_current_ += additional_size; @@ -89,26 +84,26 @@ class monotonic_buffer_resource : protected monotonic_buffer { return nullptr; } - void deallocate(void *mem, size_t size) noexcept { + void deallocate(void* mem, size_t size) noexcept { memory_debug("deallocate %zu at %p\n", size, mem); if (put_memory_back(mem, size)) { register_deallocation(size); } } - bool put_memory_back(void *mem, size_t size) noexcept { + bool put_memory_back(void* mem, size_t size) noexcept { if (unlikely(!check_memory_piece_was_used(mem, size))) { critical_dump(mem, size); } - const bool expandable = static_cast(mem) + size == memory_current_; + const bool expandable = static_cast(mem) + size == memory_current_; if (expandable) { - memory_current_ = static_cast(mem); + memory_current_ = static_cast(mem); } return expandable; } - void *get_from_pool(size_t size, bool safe = false) noexcept { + void* get_from_pool(size_t size, bool safe = false) noexcept { if (unlikely(static_cast(memory_end_ - memory_current_) < size)) { if (unlikely(!safe)) { raise_oom(size); @@ -116,13 +111,13 @@ class monotonic_buffer_resource : protected monotonic_buffer { return nullptr; } - void *mem = memory_current_; + void* mem = memory_current_; memory_current_ += size; return mem; } protected: - void critical_dump(void *mem, size_t size) const noexcept; + void critical_dump(void* mem, size_t size) const noexcept; // this function should never be called from the nested/base context, // since all allocators have their own mem stats; // when signaling OOM, we want to see the root mem stats, not the diff --git a/runtime-common/core/memory-resource/resource_allocator.h b/runtime-common/core/memory-resource/resource_allocator.h index dbde3dec99..2d29318f36 100644 --- a/runtime-common/core/memory-resource/resource_allocator.h +++ b/runtime-common/core/memory-resource/resource_allocator.h @@ -18,77 +18,71 @@ namespace memory_resource { -template +template class resource_allocator { public: using value_type = T; - template + template friend class resource_allocator; - explicit resource_allocator(MemoryResource &memory_resource) noexcept - : memory_resource_(memory_resource) {} + explicit resource_allocator(MemoryResource& memory_resource) noexcept : memory_resource_(memory_resource) {} - template - explicit resource_allocator(const resource_allocator &other) noexcept - : memory_resource_(other.memory_resource_) {} + template + explicit resource_allocator(const resource_allocator& other) noexcept : memory_resource_(other.memory_resource_) {} - value_type *allocate(size_t size, [[maybe_unused]] void const *ptr = nullptr) { + value_type* allocate(size_t size, [[maybe_unused]] void const* ptr = nullptr) { static_assert(sizeof(value_type) <= max_value_type_size(), "memory limit"); - auto result = static_cast(memory_resource_.allocate(sizeof(value_type) * size)); + auto result = static_cast(memory_resource_.allocate(sizeof(value_type) * size)); if (unlikely(!result)) { php_critical_error("not enough memory to continue"); } return result; } - void deallocate(value_type *mem, size_t size) { + void deallocate(value_type* mem, size_t size) { static_assert(sizeof(value_type) <= max_value_type_size(), "memory limit"); memory_resource_.deallocate(mem, sizeof(value_type) * size); } - static constexpr size_t max_value_type_size() { - return 128U; - } + static constexpr size_t max_value_type_size() { return 128U; } - friend inline bool operator==(const resource_allocator &lhs, const resource_allocator &rhs) noexcept { + friend inline bool operator==(const resource_allocator& lhs, const resource_allocator& rhs) noexcept { return &lhs.memory_resource_ == &rhs.memory_resource_; } - friend inline bool operator!=(const resource_allocator &lhs, const resource_allocator &rhs) noexcept { - return !(lhs == rhs); - } + friend inline bool operator!=(const resource_allocator& lhs, const resource_allocator& rhs) noexcept { return !(lhs == rhs); } private: - MemoryResource &memory_resource_; + MemoryResource& memory_resource_; }; namespace stl { -template, class KeyEqual = std::equal_to> +template , class KeyEqual = std::equal_to> using unordered_map = std::unordered_map, Resource>>; -template, class KeyEqual = std::equal_to> +template , class KeyEqual = std::equal_to> using unordered_set = std::unordered_set>; -template> +template > using map = std::map, Resource>>; -template> +template > using multimap = std::multimap, Resource>>; -template +template using deque = std::deque>; -template +template using queue = std::queue>>; -template +template using vector = std::vector>; -template +template using list = std::list>; -template +template using string = std::basic_string, resource_allocator>; } // namespace stl diff --git a/runtime-common/core/memory-resource/unsynchronized_pool_resource.cpp b/runtime-common/core/memory-resource/unsynchronized_pool_resource.cpp index 100f4b5e25..cbfc07951c 100644 --- a/runtime-common/core/memory-resource/unsynchronized_pool_resource.cpp +++ b/runtime-common/core/memory-resource/unsynchronized_pool_resource.cpp @@ -12,7 +12,7 @@ namespace memory_resource { constexpr size_t unsynchronized_pool_resource::MAX_CHUNK_BLOCK_SIZE_; -void unsynchronized_pool_resource::init(void *buffer, size_t buffer_size, size_t oom_handling_buffer_size) noexcept { +void unsynchronized_pool_resource::init(void* buffer, size_t buffer_size, size_t oom_handling_buffer_size) noexcept { monotonic_buffer_resource::init(buffer, buffer_size); huge_pieces_.hard_reset(); @@ -48,15 +48,15 @@ void unsynchronized_pool_resource::perform_defragmentation() noexcept { php_assert(free_chunks_[0].get_mem() == nullptr); for (size_t chunk_id = 1; chunk_id < free_chunks_.size(); ++chunk_id) { const size_t chunk_size = details::get_chunk_size(chunk_id); - for (void *slot_mem = free_chunks_[chunk_id].get_mem(); slot_mem; slot_mem = free_chunks_[chunk_id].get_mem()) { + for (void* slot_mem = free_chunks_[chunk_id].get_mem(); slot_mem; slot_mem = free_chunks_[chunk_id].get_mem()) { mem_list.add_memory(slot_mem, chunk_size); } } stats_.small_memory_pieces = 0; stats_.huge_memory_pieces = 0; - for (auto *free_mem = mem_list.flush(); free_mem;) { - auto *next_mem = mem_list.get_next(free_mem); + for (auto* free_mem = mem_list.flush(); free_mem;) { + auto* next_mem = mem_list.get_next(free_mem); put_memory_back(free_mem, free_mem->size()); free_mem = next_mem; } @@ -66,13 +66,13 @@ void unsynchronized_pool_resource::perform_defragmentation() noexcept { ++stats_.defragmentation_calls; } -void *unsynchronized_pool_resource::allocate_small_piece_from_fallback_resource(size_t aligned_size) noexcept { - void *mem = fallback_resource_.get_from_pool(aligned_size, true); +void* unsynchronized_pool_resource::allocate_small_piece_from_fallback_resource(size_t aligned_size) noexcept { + void* mem = fallback_resource_.get_from_pool(aligned_size, true); if (likely(mem != nullptr)) { memory_debug("allocate %zu, pool was empty, allocated address from fallback resource %p\n", aligned_size, mem); return mem; } - details::memory_chunk_tree::tree_node *smallest_huge_piece = huge_pieces_.extract_smallest(); + details::memory_chunk_tree::tree_node* smallest_huge_piece = huge_pieces_.extract_smallest(); if (!smallest_huge_piece) { perform_defragmentation(); if (mem = try_allocate_small_piece(aligned_size); mem != nullptr) { @@ -99,14 +99,14 @@ void *unsynchronized_pool_resource::allocate_small_piece_from_fallback_resource( return mem; } -void *unsynchronized_pool_resource::perform_defragmentation_and_allocate_huge_piece(size_t aligned_size) noexcept { +void* unsynchronized_pool_resource::perform_defragmentation_and_allocate_huge_piece(size_t aligned_size) noexcept { // the body of this function is moved to the cpp file intentionally, so it doesn't get inlined into the allocate method perform_defragmentation(); return allocate_huge_piece(aligned_size, false); } -bool unsynchronized_pool_resource::is_memory_from_extra_pool(void *mem, size_t size) const noexcept { - auto *extra_pool = extra_memory_head_; +bool unsynchronized_pool_resource::is_memory_from_extra_pool(void* mem, size_t size) const noexcept { + auto* extra_pool = extra_memory_head_; do { if (extra_pool->is_memory_from_this_pool(mem, size)) { return true; diff --git a/runtime-common/core/memory-resource/unsynchronized_pool_resource.h b/runtime-common/core/memory-resource/unsynchronized_pool_resource.h index b958c85fb3..a4bf2d0a0c 100644 --- a/runtime-common/core/memory-resource/unsynchronized_pool_resource.h +++ b/runtime-common/core/memory-resource/unsynchronized_pool_resource.h @@ -7,10 +7,10 @@ #include #include -#include "runtime-common/core/memory-resource/extra-memory-pool.h" #include "runtime-common/core/memory-resource/details/memory_chunk_list.h" #include "runtime-common/core/memory-resource/details/memory_chunk_tree.h" #include "runtime-common/core/memory-resource/details/universal_reallocate.h" +#include "runtime-common/core/memory-resource/extra-memory-pool.h" #include "runtime-common/core/memory-resource/monotonic_buffer_resource.h" #include "runtime-common/core/memory-resource/resource_allocator.h" #include "runtime-common/core/utils/kphp-assert-core.h" @@ -19,16 +19,16 @@ namespace memory_resource { class unsynchronized_pool_resource : private monotonic_buffer_resource { public: - using monotonic_buffer_resource::try_expand; using monotonic_buffer_resource::get_memory_stats; using monotonic_buffer_resource::memory_begin; + using monotonic_buffer_resource::try_expand; - void init(void *buffer, size_t buffer_size, size_t oom_handling_buffer_size = 0) noexcept; + void init(void* buffer, size_t buffer_size, size_t oom_handling_buffer_size = 0) noexcept; void hard_reset() noexcept; void unfreeze_oom_handling_memory() noexcept; - void *allocate(size_t size) noexcept { - void *mem = nullptr; + void* allocate(size_t size) noexcept { + void* mem = nullptr; const auto aligned_size = details::align_for_chunk(size); if (aligned_size < MAX_CHUNK_BLOCK_SIZE_) { mem = try_allocate_small_piece(aligned_size); @@ -46,21 +46,21 @@ class unsynchronized_pool_resource : private monotonic_buffer_resource { return mem; } - void *allocate0(size_t size) noexcept { - auto *mem = allocate(size); + void* allocate0(size_t size) noexcept { + auto* mem = allocate(size); if (likely(mem != nullptr)) { memset(mem, 0x00, size); } return mem; } - void *reallocate(void *mem, size_t new_size, size_t old_size) noexcept { + void* reallocate(void* mem, size_t new_size, size_t old_size) noexcept { const auto aligned_old_size = details::align_for_chunk(old_size); const auto aligned_new_size = details::align_for_chunk(new_size); return details::universal_reallocate(*this, mem, aligned_new_size, aligned_old_size); } - void deallocate(void *mem, size_t size) noexcept { + void deallocate(void* mem, size_t size) noexcept { memory_debug("deallocate %zu at %p\n", size, mem); const auto aligned_size = details::align_for_chunk(size); put_memory_back(mem, aligned_size); @@ -75,20 +75,18 @@ class unsynchronized_pool_resource : private monotonic_buffer_resource { return static_cast(memory_end_ - memory_current_) >= aligned_size || huge_pieces_.has_memory_for(aligned_size); } - extra_memory_pool *get_extra_memory_head() noexcept { - return extra_memory_head_; - } + extra_memory_pool* get_extra_memory_head() noexcept { return extra_memory_head_; } - void add_extra_memory(extra_memory_pool *extra_memory) noexcept { + void add_extra_memory(extra_memory_pool* extra_memory) noexcept { extra_memory->next_in_chain = extra_memory_head_; extra_memory_head_ = extra_memory; put_memory_back(extra_memory->memory_begin(), extra_memory->get_pool_payload_size()); } private: - void *try_allocate_small_piece(size_t aligned_size) noexcept { + void* try_allocate_small_piece(size_t aligned_size) noexcept { const auto chunk_id = details::get_chunk_id(aligned_size); - auto *mem = free_chunks_[chunk_id].get_mem(); + auto* mem = free_chunks_[chunk_id].get_mem(); if (mem) { --stats_.small_memory_pieces; memory_debug("allocate %zu, chunk found, allocated address %p\n", aligned_size, mem); @@ -99,14 +97,14 @@ class unsynchronized_pool_resource : private monotonic_buffer_resource { return mem; } - void *allocate_huge_piece(size_t aligned_size, bool safe) noexcept { - void *mem = nullptr; - if (details::memory_chunk_tree::tree_node *piece = huge_pieces_.extract(aligned_size)) { + void* allocate_huge_piece(size_t aligned_size, bool safe) noexcept { + void* mem = nullptr; + if (details::memory_chunk_tree::tree_node* piece = huge_pieces_.extract(aligned_size)) { --stats_.huge_memory_pieces; const size_t real_size = details::memory_chunk_tree::get_chunk_size(piece); mem = piece; if (const size_t left = real_size - aligned_size) { - put_memory_back(static_cast(mem) + aligned_size, left); + put_memory_back(static_cast(mem) + aligned_size, left); } memory_debug("allocate %zu, huge chunk (%zu) found, allocated address %p\n", aligned_size, real_size, mem); return piece; @@ -116,11 +114,11 @@ class unsynchronized_pool_resource : private monotonic_buffer_resource { return mem; } - void *allocate_small_piece_from_fallback_resource(size_t aligned_size) noexcept; - void *perform_defragmentation_and_allocate_huge_piece(size_t aligned_size) noexcept; - bool is_memory_from_extra_pool(void *mem, size_t size) const noexcept; + void* allocate_small_piece_from_fallback_resource(size_t aligned_size) noexcept; + void* perform_defragmentation_and_allocate_huge_piece(size_t aligned_size) noexcept; + bool is_memory_from_extra_pool(void* mem, size_t size) const noexcept; - void put_memory_back(void *mem, size_t size) noexcept { + void put_memory_back(void* mem, size_t size) noexcept { const bool from_extra_pool = (extra_memory_head_ != &extra_memory_tail_) && is_memory_from_extra_pool(mem, size); if (from_extra_pool || !monotonic_buffer_resource::put_memory_back(mem, size)) { if (size < MAX_CHUNK_BLOCK_SIZE_) { @@ -138,7 +136,7 @@ class unsynchronized_pool_resource : private monotonic_buffer_resource { monotonic_buffer_resource fallback_resource_; size_t oom_handling_memory_size_{0}; - extra_memory_pool *extra_memory_head_{nullptr}; + extra_memory_pool* extra_memory_head_{nullptr}; extra_memory_pool extra_memory_tail_{sizeof(extra_memory_pool)}; static constexpr size_t MAX_CHUNK_BLOCK_SIZE_{static_cast(16U * 1024U)}; diff --git a/runtime-common/core/runtime-core.h b/runtime-common/core/runtime-core.h index 08c0401bbb..625bfb88bd 100644 --- a/runtime-common/core/runtime-core.h +++ b/runtime-common/core/runtime-core.h @@ -18,165 +18,250 @@ #include "common/sanitizer.h" #include "common/type_traits/list_of_types.h" -#include "runtime-common/core/include.h" -#include "runtime-common/core/core-types/kphp_type_traits.h" #include "runtime-common/core/core-types/decl/shape.h" +#include "runtime-common/core/core-types/kphp_type_traits.h" +#include "runtime-common/core/include.h" // order of includes below matters, be careful #define INCLUDED_FROM_KPHP_CORE #include "runtime-common/core/array_access.h" -#include "runtime-common/core/core-types/decl/string_decl.inl" -#include "runtime-common/core/core-types/decl/array_decl.inl" #include "runtime-common/core/class-instance/class-instance-decl.inl" +#include "runtime-common/core/core-types/decl/array_decl.inl" #include "runtime-common/core/core-types/decl/mixed_decl.inl" #include "runtime-common/core/core-types/decl/string_buffer_decl.inl" +#include "runtime-common/core/core-types/decl/string_decl.inl" #include "runtime-common/core/allocator/runtime-allocator.h" #include "runtime-common/core/core-context.h" -#include "runtime-common/core/core-types/definition/string.inl" -#include "runtime-common/core/core-types/definition/array.inl" #include "runtime-common/core/class-instance/class-instance.inl" +#include "runtime-common/core/core-types/comparison_operators.inl" +#include "runtime-common/core/core-types/conversions_types.inl" +#include "runtime-common/core/core-types/definition/array.inl" #include "runtime-common/core/core-types/definition/mixed.inl" +#include "runtime-common/core/core-types/definition/string.inl" #include "runtime-common/core/core-types/definition/string_buffer.inl" -#include "runtime-common/core/core-types/conversions_types.inl" -#include "runtime-common/core/core-types/comparison_operators.inl" #undef INCLUDED_FROM_KPHP_CORE -#define FFI_CALL(call) ({ dl::CriticalSectionGuard critical_section___; (call); }) -#define FFI_INVOKE_CALLBACK(call) ({ dl::NonCriticalSectionGuard non_critical_section___; (call); }) +#define FFI_CALL(call) \ + ({ \ + dl::CriticalSectionGuard critical_section___; \ + (call); \ + }) +#define FFI_INVOKE_CALLBACK(call) \ + ({ \ + dl::NonCriticalSectionGuard non_critical_section___; \ + (call); \ + }) #define SET_MIXED_BY_INDEX(mix, idx, val) mix.set_value_return(idx, val) -#define SAFE_SET_MIXED_BY_INDEX(mix, idx, val, val_type) ({ val_type val_tmp___ = val; mix.set_value_return(idx, std::move(val_tmp___)); }) -#define MIXED_GET_IF_ISSET(mix, idx) ({mixed res_tmp___{}; mixed mix_tmp___ = mix; auto idx_tmp___ = idx; if (mix_tmp___.isset(idx_tmp___)) {res_tmp___ = mix_tmp___.get_value(idx_tmp___);} res_tmp___;}) -#define MIXED_GET_IF_NOT_EMPTY(mix, idx) ({mixed res_tmp___{}; mixed mix_tmp___ = mix; auto idx_tmp___ = idx; if (mix_tmp___.isset(idx_tmp___)) {mixed for_get_tmp___ = mix_tmp___.get_value(idx_tmp___); if (!for_get_tmp___.empty()) { res_tmp___ = for_get_tmp___; } } res_tmp___; }) - -#define ARR_ACC_SET_RETURN(obj, idx, val, method) ({mixed val_tmp___ = val; method(obj, idx, val_tmp___); val_tmp___;}) // it's always safe -#define ARR_ACC_GET_IF_ISSET(obj, idx, check_method, get_method) ({mixed res_tmp___{}; auto obj_tmp___ = obj; mixed idx_tmp___ = idx; if (check_method(obj_tmp___, idx_tmp___)) {res_tmp___ = get_method(obj_tmp___, idx_tmp___);} res_tmp___;}) -#define ARR_ACC_GET_IF_NOT_EMPTY(obj, idx, check_method, get_method) ({mixed res_tmp___{}; auto obj_tmp___ = obj; mixed idx_tmp___ = idx; if (check_method(obj_tmp___, idx_tmp___)) {mixed for_get_tmp___ = get_method(obj_tmp___, idx_tmp___); if (!for_get_tmp___.empty()) { res_tmp___ = for_get_tmp___; } } res_tmp___; }) - -#define SAFE_SET_OP(a, op, b, b_type) ({b_type b_tmp___ = b; a op std::move(b_tmp___);}) -#define SAFE_SET_FUNC_OP(a, func, b, b_type) ({b_type b_tmp___ = b; func (a, b_tmp___);}) -#define SAFE_INDEX(a, b, b_type) a[({b_type b_tmp___ = b; b_tmp___;})] -#define SAFE_SET_VALUE(a, b, b_type, c, c_type) ({b_type b_tmp___ = b; c_type c_tmp___ = c; (a).set_value (b_tmp___, c_tmp___);}) -#define SAFE_PUSH_BACK(a, b, b_type) ({b_type b_tmp___ = b; a.push_back (b_tmp___);}) -#define SAFE_PUSH_BACK_RETURN(a, b, b_type) ({b_type b_tmp___ = b; a.push_back_return (b_tmp___);}) -#define NOERR(a, a_type) ({RuntimeContext::get().php_disable_warnings++; a_type a_tmp___ = a; RuntimeContext::get().php_disable_warnings--; a_tmp___;}) -#define NOERR_VOID(a) ({RuntimeContext::get().php_disable_warnings++; a; RuntimeContext::get().php_disable_warnings--;}) +#define SAFE_SET_MIXED_BY_INDEX(mix, idx, val, val_type) \ + ({ \ + val_type val_tmp___ = val; \ + mix.set_value_return(idx, std::move(val_tmp___)); \ + }) +#define MIXED_GET_IF_ISSET(mix, idx) \ + ({ \ + mixed res_tmp___{}; \ + mixed mix_tmp___ = mix; \ + auto idx_tmp___ = idx; \ + if (mix_tmp___.isset(idx_tmp___)) { \ + res_tmp___ = mix_tmp___.get_value(idx_tmp___); \ + } \ + res_tmp___; \ + }) +#define MIXED_GET_IF_NOT_EMPTY(mix, idx) \ + ({ \ + mixed res_tmp___{}; \ + mixed mix_tmp___ = mix; \ + auto idx_tmp___ = idx; \ + if (mix_tmp___.isset(idx_tmp___)) { \ + mixed for_get_tmp___ = mix_tmp___.get_value(idx_tmp___); \ + if (!for_get_tmp___.empty()) { \ + res_tmp___ = for_get_tmp___; \ + } \ + } \ + res_tmp___; \ + }) + +#define ARR_ACC_SET_RETURN(obj, idx, val, method) \ + ({ \ + mixed val_tmp___ = val; \ + method(obj, idx, val_tmp___); \ + val_tmp___; \ + }) // it's always safe +#define ARR_ACC_GET_IF_ISSET(obj, idx, check_method, get_method) \ + ({ \ + mixed res_tmp___{}; \ + auto obj_tmp___ = obj; \ + mixed idx_tmp___ = idx; \ + if (check_method(obj_tmp___, idx_tmp___)) { \ + res_tmp___ = get_method(obj_tmp___, idx_tmp___); \ + } \ + res_tmp___; \ + }) +#define ARR_ACC_GET_IF_NOT_EMPTY(obj, idx, check_method, get_method) \ + ({ \ + mixed res_tmp___{}; \ + auto obj_tmp___ = obj; \ + mixed idx_tmp___ = idx; \ + if (check_method(obj_tmp___, idx_tmp___)) { \ + mixed for_get_tmp___ = get_method(obj_tmp___, idx_tmp___); \ + if (!for_get_tmp___.empty()) { \ + res_tmp___ = for_get_tmp___; \ + } \ + } \ + res_tmp___; \ + }) + +#define SAFE_SET_OP(a, op, b, b_type) \ + ({ \ + b_type b_tmp___ = b; \ + a op std::move(b_tmp___); \ + }) +#define SAFE_SET_FUNC_OP(a, func, b, b_type) \ + ({ \ + b_type b_tmp___ = b; \ + func(a, b_tmp___); \ + }) +#define SAFE_INDEX(a, b, b_type) \ + a[({ \ + b_type b_tmp___ = b; \ + b_tmp___; \ + })] +#define SAFE_SET_VALUE(a, b, b_type, c, c_type) \ + ({ \ + b_type b_tmp___ = b; \ + c_type c_tmp___ = c; \ + (a).set_value(b_tmp___, c_tmp___); \ + }) +#define SAFE_PUSH_BACK(a, b, b_type) \ + ({ \ + b_type b_tmp___ = b; \ + a.push_back(b_tmp___); \ + }) +#define SAFE_PUSH_BACK_RETURN(a, b, b_type) \ + ({ \ + b_type b_tmp___ = b; \ + a.push_back_return(b_tmp___); \ + }) +#define NOERR(a, a_type) \ + ({ \ + RuntimeContext::get().php_disable_warnings++; \ + a_type a_tmp___ = a; \ + RuntimeContext::get().php_disable_warnings--; \ + a_tmp___; \ + }) +#define NOERR_VOID(a) \ + ({ \ + RuntimeContext::get().php_disable_warnings++; \ + a; \ + RuntimeContext::get().php_disable_warnings--; \ + }) #define f$likely likely #define f$unlikely unlikely -template -void hard_reset_var(T &var, Args &&... args) noexcept { - new(&var) T(std::forward(args)...); +template +void hard_reset_var(T& var, Args&&... args) noexcept { + new (&var) T(std::forward(args)...); } -inline constexpr int64_t operator "" _i64(unsigned long long int v) noexcept { - return static_cast(v); -} +inline constexpr int64_t operator"" _i64(unsigned long long int v) noexcept { return static_cast(v); } inline double divide(int64_t lhs, int64_t rhs); inline double divide(double lhs, int64_t rhs); -inline double divide(const string &lhs, int64_t rhs); - -inline double divide(const mixed &lhs, int64_t rhs); +inline double divide(const string& lhs, int64_t rhs); +inline double divide(const mixed& lhs, int64_t rhs); inline double divide(int64_t lhs, double rhs); inline double divide(double lhs, double rhs) ubsan_supp("float-divide-by-zero"); -inline double divide(const string &lhs, double rhs); - -inline double divide(const mixed &lhs, double rhs); - +inline double divide(const string& lhs, double rhs); -inline double divide(int64_t lhs, const string &rhs); +inline double divide(const mixed& lhs, double rhs); -inline double divide(double lhs, const string &rhs); +inline double divide(int64_t lhs, const string& rhs); -inline double divide(const string &lhs, const string &rhs); +inline double divide(double lhs, const string& rhs); -inline double divide(const mixed &lhs, const string &rhs); +inline double divide(const string& lhs, const string& rhs); +inline double divide(const mixed& lhs, const string& rhs); -inline double divide(int64_t lhs, const mixed &rhs); +inline double divide(int64_t lhs, const mixed& rhs); -inline double divide(double lhs, const mixed &rhs); +inline double divide(double lhs, const mixed& rhs); -inline double divide(const string &lhs, const mixed &rhs); - -inline double divide(const mixed &lhs, const mixed &rhs); +inline double divide(const string& lhs, const mixed& rhs); +inline double divide(const mixed& lhs, const mixed& rhs); inline double divide(bool lhs, bool rhs); -template -inline double divide(bool lhs, const T &rhs); - -template -inline double divide(const T &lhs, bool rhs); +template +inline double divide(bool lhs, const T& rhs); -template -inline double divide(bool lhs, const array &rhs); +template +inline double divide(const T& lhs, bool rhs); -template -inline double divide(const array &lhs, bool rhs); +template +inline double divide(bool lhs, const array& rhs); -template -inline double divide(bool lhs, const class_instance &rhs); +template +inline double divide(const array& lhs, bool rhs); -template -inline double divide(const class_instance &lhs, bool rhs); +template +inline double divide(bool lhs, const class_instance& rhs); +template +inline double divide(const class_instance& lhs, bool rhs); -template -inline double divide(const array &lhs, const T1 &rhs); +template +inline double divide(const array& lhs, const T1& rhs); -template -inline double divide(const T1 &lhs, const array &rhs); +template +inline double divide(const T1& lhs, const array& rhs); +template +inline double divide(const class_instance& lhs, const T1& rhs); -template -inline double divide(const class_instance &lhs, const T1 &rhs); +template +inline double divide(const T1& lhs, const class_instance& rhs); -template -inline double divide(const T1 &lhs, const class_instance &rhs); +template +inline double divide(const array& lhs, const array& rhs); +template +inline double divide(const class_instance& lhs, const class_instance& rhs); -template -inline double divide(const array &lhs, const array &rhs); +template +inline double divide(const array& lhs, const array& rhs); -template -inline double divide(const class_instance &lhs, const class_instance &rhs); +template +inline double divide(const class_instance& lhs, const class_instance& rhs); -template -inline double divide(const array &lhs, const array &rhs); +template +inline double divide(const array& lhs, const class_instance& rhs); -template -inline double divide(const class_instance &lhs, const class_instance &rhs); +template +inline double divide(const class_instance& lhs, const array& rhs); -template -inline double divide(const array &lhs, const class_instance &rhs); +template +inline double divide(const Optional& lhs, const T2& rhs); // not defined -template -inline double divide(const class_instance &lhs, const array &rhs); +template +inline double divide(const T1& lhs, const Optional& rhs); // not defined - -template -inline double divide(const Optional &lhs, const T2 &rhs); //not defined - -template -inline double divide(const T1 &lhs, const Optional &rhs); //not defined - -template -inline int64_t spaceship(const T1 &lhs, const T2 &rhs) { +template +inline int64_t spaceship(const T1& lhs, const T2& rhs) { if (lt(lhs, rhs)) { return -1; } @@ -185,8 +270,8 @@ inline int64_t spaceship(const T1 &lhs, const T2 &rhs) { inline int64_t modulo(int64_t lhs, int64_t rhs); -template -inline int64_t modulo(const T1 &lhs, const T2 &rhs); +template +inline int64_t modulo(const T1& lhs, const T2& rhs); inline int64_t int_power(int64_t base, int64_t exp) { int64_t res = 1; @@ -200,11 +285,9 @@ inline int64_t int_power(int64_t base, int64_t exp) { return res; } -inline double float_power(double base, int64_t exp) { - return std::pow(base, exp); -} +inline double float_power(double base, int64_t exp) { return std::pow(base, exp); } -inline mixed var_power(const mixed &base, const mixed &exp) { +inline mixed var_power(const mixed& base, const mixed& exp) { if (base.is_int() && exp.is_int() && exp.to_int() >= 0) { return int_power(base.to_int(), exp.to_int()); } @@ -226,249 +309,225 @@ inline mixed var_power(const mixed &base, const mixed &exp) { return std::pow(float_base, float_exp); } -inline int64_t &power_self(int64_t &base, int64_t exp) { - return base = int_power(base, exp); -} - -inline double &power_self(double &base, int64_t exp) { - return base = float_power(base, exp); -} - -inline mixed &power_self(mixed &base, const mixed &exp) { - return base = var_power(base, exp); -} - -template -inline T1 ÷_self(T1 &lhs, const T2 &rhs); - +inline int64_t& power_self(int64_t& base, int64_t exp) { return base = int_power(base, exp); } -inline int64_t &modulo_self(int64_t &lhs, int64_t rhs); +inline double& power_self(double& base, int64_t exp) { return base = float_power(base, exp); } -template -inline T1 &modulo_self(T1 &lhs, const T2 &rhs); +inline mixed& power_self(mixed& base, const mixed& exp) { return base = var_power(base, exp); } +template +inline T1& divide_self(T1& lhs, const T2& rhs); -template -inline void assign(T0 &dest, const T &from); +inline int64_t& modulo_self(int64_t& lhs, int64_t rhs); +template +inline T1& modulo_self(T1& lhs, const T2& rhs); -inline bool &boolval_ref(bool &val); +template +inline void assign(T0& dest, const T& from); -inline bool &boolval_ref(mixed &val); +inline bool& boolval_ref(bool& val); -inline const bool &boolval_ref(const bool &val); +inline bool& boolval_ref(mixed& val); -inline const bool &boolval_ref(const mixed &val); +inline const bool& boolval_ref(const bool& val); +inline const bool& boolval_ref(const mixed& val); -inline int64_t &intval_ref(int64_t &val, const char *function); +inline int64_t& intval_ref(int64_t& val, const char* function); -inline int64_t &intval_ref(mixed &val, const char *function); +inline int64_t& intval_ref(mixed& val, const char* function); -inline const int64_t &intval_ref(const int64_t &val, const char *function); +inline const int64_t& intval_ref(const int64_t& val, const char* function); -inline const int64_t &intval_ref(const mixed &val, const char *function); +inline const int64_t& intval_ref(const mixed& val, const char* function); +inline double& floatval_ref(double& val); -inline double &floatval_ref(double &val); +inline double& floatval_ref(mixed& val); -inline double &floatval_ref(mixed &val); +inline const double& floatval_ref(const double& val); -inline const double &floatval_ref(const double &val); +inline const double& floatval_ref(const mixed& val); -inline const double &floatval_ref(const mixed &val); +inline string& strval_ref(string& val, const char* function); +inline string& strval_ref(mixed& val, const char* function); -inline string &strval_ref(string &val, const char *function); +inline const string& strval_ref(const string& val, const char* function); -inline string &strval_ref(mixed &val, const char *function); +inline const string& strval_ref(const mixed& val, const char* function); -inline const string &strval_ref(const string &val, const char *function); +template +inline array& arrayval_ref(array& val, const char* function); -inline const string &strval_ref(const mixed &val, const char *function); +inline array& arrayval_ref(mixed& val, const char* function); +template +inline array& arrayval_ref(Optional>& val, const char* function); -template -inline array &arrayval_ref(array &val, const char *function); +template +inline const array& arrayval_ref(const array& val, const char* function); -inline array &arrayval_ref(mixed &val, const char *function); +inline const array& arrayval_ref(const mixed& val, const char* function); -template -inline array &arrayval_ref(Optional> &val, const char *function); +template +inline const array& arrayval_ref(const Optional>& val, const char* function); -template -inline const array &arrayval_ref(const array &val, const char *function); +template > +inline bool f$empty(const T& v); +inline bool f$empty(const string& v); +inline bool f$empty(const mixed& v); +template +inline bool f$empty(const array&); +template +inline bool f$empty(const class_instance&); +template +inline bool f$empty(const Optional&); -inline const array &arrayval_ref(const mixed &val, const char *function); +template +bool f$is_numeric(const T&); +template +inline bool f$is_numeric(const Optional& v); +inline bool f$is_numeric(const string& v); +inline bool f$is_numeric(const mixed& v); -template -inline const array &arrayval_ref(const Optional> &val, const char *function); +template +inline bool f$is_bool(const T& v); +template +inline bool f$is_bool(const Optional& v); +inline bool f$is_bool(const mixed& v); -template> -inline bool f$empty(const T &v); -inline bool f$empty(const string &v); -inline bool f$empty(const mixed &v); -template -inline bool f$empty(const array &); -template -inline bool f$empty(const class_instance &); -template -inline bool f$empty(const Optional &); +template +inline bool f$is_int(const T&); +template +inline bool f$is_int(const Optional& v); +inline bool f$is_int(const mixed& v); +template +inline bool f$is_float(const T& v); +template +inline bool f$is_float(const Optional& v); +inline bool f$is_float(const mixed& v); -template -bool f$is_numeric(const T &); -template -inline bool f$is_numeric(const Optional &v); -inline bool f$is_numeric(const string &v); -inline bool f$is_numeric(const mixed &v); +template +inline bool f$is_scalar(const T& v); +template +inline bool f$is_scalar(const Optional& v); +inline bool f$is_scalar(const mixed& v); -template -inline bool f$is_bool(const T &v); -template -inline bool f$is_bool(const Optional &v); -inline bool f$is_bool(const mixed &v); +template +inline bool f$is_string(const T& v); +template +inline bool f$is_string(const Optional& v); +inline bool f$is_string(const mixed& v); -template -inline bool f$is_int(const T &); -template -inline bool f$is_int(const Optional &v); -inline bool f$is_int(const mixed &v); +template +inline bool f$is_array(const T& v); +template +inline bool f$is_array(const Optional& v); +inline bool f$is_array(const mixed& v); -template -inline bool f$is_float(const T &v); -template -inline bool f$is_float(const Optional &v); -inline bool f$is_float(const mixed &v); +template +bool f$is_object(const T&); +template +inline bool f$is_object(const class_instance& v); +template +inline bool f$is_integer(const T& v); -template -inline bool f$is_scalar(const T &v); -template -inline bool f$is_scalar(const Optional &v); -inline bool f$is_scalar(const mixed &v); +template +inline bool f$is_long(const T& v); +template +inline bool f$is_double(const T& v); -template -inline bool f$is_string(const T &v); -template -inline bool f$is_string(const Optional &v); -inline bool f$is_string(const mixed &v); +template +inline bool f$is_real(const T& v); - -template -inline bool f$is_array(const T &v); -template -inline bool f$is_array(const Optional &v); -inline bool f$is_array(const mixed &v); - - -template -bool f$is_object(const T &); -template -inline bool f$is_object(const class_instance &v); - - -template -inline bool f$is_integer(const T &v); - -template -inline bool f$is_long(const T &v); - -template -inline bool f$is_double(const T &v); - -template -inline bool f$is_real(const T &v); - -template -inline bool f$is_a(const class_instance &base) { +template +inline bool f$is_a(const class_instance& base) { return base.template is_a(); } -template -inline bool f$is_a(const mixed &base) { +template +inline bool f$is_a(const mixed& base) { return base.is_a(); } -template -inline ClassInstanceDerived f$instance_cast(const class_instance &base, const string &) { +template +inline ClassInstanceDerived f$instance_cast(const class_instance& base, const string&) { return base.template cast_to(); } -template -inline ClassInstanceDerived f$instance_cast(const mixed &base, const string &s) { - return from_mixed(base, s); +template +inline ClassInstanceDerived f$instance_cast(const mixed& base, const string& s) { + return from_mixed(base, s); } -inline const char *get_type_c_str(bool); -inline const char *get_type_c_str(int64_t); -inline const char *get_type_c_str(double); -inline const char *get_type_c_str(const string &v); -inline const char *get_type_c_str(const mixed &v); -template -inline const char *get_type_c_str(const array &v); -template -inline const char *get_type_c_str(const class_instance &v); +inline const char* get_type_c_str(bool); +inline const char* get_type_c_str(int64_t); +inline const char* get_type_c_str(double); +inline const char* get_type_c_str(const string& v); +inline const char* get_type_c_str(const mixed& v); +template +inline const char* get_type_c_str(const array& v); +template +inline const char* get_type_c_str(const class_instance& v); -template -inline string f$get_type(const T &v); +template +inline string f$get_type(const T& v); inline string f$get_class(bool); inline string f$get_class(int64_t); inline string f$get_class(double); -inline string f$get_class(const string &v); -inline string f$get_class(const mixed &v); -template -inline string f$get_class(const array &v); -template -inline string f$get_class(const class_instance &v); - -template -inline int64_t f$get_hash_of_class(const class_instance &klass); - +inline string f$get_class(const string& v); +inline string f$get_class(const mixed& v); +template +inline string f$get_class(const array& v); +template +inline string f$get_class(const class_instance& v); -inline int64_t f$count(const mixed &v); +template +inline int64_t f$get_hash_of_class(const class_instance& klass); -template -inline int64_t f$count(const Optional &a); +inline int64_t f$count(const mixed& v); -template -inline int64_t f$count(const array &a); +template +inline int64_t f$count(const Optional& a); -template -inline int64_t f$count(const std::tuple &a); +template +inline int64_t f$count(const array& a); -template -inline int64_t f$count(const T &v); +template +inline int64_t f$count(const std::tuple& a); +template +inline int64_t f$count(const T& v); -template -int64_t f$sizeof(const T &v); +template +int64_t f$sizeof(const T& v); +inline string& append(string& dest, tmp_string from); +inline string& append(string& dest, const string& from); +inline string& append(string& dest, int64_t from); -inline string &append(string &dest, tmp_string from); -inline string &append(string &dest, const string &from); -inline string &append(string &dest, int64_t from); +template +inline string& append(Optional& dest, const T& from); -template -inline string &append(Optional &dest, const T &from); +template +inline string& append(string& dest, const T& from); -template -inline string &append(string &dest, const T &from); +template +inline mixed& append(mixed& dest, const T& from); -template -inline mixed &append(mixed &dest, const T &from); +template +inline T0& append(T0& dest, const T& from); -template -inline T0 &append(T0 &dest, const T &from); - - -inline string f$gettype(const mixed &v); - -template -inline bool f$function_exists(const T &a1); +inline string f$gettype(const mixed& v); +template +inline bool f$function_exists(const T& a1); constexpr int32_t E_ERROR = 1; constexpr int32_t E_WARNING = 2; @@ -489,106 +548,101 @@ constexpr int32_t E_ALL = 32767; inline mixed f$error_get_last(); -inline void f$warning(const string &message); - -#define f$critical_error(message) \ - php_critical_error("%s", message.c_str()); - -template -inline int64_t f$get_reference_counter(const array &v); - -template -inline int64_t f$get_reference_counter(const class_instance &v); +inline void f$warning(const string& message); -inline int64_t f$get_reference_counter(const string &v); +#define f$critical_error(message) php_critical_error("%s", message.c_str()); -inline int64_t f$get_reference_counter(const mixed &v); +template +inline int64_t f$get_reference_counter(const array& v); +template +inline int64_t f$get_reference_counter(const class_instance& v); -template -inline T &val(T &x); +inline int64_t f$get_reference_counter(const string& v); -template -inline const T &val(const T &x); +inline int64_t f$get_reference_counter(const mixed& v); -template -inline T &ref(T &x); +template +inline T& val(T& x); -template -inline const T &val(const Optional &x); +template +inline const T& val(const T& x); -template -inline T &val(Optional &x); +template +inline T& ref(T& x); -template -inline T &ref(Optional &x); +template +inline const T& val(const Optional& x); +template +inline T& val(Optional& x); -template -inline typename array::iterator begin(array &x); +template +inline T& ref(Optional& x); -template -inline typename array::const_iterator begin(const array &x); +template +inline typename array::iterator begin(array& x); -template -inline typename array::const_iterator const_begin(const array &x); +template +inline typename array::const_iterator begin(const array& x); -inline array::iterator begin(mixed &x); +template +inline typename array::const_iterator const_begin(const array& x); -inline array::const_iterator begin(const mixed &x); +inline array::iterator begin(mixed& x); -inline array::const_iterator const_begin(const mixed &x); +inline array::const_iterator begin(const mixed& x); -template -inline typename array::iterator begin(Optional> &x); +inline array::const_iterator const_begin(const mixed& x); -template -inline typename array::const_iterator begin(const Optional> &x); +template +inline typename array::iterator begin(Optional>& x); -template -inline typename array::const_iterator const_begin(const Optional> &x); +template +inline typename array::const_iterator begin(const Optional>& x); -template -inline typename array::iterator end(array &x); +template +inline typename array::const_iterator const_begin(const Optional>& x); -template -inline typename array::const_iterator end(const array &x); +template +inline typename array::iterator end(array& x); -template -inline typename array::const_iterator const_end(const array &x); +template +inline typename array::const_iterator end(const array& x); -inline array::iterator end(mixed &x); +template +inline typename array::const_iterator const_end(const array& x); -inline array::const_iterator end(const mixed &x); +inline array::iterator end(mixed& x); -inline array::const_iterator const_end(const mixed &x); +inline array::const_iterator end(const mixed& x); -template -inline typename array::iterator end(Optional> &x); +inline array::const_iterator const_end(const mixed& x); -template -inline typename array::const_iterator end(const Optional> &x); +template +inline typename array::iterator end(Optional>& x); -template -inline typename array::const_iterator const_end(const Optional> &x); +template +inline typename array::const_iterator end(const Optional>& x); +template +inline typename array::const_iterator const_end(const Optional>& x); -inline void clear_array(mixed &v); +inline void clear_array(mixed& v); -template -inline void clear_array(array &a); +template +inline void clear_array(array& a); -template -inline void clear_array(Optional> &a); +template +inline void clear_array(Optional>& a); -template -inline void unset(array &x); +template +inline void unset(array& x); -template -inline void unset(class_instance &x); - -inline void unset(mixed &x); +template +inline void unset(class_instance& x); +inline void unset(mixed& x); /* * @@ -596,26 +650,15 @@ inline void unset(mixed &x); * */ -double divide(int64_t lhs, int64_t rhs) { - return divide(static_cast(lhs), static_cast(rhs)); -} +double divide(int64_t lhs, int64_t rhs) { return divide(static_cast(lhs), static_cast(rhs)); } -double divide(double lhs, int64_t rhs) { - return divide(lhs, static_cast(rhs)); -} - -double divide(const string &lhs, int64_t rhs) { - return divide(f$floatval(lhs), rhs); -} +double divide(double lhs, int64_t rhs) { return divide(lhs, static_cast(rhs)); } -double divide(const mixed &lhs, int64_t rhs) { - return divide(f$floatval(lhs), rhs); -} +double divide(const string& lhs, int64_t rhs) { return divide(f$floatval(lhs), rhs); } +double divide(const mixed& lhs, int64_t rhs) { return divide(f$floatval(lhs), rhs); } -double divide(int64_t lhs, double rhs) { - return divide(static_cast(lhs), rhs); -} +double divide(int64_t lhs, double rhs) { return divide(static_cast(lhs), rhs); } double divide(double lhs, double rhs) { if (rhs == 0) { @@ -625,154 +668,127 @@ double divide(double lhs, double rhs) { return lhs / rhs; } -double divide(const string &lhs, double rhs) { - return divide(f$floatval(lhs), rhs); -} - -double divide(const mixed &lhs, double rhs) { - return divide(f$floatval(lhs), rhs); -} +double divide(const string& lhs, double rhs) { return divide(f$floatval(lhs), rhs); } +double divide(const mixed& lhs, double rhs) { return divide(f$floatval(lhs), rhs); } -double divide(int64_t lhs, const string &rhs) { - return divide(lhs, f$floatval(rhs)); -} +double divide(int64_t lhs, const string& rhs) { return divide(lhs, f$floatval(rhs)); } -double divide(double lhs, const string &rhs) { - return divide(lhs, f$floatval(rhs)); -} - -double divide(const string &lhs, const string &rhs) { - return divide(f$floatval(lhs), f$floatval(rhs)); -} - -double divide(const mixed &lhs, const string &rhs) { - return divide(lhs, f$floatval(rhs)); -} +double divide(double lhs, const string& rhs) { return divide(lhs, f$floatval(rhs)); } +double divide(const string& lhs, const string& rhs) { return divide(f$floatval(lhs), f$floatval(rhs)); } -double divide(int64_t lhs, const mixed &rhs) { - return divide(lhs, f$floatval(rhs)); -} +double divide(const mixed& lhs, const string& rhs) { return divide(lhs, f$floatval(rhs)); } -double divide(double lhs, const mixed &rhs) { - return divide(lhs, f$floatval(rhs)); -} +double divide(int64_t lhs, const mixed& rhs) { return divide(lhs, f$floatval(rhs)); } -double divide(const string &lhs, const mixed &rhs) { - return divide(f$floatval(lhs), rhs); -} +double divide(double lhs, const mixed& rhs) { return divide(lhs, f$floatval(rhs)); } -double divide(const mixed &lhs, const mixed &rhs) { - return divide(f$floatval(lhs), f$floatval(rhs)); -} +double divide(const string& lhs, const mixed& rhs) { return divide(f$floatval(lhs), rhs); } +double divide(const mixed& lhs, const mixed& rhs) { return divide(f$floatval(lhs), f$floatval(rhs)); } double divide(bool lhs, bool rhs) { php_warning("Both arguments of operator '/' are bool"); return divide(static_cast(lhs), static_cast(rhs)); } -template -double divide(bool lhs, const T &rhs) { +template +double divide(bool lhs, const T& rhs) { php_warning("First argument of operator '/' is bool"); return divide(static_cast(lhs), f$floatval(rhs)); } -template -double divide(const T &lhs, bool rhs) { +template +double divide(const T& lhs, bool rhs) { php_warning("Second argument of operator '/' is bool"); return divide(f$floatval(lhs), static_cast(rhs)); } -template -double divide(bool, const array &) { +template +double divide(bool, const array&) { php_warning("Unsupported operand types for operator '/' bool and array"); return 0.0; } -template -double divide(const array &, bool) { +template +double divide(const array&, bool) { php_warning("Unsupported operand types for operator '/' array and bool"); return 0.0; } -template -double divide(bool, const class_instance &) { +template +double divide(bool, const class_instance&) { php_warning("Unsupported operand types for operator '/' bool and object"); return 0.0; } -template -double divide(const class_instance &, bool) { +template +double divide(const class_instance&, bool) { php_warning("Unsupported operand types for operator '/' object and bool"); return 0.0; } - -template -double divide(const array &lhs, const T1 &rhs) { +template +double divide(const array& lhs, const T1& rhs) { php_warning("First argument of operator '/' is array"); return divide(f$count(lhs), rhs); } -template -double divide(const T1 &lhs, const array &rhs) { +template +double divide(const T1& lhs, const array& rhs) { php_warning("Second argument of operator '/' is array"); return divide(lhs, f$count(rhs)); } - -template -double divide(const class_instance &, const T1 &rhs) { +template +double divide(const class_instance&, const T1& rhs) { php_warning("First argument of operator '/' is object"); return divide(1.0, rhs); } -template -double divide(const T1 &lhs, const class_instance &) { +template +double divide(const T1& lhs, const class_instance&) { php_warning("Second argument of operator '/' is object"); return lhs; } - -template -double divide(const array &, const array &) { +template +double divide(const array&, const array&) { php_warning("Unsupported operand types for operator '/' array and array"); return 0.0; } -template -double divide(const class_instance &, const class_instance &) { +template +double divide(const class_instance&, const class_instance&) { php_warning("Unsupported operand types for operator '/' object and object"); return 0.0; } -template -double divide(const array &, const array &) { +template +double divide(const array&, const array&) { php_warning("Unsupported operand types for operator '/' array and array"); return 0.0; } -template -double divide(const class_instance &, const class_instance &) { +template +double divide(const class_instance&, const class_instance&) { php_warning("Unsupported operand types for operator '/' object and object"); return 0.0; } -template -double divide(const array &, const class_instance &) { +template +double divide(const array&, const class_instance&) { php_warning("Unsupported operand types for operator '/' array and object"); return 0.0; } -template -double divide(const class_instance &, const array &) { +template +double divide(const class_instance&, const array&) { php_warning("Unsupported operand types for operator '/' object and array"); return 0.0; } - int64_t modulo(int64_t lhs, int64_t rhs) { if (rhs == 0) { php_warning("Modulo by zero"); @@ -781,8 +797,8 @@ int64_t modulo(int64_t lhs, int64_t rhs) { return lhs % rhs; } -template -int64_t modulo(const T1 &lhs, const T2 &rhs) { +template +int64_t modulo(const T1& lhs, const T2& rhs) { int64_t div = f$intval(lhs); int64_t mod = f$intval(rhs); @@ -800,450 +816,360 @@ int64_t modulo(const T1 &lhs, const T2 &rhs) { return div % mod; } - -template -T1 ÷_self(T1 &lhs, const T2 &rhs) { +template +T1& divide_self(T1& lhs, const T2& rhs) { return lhs = divide(lhs, rhs); } +int64_t& modulo_self(int64_t& lhs, int64_t rhs) { return lhs = modulo(lhs, rhs); } -int64_t &modulo_self(int64_t &lhs, int64_t rhs) { - return lhs = modulo(lhs, rhs); -} - -template -T1 &modulo_self(T1 &lhs, const T2 &rhs) { +template +T1& modulo_self(T1& lhs, const T2& rhs) { return lhs = modulo(lhs, rhs); } - -template -void assign(T0 &dest, const T &from) { +template +void assign(T0& dest, const T& from) { dest = from; } -bool &boolval_ref(bool &val) { - return val; -} +bool& boolval_ref(bool& val) { return val; } -bool &boolval_ref(mixed &val) { - return val.as_bool("unknown"); -} +bool& boolval_ref(mixed& val) { return val.as_bool("unknown"); } -const bool &boolval_ref(const bool &val) { - return val; -} +const bool& boolval_ref(const bool& val) { return val; } -const bool &boolval_ref(const mixed &val) { - return val.as_bool("unknown"); -} +const bool& boolval_ref(const mixed& val) { return val.as_bool("unknown"); } +int64_t& intval_ref(int64_t& val, const char*) { return val; } -int64_t &intval_ref(int64_t &val, const char *) { - return val; -} +int64_t& intval_ref(mixed& val, const char* function) { return val.as_int(function); } -int64_t &intval_ref(mixed &val, const char *function) { - return val.as_int(function); -} - -const int64_t &intval_ref(const int64_t &val, const char *) { - return val; -} - -const int64_t &intval_ref(const mixed &val, const char *function) { - return val.as_int(function); -} +const int64_t& intval_ref(const int64_t& val, const char*) { return val; } +const int64_t& intval_ref(const mixed& val, const char* function) { return val.as_int(function); } -double &floatval_ref(double &val) { - return val; -} - -double &floatval_ref(mixed &val) { - return val.as_float("unknown"); -} - -const double &floatval_ref(const double &val) { - return val; -} +double& floatval_ref(double& val) { return val; } -const double &floatval_ref(const mixed &val) { - return val.as_float("unknown"); -} +double& floatval_ref(mixed& val) { return val.as_float("unknown"); } +const double& floatval_ref(const double& val) { return val; } -string &strval_ref(string &val, const char *) { - return val; -} +const double& floatval_ref(const mixed& val) { return val.as_float("unknown"); } -string &strval_ref(mixed &val, const char *function) { - return val.as_string(function); -} +string& strval_ref(string& val, const char*) { return val; } -const string &strval_ref(const string &val, const char *) { - return val; -} +string& strval_ref(mixed& val, const char* function) { return val.as_string(function); } -const string &strval_ref(const mixed &val, const char *function) { - return val.as_string(function); -} +const string& strval_ref(const string& val, const char*) { return val; } +const string& strval_ref(const mixed& val, const char* function) { return val.as_string(function); } -template -array &arrayval_ref(array &val, const char *) { +template +array& arrayval_ref(array& val, const char*) { return val; } -array &arrayval_ref(mixed &val, const char *function) { - return val.as_array(function); -} +array& arrayval_ref(mixed& val, const char* function) { return val.as_array(function); } -template -array &arrayval_ref(Optional> &val, const char *function) { +template +array& arrayval_ref(Optional>& val, const char* function) { if (unlikely(!val.has_value())) { php_warning("%s() expects parameter to be array, null or false is given", function); } return val.ref(); } -template -const array &arrayval_ref(const array &val, const char *) { +template +const array& arrayval_ref(const array& val, const char*) { return val; } -const array &arrayval_ref(const mixed &val, const char *function) { - return val.as_array(function); -} +const array& arrayval_ref(const mixed& val, const char* function) { return val.as_array(function); } -template -const array &arrayval_ref(const Optional> &val, const char *function) { +template +const array& arrayval_ref(const Optional>& val, const char* function) { if (unlikely(!val.has_value())) { php_warning("%s() expects parameter to be array, null or false is given", function); } return val.val(); } -template -const T &convert_to::convert(const T &val) { +template +const T& convert_to::convert(const T& val) { return val; } -template -T &&convert_to::convert(T &&val) { +template +T&& convert_to::convert(T&& val) { return std::move(val); } -template -T convert_to::convert(const Unknown &) { +template +T convert_to::convert(const Unknown&) { return T(); } -template -template -T convert_to::convert(T1 &&val) { +template +template +T convert_to::convert(T1&& val) { return T(std::forward(val)); } -template<> -template -bool convert_to::convert(T1 &&val) { +template <> +template +bool convert_to::convert(T1&& val) { return f$boolval(std::forward(val)); } -template<> -template -int64_t convert_to::convert(T1 &&val) { +template <> +template +int64_t convert_to::convert(T1&& val) { return f$intval(std::forward(val)); } -template<> -template -double convert_to::convert(T1 &&val) { +template <> +template +double convert_to::convert(T1&& val) { return f$floatval(std::forward(val)); } -template<> -template -string convert_to::convert(T1 &&val) { +template <> +template +string convert_to::convert(T1&& val) { return f$strval(std::forward(val)); } -template<> -template -array convert_to>::convert(T1 &&val) { +template <> +template +array convert_to>::convert(T1&& val) { return f$arrayval(std::forward(val)); } -template<> -template -mixed convert_to::convert(T1 &&val) { +template <> +template +mixed convert_to::convert(T1&& val) { return mixed{std::forward(val)}; } - -template -inline bool f$empty(const T &v) { +template +inline bool f$empty(const T& v) { return v == 0; } -bool f$empty(const string &v) { +bool f$empty(const string& v) { string::size_type l = v.size(); return l == 0 || (l == 1 && v[0] == '0'); } -template -bool f$empty(const array &a) { +template +bool f$empty(const array& a) { return a.empty(); } -template -bool f$empty(const class_instance &o) { - return o.is_null(); // false/null inside instance (in PHP, empty(false)=true behaves identically) +template +bool f$empty(const class_instance& o) { + return o.is_null(); // false/null inside instance (in PHP, empty(false)=true behaves identically) } -bool f$empty(const mixed &v) { - return v.empty(); -} +bool f$empty(const mixed& v) { return v.empty(); } -template -bool f$empty(const Optional &a) { +template +bool f$empty(const Optional& a) { return a.has_value() ? f$empty(a.val()) : true; } -int64_t f$count(const mixed &v) { - return v.count(); -} +int64_t f$count(const mixed& v) { return v.count(); } -template -int64_t f$count(const Optional &a) { - auto count_lambda = [](const auto &v) { return f$count(v);}; +template +int64_t f$count(const Optional& a) { + auto count_lambda = [](const auto& v) { return f$count(v); }; return call_fun_on_optional_value(count_lambda, a); } -template -int64_t f$count(const array &a) { +template +int64_t f$count(const array& a) { return a.count(); } -template -inline int64_t f$count(const std::tuple &a __attribute__ ((unused))) { +template +inline int64_t f$count(const std::tuple& a __attribute__((unused))) { return static_cast(std::tuple_size>::value); } -template -int64_t f$count(const T &) { +template +int64_t f$count(const T&) { php_warning("Count on non-array"); return 1; } - -template -int64_t f$sizeof(const T &v) { +template +int64_t f$sizeof(const T& v) { return f$count(v); } - -template -bool f$is_numeric(const T &) { +template +bool f$is_numeric(const T&) { static_assert(!std::is_same{}, "int is forbidden"); return std::is_same{} || std::is_same{}; } -bool f$is_numeric(const string &v) { - return v.is_numeric(); -} +bool f$is_numeric(const string& v) { return v.is_numeric(); } -bool f$is_numeric(const mixed &v) { - return v.is_numeric(); -} +bool f$is_numeric(const mixed& v) { return v.is_numeric(); } -template -inline bool f$is_numeric(const Optional &v) { +template +inline bool f$is_numeric(const Optional& v) { return v.has_value() ? f$is_numeric(v.val()) : false; } - -template -bool f$is_null(const T &) { +template +bool f$is_null(const T&) { return false; } -template -bool f$is_null(const class_instance &v) { +template +bool f$is_null(const class_instance& v) { return v.is_null(); } -template -inline bool f$is_null(const Optional &v) { +template +inline bool f$is_null(const Optional& v) { return v.has_value() ? f$is_null(v.val()) : v.value_state() == OptionalState::null_value; } -bool f$is_null(const mixed &v) { - return v.is_null(); -} +bool f$is_null(const mixed& v) { return v.is_null(); } - -template -bool f$is_bool(const T &) { +template +bool f$is_bool(const T&) { return std::is_same::value; } -template -inline bool f$is_bool(const Optional &v) { +template +inline bool f$is_bool(const Optional& v) { return v.has_value() ? f$is_bool(v.val()) : v.is_false(); } -bool f$is_bool(const mixed &v) { - return v.is_bool(); -} - +bool f$is_bool(const mixed& v) { return v.is_bool(); } -template -bool f$is_int(const T &) { +template +bool f$is_int(const T&) { static_assert(!std::is_same{}, "int is forbidden"); return std::is_same{}; } -template -inline bool f$is_int(const Optional &v) { +template +inline bool f$is_int(const Optional& v) { return v.has_value() ? f$is_int(v.val()) : false; } -bool f$is_int(const mixed &v) { - return v.is_int(); -} - +bool f$is_int(const mixed& v) { return v.is_int(); } -template -bool f$is_float(const T &) { +template +bool f$is_float(const T&) { return std::is_same::value; } -template -inline bool f$is_float(const Optional &v) { +template +inline bool f$is_float(const Optional& v) { return v.has_value() ? f$is_float(v.val()) : false; } -bool f$is_float(const mixed &v) { - return v.is_float(); -} - +bool f$is_float(const mixed& v) { return v.is_float(); } -template -bool f$is_scalar(const T &) { +template +bool f$is_scalar(const T&) { return std::is_arithmetic::value || std::is_same::value; } -template -inline bool f$is_scalar(const Optional &v) { - auto is_scalar_lambda = [](const auto &v) { return f$is_scalar(v);}; +template +inline bool f$is_scalar(const Optional& v) { + auto is_scalar_lambda = [](const auto& v) { return f$is_scalar(v); }; return call_fun_on_optional_value(is_scalar_lambda, v); } -bool f$is_scalar(const mixed &v) { - return v.is_scalar(); -} +bool f$is_scalar(const mixed& v) { return v.is_scalar(); } - -template -bool f$is_string(const T &) { +template +bool f$is_string(const T&) { return std::is_same::value; } -template -inline bool f$is_string(const Optional &v) { +template +inline bool f$is_string(const Optional& v) { return v.has_value() ? f$is_string(v.val()) : false; } -bool f$is_string(const mixed &v) { - return v.is_string(); -} - +bool f$is_string(const mixed& v) { return v.is_string(); } -template -inline bool f$is_array(const T &) { +template +inline bool f$is_array(const T&) { return is_array::value; } -bool f$is_array(const mixed &v) { - return v.is_array(); -} +bool f$is_array(const mixed& v) { return v.is_array(); } -template -inline bool f$is_array(const Optional &v) { +template +inline bool f$is_array(const Optional& v) { return v.has_value() ? f$is_array(v.val()) : false; } -template -bool f$is_object(const T &) { +template +bool f$is_object(const T&) { return false; } -template -bool f$is_object(const class_instance &v) { +template +bool f$is_object(const class_instance& v) { return !v.is_null(); } - -template -bool f$is_integer(const T &v) { +template +bool f$is_integer(const T& v) { return f$is_int(v); } -template -bool f$is_long(const T &v) { +template +bool f$is_long(const T& v) { return f$is_int(v); } -template -bool f$is_double(const T &v) { +template +bool f$is_double(const T& v) { return f$is_float(v); } -template -bool f$is_real(const T &v) { +template +bool f$is_real(const T& v) { return f$is_float(v); } -const char *get_type_c_str(bool) { - return "boolean"; -} +const char* get_type_c_str(bool) { return "boolean"; } -const char *get_type_c_str(int64_t) { - return "integer"; -} +const char* get_type_c_str(int64_t) { return "integer"; } -const char *get_type_c_str(double) { - return "double"; -} +const char* get_type_c_str(double) { return "double"; } -const char *get_type_c_str(const string &) { - return "string"; -} +const char* get_type_c_str(const string&) { return "string"; } -const char *get_type_c_str(const mixed &v) { - return v.get_type_c_str(); -} +const char* get_type_c_str(const mixed& v) { return v.get_type_c_str(); } -template -const char *get_type_c_str(const array &) { +template +const char* get_type_c_str(const array&) { return "array"; } -template -const char *get_type_c_str(const class_instance &) { +template +const char* get_type_c_str(const class_instance&) { return "object"; } - -template -string f$get_type(const T &v) { - const char *res = get_type_c_str(v); +template +string f$get_type(const T& v) { + const char* res = get_type_c_str(v); return {res, static_cast(strlen(res))}; } - string f$get_class(bool) { php_warning("Called get_class() on boolean"); return {}; @@ -1259,265 +1185,222 @@ string f$get_class(double) { return {}; } -string f$get_class(const string &) { +string f$get_class(const string&) { php_warning("Called get_class() on string"); return {}; } -string f$get_class(const mixed &v) { +string f$get_class(const mixed& v) { php_warning("Called get_class() on %s", v.get_type_c_str()); return {}; } -template -string f$get_class(const array &) { +template +string f$get_class(const array&) { php_warning("Called get_class() on array"); return {}; } -template -string f$get_class(const class_instance &v) { +template +string f$get_class(const class_instance& v) { return string(v.get_class()); } -template -inline int64_t f$get_hash_of_class(const class_instance &klass) { +template +inline int64_t f$get_hash_of_class(const class_instance& klass) { return klass.get_hash(); } -inline string &append(string &dest, tmp_string from) { - return dest.append(from.data, from.size); -} +inline string& append(string& dest, tmp_string from) { return dest.append(from.data, from.size); } -string &append(string &dest, const string &from) { - return dest.append(from); -} +string& append(string& dest, const string& from) { return dest.append(from); } -inline string &append(string &dest, int64_t from) { - return dest.append(from); -} +inline string& append(string& dest, int64_t from) { return dest.append(from); } -template -string &append(Optional &dest, const T &from) { +template +string& append(Optional& dest, const T& from) { return append(dest.ref(), from); } -template -string &append(string &dest, const T &from) { +template +string& append(string& dest, const T& from) { return dest.append(f$strval(from)); } -template -mixed &append(mixed &dest, const T &from) { +template +mixed& append(mixed& dest, const T& from) { return dest.append(f$strval(from)); } -inline mixed &append(mixed &dest, tmp_string from) { - return dest.append(from); -} +inline mixed& append(mixed& dest, tmp_string from) { return dest.append(from); } -template -T0 &append(T0 &dest, const T &from) { +template +T0& append(T0& dest, const T& from) { php_warning("Wrong arguments types %s and %s for operator .=", get_type_c_str(dest), get_type_c_str(from)); return dest; } +string f$gettype(const mixed& v) { return v.get_type_str(); } -string f$gettype(const mixed &v) { - return v.get_type_str(); -} - -template -bool f$function_exists(const T &) { +template +bool f$function_exists(const T&) { return true; } +mixed f$error_get_last() { return {}; } -mixed f$error_get_last() { - return {}; -} - -void f$warning(const string &message) { - php_warning("%s", message.c_str()); -} +void f$warning(const string& message) { php_warning("%s", message.c_str()); } -template -int64_t f$get_reference_counter(const array &v) { +template +int64_t f$get_reference_counter(const array& v) { return v.get_reference_counter(); } -template -int64_t f$get_reference_counter(const class_instance &v) { +template +int64_t f$get_reference_counter(const class_instance& v) { return v.get_reference_counter(); } -int64_t f$get_reference_counter(const string &v) { - return v.get_reference_counter(); -} - -int64_t f$get_reference_counter(const mixed &v) { - return v.get_reference_counter(); -} +int64_t f$get_reference_counter(const string& v) { return v.get_reference_counter(); } +int64_t f$get_reference_counter(const mixed& v) { return v.get_reference_counter(); } -template -T &val(T &x) { +template +T& val(T& x) { return x; } -template -const T &val(const T &x) { +template +const T& val(const T& x) { return x; } -template -T &ref(T &x) { +template +T& ref(T& x) { return x; } -template -const T &val(const Optional &x) { +template +const T& val(const Optional& x) { return x.val(); } -template -T &val(Optional &x) { +template +T& val(Optional& x) { return x.val(); } -template -T &ref(Optional &x) { +template +T& ref(Optional& x) { return x.ref(); } - -template -typename array::iterator begin(array &x) { +template +typename array::iterator begin(array& x) { return x.begin(); } -template -typename array::const_iterator begin(const array &x) { +template +typename array::const_iterator begin(const array& x) { return x.begin(); } -template -typename array::const_iterator const_begin(const array &x) { +template +typename array::const_iterator const_begin(const array& x) { return x.begin(); } +array::iterator begin(mixed& x) { return x.begin(); } -array::iterator begin(mixed &x) { - return x.begin(); -} +array::const_iterator begin(const mixed& x) { return x.begin(); } -array::const_iterator begin(const mixed &x) { - return x.begin(); -} +array::const_iterator const_begin(const mixed& x) { return x.begin(); } -array::const_iterator const_begin(const mixed &x) { - return x.begin(); -} - - -template -typename array::iterator begin(Optional> &x) { +template +typename array::iterator begin(Optional>& x) { if (unlikely(!x.has_value())) { php_warning("Invalid argument supplied for foreach(), false or null is given"); } return x.val().begin(); } -template -typename array::const_iterator begin(const Optional> &x) { +template +typename array::const_iterator begin(const Optional>& x) { if (unlikely(!x.has_value())) { php_warning("Invalid argument supplied for foreach(), false or null is given"); } return x.val().begin(); } -template -typename array::const_iterator const_begin(const Optional> &x) { +template +typename array::const_iterator const_begin(const Optional>& x) { if (unlikely(!x.has_value())) { php_warning("Invalid argument supplied for foreach(), false or null is given"); } return x.val().begin(); } - -template -typename array::iterator end(array &x) { +template +typename array::iterator end(array& x) { return x.end(); } -template -typename array::const_iterator end(const array &x) { +template +typename array::const_iterator end(const array& x) { return x.end(); } -template -typename array::const_iterator const_end(const array &x) { +template +typename array::const_iterator const_end(const array& x) { return x.end(); } -array::iterator end(mixed &x) { - return x.end(); -} +array::iterator end(mixed& x) { return x.end(); } -array::const_iterator end(const mixed &x) { - return x.end(); -} - -array::const_iterator const_end(const mixed &x) { - return x.end(); -} +array::const_iterator end(const mixed& x) { return x.end(); } +array::const_iterator const_end(const mixed& x) { return x.end(); } -template -typename array::iterator end(Optional> &x) { +template +typename array::iterator end(Optional>& x) { return x.val().end(); } -template -typename array::const_iterator end(const Optional> &x) { +template +typename array::const_iterator end(const Optional>& x) { return x.val().end(); } -template -typename array::const_iterator const_end(const Optional> &x) { +template +typename array::const_iterator const_end(const Optional>& x) { return x.val().end(); } +void clear_array(mixed& v) { v.clear(); } -void clear_array(mixed &v) { - v.clear(); -} - -template -void clear_array(array &a) { +template +void clear_array(array& a) { a.clear(); } -template -void clear_array(Optional> &a) { +template +void clear_array(Optional>& a) { a = false; } -template -void unset(array &x) { +template +void unset(array& x) { x = {}; } -template -void unset(class_instance &x) { +template +void unset(class_instance& x) { x = {}; } -void unset(mixed &x) { - x = {}; -} +void unset(mixed& x) { x = {}; } -template +template inline decltype(auto) check_not_null(T&& val) { if (f$is_null(val)) { php_warning("not_null is called on null"); @@ -1525,7 +1408,7 @@ inline decltype(auto) check_not_null(T&& val) { return std::forward(val); } -template +template inline decltype(auto) check_not_false(T&& val) { if (f$is_bool(val) && !f$boolval(val)) { php_warning("not_false is called on false"); @@ -1533,7 +1416,7 @@ inline decltype(auto) check_not_false(T&& val) { return std::forward(val); } -template +template using future = int64_t; -template +template using future_queue = int64_t; diff --git a/runtime-common/core/utils/hash.h b/runtime-common/core/utils/hash.h index 13fdaece98..c7b00051d9 100644 --- a/runtime-common/core/utils/hash.h +++ b/runtime-common/core/utils/hash.h @@ -9,7 +9,7 @@ // from boost // see https://www.boost.org/doc/libs/1_55_0/doc/html/hash/reference.html#boost.hash_combine -template -void hash_combine(size_t &seed, const T &v) noexcept { +template +void hash_combine(size_t& seed, const T& v) noexcept { seed ^= std::hash{}(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2); } diff --git a/runtime-common/core/utils/kphp-assert-core.h b/runtime-common/core/utils/kphp-assert-core.h index ee83cb5d01..c0aff98a75 100644 --- a/runtime-common/core/utils/kphp-assert-core.h +++ b/runtime-common/core/utils/kphp-assert-core.h @@ -4,21 +4,23 @@ #include "common/wrappers/likely.h" -void php_debug(char const *message, ...) __attribute__ ((format (printf, 1, 2))); -void php_notice(char const *message, ...) __attribute__ ((format (printf, 1, 2))); -void php_warning(char const *message, ...) __attribute__ ((format (printf, 1, 2))); -void php_error(char const *message, ...) __attribute__ ((format (printf, 1, 2))); +void php_debug(char const* message, ...) __attribute__((format(printf, 1, 2))); +void php_notice(char const* message, ...) __attribute__((format(printf, 1, 2))); +void php_warning(char const* message, ...) __attribute__((format(printf, 1, 2))); +void php_error(char const* message, ...) __attribute__((format(printf, 1, 2))); -[[noreturn]] void php_assert__(const char *msg, const char *file, int line); +[[noreturn]] void php_assert__(const char* msg, const char* file, int line); [[noreturn]] void critical_error_handler(); -#define php_assert(EX) do { \ - if (unlikely(!(EX))) { \ - php_assert__ (#EX, __FILE__, __LINE__); \ - } \ -} while(0) +#define php_assert(EX) \ + do { \ + if (unlikely(!(EX))) { \ + php_assert__(#EX, __FILE__, __LINE__); \ + } \ + } while (0) -#define php_critical_error(format, ...) do { \ - php_error ("Critical error \"" format "\" in file %s on line %d", ##__VA_ARGS__, __FILE__, __LINE__); \ - critical_error_handler(); \ -} while(0) +#define php_critical_error(format, ...) \ + do { \ + php_error("Critical error \"" format "\" in file %s on line %d", ##__VA_ARGS__, __FILE__, __LINE__); \ + critical_error_handler(); \ + } while (0) diff --git a/runtime-common/core/utils/migration-php8.cpp b/runtime-common/core/utils/migration-php8.cpp index db3a9d0cf6..ae13ec07ef 100644 --- a/runtime-common/core/utils/migration-php8.cpp +++ b/runtime-common/core/utils/migration-php8.cpp @@ -6,14 +6,8 @@ #include "runtime-common/core/runtime-core.h" -void f$set_migration_php8_warning(int mask) { - RuntimeContext::get().show_migration_php8_warning = mask; -} +void f$set_migration_php8_warning(int mask) { RuntimeContext::get().show_migration_php8_warning = mask; } -static void reset_migration_php8_global_vars() { - RuntimeContext::get().show_migration_php8_warning = 0; -} +static void reset_migration_php8_global_vars() { RuntimeContext::get().show_migration_php8_warning = 0; } -void free_migration_php8() { - reset_migration_php8_global_vars(); -} +void free_migration_php8() { reset_migration_php8_global_vars(); } diff --git a/runtime-common/core/utils/small-object-storage.h b/runtime-common/core/utils/small-object-storage.h index 0a5b1cdd41..743cb62528 100644 --- a/runtime-common/core/utils/small-object-storage.h +++ b/runtime-common/core/utils/small-object-storage.h @@ -11,36 +11,36 @@ #include "runtime-common/core/allocator/runtime-allocator.h" -template +template union small_object_storage { std::array storage_; - void *storage_ptr; + void* storage_ptr; - template - std::enable_if_t emplace(Args &&...args) noexcept { + template + std::enable_if_t emplace(Args&&... args) noexcept { return new (storage_.data()) T(std::forward(args)...); } - template - std::enable_if_t get() noexcept { - return reinterpret_cast(storage_.data()); + template + std::enable_if_t get() noexcept { + return reinterpret_cast(storage_.data()); } - template + template std::enable_if_t destroy() noexcept { get()->~T(); } - template - std::enable_if_t < limit emplace(Args &&...args) noexcept { + template + std::enable_if_t < limit emplace(Args&&... args) noexcept { storage_ptr = RuntimeAllocator::get().alloc_script_memory(sizeof(T)); return new (storage_ptr) T(std::forward(args)...); } - template - std::enable_if_t < limit get() noexcept { - return static_cast(storage_ptr); + template + std::enable_if_t < limit get() noexcept { + return static_cast(storage_ptr); } - template - std::enable_if_t < limit destroy() noexcept { - T *mem = get(); + template + std::enable_if_t < limit destroy() noexcept { + T* mem = get(); mem->~T(); RuntimeAllocator::get().free_script_memory(mem, sizeof(T)); } diff --git a/runtime-common/stdlib/array/array-functions.cpp b/runtime-common/stdlib/array/array-functions.cpp index 53b75a1148..e9095533e3 100644 --- a/runtime-common/stdlib/array/array-functions.cpp +++ b/runtime-common/stdlib/array/array-functions.cpp @@ -13,9 +13,9 @@ namespace { -template -void walk_parts(const char *d, int64_t d_len, const string &str, int64_t limit, FN handle_part) noexcept { - const char *s = str.c_str(); +template +void walk_parts(const char* d, int64_t d_len, const string& str, int64_t limit, FN handle_part) noexcept { + const char* s = str.c_str(); int64_t s_len = str.size(); int64_t prev = 0; @@ -89,7 +89,7 @@ array range_int(int64_t from, int64_t to, int64_t step) { } } -array range_string(const string &from_s, const string &to_s, int64_t step) { +array range_string(const string& from_s, const string& to_s, int64_t step) { if (from_s.empty() || to_s.empty() || from_s.size() > 1 || to_s.size() > 1) { php_warning("Wrong parameters \"%s\" and \"%s\" for function range", from_s.c_str(), to_s.c_str()); return {}; @@ -117,10 +117,10 @@ array range_string(const string &from_s, const string &to_s, int64_t step namespace array_functions_impl_ { -string implode_string_vector(const string &s, const array &a) noexcept { +string implode_string_vector(const string& s, const array& a) noexcept { // we use a precondition here that array is not empty: count-1 is not negative, elems[0] is valid int64_t count = a.count(); - const string *elems = a.get_const_vector_pointer(); + const string* elems = a.get_const_vector_pointer(); int result_size = 0; for (int64_t i = 0; i < count; i++) { @@ -148,14 +148,14 @@ string implode_string_vector(const string &s, const array &a) noexcept { } // namespace array_functions_impl_ -string f$_explode_nth(const string &delimiter, const string &str, int64_t index) noexcept { +string f$_explode_nth(const string& delimiter, const string& str, int64_t index) noexcept { if (delimiter.empty()) { php_warning("Empty delimiter in function explode"); return {}; } int result_index = 0; string res; - walk_parts(delimiter.c_str(), delimiter.size(), str, index + 2, [&](const char *s, string::size_type l) noexcept { + walk_parts(delimiter.c_str(), delimiter.size(), str, index + 2, [&](const char* s, string::size_type l) noexcept { if (result_index++ == index) { res = string(s, l); } @@ -163,103 +163,101 @@ string f$_explode_nth(const string &delimiter, const string &str, int64_t index) return res; } -string f$_explode_1(const string &delimiter, const string &str) noexcept { - return f$_explode_nth(delimiter, str, 0); -} +string f$_explode_1(const string& delimiter, const string& str) noexcept { return f$_explode_nth(delimiter, str, 0); } -std::tuple f$_explode_tuple2(const string &delimiter, const string &str, int64_t mask, int64_t limit) noexcept { +std::tuple f$_explode_tuple2(const string& delimiter, const string& str, int64_t mask, int64_t limit) noexcept { if (delimiter.empty()) { php_warning("Empty delimiter in function explode"); return {}; } int result_index = 0; std::tuple res; - walk_parts(delimiter.c_str(), delimiter.size(), str, limit, [&](const char *s, string::size_type l) { + walk_parts(delimiter.c_str(), delimiter.size(), str, limit, [&](const char* s, string::size_type l) { int index = result_index++; if (((1 << index) & mask) == 0) { return; // this result index will be discarded, don't allocate the string } switch (index) { - case 0: - std::get<0>(res) = string(s, l); - return; - case 1: - std::get<1>(res) = string(s, l); - return; - default: - return; + case 0: + std::get<0>(res) = string(s, l); + return; + case 1: + std::get<1>(res) = string(s, l); + return; + default: + return; } }); return res; } -std::tuple f$_explode_tuple3(const string &delimiter, const string &str, int64_t mask, int64_t limit) noexcept { +std::tuple f$_explode_tuple3(const string& delimiter, const string& str, int64_t mask, int64_t limit) noexcept { if (delimiter.empty()) { php_warning("Empty delimiter in function explode"); return {}; } int result_index = 0; std::tuple res; - walk_parts(delimiter.c_str(), delimiter.size(), str, limit, [&](const char *s, string::size_type l) { + walk_parts(delimiter.c_str(), delimiter.size(), str, limit, [&](const char* s, string::size_type l) { int index = result_index++; if (((1 << index) & mask) == 0) { return; // this result index will be discarded, don't allocate the string } switch (index) { - case 0: - std::get<0>(res) = string(s, l); - return; - case 1: - std::get<1>(res) = string(s, l); - return; - case 2: - std::get<2>(res) = string(s, l); - return; - default: - return; + case 0: + std::get<0>(res) = string(s, l); + return; + case 1: + std::get<1>(res) = string(s, l); + return; + case 2: + std::get<2>(res) = string(s, l); + return; + default: + return; } }); return res; } -std::tuple f$_explode_tuple4(const string &delimiter, const string &str, int64_t mask, int64_t limit) noexcept { +std::tuple f$_explode_tuple4(const string& delimiter, const string& str, int64_t mask, int64_t limit) noexcept { if (delimiter.empty()) { php_warning("Empty delimiter in function explode"); return {}; } int result_index = 0; std::tuple res; - walk_parts(delimiter.c_str(), delimiter.size(), str, limit, [&](const char *s, string::size_type l) { + walk_parts(delimiter.c_str(), delimiter.size(), str, limit, [&](const char* s, string::size_type l) { int index = result_index++; if (((1 << index) & mask) == 0) { return; // this result index will be discarded, don't allocate the string } switch (index) { - case 0: - std::get<0>(res) = string(s, l); - return; - case 1: - std::get<1>(res) = string(s, l); - return; - case 2: - std::get<2>(res) = string(s, l); - return; - case 3: - std::get<3>(res) = string(s, l); - return; - default: - return; + case 0: + std::get<0>(res) = string(s, l); + return; + case 1: + std::get<1>(res) = string(s, l); + return; + case 2: + std::get<2>(res) = string(s, l); + return; + case 3: + std::get<3>(res) = string(s, l); + return; + default: + return; } }); return res; } -array explode(char delimiter, const string &str, int64_t limit) noexcept { +array explode(char delimiter, const string& str, int64_t limit) noexcept { array res(array_size(limit < 10 ? limit : 1, true)); - walk_parts(std::addressof(delimiter), 1, str, limit, [&](const char *s, string::size_type l) { res.push_back(string(s, l)); }); + walk_parts(std::addressof(delimiter), 1, str, limit, [&](const char* s, string::size_type l) { res.push_back(string(s, l)); }); return res; } -array f$explode(const string &delimiter, const string &str, int64_t limit) noexcept { +array f$explode(const string& delimiter, const string& str, int64_t limit) noexcept { if (limit < 1) { php_warning("Wrong limit %" PRIi64 " specified in function explode", limit); limit = 1; @@ -270,11 +268,11 @@ array f$explode(const string &delimiter, const string &str, int64_t limi } array res(array_size(limit < 10 ? limit : 1, true)); - walk_parts(delimiter.c_str(), delimiter.size(), str, limit, [&](const char *s, string::size_type l) { res.push_back(string(s, l)); }); + walk_parts(delimiter.c_str(), delimiter.size(), str, limit, [&](const char* s, string::size_type l) { res.push_back(string(s, l)); }); return res; } -array f$range(const mixed &from, const mixed &to, int64_t step) { +array f$range(const mixed& from, const mixed& to, int64_t step) { if ((from.is_string() && !from.is_numeric()) || (to.is_string() && !to.is_numeric())) { return range_string(from.to_string(), to.to_string(), step); } diff --git a/runtime-common/stdlib/array/array-functions.h b/runtime-common/stdlib/array/array-functions.h index 6ff9812214..4bbcdb713e 100644 --- a/runtime-common/stdlib/array/array-functions.h +++ b/runtime-common/stdlib/array/array-functions.h @@ -18,28 +18,28 @@ inline constexpr int64_t SORT_STRING = 2; namespace array_functions_impl_ { -string implode_string_vector(const string &s, const array &a) noexcept; +string implode_string_vector(const string& s, const array& a) noexcept; -template -auto transform_to_vector(const array &a, const F &op) noexcept { +template +auto transform_to_vector(const array& a, const F& op) noexcept { array::ResultType> result(array_size(a.count(), true)); - for (const auto &it : a) { + for (const auto& it : a) { result.push_back(op(it)); } return result; } -template -array array_diff(const array &a1, const array &a2, const Proj &projector) noexcept { +template +array array_diff(const array& a1, const array& a2, const Proj& projector) noexcept { array result(a1.size()); array values{array_size{a2.count(), false}}; - for (const auto &it : a2) { + for (const auto& it : a2) { values.set_value(projector(it.get_value()), 1); } - for (const auto &it : a1) { + for (const auto& it : a1) { if (!values.has_key(projector(it.get_value()))) { result.set_value(it); } @@ -47,69 +47,55 @@ array array_diff(const array &a1, const array &a2, const Proj &project return result; } -template +template struct sort_compare { - bool operator()(const T &h1, const T &h2) const { - return lt(h2, h1); - } + bool operator()(const T& h1, const T& h2) const { return lt(h2, h1); } }; -template +template struct sort_compare_numeric { static_assert(!std::is_same{}, "int is forbidden"); - bool operator()(const T &h1, const T &h2) const { - return f$floatval(h1) > f$floatval(h2); - } + bool operator()(const T& h1, const T& h2) const { return f$floatval(h1) > f$floatval(h2); } }; -template<> +template <> struct sort_compare_numeric : std::greater {}; -template +template struct sort_compare_string { - bool operator()(const T &h1, const T &h2) const { - return f$strval(h1).compare(f$strval(h2)) > 0; - } + bool operator()(const T& h1, const T& h2) const { return f$strval(h1).compare(f$strval(h2)) > 0; } }; -template +template struct sort_compare_natural { - bool operator()(const T &h1, const T &h2) const { - return f$strnatcmp(f$strval(h1), f$strval(h2)) > 0; - } + bool operator()(const T& h1, const T& h2) const { return f$strnatcmp(f$strval(h1), f$strval(h2)) > 0; } }; -template +template struct rsort_compare { - bool operator()(const T &h1, const T &h2) const { - return lt(h1, h2); - } + bool operator()(const T& h1, const T& h2) const { return lt(h1, h2); } }; -template +template struct rsort_compare_numeric { static_assert(!std::is_same{}, "int is forbidden"); - bool operator()(const T &h1, const T &h2) const { - return f$floatval(h1) < f$floatval(h2); - } + bool operator()(const T& h1, const T& h2) const { return f$floatval(h1) < f$floatval(h2); } }; -template<> +template <> struct rsort_compare_numeric : std::less {}; -template +template struct rsort_compare_string { - bool operator()(const T &h1, const T &h2) const { - return f$strval(h1).compare(f$strval(h2)) < 0; - } + bool operator()(const T& h1, const T& h2) const { return f$strval(h1).compare(f$strval(h2)) < 0; } }; } // namespace array_functions_impl_ -template -string f$implode(const string &s, const array &a) noexcept { +template +string f$implode(const string& s, const array& a) noexcept { int64_t count = a.count(); if (count == 1) { return f$strval(a.begin().get_value()); @@ -131,7 +117,7 @@ string f$implode(const string &s, const array &a) noexcept { // fallback to the generic iterator + string_buffer solution - string_buffer &SB = RuntimeContext::get().static_SB; + string_buffer& SB = RuntimeContext::get().static_SB; SB.clean(); auto it = a.begin(); @@ -148,22 +134,22 @@ string f$implode(const string &s, const array &a) noexcept { return SB.str(); } -array explode(char delimiter, const string &str, int64_t limit = std::numeric_limits::max()) noexcept; +array explode(char delimiter, const string& str, int64_t limit = std::numeric_limits::max()) noexcept; -array f$explode(const string &delimiter, const string &str, int64_t limit = std::numeric_limits::max()) noexcept; +array f$explode(const string& delimiter, const string& str, int64_t limit = std::numeric_limits::max()) noexcept; -string f$_explode_nth(const string &delimiter, const string &str, int64_t index) noexcept; +string f$_explode_nth(const string& delimiter, const string& str, int64_t index) noexcept; -string f$_explode_1(const string &delimiter, const string &str) noexcept; +string f$_explode_1(const string& delimiter, const string& str) noexcept; -std::tuple f$_explode_tuple2(const string &delimiter, const string &str, int64_t mask, int64_t limit = 2 + 1) noexcept; +std::tuple f$_explode_tuple2(const string& delimiter, const string& str, int64_t mask, int64_t limit = 2 + 1) noexcept; -std::tuple f$_explode_tuple3(const string &delimiter, const string &str, int64_t mask, int64_t limit = 3 + 1) noexcept; +std::tuple f$_explode_tuple3(const string& delimiter, const string& str, int64_t mask, int64_t limit = 3 + 1) noexcept; -std::tuple f$_explode_tuple4(const string &delimiter, const string &str, int64_t mask, int64_t limit = 4 + 1) noexcept; +std::tuple f$_explode_tuple4(const string& delimiter, const string& str, int64_t mask, int64_t limit = 4 + 1) noexcept; -template -array f$array_reverse(const array &a, bool preserve_keys = false) noexcept { +template +array f$array_reverse(const array& a, bool preserve_keys = false) noexcept { array result(a.size()); const auto first = a.begin(); @@ -179,16 +165,16 @@ array f$array_reverse(const array &a, bool preserve_keys = false) noexcept return result; } -template -array f$array_intersect(const array &a1, const array &a2) noexcept { +template +array f$array_intersect(const array& a1, const array& a2) noexcept { array result(a1.size().min(a2.size())); array values(array_size(a2.count(), false)); - for (const auto &it : a2) { + for (const auto& it : a2) { values.set_value(f$strval(it.get_value()), 1); } - for (const auto &it : a1) { + for (const auto& it : a1) { if (values.has_key(f$strval(it.get_value()))) { result.set_value(it); } @@ -196,10 +182,10 @@ array f$array_intersect(const array &a1, const array &a2) noexcept { return result; } -template -array f$array_intersect_key(const array &a1, const array &a2) noexcept { +template +array f$array_intersect_key(const array& a1, const array& a2) noexcept { array result(a1.size().min(a2.size())); - for (const auto &it : a1) { + for (const auto& it : a1) { if (a2.has_key(it.get_key())) { result.set_value(it); } @@ -207,71 +193,71 @@ array f$array_intersect_key(const array &a1, const array &a2) noexcept return result; } -template -bool f$array_key_exists(int64_t int_key, const array &a) noexcept { +template +bool f$array_key_exists(int64_t int_key, const array& a) noexcept { return a.has_key(int_key); } -template -bool f$array_key_exists(const string &string_key, const array &a) noexcept { +template +bool f$array_key_exists(const string& string_key, const array& a) noexcept { return a.has_key(string_key); } -template -bool f$array_key_exists(const mixed &v, const array &a) noexcept { +template +bool f$array_key_exists(const mixed& v, const array& a) noexcept { return (v.is_int() || v.is_string() || v.is_null()) && a.has_key(v); } -template -bool f$array_key_exists(const Optional &v, const array &a) noexcept { +template +bool f$array_key_exists(const Optional& v, const array& a) noexcept { return f$array_key_exists(mixed(v), a); } -template>> -constexpr bool f$array_key_exists(K /*key*/, const array & /*a*/) noexcept { +template >> +constexpr bool f$array_key_exists(K /*key*/, const array& /*a*/) noexcept { return false; } -template -array::key_type> f$array_keys(const array &a) noexcept { +template +array::key_type> f$array_keys(const array& a) noexcept { using Iterator = typename array::const_iterator; return array_functions_impl_::transform_to_vector(a, [](Iterator it) { return it.get_key(); }); } -template -array f$array_keys_as_strings(const array &a) noexcept { +template +array f$array_keys_as_strings(const array& a) noexcept { using Iterator = typename array::const_iterator; return array_functions_impl_::transform_to_vector(a, [](Iterator it) { return it.get_key().to_string(); }); } -template -array f$array_keys_as_ints(const array &a) noexcept { +template +array f$array_keys_as_ints(const array& a) noexcept { using Iterator = typename array::const_iterator; return array_functions_impl_::transform_to_vector(a, [](Iterator it) { return it.get_key().to_int(); }); } -template -array f$array_unique(const array &a, int64_t flags = SORT_STRING) noexcept { +template +array f$array_unique(const array& a, int64_t flags = SORT_STRING) noexcept { array values(array_size(a.count(), false)); array result(a.size()); - auto lookup = [flags, &values](const auto &value) -> int64_t & { + auto lookup = [flags, &values](const auto& value) -> int64_t& { switch (flags) { - case SORT_REGULAR: - return values[value]; - case SORT_NUMERIC: - return values[f$intval(value)]; - case SORT_STRING: - return values[f$strval(value)]; - default: - php_warning("Unsupported flags in function array_unique"); - return values[f$strval(value)]; + case SORT_REGULAR: + return values[value]; + case SORT_NUMERIC: + return values[f$intval(value)]; + case SORT_STRING: + return values[f$strval(value)]; + default: + php_warning("Unsupported flags in function array_unique"); + return values[f$strval(value)]; } }; - for (const auto &it : a) { - const T &value = it.get_value(); - int64_t &cnt = lookup(value); + for (const auto& it : a) { + const T& value = it.get_value(); + int64_t& cnt = lookup(value); if (!cnt) { cnt = 1; result.set_value(it); @@ -280,40 +266,40 @@ array f$array_unique(const array &a, int64_t flags = SORT_STRING) noexcept return result; } -template -array f$array_values(const array &a) noexcept { +template +array f$array_values(const array& a) noexcept { using Iterator = typename array::const_iterator; return array_functions_impl_::transform_to_vector(a, [](Iterator it) { return it.get_value(); }); } -template -T f$array_shift(array &a) noexcept { +template +T f$array_shift(array& a) noexcept { return a.shift(); } -template -int64_t f$array_unshift(array &a, const T1 &val) noexcept { +template +int64_t f$array_unshift(array& a, const T1& val) noexcept { return a.unshift(val); } -template -T f$array_merge(const T &a1) noexcept { +template +T f$array_merge(const T& a1) noexcept { T result(a1.size()); result.merge_with(a1); return result; } -template -T f$array_merge(const T &a1, const T &a2) noexcept { +template +T f$array_merge(const T& a1, const T& a2) noexcept { T result(a1.size() + a2.size()); result.merge_with(a1); result.merge_with(a2); return result; } -template -T f$array_merge(const T &a1, const T &a2, const T &a3, const T &a4 = {}, const T &a5 = {}, const T &a6 = {}, const T &a7 = {}, const T &a8 = {}, - const T &a9 = {}, const T &a10 = {}, const T &a11 = {}, const T &a12 = {}) noexcept { +template +T f$array_merge(const T& a1, const T& a2, const T& a3, const T& a4 = {}, const T& a5 = {}, const T& a6 = {}, const T& a7 = {}, const T& a8 = {}, + const T& a9 = {}, const T& a10 = {}, const T& a11 = {}, const T& a12 = {}) noexcept { T result(a1.size() + a2.size() + a3.size() + a4.size() + a5.size() + a6.size() + a7.size() + a8.size() + a9.size() + a10.size() + a11.size() + a12.size()); result.merge_with(a1); result.merge_with(a2); @@ -330,39 +316,39 @@ T f$array_merge(const T &a1, const T &a2, const T &a3, const T &a4 = {}, const T return result; } -template -void f$array_merge_into(T &a, const T1 &another_array) noexcept { +template +void f$array_merge_into(T& a, const T1& another_array) noexcept { a.merge_with(another_array); } -template -void f$array_reserve(array &a, int64_t int_size, int64_t string_size, bool make_vector_if_possible = true) noexcept { +template +void f$array_reserve(array& a, int64_t int_size, int64_t string_size, bool make_vector_if_possible = true) noexcept { a.reserve(int_size + string_size, make_vector_if_possible); } -template -void f$array_reserve_vector(array &a, int64_t size) noexcept { +template +void f$array_reserve_vector(array& a, int64_t size) noexcept { a.reserve(size, true); } -template -void f$array_reserve_map_int_keys(array &a, int64_t size) noexcept { +template +void f$array_reserve_map_int_keys(array& a, int64_t size) noexcept { a.reserve(size, false); } -template -void f$array_reserve_map_string_keys(array &a, int64_t size) noexcept { +template +void f$array_reserve_map_string_keys(array& a, int64_t size) noexcept { a.reserve(size, false); } -template -void f$array_reserve_from(array &a, const array &base) noexcept { +template +void f$array_reserve_from(array& a, const array& base) noexcept { auto size_info = base.size(); f$array_reserve(a, size_info.size, size_info.is_vector); } -template -array> f$array_chunk(const array &a, int64_t chunk_size, bool preserve_keys = false) noexcept { +template +array> f$array_chunk(const array& a, int64_t chunk_size, bool preserve_keys = false) noexcept { if (unlikely(chunk_size <= 0)) { php_warning("Parameter chunk_size if function array_chunk must be positive"); return array>(); @@ -377,7 +363,7 @@ array> f$array_chunk(const array &a, int64_t chunk_size, bool preser } array res(new_size); - for (const auto &it : a) { + for (const auto& it : a) { if (res.count() == chunk_size) { result.emplace_back(std::move(res)); res = array(new_size); @@ -397,33 +383,33 @@ array> f$array_chunk(const array &a, int64_t chunk_size, bool preser return result; } -template -array f$array_diff(const array &a1, const array &a2) noexcept { - return array_functions_impl_::array_diff(a1, a2, [](const auto &val) { return f$strval(val); }); +template +array f$array_diff(const array& a1, const array& a2) noexcept { + return array_functions_impl_::array_diff(a1, a2, [](const auto& val) { return f$strval(val); }); } -template<> -inline array f$array_diff(const array &a1, const array &a2) noexcept { +template <> +inline array f$array_diff(const array& a1, const array& a2) noexcept { return array_functions_impl_::array_diff(a1, a2, [](int64_t val) { return val; }); } -template -array f$array_diff(const array &a1, const array &a2, const array &a3) noexcept { +template +array f$array_diff(const array& a1, const array& a2, const array& a3) noexcept { return f$array_diff(f$array_diff(a1, a2), a3); } -template -T f$array_first_value(const array &a) noexcept { +template +T f$array_first_value(const array& a) noexcept { return a.empty() ? T() : a.begin().get_value(); // in PHP 'false' on empty, here T() } -template -array::key_type> f$array_flip(const array &a) noexcept { +template +array::key_type> f$array_flip(const array& a) noexcept { static_assert(!std::is_same{}, "int is forbidden"); array::key_type> result; - for (const auto &it : a) { - const auto &value = it.get_value(); + for (const auto& it : a) { + const auto& value = it.get_value(); if (vk::is_type_in_list{} || f$is_int(value) || f$is_string(value)) { result.set_value(value, it.get_key()); } else { @@ -434,48 +420,48 @@ array::key_type> f$array_flip(const array &a) noexcept { return result; } -template -mixed f$array_last_key(const array &a) noexcept { +template +mixed f$array_last_key(const array& a) noexcept { return a.empty() ? mixed() : (--a.end()).get_key(); } -template -T f$array_last_value(const array &a) noexcept { +template +T f$array_last_value(const array& a) noexcept { return a.empty() ? T() : (--a.end()).get_value(); // in PHP 'false' on empty, here T() } -template -T f$array_replace(const T &base_array, const T &replacements = T()) noexcept { +template +T f$array_replace(const T& base_array, const T& replacements = T()) noexcept { auto result = T::convert_from(base_array); - for (const auto &it : replacements) { + for (const auto& it : replacements) { result.set_value(it); } return result; } -template -T f$array_replace(const T &base_array, const T &replacements_1, const T &replacements_2, const T &replacements_3 = T(), const T &replacements_4 = T(), - const T &replacements_5 = T(), const T &replacements_6 = T(), const T &replacements_7 = T(), const T &replacements_8 = T(), - const T &replacements_9 = T(), const T &replacements_10 = T(), const T &replacements_11 = T()) noexcept { +template +T f$array_replace(const T& base_array, const T& replacements_1, const T& replacements_2, const T& replacements_3 = T(), const T& replacements_4 = T(), + const T& replacements_5 = T(), const T& replacements_6 = T(), const T& replacements_7 = T(), const T& replacements_8 = T(), + const T& replacements_9 = T(), const T& replacements_10 = T(), const T& replacements_11 = T()) noexcept { return f$array_replace( - f$array_replace( f$array_replace( - f$array_replace(f$array_replace(f$array_replace(f$array_replace(f$array_replace(f$array_replace(f$array_replace(f$array_replace(base_array, - replacements_1), - replacements_2), - replacements_3), - replacements_4), - replacements_5), - replacements_6), - replacements_7), - replacements_8), - replacements_9), - replacements_10), - replacements_11); -} - -template -array f$array_slice(const array &a, int64_t offset, const mixed &length_var = mixed(), bool preserve_keys = false) noexcept { + f$array_replace( + f$array_replace( + f$array_replace(f$array_replace(f$array_replace(f$array_replace(f$array_replace(f$array_replace(f$array_replace(base_array, replacements_1), + replacements_2), + replacements_3), + replacements_4), + replacements_5), + replacements_6), + replacements_7), + replacements_8), + replacements_9), + replacements_10), + replacements_11); +} + +template +array f$array_slice(const array& a, int64_t offset, const mixed& length_var = mixed(), bool preserve_keys = false) noexcept { auto size = a.count(); int64_t length = 0; @@ -522,12 +508,12 @@ array f$array_slice(const array &a, int64_t offset, const mixed &length_va return result; } -template{}, int64_t, double>> -ReturnT f$array_sum(const array &a) noexcept { +template {}, int64_t, double>> +ReturnT f$array_sum(const array& a) noexcept { static_assert(!std::is_same_v, "int is forbidden"); ReturnT result = 0; - for (const auto &it : a) { + for (const auto& it : a) { if constexpr (std::is_same_v) { result += it.get_value(); } else { @@ -537,9 +523,9 @@ ReturnT f$array_sum(const array &a) noexcept { return result; } -template -typename array::key_type f$array_search(const T1 &val, const array &a, bool strict = false) noexcept { - for (const auto &it : a) { +template +typename array::key_type f$array_search(const T1& val, const array& a, bool strict = false) noexcept { + for (const auto& it : a) { if (strict ? equals(it.get_value(), val) : eq2(it.get_value(), val)) { return it.get_key(); } @@ -548,16 +534,16 @@ typename array::key_type f$array_search(const T1 &val, const array &a, boo return typename array::key_type(false); } -template -bool f$in_array(const T1 &value, const array &a, bool strict = false) noexcept { +template +bool f$in_array(const T1& value, const array& a, bool strict = false) noexcept { if (!strict) { - for (const auto &it : a) { + for (const auto& it : a) { if (eq2(it.get_value(), value)) { return true; } } } else { - for (const auto &it : a) { + for (const auto& it : a) { if (equals(it.get_value(), value)) { return true; } @@ -566,29 +552,29 @@ bool f$in_array(const T1 &value, const array &a, bool strict = false) noexcep return false; } -template -int64_t f$array_push(array &a, const T2 &val) noexcept { +template +int64_t f$array_push(array& a, const T2& val) noexcept { a.push_back(val); return a.count(); } -template -int64_t f$array_push(array &a, const T2 &val2, const T3 &val3) noexcept { +template +int64_t f$array_push(array& a, const T2& val2, const T3& val3) noexcept { a.push_back(val2); a.push_back(val3); return a.count(); } -template -int64_t f$array_push(array &a, const T2 &val2, const T3 &val3, const T4 &val4) noexcept { +template +int64_t f$array_push(array& a, const T2& val2, const T3& val3, const T4& val4) noexcept { a.push_back(val2); a.push_back(val3); a.push_back(val4); return a.count(); } -template -int64_t f$array_push(array &a, const T2 &val2, const T3 &val3, const T4 &val4, const T5 &val5) noexcept { +template +int64_t f$array_push(array& a, const T2& val2, const T3& val3, const T4& val4, const T5& val5) noexcept { a.push_back(val2); a.push_back(val3); a.push_back(val4); @@ -596,8 +582,8 @@ int64_t f$array_push(array &a, const T2 &val2, const T3 &val3, const T4 &val return a.count(); } -template -int64_t f$array_push(array &a, const T2 &val2, const T3 &val3, const T4 &val4, const T5 &val5, const T6 &val6) noexcept { +template +int64_t f$array_push(array& a, const T2& val2, const T3& val3, const T4& val4, const T5& val5, const T6& val6) noexcept { a.push_back(val2); a.push_back(val3); a.push_back(val4); @@ -606,126 +592,126 @@ int64_t f$array_push(array &a, const T2 &val2, const T3 &val3, const T4 &val return a.count(); } -template -T f$array_pop(array &a) noexcept { +template +T f$array_pop(array& a) noexcept { return a.pop(); } -template -T f$array_unset(array &arr, int64_t key) noexcept { +template +T f$array_unset(array& arr, int64_t key) noexcept { return arr.unset(key); } -template -T f$array_unset(array &arr, const string &key) noexcept { +template +T f$array_unset(array& arr, const string& key) noexcept { return arr.unset(key); } -template -T f$array_unset(array &arr, const mixed &key) noexcept { +template +T f$array_unset(array& arr, const mixed& key) noexcept { return arr.unset(key); } -template -bool f$array_is_vector(const array &a) noexcept { +template +bool f$array_is_vector(const array& a) noexcept { return a.is_vector(); } -template -bool f$array_is_list(const array &a) noexcept { +template +bool f$array_is_list(const array& a) noexcept { // is_vector() is fast, but not enough; // is_pseudo_vector() doesn't cover is_vector() case, // so we need to call both of them to get the precise and PHP-compatible answer return a.is_vector() || a.is_pseudo_vector(); } -template -void f$sort(array &a, int64_t flag = SORT_REGULAR) { +template +void f$sort(array& a, int64_t flag = SORT_REGULAR) { switch (flag) { - case SORT_REGULAR: - return a.sort(array_functions_impl_::sort_compare(), true); - case SORT_NUMERIC: - return a.sort(array_functions_impl_::sort_compare_numeric(), true); - case SORT_STRING: - return a.sort(array_functions_impl_::sort_compare_string(), true); - default: - php_warning("Unsupported sort_flag in function sort"); + case SORT_REGULAR: + return a.sort(array_functions_impl_::sort_compare(), true); + case SORT_NUMERIC: + return a.sort(array_functions_impl_::sort_compare_numeric(), true); + case SORT_STRING: + return a.sort(array_functions_impl_::sort_compare_string(), true); + default: + php_warning("Unsupported sort_flag in function sort"); } } -template -void f$rsort(array &a, int64_t flag = SORT_REGULAR) { +template +void f$rsort(array& a, int64_t flag = SORT_REGULAR) { switch (flag) { - case SORT_REGULAR: - return a.sort(array_functions_impl_::rsort_compare(), true); - case SORT_NUMERIC: - return a.sort(array_functions_impl_::rsort_compare_numeric(), true); - case SORT_STRING: - return a.sort(array_functions_impl_::rsort_compare_string(), true); - default: - php_warning("Unsupported sort_flag in function rsort"); + case SORT_REGULAR: + return a.sort(array_functions_impl_::rsort_compare(), true); + case SORT_NUMERIC: + return a.sort(array_functions_impl_::rsort_compare_numeric(), true); + case SORT_STRING: + return a.sort(array_functions_impl_::rsort_compare_string(), true); + default: + php_warning("Unsupported sort_flag in function rsort"); } } -template -void f$arsort(array &a, int64_t flag = SORT_REGULAR) { +template +void f$arsort(array& a, int64_t flag = SORT_REGULAR) { switch (flag) { - case SORT_REGULAR: - return a.sort(array_functions_impl_::rsort_compare(), false); - case SORT_NUMERIC: - return a.sort(array_functions_impl_::rsort_compare_numeric(), false); - case SORT_STRING: - return a.sort(array_functions_impl_::rsort_compare_string(), false); - default: - php_warning("Unsupported sort_flag in function arsort"); + case SORT_REGULAR: + return a.sort(array_functions_impl_::rsort_compare(), false); + case SORT_NUMERIC: + return a.sort(array_functions_impl_::rsort_compare_numeric(), false); + case SORT_STRING: + return a.sort(array_functions_impl_::rsort_compare_string(), false); + default: + php_warning("Unsupported sort_flag in function arsort"); } } -template -void f$ksort(array &a, int64_t flag = SORT_REGULAR) { +template +void f$ksort(array& a, int64_t flag = SORT_REGULAR) { switch (flag) { - case SORT_REGULAR: - return a.ksort(array_functions_impl_::sort_compare::key_type>()); - case SORT_NUMERIC: - return a.ksort(array_functions_impl_::sort_compare_numeric::key_type>()); - case SORT_STRING: - return a.ksort(array_functions_impl_::sort_compare_string::key_type>()); - default: - php_warning("Unsupported sort_flag in function ksort"); + case SORT_REGULAR: + return a.ksort(array_functions_impl_::sort_compare::key_type>()); + case SORT_NUMERIC: + return a.ksort(array_functions_impl_::sort_compare_numeric::key_type>()); + case SORT_STRING: + return a.ksort(array_functions_impl_::sort_compare_string::key_type>()); + default: + php_warning("Unsupported sort_flag in function ksort"); } } -template -void f$krsort(array &a, int64_t flag = SORT_REGULAR) { +template +void f$krsort(array& a, int64_t flag = SORT_REGULAR) { switch (flag) { - case SORT_REGULAR: - return a.ksort(array_functions_impl_::rsort_compare::key_type>()); - case SORT_NUMERIC: - return a.ksort(array_functions_impl_::rsort_compare_numeric::key_type>()); - case SORT_STRING: - return a.ksort(array_functions_impl_::rsort_compare_string::key_type>()); - default: - php_warning("Unsupported sort_flag in function krsort"); + case SORT_REGULAR: + return a.ksort(array_functions_impl_::rsort_compare::key_type>()); + case SORT_NUMERIC: + return a.ksort(array_functions_impl_::rsort_compare_numeric::key_type>()); + case SORT_STRING: + return a.ksort(array_functions_impl_::rsort_compare_string::key_type>()); + default: + php_warning("Unsupported sort_flag in function krsort"); } } -template -void f$asort(array &a, int64_t flag = SORT_REGULAR) { +template +void f$asort(array& a, int64_t flag = SORT_REGULAR) { switch (flag) { - case SORT_REGULAR: - return a.sort(array_functions_impl_::sort_compare(), false); - case SORT_NUMERIC: - return a.sort(array_functions_impl_::sort_compare_numeric(), false); - case SORT_STRING: - return a.sort(array_functions_impl_::sort_compare_string(), false); - default: - php_warning("Unsupported sort_flag in function asort"); + case SORT_REGULAR: + return a.sort(array_functions_impl_::sort_compare(), false); + case SORT_NUMERIC: + return a.sort(array_functions_impl_::sort_compare_numeric(), false); + case SORT_STRING: + return a.sort(array_functions_impl_::sort_compare_string(), false); + default: + php_warning("Unsupported sort_flag in function asort"); } } -template -void f$natsort(array &a) { +template +void f$natsort(array& a) { return a.sort(array_functions_impl_::sort_compare_natural::key_type>(), false); } -array f$range(const mixed &from, const mixed &to, int64_t step = 1); +array f$range(const mixed& from, const mixed& to, int64_t step = 1); diff --git a/runtime-common/stdlib/array/to-array-processor.h b/runtime-common/stdlib/array/to-array-processor.h index 2eab2ef7e0..d6dd36066f 100644 --- a/runtime-common/stdlib/array/to-array-processor.h +++ b/runtime-common/stdlib/array/to-array-processor.h @@ -14,7 +14,7 @@ class ShapeKeyDemangle : vk::not_copyable { public: friend class vk::singleton; - void init(std::unordered_map &&shape_keys_storage) noexcept { + void init(std::unordered_map&& shape_keys_storage) noexcept { inited_ = true; shape_keys_storage_ = std::move(shape_keys_storage); } @@ -35,43 +35,40 @@ class ShapeKeyDemangle : vk::not_copyable { class ToArrayVisitor { public: - explicit ToArrayVisitor(bool with_class_names) - : with_class_names_(with_class_names) {} + explicit ToArrayVisitor(bool with_class_names) : with_class_names_(with_class_names) {} - array flush_result() && noexcept { - return std::move(result_); - } + array flush_result() && noexcept { return std::move(result_); } - template - void operator()(const char *field_name, const T &value) { + template + void operator()(const char* field_name, const T& value) { process_impl(field_name, value); } - template - static void process_tuple(const std::tuple &tuple, ToArrayVisitor &visitor, std::index_sequence /*indexes*/) { + template + static void process_tuple(const std::tuple& tuple, ToArrayVisitor& visitor, std::index_sequence /*indexes*/) { (visitor.process_impl("", std::get(tuple)), ...); } - template - static void process_shape(const shape, T...> &shape, ToArrayVisitor &visitor) { - auto &demangler = vk::singleton::get(); + template + static void process_shape(const shape, T...>& shape, ToArrayVisitor& visitor) { + auto& demangler = vk::singleton::get(); (visitor.process_impl(demangler.get_key_by(Is).data(), shape.template get()), ...); } private: - template - void process_impl(const char *field_name, const T &value) { + template + void process_impl(const char* field_name, const T& value) { add_value(field_name, value); } - template - void process_impl(const char *field_name, const Optional &value) { - auto process_impl_lambda = [this, field_name](const auto &v) { return this->process_impl(field_name, v); }; + template + void process_impl(const char* field_name, const Optional& value) { + auto process_impl_lambda = [this, field_name](const auto& v) { return this->process_impl(field_name, v); }; call_fun_on_optional_value(process_impl_lambda, value); } - template - void process_impl(const char *field_name, const array &value) { + template + void process_impl(const char* field_name, const array& value) { array converted_value(value.size()); for (auto it = value.begin(); it != value.end(); ++it) { process_impl("", it.get_value()); @@ -81,13 +78,13 @@ class ToArrayVisitor { add_value(field_name, converted_value); } - template - void process_impl(const char *field_name, const class_instance &instance) { + template + void process_impl(const char* field_name, const class_instance& instance) { add_value(field_name, instance.is_null() ? mixed{} : f$to_array_debug(instance, with_class_names_)); } - template - void process_impl(const char *field_name, const std::tuple &value) { + template + void process_impl(const char* field_name, const std::tuple& value) { ToArrayVisitor tuple_processor{with_class_names_}; tuple_processor.result_.reserve(sizeof...(Args), true); @@ -95,8 +92,8 @@ class ToArrayVisitor { add_value(field_name, std::move(tuple_processor).flush_result()); } - template - void process_impl(const char *field_name, const shape, T...> &value) { + template + void process_impl(const char* field_name, const shape, T...>& value) { ToArrayVisitor shape_processor{with_class_names_}; shape_processor.result_.reserve(sizeof...(Is), true); @@ -104,8 +101,8 @@ class ToArrayVisitor { add_value(field_name, std::move(shape_processor).flush_result()); } - template - void add_value(const char *field_name, T &&value) { + template + void add_value(const char* field_name, T&& value) { if (field_name[0] != '\0') { result_.set_value(string{field_name}, std::forward(value)); } else { @@ -117,8 +114,8 @@ class ToArrayVisitor { bool with_class_names_{false}; }; -template -array f$to_array_debug(const class_instance &klass, bool with_class_names = false) { +template +array f$to_array_debug(const class_instance& klass, bool with_class_names = false) { array result; if (klass.is_null()) { return result; @@ -136,31 +133,31 @@ array f$to_array_debug(const class_instance &klass, bool with_class_na return result; } -template -array f$to_array_debug(const std::tuple &tuple, bool with_class_names = false) { +template +array f$to_array_debug(const std::tuple& tuple, bool with_class_names = false) { ToArrayVisitor visitor{with_class_names}; ToArrayVisitor::process_tuple(tuple, visitor, std::index_sequence_for{}); return std::move(visitor).flush_result(); } -template -array f$to_array_debug(const shape, T...> &shape, bool with_class_names = false) { +template +array f$to_array_debug(const shape, T...>& shape, bool with_class_names = false) { ToArrayVisitor visitor{with_class_names}; ToArrayVisitor::process_shape(shape, visitor); return std::move(visitor).flush_result(); } -template -array f$instance_to_array(const class_instance &klass, bool with_class_names = false) { +template +array f$instance_to_array(const class_instance& klass, bool with_class_names = false) { return f$to_array_debug(klass, with_class_names); } -template -array f$instance_to_array(const std::tuple &tuple, bool with_class_names = false) { +template +array f$instance_to_array(const std::tuple& tuple, bool with_class_names = false) { return f$to_array_debug(tuple, with_class_names); } -template -array f$instance_to_array(const shape, T...> &shape, bool with_class_names = false) { +template +array f$instance_to_array(const shape, T...>& shape, bool with_class_names = false) { return f$to_array_debug(shape, with_class_names); } diff --git a/runtime-common/stdlib/math/bcmath-functions.cpp b/runtime-common/stdlib/math/bcmath-functions.cpp index 1bcbc9429b..56d199a155 100644 --- a/runtime-common/stdlib/math/bcmath-functions.cpp +++ b/runtime-common/stdlib/math/bcmath-functions.cpp @@ -21,7 +21,7 @@ string bc_zero(int scale) noexcept { namespace legacy { // parse a number into parts, returns scale on success and -1 on error -int bc_parse_number_impl(const string &s, int &lsign, int &lint, int &ldot, int &lfrac, int &lscale) noexcept { +int bc_parse_number_impl(const string& s, int& lsign, int& lint, int& ldot, int& lfrac, int& lscale) noexcept { int i = 0; lsign = 1; if (s[i] == '-' || s[i] == '+') { @@ -70,7 +70,7 @@ int bc_parse_number_impl(const string &s, int &lsign, int &lint, int &ldot, int return lscale; } -int bc_comp_impl(const char *lhs, int lint, int ldot, int lfrac, int lscale, const char *rhs, int rint, int rdot, int rfrac, int rscale, int scale) noexcept { +int bc_comp_impl(const char* lhs, int lint, int ldot, int lfrac, int lscale, const char* rhs, int rint, int rdot, int rfrac, int rscale, int scale) noexcept { int llen = ldot - lint; int rlen = rdot - rint; @@ -96,7 +96,7 @@ int bc_comp_impl(const char *lhs, int lint, int ldot, int lfrac, int lscale, con return 0; } -string bc_round(char *lhs, int lint, int ldot, int lfrac, int lscale, int scale, int sign, int add_trailing_zeroes) noexcept { +string bc_round(char* lhs, int lint, int ldot, int lfrac, int lscale, int scale, int sign, int add_trailing_zeroes) noexcept { while (lhs[lint] == '0' && lint + 1 < ldot) { lint++; } @@ -138,7 +138,7 @@ string bc_round(char *lhs, int lint, int ldot, int lfrac, int lscale, int scale, } } -string bc_add_positive(const char *lhs, int lint, int ldot, int lfrac, int lscale, const char *rhs, int rint, int rdot, int rfrac, int rscale, int scale, +string bc_add_positive(const char* lhs, int lint, int ldot, int lfrac, int lscale, const char* rhs, int rint, int rdot, int rfrac, int rscale, int scale, int sign) noexcept { int llen = ldot - lint; int rlen = rdot - rint; @@ -191,7 +191,7 @@ string bc_add_positive(const char *lhs, int lint, int ldot, int lfrac, int lscal return bc_round(result.buffer(), resint, resdot, resfrac, resscale, scale, sign, 1); } -string bc_sub_positive(const char *lhs, int lint, int ldot, int lfrac, int lscale, const char *rhs, int rint, int rdot, int rfrac, int rscale, int scale, +string bc_sub_positive(const char* lhs, int lint, int ldot, int lfrac, int lscale, const char* rhs, int rint, int rdot, int rfrac, int rscale, int scale, int sign) noexcept { int llen = ldot - lint; int rlen = rdot - rint; @@ -254,7 +254,7 @@ string bc_sub_positive(const char *lhs, int lint, int ldot, int lfrac, int lscal return bc_round(result.buffer(), resint, resdot, resfrac, resscale, scale, sign, 1); } -string bc_mul_positive_impl(const char *lhs, int lint, int ldot, int lfrac, int lscale, const char *rhs, int rint, int rdot, int rfrac, int rscale, int scale, +string bc_mul_positive_impl(const char* lhs, int lint, int ldot, int lfrac, int lscale, const char* rhs, int rint, int rdot, int rfrac, int rscale, int scale, int sign) noexcept { int llen = ldot - lint; int rlen = rdot - rint; @@ -266,7 +266,7 @@ string bc_mul_positive_impl(const char *lhs, int lint, int ldot, int lfrac, int int result_size = result_len + result_scale + 3; string result(static_cast(result_size), false); - int *res = (int *)RuntimeAllocator::get().alloc0_script_memory(static_cast(sizeof(int) * result_size)); + int* res = (int*)RuntimeAllocator::get().alloc0_script_memory(static_cast(sizeof(int) * result_size)); for (int i = -lscale; i < llen; i++) { int x = (i < 0 ? lhs[lfrac - i - 1] : lhs[ldot - i - 1]) - '0'; for (int j = -rscale; j < rlen; j++) { @@ -301,7 +301,7 @@ string bc_mul_positive_impl(const char *lhs, int lint, int ldot, int lfrac, int return bc_round(result.buffer(), resint, resdot, resfrac, resscale, scale, sign, 1); } -string bc_div_positive_impl(const char *lhs, int lint, int ldot, int lfrac, int lscale, const char *rhs, int rint, int rdot, int rfrac, int rscale, int scale, +string bc_div_positive_impl(const char* lhs, int lint, int ldot, int lfrac, int lscale, const char* rhs, int rint, int rdot, int rfrac, int rscale, int scale, int sign) noexcept { int llen = ldot - lint; int rlen = rdot - rint; @@ -319,8 +319,8 @@ string bc_div_positive_impl(const char *lhs, int lint, int ldot, int lfrac, int int dividend_len = llen + lscale; int divider_len = rlen + rscale; - int *dividend = (int *)RuntimeAllocator::get().alloc0_script_memory(static_cast(sizeof(int) * (result_size + dividend_len + divider_len))); - int *divider = (int *)RuntimeAllocator::get().alloc_script_memory(static_cast(sizeof(int) * divider_len)); + int* dividend = (int*)RuntimeAllocator::get().alloc0_script_memory(static_cast(sizeof(int) * (result_size + dividend_len + divider_len))); + int* divider = (int*)RuntimeAllocator::get().alloc_script_memory(static_cast(sizeof(int) * divider_len)); for (int i = -lscale; i < llen; i++) { int x = (i < 0 ? lhs[lfrac - i - 1] : lhs[ldot - i - 1]) - '0'; @@ -416,7 +416,7 @@ string bc_div_positive_impl(const char *lhs, int lint, int ldot, int lfrac, int return bc_round(result.buffer(), resint, resdot, resfrac, resscale, scale, sign, 0); } -string bc_add_impl(const char *lhs, int lsign, int lint, int ldot, int lfrac, int lscale, const char *rhs, int rsign, int rint, int rdot, int rfrac, int rscale, +string bc_add_impl(const char* lhs, int lsign, int lint, int ldot, int lfrac, int lscale, const char* rhs, int rsign, int rint, int rdot, int rfrac, int rscale, int scale) noexcept { if (lsign > 0 && rsign > 0) { return bc_add_positive(lhs, lint, ldot, lfrac, lscale, rhs, rint, rdot, rfrac, rscale, scale, 1); @@ -447,34 +447,34 @@ string bc_add_impl(const char *lhs, int lsign, int lint, int ldot, int lfrac, in } // namespace legacy -int bc_comp(const bcmath_impl_::BcNum &lhs, const bcmath_impl_::BcNum &rhs, int scale) noexcept { +int bc_comp(const bcmath_impl_::BcNum& lhs, const bcmath_impl_::BcNum& rhs, int scale) noexcept { return legacy::bc_comp_impl(lhs.str.c_str(), lhs.n_int, lhs.n_dot, lhs.n_frac, lhs.n_scale, rhs.str.c_str(), rhs.n_int, rhs.n_dot, rhs.n_frac, rhs.n_scale, scale); } -string bc_mul_positive(const bcmath_impl_::BcNum &lhs, const bcmath_impl_::BcNum &rhs, int scale, int sign) noexcept { +string bc_mul_positive(const bcmath_impl_::BcNum& lhs, const bcmath_impl_::BcNum& rhs, int scale, int sign) noexcept { return legacy::bc_mul_positive_impl(lhs.str.c_str(), lhs.n_int, lhs.n_dot, lhs.n_frac, lhs.n_scale, rhs.str.c_str(), rhs.n_int, rhs.n_dot, rhs.n_frac, rhs.n_scale, scale, sign); } -string bc_div_positive(const bcmath_impl_::BcNum &lhs, const bcmath_impl_::BcNum &rhs, int scale, int sign) noexcept { +string bc_div_positive(const bcmath_impl_::BcNum& lhs, const bcmath_impl_::BcNum& rhs, int scale, int sign) noexcept { return legacy::bc_div_positive_impl(lhs.str.c_str(), lhs.n_int, lhs.n_dot, lhs.n_frac, lhs.n_scale, rhs.str.c_str(), rhs.n_int, rhs.n_dot, rhs.n_frac, rhs.n_scale, scale, sign); } -string bc_add(const bcmath_impl_::BcNum &lhs, const bcmath_impl_::BcNum &rhs, int scale) noexcept { +string bc_add(const bcmath_impl_::BcNum& lhs, const bcmath_impl_::BcNum& rhs, int scale) noexcept { return legacy::bc_add_impl(lhs.str.c_str(), lhs.n_sign, lhs.n_int, lhs.n_dot, lhs.n_frac, lhs.n_scale, rhs.str.c_str(), rhs.n_sign, rhs.n_int, rhs.n_dot, rhs.n_frac, rhs.n_scale, scale); } -string bc_sub(const bcmath_impl_::BcNum &lhs, const bcmath_impl_::BcNum &rhs, int scale) noexcept { +string bc_sub(const bcmath_impl_::BcNum& lhs, const bcmath_impl_::BcNum& rhs, int scale) noexcept { return legacy::bc_add_impl(lhs.str.c_str(), lhs.n_sign, lhs.n_int, lhs.n_dot, lhs.n_frac, lhs.n_scale, rhs.str.c_str(), (-1) * rhs.n_sign, rhs.n_int, rhs.n_dot, rhs.n_frac, rhs.n_scale, scale); } } // namespace -std::pair bcmath_impl_::bc_parse_number(const string &num) noexcept { +std::pair bcmath_impl_::bc_parse_number(const string& num) noexcept { BcNum bc_num; bc_num.str = num; bool success = legacy::bc_parse_number_impl(num, bc_num.n_sign, bc_num.n_int, bc_num.n_dot, bc_num.n_frac, bc_num.n_scale) >= 0; @@ -482,7 +482,7 @@ std::pair bcmath_impl_::bc_parse_number(const string } void f$bcscale(int64_t scale) noexcept { - auto &math_lib_context{MathLibContext::get()}; + auto& math_lib_context{MathLibContext::get()}; if (scale < 0) { math_lib_context.bc_scale = 0; } else { @@ -490,9 +490,9 @@ void f$bcscale(int64_t scale) noexcept { } } -string f$bcdiv(const string &lhs_str, const string &rhs_str, int64_t scale) noexcept { - auto &math_lib_context{MathLibContext::get()}; - const auto &math_lib_constants{MathLibConstants::get()}; +string f$bcdiv(const string& lhs_str, const string& rhs_str, int64_t scale) noexcept { + auto& math_lib_context{MathLibContext::get()}; + const auto& math_lib_constants{MathLibConstants::get()}; if (scale == std::numeric_limits::min()) { scale = math_lib_context.bc_scale; } @@ -523,7 +523,7 @@ string f$bcdiv(const string &lhs_str, const string &rhs_str, int64_t scale) noex return bc_div_positive(lhs, rhs, static_cast(scale), lhs.n_sign * rhs.n_sign); } -static string scale_num(const string &num, int64_t scale) noexcept { +static string scale_num(const string& num, int64_t scale) noexcept { if (scale > 0) { string result = num; result.append(1, '.'); @@ -533,9 +533,9 @@ static string scale_num(const string &num, int64_t scale) noexcept { return num; } -string f$bcmod(const string &lhs_str, const string &rhs_str, int64_t scale) noexcept { - auto &math_lib_context{MathLibContext::get()}; - const auto &math_lib_constants{MathLibConstants::get()}; +string f$bcmod(const string& lhs_str, const string& rhs_str, int64_t scale) noexcept { + auto& math_lib_context{MathLibContext::get()}; + const auto& math_lib_constants{MathLibConstants::get()}; if (scale == std::numeric_limits::min()) { scale = math_lib_context.bc_scale; } @@ -584,7 +584,7 @@ string f$bcmod(const string &lhs_str, const string &rhs_str, int64_t scale) noex return bc_div_positive(x, math_lib_constants.BC_NUM_ONE, scale, result_sign); } -static std::pair bc_num2int(const bcmath_impl_::BcNum &num) noexcept { +static std::pair bc_num2int(const bcmath_impl_::BcNum& num) noexcept { if (num.n_dot - num.n_int > 18) { return {0, false}; } @@ -600,9 +600,9 @@ static std::pair bc_num2int(const bcmath_impl_::BcNum &num) return {ingeger, true}; } -string f$bcpow(const string &lhs_str, const string &rhs_str, int64_t scale) noexcept { - auto &math_lib_context{MathLibContext::get()}; - const auto &math_lib_constants{MathLibConstants::get()}; +string f$bcpow(const string& lhs_str, const string& rhs_str, int64_t scale) noexcept { + auto& math_lib_context{MathLibContext::get()}; + const auto& math_lib_constants{MathLibConstants::get()}; if (scale == std::numeric_limits::min()) { scale = math_lib_context.bc_scale; } @@ -672,7 +672,7 @@ string f$bcpow(const string &lhs_str, const string &rhs_str, int64_t scale) noex string result = temp; if (neg) { - const bcmath_impl_::BcNum &temp_bc_num = bcmath_impl_::bc_parse_number(temp).first; + const bcmath_impl_::BcNum& temp_bc_num = bcmath_impl_::bc_parse_number(temp).first; if (bc_comp(temp_bc_num, math_lib_constants.BC_NUM_ZERO, temp_bc_num.n_scale) != 0) { result = f$bcdiv(math_lib_constants.ONE, temp, rscale); } @@ -681,8 +681,8 @@ string f$bcpow(const string &lhs_str, const string &rhs_str, int64_t scale) noex return f$bcadd(result, math_lib_constants.ZERO, scale); } -string f$bcadd(const string &lhs_str, const string &rhs_str, int64_t scale) noexcept { - const auto &math_lib_constants{MathLibConstants::get()}; +string f$bcadd(const string& lhs_str, const string& rhs_str, int64_t scale) noexcept { + const auto& math_lib_constants{MathLibConstants::get()}; if (lhs_str.empty()) { return f$bcadd(math_lib_constants.ZERO, rhs_str, scale); } @@ -713,8 +713,8 @@ string f$bcadd(const string &lhs_str, const string &rhs_str, int64_t scale) noex return bc_add(lhs, rhs, static_cast(scale)); } -string f$bcsub(const string &lhs_str, const string &rhs_str, int64_t scale) noexcept { - const auto &math_lib_constants{MathLibConstants::get()}; +string f$bcsub(const string& lhs_str, const string& rhs_str, int64_t scale) noexcept { + const auto& math_lib_constants{MathLibConstants::get()}; if (lhs_str.empty()) { return f$bcsub(math_lib_constants.ZERO, rhs_str, scale); } @@ -747,8 +747,8 @@ string f$bcsub(const string &lhs_str, const string &rhs_str, int64_t scale) noex return bc_add(lhs, rhs, static_cast(scale)); } -string f$bcmul(const string &lhs_str, const string &rhs_str, int64_t scale) noexcept { - const auto &math_lib_constants{MathLibConstants::get()}; +string f$bcmul(const string& lhs_str, const string& rhs_str, int64_t scale) noexcept { + const auto& math_lib_constants{MathLibConstants::get()}; if (lhs_str.empty()) { return f$bcmul(math_lib_constants.ZERO, rhs_str, scale); } @@ -779,8 +779,8 @@ string f$bcmul(const string &lhs_str, const string &rhs_str, int64_t scale) noex return bc_mul_positive(lhs, rhs, static_cast(scale), lhs.n_sign * rhs.n_sign); } -int64_t f$bccomp(const string &lhs_str, const string &rhs_str, int64_t scale) noexcept { - const auto &math_lib_constants{MathLibConstants::get()}; +int64_t f$bccomp(const string& lhs_str, const string& rhs_str, int64_t scale) noexcept { + const auto& math_lib_constants{MathLibConstants::get()}; if (lhs_str.empty()) { return f$bccomp(math_lib_constants.ZERO, rhs_str, scale); } @@ -818,7 +818,7 @@ int64_t f$bccomp(const string &lhs_str, const string &rhs_str, int64_t scale) no // In some places we need to check if the number NUM is almost zero. // Specifically, all but the last digit is 0 and the last digit is 1. // Last digit is defined by scale. -static bool bc_is_near_zero(const bcmath_impl_::BcNum &num, int scale) noexcept { +static bool bc_is_near_zero(const bcmath_impl_::BcNum& num, int scale) noexcept { if (scale > num.n_scale) { scale = num.n_scale; } @@ -835,7 +835,7 @@ static bool bc_is_near_zero(const bcmath_impl_::BcNum &num, int scale) noexcept } const int count = scale - 1; - const char *ptr = num.str.c_str() + num.n_frac; + const char* ptr = num.str.c_str() + num.n_frac; for (int i = 0; i < count; ++i) { if (ptr[i] != '0') { @@ -846,8 +846,8 @@ static bool bc_is_near_zero(const bcmath_impl_::BcNum &num, int scale) noexcept return ptr[count] == '1' || ptr[count] == '0'; } -static std::pair bc_sqrt_calc_initial_guess(const bcmath_impl_::BcNum &num, int cmp_with_one) noexcept { - const auto &math_lib_constants{MathLibConstants::get()}; +static std::pair bc_sqrt_calc_initial_guess(const bcmath_impl_::BcNum& num, int cmp_with_one) noexcept { + const auto& math_lib_constants{MathLibConstants::get()}; if (cmp_with_one < 0) { // the number is between 0 and 1. Guess should start at 1. return {math_lib_constants.BC_NUM_ONE, num.n_scale}; @@ -860,8 +860,8 @@ static std::pair bc_sqrt_calc_initial_guess(const bcma return {std::move(guess), 3}; } -static std::pair bc_sqrt(const bcmath_impl_::BcNum &num, int scale) noexcept { - const auto &math_lib_constants{MathLibConstants::get()}; +static std::pair bc_sqrt(const bcmath_impl_::BcNum& num, int scale) noexcept { + const auto& math_lib_constants{MathLibConstants::get()}; // initial checks const int cmp_zero = bc_comp(num, math_lib_constants.BC_NUM_ZERO, num.n_scale); if (cmp_zero < 0 || num.n_sign == -1) { @@ -907,7 +907,7 @@ static std::pair bc_sqrt(const bcmath_impl_::BcNum &num, int scale return {bc_div_positive(guess, math_lib_constants.BC_NUM_ONE, rscale, 1), true}; } -string f$bcsqrt(const string &num_str, int64_t scale) noexcept { +string f$bcsqrt(const string& num_str, int64_t scale) noexcept { if (scale == std::numeric_limits::min()) { scale = MathLibContext::get().bc_scale; } @@ -931,6 +931,6 @@ string f$bcsqrt(const string &num_str, int64_t scale) noexcept { return {}; } - const bcmath_impl_::BcNum &sqrt_bc_num = bcmath_impl_::bc_parse_number(sqrt).first; + const bcmath_impl_::BcNum& sqrt_bc_num = bcmath_impl_::bc_parse_number(sqrt).first; return bc_div_positive(sqrt_bc_num, MathLibConstants::get().BC_NUM_ONE, scale, 1); } diff --git a/runtime-common/stdlib/math/bcmath-functions.h b/runtime-common/stdlib/math/bcmath-functions.h index a0da7fc056..6fd4adbebb 100644 --- a/runtime-common/stdlib/math/bcmath-functions.h +++ b/runtime-common/stdlib/math/bcmath-functions.h @@ -9,24 +9,24 @@ namespace bcmath_impl_ { -std::pair bc_parse_number(const string &num) noexcept; +std::pair bc_parse_number(const string& num) noexcept; } // namespace bcmath_impl_ void f$bcscale(int64_t scale) noexcept; -string f$bcdiv(const string &lhs_str, const string &rhs_str, int64_t scale = std::numeric_limits::min()) noexcept; +string f$bcdiv(const string& lhs_str, const string& rhs_str, int64_t scale = std::numeric_limits::min()) noexcept; -string f$bcmod(const string &lhs_str, const string &rhs_str, int64_t scale = std::numeric_limits::min()) noexcept; +string f$bcmod(const string& lhs_str, const string& rhs_str, int64_t scale = std::numeric_limits::min()) noexcept; -string f$bcpow(const string &lhs_str, const string &rhs_str, int64_t scale = std::numeric_limits::min()) noexcept; +string f$bcpow(const string& lhs_str, const string& rhs_str, int64_t scale = std::numeric_limits::min()) noexcept; -string f$bcadd(const string &lhs_str, const string &rhs_str, int64_t scale = std::numeric_limits::min()) noexcept; +string f$bcadd(const string& lhs_str, const string& rhs_str, int64_t scale = std::numeric_limits::min()) noexcept; -string f$bcsub(const string &lhs_str, const string &rhs_str, int64_t scale = std::numeric_limits::min()) noexcept; +string f$bcsub(const string& lhs_str, const string& rhs_str, int64_t scale = std::numeric_limits::min()) noexcept; -string f$bcmul(const string &lhs_str, const string &rhs_str, int64_t scale = std::numeric_limits::min()) noexcept; +string f$bcmul(const string& lhs_str, const string& rhs_str, int64_t scale = std::numeric_limits::min()) noexcept; -int64_t f$bccomp(const string &lhs_str, const string &rhs_str, int64_t scale = std::numeric_limits::min()) noexcept; +int64_t f$bccomp(const string& lhs_str, const string& rhs_str, int64_t scale = std::numeric_limits::min()) noexcept; -string f$bcsqrt(const string &num_str, int64_t scale = std::numeric_limits::min()) noexcept; +string f$bcsqrt(const string& num_str, int64_t scale = std::numeric_limits::min()) noexcept; diff --git a/runtime-common/stdlib/math/math-context.cpp b/runtime-common/stdlib/math/math-context.cpp index 593490a916..0a50dc1422 100644 --- a/runtime-common/stdlib/math/math-context.cpp +++ b/runtime-common/stdlib/math/math-context.cpp @@ -13,13 +13,10 @@ constexpr std::string_view ZERO_DOT_FIVE_ = "0.5"; } // namespace MathLibConstants::MathLibConstants() noexcept - : ONE(ONE_.data(), static_cast(ONE_.size())) - , ZERO(ZERO_.data(), static_cast(ZERO_.size())) - , TEN(TEN_.data(), static_cast(TEN_.size())) - , ZERO_DOT_FIVE(ZERO_DOT_FIVE_.data(), static_cast(ZERO_DOT_FIVE_.size())) - , BC_NUM_ONE(bcmath_impl_::bc_parse_number(ONE).first) - , BC_NUM_ZERO(bcmath_impl_::bc_parse_number(ZERO).first) - , BC_ZERO_DOT_FIVE(bcmath_impl_::bc_parse_number(ZERO_DOT_FIVE).first) { + : ONE(ONE_.data(), static_cast(ONE_.size())), ZERO(ZERO_.data(), static_cast(ZERO_.size())), + TEN(TEN_.data(), static_cast(TEN_.size())), + ZERO_DOT_FIVE(ZERO_DOT_FIVE_.data(), static_cast(ZERO_DOT_FIVE_.size())), BC_NUM_ONE(bcmath_impl_::bc_parse_number(ONE).first), + BC_NUM_ZERO(bcmath_impl_::bc_parse_number(ZERO).first), BC_ZERO_DOT_FIVE(bcmath_impl_::bc_parse_number(ZERO_DOT_FIVE).first) { ONE.set_reference_counter_to(ExtraRefCnt::for_global_const); ZERO.set_reference_counter_to(ExtraRefCnt::for_global_const); diff --git a/runtime-common/stdlib/math/math-context.h b/runtime-common/stdlib/math/math-context.h index fa9dc43e37..cc83c888e7 100644 --- a/runtime-common/stdlib/math/math-context.h +++ b/runtime-common/stdlib/math/math-context.h @@ -23,7 +23,7 @@ struct BcNum { struct MathLibContext final : vk::not_copyable { int64_t bc_scale{}; - static MathLibContext &get() noexcept; + static MathLibContext& get() noexcept; }; struct MathLibConstants final : vk::not_copyable { @@ -38,5 +38,5 @@ struct MathLibConstants final : vk::not_copyable { MathLibConstants() noexcept; - static const MathLibConstants &get() noexcept; + static const MathLibConstants& get() noexcept; }; diff --git a/runtime-common/stdlib/math/math-functions.cpp b/runtime-common/stdlib/math/math-functions.cpp index 5ffca12848..302592d6cd 100644 --- a/runtime-common/stdlib/math/math-functions.cpp +++ b/runtime-common/stdlib/math/math-functions.cpp @@ -16,7 +16,7 @@ string f$dechex(int64_t number) noexcept { char s[17]; int i = 16; - const auto &lhex_digits{StringLibConstants::get().lhex_digits}; + const auto& lhex_digits{StringLibConstants::get().lhex_digits}; do { s[--i] = lhex_digits[v & 15]; v >>= 4; @@ -25,7 +25,7 @@ string f$dechex(int64_t number) noexcept { return {s + i, static_cast(16 - i)}; } -int64_t f$hexdec(const string &number) noexcept { +int64_t f$hexdec(const string& number) noexcept { uint64_t v = 0; bool bad_str_param = number.empty(); bool overflow = false; diff --git a/runtime-common/stdlib/math/math-functions.h b/runtime-common/stdlib/math/math-functions.h index 99708d485d..d54b4afd4d 100644 --- a/runtime-common/stdlib/math/math-functions.h +++ b/runtime-common/stdlib/math/math-functions.h @@ -13,8 +13,8 @@ namespace math_functions_impl_ { -template -uint64_t mult_and_add(uint64_t x, uint8_t y, bool &overflow) noexcept { +template +uint64_t mult_and_add(uint64_t x, uint8_t y, bool& overflow) noexcept { const uint64_t r = x * M + y; overflow = overflow || r < x || r > static_cast(std::numeric_limits::max()); return r; @@ -34,23 +34,23 @@ inline double f$log(double v) noexcept; inline double f$log(double v, double base) noexcept; -template -inline T f$min(const array &a) noexcept; +template +inline T f$min(const array& a) noexcept; -template -inline T f$max(const array &a) noexcept; +template +inline T f$max(const array& a) noexcept; -template -inline T f$min(const T &arg1) noexcept; +template +inline T f$min(const T& arg1) noexcept; -template -inline T f$min(const T &arg1, const T &arg2, Args &&...args) noexcept; +template +inline T f$min(const T& arg1, const T& arg2, Args&&... args) noexcept; -template -inline T f$max(const T &arg1) noexcept; +template +inline T f$max(const T& arg1) noexcept; -template -inline T f$max(const T &arg1, const T &arg2, Args &&...args) noexcept; +template +inline T f$max(const T& arg1, const T& arg2, Args&&... args) noexcept; inline double f$pi() noexcept; @@ -58,7 +58,7 @@ inline double f$round(double v, int64_t precision = 0) noexcept; inline double f$sqrt(double v) noexcept; -inline mixed f$abs(const mixed &v) noexcept { +inline mixed f$abs(const mixed& v) noexcept { mixed num = v.to_numeric(); if (num.is_int()) { return std::abs(num.to_int()); @@ -66,41 +66,23 @@ inline mixed f$abs(const mixed &v) noexcept { return std::fabs(num.to_float()); } -inline int64_t f$abs(int64_t v) noexcept { - return std::abs(v); -} +inline int64_t f$abs(int64_t v) noexcept { return std::abs(v); } -inline double f$abs(double v) noexcept { - return std::abs(v); -} +inline double f$abs(double v) noexcept { return std::abs(v); } -inline int64_t f$abs(const Optional &v) noexcept { - return f$abs(val(v)); -} +inline int64_t f$abs(const Optional& v) noexcept { return f$abs(val(v)); } -inline int64_t f$abs(const Optional &v) noexcept { - return f$abs(static_cast(val(v))); -} +inline int64_t f$abs(const Optional& v) noexcept { return f$abs(static_cast(val(v))); } -inline double f$abs(const Optional &v) noexcept { - return f$abs(val(v)); -} +inline double f$abs(const Optional& v) noexcept { return f$abs(val(v)); } -inline double f$ceil(double v) noexcept { - return ceil(v); -} +inline double f$ceil(double v) noexcept { return ceil(v); } -inline double f$cos(double v) noexcept { - return cos(v); -} +inline double f$cos(double v) noexcept { return cos(v); } -inline double f$deg2rad(double v) noexcept { - return v * M_PI / 180; -} +inline double f$deg2rad(double v) noexcept { return v * M_PI / 180; } -inline double f$floor(double v) noexcept { - return floor(v); -} +inline double f$floor(double v) noexcept { return floor(v); } inline double f$log(double v) noexcept { if (v <= 0.0) { @@ -116,8 +98,8 @@ inline double f$log(double v, double base) noexcept { return log(v) / log(base); } -template -T f$min(const array &a) noexcept { +template +T f$min(const array& a) noexcept { if (a.count() == 0) { php_warning("Empty array specified to function min"); return T(); @@ -133,8 +115,8 @@ T f$min(const array &a) noexcept { return res; } -template -T f$max(const array &a) noexcept { +template +T f$max(const array& a) noexcept { if (a.count() == 0) { php_warning("Empty array specified to function max"); return T(); @@ -150,29 +132,27 @@ T f$max(const array &a) noexcept { return res; } -template -T f$min(const T &arg1) noexcept { +template +T f$min(const T& arg1) noexcept { return arg1; } -template -T f$min(const T &arg1, const T &arg2, Args &&...args) noexcept { +template +T f$min(const T& arg1, const T& arg2, Args&&... args) noexcept { return f$min(lt(arg1, arg2) ? arg1 : arg2, std::forward(args)...); } -template -T f$max(const T &arg1) noexcept { +template +T f$max(const T& arg1) noexcept { return arg1; } -template -T f$max(const T &arg1, const T &arg2, Args &&...args) noexcept { +template +T f$max(const T& arg1, const T& arg2, Args&&... args) noexcept { return f$max(lt(arg2, arg1) ? arg1 : arg2, std::forward(args)...); } -inline double f$pi() noexcept { - return M_PI; -} +inline double f$pi() noexcept { return M_PI; } inline double f$round(double v, int64_t precision) noexcept { if (std::abs(precision) > 100) { @@ -191,6 +171,6 @@ inline double f$sqrt(double v) noexcept { return sqrt(v); } -int64_t f$hexdec(const string &number) noexcept; +int64_t f$hexdec(const string& number) noexcept; string f$dechex(int64_t number) noexcept; diff --git a/runtime-common/stdlib/serialization/from-json-processor.h b/runtime-common/stdlib/serialization/from-json-processor.h index 2d363baa35..968e4afaa8 100644 --- a/runtime-common/stdlib/serialization/from-json-processor.h +++ b/runtime-common/stdlib/serialization/from-json-processor.h @@ -9,16 +9,14 @@ #include "runtime-common/stdlib/serialization/json-processor-utils.h" #include "runtime-common/stdlib/serialization/serialization-context.h" -template +template class FromJsonVisitor { public: - explicit FromJsonVisitor(const mixed &json, bool flatten_class, JsonPath &json_path) noexcept - : json_(json) - , flatten_class_(flatten_class) - , json_path_(json_path) {} + explicit FromJsonVisitor(const mixed& json, bool flatten_class, JsonPath& json_path) noexcept + : json_(json), flatten_class_(flatten_class), json_path_(json_path) {} - template - void operator()(const char *key, T &value, bool required = false) noexcept { + template + void operator()(const char* key, T& value, bool required = false) noexcept { if (!error_.empty()) { return; } @@ -27,7 +25,7 @@ class FromJsonVisitor { return; } json_path_.enter(key); - const auto *json_value = json_.as_array().find_value(string{key}); + const auto* json_value = json_.as_array().find_value(string{key}); if (required && !json_value) { error_.append("absent required field "); error_.append(json_path_.to_string()); @@ -38,19 +36,13 @@ class FromJsonVisitor { json_path_.leave(); } - bool has_error() const noexcept { - return !error_.empty(); - } - const string &get_error() const noexcept { - return error_; - } + bool has_error() const noexcept { return !error_.empty(); } + const string& get_error() const noexcept { return error_; } - static const char *get_json_obj_magic_key() noexcept { - return "__json_obj_magic"; - } + static const char* get_json_obj_magic_key() noexcept { return "__json_obj_magic"; } private: - [[gnu::noinline]] void on_input_type_mismatch(const mixed &json) noexcept { + [[gnu::noinline]] void on_input_type_mismatch(const mixed& json) noexcept { error_.assign("unexpected type "); if (json.is_array()) { error_.append(json.as_array().is_vector() ? "array" : "object"); @@ -61,7 +53,7 @@ class FromJsonVisitor { error_.append(json_path_.to_string()); } - void do_set(bool &value, const mixed &json) noexcept { + void do_set(bool& value, const mixed& json) noexcept { if (!json.is_bool()) { on_input_type_mismatch(json); return; @@ -69,7 +61,7 @@ class FromJsonVisitor { value = json.as_bool(); } - void do_set(std::int64_t &value, const mixed &json) noexcept { + void do_set(std::int64_t& value, const mixed& json) noexcept { if (!json.is_int()) { on_input_type_mismatch(json); return; @@ -77,7 +69,7 @@ class FromJsonVisitor { value = json.as_int(); } - void do_set(double &value, const mixed &json) noexcept { + void do_set(double& value, const mixed& json) noexcept { if (!json.is_float() && !json.is_int()) { on_input_type_mismatch(json); return; @@ -85,7 +77,7 @@ class FromJsonVisitor { value = json.is_int() ? json.as_int() : json.as_double(); } - void do_set(string &value, const mixed &json) noexcept { + void do_set(string& value, const mixed& json) noexcept { if (!json.is_string()) { on_input_type_mismatch(json); return; @@ -93,7 +85,7 @@ class FromJsonVisitor { value = json.as_string(); } - void do_set(JsonRawString &value, const mixed &json) noexcept { + void do_set(JsonRawString& value, const mixed& json) noexcept { runtime_context_buffer.clean(); if (!impl_::JsonEncoder{0, false, get_json_obj_magic_key()}.encode(json, runtime_context_buffer)) { error_.append("failed to decode @kphp-json raw_string field "); @@ -103,8 +95,8 @@ class FromJsonVisitor { value.str = runtime_context_buffer.str(); } - template - void do_set(Optional &value, const mixed &json) noexcept { + template + void do_set(Optional& value, const mixed& json) noexcept { if (json.is_null()) { value = Optional{}; return; @@ -112,15 +104,15 @@ class FromJsonVisitor { do_set(value.ref(), json); } - template - void do_set(class_instance &klass, const mixed &json) noexcept; + template + void do_set(class_instance& klass, const mixed& json) noexcept; // just don't fail compilation with empty untyped arrays - void do_set(array & /*array*/, const mixed & /*json*/) noexcept {} + void do_set(array& /*array*/, const mixed& /*json*/) noexcept {} - template - void do_set_array(array &array, const mixed &json) noexcept { - const auto &json_array = json.as_array(); + template + void do_set_array(array& array, const mixed& json) noexcept { + const auto& json_array = json.as_array(); const auto array_size = json_array.size(); // overwrite (but not just merge) array data array.clear(); @@ -137,8 +129,8 @@ class FromJsonVisitor { json_path_.leave(); } - template - void do_set(array &array, const mixed &json) noexcept { + template + void do_set(array& array, const mixed& json) noexcept { if (json.is_array()) { do_set_array(array, json); } else { @@ -146,7 +138,7 @@ class FromJsonVisitor { } } - void do_set(mixed &value, const mixed &json) noexcept { + void do_set(mixed& value, const mixed& json) noexcept { if (json.is_array()) { array array; do_set(array, json); @@ -157,15 +149,15 @@ class FromJsonVisitor { } string error_; - const mixed &json_; + const mixed& json_; bool flatten_class_{false}; - JsonPath &json_path_; + JsonPath& json_path_; - string_buffer &runtime_context_buffer{RuntimeContext::get().static_SB}; + string_buffer& runtime_context_buffer{RuntimeContext::get().static_SB}; }; -template -class_instance from_json_impl(const mixed &json, JsonPath &json_path) noexcept { +template +class_instance from_json_impl(const mixed& json, JsonPath& json_path) noexcept { class_instance instance; if constexpr (std::is_empty_v) { instance.empty_alloc(); @@ -184,9 +176,9 @@ class_instance from_json_impl(const mixed &json, JsonPath &json_path) noexcep return SerializationLibContext::get().last_json_processor_error.empty() ? instance : class_instance{}; } -template -template -void FromJsonVisitor::do_set(class_instance &klass, const mixed &json) noexcept { +template +template +void FromJsonVisitor::do_set(class_instance& klass, const mixed& json) noexcept { if constexpr (!impl_::IsJsonFlattenClass::value) { if (json.is_null()) { return; @@ -199,9 +191,9 @@ void FromJsonVisitor::do_set(class_instance &klass, const mixed &json) n klass = from_json_impl(json, json_path_); } -template -ClassName f$JsonEncoder$$from_json_impl(Tag /*tag*/, const string &json_string, const string & /*class_mame*/) noexcept { - auto &msg = SerializationLibContext::get().last_json_processor_error; +template +ClassName f$JsonEncoder$$from_json_impl(Tag /*tag*/, const string& json_string, const string& /*class_mame*/) noexcept { + auto& msg = SerializationLibContext::get().last_json_processor_error; msg = {}; auto [json, success] = json_decode(json_string, FromJsonVisitor::get_json_obj_magic_key()); @@ -222,6 +214,4 @@ ClassName f$JsonEncoder$$from_json_impl(Tag /*tag*/, const string &json_string, return from_json_impl(json, json_path); } -inline string f$JsonEncoder$$getLastError() noexcept { - return SerializationLibContext::get().last_json_processor_error; -} +inline string f$JsonEncoder$$getLastError() noexcept { return SerializationLibContext::get().last_json_processor_error; } diff --git a/runtime-common/stdlib/serialization/json-functions.cpp b/runtime-common/stdlib/serialization/json-functions.cpp index 273d70783f..896d7beb6f 100644 --- a/runtime-common/stdlib/serialization/json-functions.cpp +++ b/runtime-common/stdlib/serialization/json-functions.cpp @@ -12,7 +12,7 @@ // for classes, e.g. `JsonEncoder::encode(new A)`, see json-writer.cpp and from/to visitors namespace { -void json_append_one_char(unsigned int c, string_buffer &sb) noexcept { +void json_append_one_char(unsigned int c, string_buffer& sb) noexcept { sb.append_char('\\'); sb.append_char('u'); sb.append_char("0123456789abcdef"[c >> 12]); @@ -21,7 +21,7 @@ void json_append_one_char(unsigned int c, string_buffer &sb) noexcept { sb.append_char("0123456789abcdef"[c & 15]); } -bool json_append_char(unsigned int c, string_buffer &sb) noexcept { +bool json_append_char(unsigned int c, string_buffer& sb) noexcept { if (c < 0x10000) { if (0xD7FF < c && c < 0xE000) { return false; @@ -38,7 +38,7 @@ bool json_append_char(unsigned int c, string_buffer &sb) noexcept { return false; } -bool do_json_encode_string_php(const JsonPath &json_path, const char *s, int len, int64_t options, string_buffer &sb) noexcept { +bool do_json_encode_string_php(const JsonPath& json_path, const char* s, int len, int64_t options, string_buffer& sb) noexcept { int begin_pos = sb.size(); if (options & JSON_UNESCAPED_UNICODE) { sb.reserve(2 * len + 2); @@ -56,108 +56,108 @@ bool do_json_encode_string_php(const JsonPath &json_path, const char *s, int len for (int pos = 0; pos < len; pos++) { switch (s[pos]) { - case '"': - sb.append_char('\\'); - sb.append_char('"'); - break; - case '\\': - sb.append_char('\\'); - sb.append_char('\\'); - break; - case '/': - sb.append_char('\\'); - sb.append_char('/'); - break; - case '\b': - sb.append_char('\\'); - sb.append_char('b'); - break; - case '\f': - sb.append_char('\\'); - sb.append_char('f'); - break; - case '\n': - sb.append_char('\\'); - sb.append_char('n'); - break; - case '\r': - sb.append_char('\\'); - sb.append_char('r'); - break; - case '\t': - sb.append_char('\\'); - sb.append_char('t'); - break; - case 0 ... 7: - case 11: - case 14 ... 31: - json_append_one_char(s[pos], sb); - break; - case -128 ... - 1: { - const int a = s[pos]; - if ((a & 0x40) == 0) { - return fire_error(pos); - } + case '"': + sb.append_char('\\'); + sb.append_char('"'); + break; + case '\\': + sb.append_char('\\'); + sb.append_char('\\'); + break; + case '/': + sb.append_char('\\'); + sb.append_char('/'); + break; + case '\b': + sb.append_char('\\'); + sb.append_char('b'); + break; + case '\f': + sb.append_char('\\'); + sb.append_char('f'); + break; + case '\n': + sb.append_char('\\'); + sb.append_char('n'); + break; + case '\r': + sb.append_char('\\'); + sb.append_char('r'); + break; + case '\t': + sb.append_char('\\'); + sb.append_char('t'); + break; + case 0 ... 7: + case 11: + case 14 ... 31: + json_append_one_char(s[pos], sb); + break; + case -128 ... - 1: { + const int a = s[pos]; + if ((a & 0x40) == 0) { + return fire_error(pos); + } - const int b = s[++pos]; - if ((b & 0xc0) != 0x80) { + const int b = s[++pos]; + if ((b & 0xc0) != 0x80) { + return fire_error(pos); + } + if ((a & 0x20) == 0) { + if ((a & 0x1e) <= 0) { return fire_error(pos); } - if ((a & 0x20) == 0) { - if ((a & 0x1e) <= 0) { - return fire_error(pos); - } - if (options & JSON_UNESCAPED_UNICODE) { - sb.append_char(static_cast(a)); - sb.append_char(static_cast(b)); - } else if (!json_append_char(((a & 0x1f) << 6) | (b & 0x3f), sb)) { - return fire_error(pos); - } - break; - } - - const int c = s[++pos]; - if ((c & 0xc0) != 0x80) { + if (options & JSON_UNESCAPED_UNICODE) { + sb.append_char(static_cast(a)); + sb.append_char(static_cast(b)); + } else if (!json_append_char(((a & 0x1f) << 6) | (b & 0x3f), sb)) { return fire_error(pos); } - if ((a & 0x10) == 0) { - if (((a & 0x0f) | (b & 0x20)) <= 0) { - return fire_error(pos); - } - if (options & JSON_UNESCAPED_UNICODE) { - sb.append_char(static_cast(a)); - sb.append_char(static_cast(b)); - sb.append_char(static_cast(c)); - } else if (!json_append_char(((a & 0x0f) << 12) | ((b & 0x3f) << 6) | (c & 0x3f), sb)) { - return fire_error(pos); - } - break; - } + break; + } - const int d = s[++pos]; - if ((d & 0xc0) != 0x80) { + const int c = s[++pos]; + if ((c & 0xc0) != 0x80) { + return fire_error(pos); + } + if ((a & 0x10) == 0) { + if (((a & 0x0f) | (b & 0x20)) <= 0) { return fire_error(pos); } - if ((a & 0x08) == 0) { - if (((a & 0x07) | (b & 0x30)) <= 0) { - return fire_error(pos); - } - if (options & JSON_UNESCAPED_UNICODE) { - sb.append_char(static_cast(a)); - sb.append_char(static_cast(b)); - sb.append_char(static_cast(c)); - sb.append_char(static_cast(d)); - } else if (!json_append_char(((a & 0x07) << 18) | ((b & 0x3f) << 12) | ((c & 0x3f) << 6) | (d & 0x3f), sb)) { - return fire_error(pos); - } - break; + if (options & JSON_UNESCAPED_UNICODE) { + sb.append_char(static_cast(a)); + sb.append_char(static_cast(b)); + sb.append_char(static_cast(c)); + } else if (!json_append_char(((a & 0x0f) << 12) | ((b & 0x3f) << 6) | (c & 0x3f), sb)) { + return fire_error(pos); } + break; + } + const int d = s[++pos]; + if ((d & 0xc0) != 0x80) { return fire_error(pos); } - default: - sb.append_char(s[pos]); + if ((a & 0x08) == 0) { + if (((a & 0x07) | (b & 0x30)) <= 0) { + return fire_error(pos); + } + if (options & JSON_UNESCAPED_UNICODE) { + sb.append_char(static_cast(a)); + sb.append_char(static_cast(b)); + sb.append_char(static_cast(c)); + sb.append_char(static_cast(d)); + } else if (!json_append_char(((a & 0x07) << 18) | ((b & 0x3f) << 12) | ((c & 0x3f) << 6) | (d & 0x3f), sb)) { + return fire_error(pos); + } break; + } + + return fire_error(pos); + } + default: + sb.append_char(s[pos]); + break; } } @@ -165,8 +165,8 @@ bool do_json_encode_string_php(const JsonPath &json_path, const char *s, int len return true; } -bool do_json_encode_string_vkext(const char *s, int len, string_buffer &sb) noexcept { - auto &ctx = RuntimeContext::get(); // dirty hack :( +bool do_json_encode_string_vkext(const char* s, int len, string_buffer& sb) noexcept { + auto& ctx = RuntimeContext::get(); // dirty hack :( sb.reserve(2 * len + 2); if (ctx.sb_lib_context.error_flag == STRING_BUFFER_ERROR_FLAG_FAILED) { return false; @@ -178,28 +178,28 @@ bool do_json_encode_string_vkext(const char *s, int len, string_buffer &sb) noex char c = s[pos]; if (unlikely(static_cast(c) < 32U)) { switch (c) { - case '\b': - sb.append_char('\\'); - sb.append_char('b'); - break; - case '\f': - sb.append_char('\\'); - sb.append_char('f'); - break; - case '\n': - sb.append_char('\\'); - sb.append_char('n'); - break; - case '\r': - sb.append_char('\\'); - sb.append_char('r'); - break; - case '\t': - sb.append_char('\\'); - sb.append_char('t'); - break; - default: - break; + case '\b': + sb.append_char('\\'); + sb.append_char('b'); + break; + case '\f': + sb.append_char('\\'); + sb.append_char('f'); + break; + case '\n': + sb.append_char('\\'); + sb.append_char('n'); + break; + case '\r': + sb.append_char('\\'); + sb.append_char('r'); + break; + case '\t': + sb.append_char('\\'); + sb.append_char('t'); + break; + default: + break; } } else { if (c == '"' || c == '\\' || c == '/') { @@ -228,7 +228,7 @@ string JsonPath::to_string() const { result.reserve_at_least((num_parts + 1) * 8); result.push_back('/'); for (unsigned i = 0; i < num_parts; i++) { - const char *key = arr[i]; + const char* key = arr[i]; if (key == nullptr) { // int key indexing result.append("[.]"); @@ -247,12 +247,10 @@ string JsonPath::to_string() const { namespace impl_ { -JsonEncoder::JsonEncoder(int64_t options, bool simple_encode, const char *json_obj_magic_key) noexcept - : options_(options) - , simple_encode_(simple_encode) - , json_obj_magic_key_(json_obj_magic_key) {} +JsonEncoder::JsonEncoder(int64_t options, bool simple_encode, const char* json_obj_magic_key) noexcept + : options_(options), simple_encode_(simple_encode), json_obj_magic_key_(json_obj_magic_key) {} -bool JsonEncoder::encode(bool b, string_buffer &sb) noexcept { +bool JsonEncoder::encode(bool b, string_buffer& sb) noexcept { if (b) { sb.append("true", 4); } else { @@ -261,17 +259,17 @@ bool JsonEncoder::encode(bool b, string_buffer &sb) noexcept { return true; } -bool JsonEncoder::encode_null(string_buffer &sb) const noexcept { +bool JsonEncoder::encode_null(string_buffer& sb) const noexcept { sb.append("null", 4); return true; } -bool JsonEncoder::encode(int64_t i, string_buffer &sb) noexcept { +bool JsonEncoder::encode(int64_t i, string_buffer& sb) noexcept { sb << i; return true; } -bool JsonEncoder::encode(double d, string_buffer &sb) noexcept { +bool JsonEncoder::encode(double d, string_buffer& sb) noexcept { if (vk::any_of_equal(std::fpclassify(d), FP_INFINITE, FP_NAN)) { php_warning("%s: strange double %lf in function json_encode", json_path_.to_string().c_str(), d); if (options_ & JSON_PARTIAL_OUTPUT_ON_ERROR) { @@ -285,26 +283,26 @@ bool JsonEncoder::encode(double d, string_buffer &sb) noexcept { return true; } -bool JsonEncoder::encode(const string &s, string_buffer &sb) noexcept { +bool JsonEncoder::encode(const string& s, string_buffer& sb) noexcept { return simple_encode_ ? do_json_encode_string_vkext(s.c_str(), s.size(), sb) : do_json_encode_string_php(json_path_, s.c_str(), s.size(), options_, sb); } -bool JsonEncoder::encode(const mixed &v, string_buffer &sb) noexcept { +bool JsonEncoder::encode(const mixed& v, string_buffer& sb) noexcept { switch (v.get_type()) { - case mixed::type::NUL: - return encode_null(sb); - case mixed::type::BOOLEAN: - return encode(v.as_bool(), sb); - case mixed::type::INTEGER: - return encode(v.as_int(), sb); - case mixed::type::FLOAT: - return encode(v.as_double(), sb); - case mixed::type::STRING: - return encode(v.as_string(), sb); - case mixed::type::ARRAY: - return encode(v.as_array(), sb); - default: - __builtin_unreachable(); + case mixed::type::NUL: + return encode_null(sb); + case mixed::type::BOOLEAN: + return encode(v.as_bool(), sb); + case mixed::type::INTEGER: + return encode(v.as_int(), sb); + case mixed::type::FLOAT: + return encode(v.as_double(), sb); + case mixed::type::STRING: + return encode(v.as_string(), sb); + case mixed::type::ARRAY: + return encode(v.as_array(), sb); + default: + __builtin_unreachable(); } } @@ -312,240 +310,240 @@ bool JsonEncoder::encode(const mixed &v, string_buffer &sb) noexcept { namespace { -void json_skip_blanks(const char *s, int &i) noexcept { +void json_skip_blanks(const char* s, int& i) noexcept { while (vk::any_of_equal(s[i], ' ', '\t', '\r', '\n')) { i++; } } -bool do_json_decode(const char *s, int s_len, int &i, mixed &v, const char *json_obj_magic_key) noexcept { +bool do_json_decode(const char* s, int s_len, int& i, mixed& v, const char* json_obj_magic_key) noexcept { if (!v.is_null()) { v.destroy(); } json_skip_blanks(s, i); switch (s[i]) { - case 'n': - if (s[i + 1] == 'u' && s[i + 2] == 'l' && s[i + 3] == 'l') { - i += 4; - return true; - } - break; - case 't': - if (s[i + 1] == 'r' && s[i + 2] == 'u' && s[i + 3] == 'e') { - i += 4; - new (&v) mixed(true); - return true; - } - break; - case 'f': - if (s[i + 1] == 'a' && s[i + 2] == 'l' && s[i + 3] == 's' && s[i + 4] == 'e') { - i += 5; - new (&v) mixed(false); - return true; - } - break; - case '"': { - int j = i + 1; - int slashes = 0; - while (j < s_len && s[j] != '"') { - if (s[j] == '\\') { - slashes++; - j++; - } + case 'n': + if (s[i + 1] == 'u' && s[i + 2] == 'l' && s[i + 3] == 'l') { + i += 4; + return true; + } + break; + case 't': + if (s[i + 1] == 'r' && s[i + 2] == 'u' && s[i + 3] == 'e') { + i += 4; + new (&v) mixed(true); + return true; + } + break; + case 'f': + if (s[i + 1] == 'a' && s[i + 2] == 'l' && s[i + 3] == 's' && s[i + 4] == 'e') { + i += 5; + new (&v) mixed(false); + return true; + } + break; + case '"': { + int j = i + 1; + int slashes = 0; + while (j < s_len && s[j] != '"') { + if (s[j] == '\\') { + slashes++; j++; } - if (j < s_len) { - int len = j - i - 1 - slashes; - - string value(len, false); - - i++; - int l; - for (l = 0; l < len && i < j; l++) { - char c = s[i]; - if (c == '\\') { - i++; - switch (s[i]) { - case '"': - case '\\': - case '/': - value[l] = s[i]; - break; - case 'b': - value[l] = '\b'; - break; - case 'f': - value[l] = '\f'; - break; - case 'n': - value[l] = '\n'; - break; - case 'r': - value[l] = '\r'; - break; - case 't': - value[l] = '\t'; - break; - case 'u': - if (isxdigit(s[i + 1]) && isxdigit(s[i + 2]) && isxdigit(s[i + 3]) && isxdigit(s[i + 4])) { - int num = 0; + j++; + } + if (j < s_len) { + int len = j - i - 1 - slashes; + + string value(len, false); + + i++; + int l; + for (l = 0; l < len && i < j; l++) { + char c = s[i]; + if (c == '\\') { + i++; + switch (s[i]) { + case '"': + case '\\': + case '/': + value[l] = s[i]; + break; + case 'b': + value[l] = '\b'; + break; + case 'f': + value[l] = '\f'; + break; + case 'n': + value[l] = '\n'; + break; + case 'r': + value[l] = '\r'; + break; + case 't': + value[l] = '\t'; + break; + case 'u': + if (isxdigit(s[i + 1]) && isxdigit(s[i + 2]) && isxdigit(s[i + 3]) && isxdigit(s[i + 4])) { + int num = 0; + for (int t = 0; t < 4; t++) { + char c = s[++i]; + if ('0' <= c && c <= '9') { + num = num * 16 + c - '0'; + } else { + c |= 0x20; + if ('a' <= c && c <= 'f') { + num = num * 16 + c - 'a' + 10; + } + } + } + + if (0xD7FF < num && num < 0xE000) { + if (s[i + 1] == '\\' && s[i + 2] == 'u' && isxdigit(s[i + 3]) && isxdigit(s[i + 4]) && isxdigit(s[i + 5]) && isxdigit(s[i + 6])) { + i += 2; + int u = 0; for (int t = 0; t < 4; t++) { char c = s[++i]; if ('0' <= c && c <= '9') { - num = num * 16 + c - '0'; + u = u * 16 + c - '0'; } else { c |= 0x20; if ('a' <= c && c <= 'f') { - num = num * 16 + c - 'a' + 10; + u = u * 16 + c - 'a' + 10; } } } - if (0xD7FF < num && num < 0xE000) { - if (s[i + 1] == '\\' && s[i + 2] == 'u' && isxdigit(s[i + 3]) && isxdigit(s[i + 4]) && isxdigit(s[i + 5]) && isxdigit(s[i + 6])) { - i += 2; - int u = 0; - for (int t = 0; t < 4; t++) { - char c = s[++i]; - if ('0' <= c && c <= '9') { - u = u * 16 + c - '0'; - } else { - c |= 0x20; - if ('a' <= c && c <= 'f') { - u = u * 16 + c - 'a' + 10; - } - } - } - - if (0xD7FF < u && u < 0xE000) { - num = (((num & 0x3FF) << 10) | (u & 0x3FF)) + 0x10000; - } else { - i -= 6; - return false; - } - } else { - return false; - } - } - - if (num < 128) { - value[l] = static_cast(num); - } else if (num < 0x800) { - value[l++] = static_cast(0xc0 + (num >> 6)); - value[l] = static_cast(0x80 + (num & 63)); - } else if (num < 0xffff) { - value[l++] = static_cast(0xe0 + (num >> 12)); - value[l++] = static_cast(0x80 + ((num >> 6) & 63)); - value[l] = static_cast(0x80 + (num & 63)); + if (0xD7FF < u && u < 0xE000) { + num = (((num & 0x3FF) << 10) | (u & 0x3FF)) + 0x10000; } else { - value[l++] = static_cast(0xf0 + (num >> 18)); - value[l++] = static_cast(0x80 + ((num >> 12) & 63)); - value[l++] = static_cast(0x80 + ((num >> 6) & 63)); - value[l] = static_cast(0x80 + (num & 63)); + i -= 6; + return false; } - break; + } else { + return false; } - /* fallthrough */ - default: - return false; + } + + if (num < 128) { + value[l] = static_cast(num); + } else if (num < 0x800) { + value[l++] = static_cast(0xc0 + (num >> 6)); + value[l] = static_cast(0x80 + (num & 63)); + } else if (num < 0xffff) { + value[l++] = static_cast(0xe0 + (num >> 12)); + value[l++] = static_cast(0x80 + ((num >> 6) & 63)); + value[l] = static_cast(0x80 + (num & 63)); + } else { + value[l++] = static_cast(0xf0 + (num >> 18)); + value[l++] = static_cast(0x80 + ((num >> 12) & 63)); + value[l++] = static_cast(0x80 + ((num >> 6) & 63)); + value[l] = static_cast(0x80 + (num & 63)); + } + break; } - i++; - } else { - value[l] = s[i++]; - } - } - value.shrink(l); - - new (&v) mixed(value); - i++; - return true; - } - break; - } - case '[': { - array res; - i++; - json_skip_blanks(s, i); - if (s[i] != ']') { - do { - mixed value; - if (!do_json_decode(s, s_len, i, value, json_obj_magic_key)) { + /* fallthrough */ + default: return false; } - res.push_back(value); - json_skip_blanks(s, i); - } while (s[i++] == ','); - - if (s[i - 1] != ']') { - return false; + i++; + } else { + value[l] = s[i++]; } - } else { - i++; } + value.shrink(l); - new (&v) mixed(res); + new (&v) mixed(value); + i++; return true; } - case '{': { - array res; + break; + } + case '[': { + array res; + i++; + json_skip_blanks(s, i); + if (s[i] != ']') { + do { + mixed value; + if (!do_json_decode(s, s_len, i, value, json_obj_magic_key)) { + return false; + } + res.push_back(value); + json_skip_blanks(s, i); + } while (s[i++] == ','); + + if (s[i - 1] != ']') { + return false; + } + } else { i++; - json_skip_blanks(s, i); - if (s[i] != '}') { - do { - mixed key; - if (!do_json_decode(s, s_len, i, key, json_obj_magic_key) || !key.is_string()) { - return false; - } - json_skip_blanks(s, i); - if (s[i++] != ':') { - return false; - } + } - if (!do_json_decode(s, s_len, i, res[key], json_obj_magic_key)) { - return false; - } - json_skip_blanks(s, i); - } while (s[i++] == ','); + new (&v) mixed(res); + return true; + } + case '{': { + array res; + i++; + json_skip_blanks(s, i); + if (s[i] != '}') { + do { + mixed key; + if (!do_json_decode(s, s_len, i, key, json_obj_magic_key) || !key.is_string()) { + return false; + } + json_skip_blanks(s, i); + if (s[i++] != ':') { + return false; + } - if (s[i - 1] != '}') { + if (!do_json_decode(s, s_len, i, res[key], json_obj_magic_key)) { return false; } - } else { - i++; - } + json_skip_blanks(s, i); + } while (s[i++] == ','); - // it's impossible to distinguish whether empty php array was an json array or json object; - // to overcome it we add dummy key to php array that make array::is_vector() returning false, so we have difference - if (json_obj_magic_key && res.empty()) { - res[string{json_obj_magic_key}] = true; + if (s[i - 1] != '}') { + return false; } + } else { + i++; + } - new (&v) mixed(res); - return true; + // it's impossible to distinguish whether empty php array was an json array or json object; + // to overcome it we add dummy key to php array that make array::is_vector() returning false, so we have difference + if (json_obj_magic_key && res.empty()) { + res[string{json_obj_magic_key}] = true; } - default: { - int j = i; - while (s[j] == '-' || ('0' <= s[j] && s[j] <= '9') || s[j] == 'e' || s[j] == 'E' || s[j] == '+' || s[j] == '.') { - j++; + + new (&v) mixed(res); + return true; + } + default: { + int j = i; + while (s[j] == '-' || ('0' <= s[j] && s[j] <= '9') || s[j] == 'e' || s[j] == 'E' || s[j] == '+' || s[j] == '.') { + j++; + } + if (j > i) { + int64_t intval = 0; + if (php_try_to_int(s + i, j - i, &intval)) { + i = j; + new (&v) mixed(intval); + return true; } - if (j > i) { - int64_t intval = 0; - if (php_try_to_int(s + i, j - i, &intval)) { - i = j; - new (&v) mixed(intval); - return true; - } - char *end_ptr; - double floatval = strtod(s + i, &end_ptr); - if (end_ptr == s + j) { - i = j; - new (&v) mixed(floatval); - return true; - } + char* end_ptr; + double floatval = strtod(s + i, &end_ptr); + if (end_ptr == s + j) { + i = j; + new (&v) mixed(floatval); + return true; } - break; } + break; + } } return false; @@ -553,7 +551,7 @@ bool do_json_decode(const char *s, int s_len, int &i, mixed &v, const char *json } // namespace -std::pair json_decode(const string &v, const char *json_obj_magic_key) noexcept { +std::pair json_decode(const string& v, const char* json_obj_magic_key) noexcept { mixed result; int i = 0; if (do_json_decode(v.c_str(), v.size(), i, result, json_obj_magic_key)) { @@ -567,7 +565,7 @@ std::pair json_decode(const string &v, const char *json_obj_magic_k return {}; } -mixed f$json_decode(const string &v, bool assoc) noexcept { +mixed f$json_decode(const string& v, bool assoc) noexcept { // TODO It was a warning before (in case if assoc is false), but then it was disabled, should we enable it again? static_cast(assoc); return json_decode(v).first; diff --git a/runtime-common/stdlib/serialization/json-functions.h b/runtime-common/stdlib/serialization/json-functions.h index b2e56a209b..b7feaf9406 100644 --- a/runtime-common/stdlib/serialization/json-functions.h +++ b/runtime-common/stdlib/serialization/json-functions.h @@ -21,19 +21,17 @@ constexpr int64_t JSON_AVAILABLE_FLAGS_TYPED = JSON_PRETTY_PRINT | JSON_PRESERVE struct JsonPath { constexpr static int MAX_DEPTH = 8; - std::array arr; + std::array arr; unsigned depth = 0; - void enter(const char *key) noexcept { + void enter(const char* key) noexcept { if (depth < arr.size()) { arr[depth] = key; } depth++; } - void leave() noexcept { - depth--; - } + void leave() noexcept { depth--; } string to_string() const; }; @@ -44,32 +42,32 @@ namespace impl_ { // todo somewhen, unify this JsonEncoder and JsonWriter, and support JSON_PRETTY_PRINT then class JsonEncoder : vk::not_copyable { public: - JsonEncoder(int64_t options, bool simple_encode, const char *json_obj_magic_key = nullptr) noexcept; + JsonEncoder(int64_t options, bool simple_encode, const char* json_obj_magic_key = nullptr) noexcept; // todo:k2 change static_SB everywhere to string_buffer arg - bool encode(bool b, string_buffer &sb) noexcept; - bool encode(int64_t i, string_buffer &sb) noexcept; - bool encode(const string &s, string_buffer &sb) noexcept; - bool encode(double d, string_buffer &sb) noexcept; - bool encode(const mixed &v, string_buffer &sb) noexcept; + bool encode(bool b, string_buffer& sb) noexcept; + bool encode(int64_t i, string_buffer& sb) noexcept; + bool encode(const string& s, string_buffer& sb) noexcept; + bool encode(double d, string_buffer& sb) noexcept; + bool encode(const mixed& v, string_buffer& sb) noexcept; - template - bool encode(const array &arr, string_buffer &sb) noexcept; + template + bool encode(const array& arr, string_buffer& sb) noexcept; - template - bool encode(const Optional &opt, string_buffer &sb) noexcept; + template + bool encode(const Optional& opt, string_buffer& sb) noexcept; private: - bool encode_null(string_buffer &sb) const noexcept; + bool encode_null(string_buffer& sb) const noexcept; JsonPath json_path_; const int64_t options_{0}; const bool simple_encode_{false}; - const char *json_obj_magic_key_{nullptr}; + const char* json_obj_magic_key_{nullptr}; }; -template -bool JsonEncoder::encode(const array &arr, string_buffer &sb) noexcept { +template +bool JsonEncoder::encode(const array& arr, string_buffer& sb) noexcept { bool is_vector = arr.is_vector(); const bool force_object = static_cast(JSON_FORCE_OBJECT & options_); if (!force_object && !is_vector && arr.is_pseudo_vector()) { @@ -105,14 +103,14 @@ bool JsonEncoder::encode(const array &arr, string_buffer &sb) noexcept { sb << ','; } is_first = false; - const char *next_key = nullptr; + const char* next_key = nullptr; const auto key = p.get_key(); if (array::is_int_key(key)) { auto int_key = key.to_int(); next_key = nullptr; sb << '"' << int_key << '"'; } else { - const string &str_key = key.as_string(); + const string& str_key = key.as_string(); // skip service key intended only for distinguish empty json object with empty json array if (json_obj_magic_key_ && !strcmp(json_obj_magic_key_, str_key.c_str())) { continue; @@ -139,23 +137,23 @@ bool JsonEncoder::encode(const array &arr, string_buffer &sb) noexcept { return true; } -template -bool JsonEncoder::encode(const Optional &opt, string_buffer &sb) noexcept { +template +bool JsonEncoder::encode(const Optional& opt, string_buffer& sb) noexcept { switch (opt.value_state()) { - case OptionalState::has_value: - return encode(opt.val(), sb); - case OptionalState::false_value: - return encode(false, sb); - case OptionalState::null_value: - return encode_null(sb); + case OptionalState::has_value: + return encode(opt.val(), sb); + case OptionalState::false_value: + return encode(false, sb); + case OptionalState::null_value: + return encode_null(sb); } __builtin_unreachable(); } } // namespace impl_ -template -Optional f$json_encode(const T &v, int64_t options = 0, bool simple_encode = false) noexcept { +template +Optional f$json_encode(const T& v, int64_t options = 0, bool simple_encode = false) noexcept { const bool has_unsupported_option = static_cast(options & ~JSON_AVAILABLE_OPTIONS); if (unlikely(has_unsupported_option)) { php_warning("Wrong parameter options = %" PRIi64 " in function json_encode", options); @@ -168,10 +166,10 @@ Optional f$json_encode(const T &v, int64_t options = 0, bool simple_enco return sb.c_str(); } -template -inline Optional f$vk_json_encode(const T &v) noexcept { +template +inline Optional f$vk_json_encode(const T& v) noexcept { return f$json_encode(v, 0, true); } -std::pair json_decode(const string &v, const char *json_obj_magic_key = nullptr) noexcept; -mixed f$json_decode(const string &v, bool assoc = false) noexcept; +std::pair json_decode(const string& v, const char* json_obj_magic_key = nullptr) noexcept; +mixed f$json_decode(const string& v, bool assoc = false) noexcept; diff --git a/runtime-common/stdlib/serialization/json-processor-utils.h b/runtime-common/stdlib/serialization/json-processor-utils.h index a27f5d1f86..fbf293e073 100644 --- a/runtime-common/stdlib/serialization/json-processor-utils.h +++ b/runtime-common/stdlib/serialization/json-processor-utils.h @@ -9,21 +9,20 @@ #include "runtime-common/core/runtime-core.h" namespace impl_ { -template> +template > struct IsJsonFlattenClass : std::false_type {}; -template +template struct IsJsonFlattenClass> : std::true_type {}; -template> +template > struct HasClassWakeupMethod : std::false_type {}; -template +template struct HasClassWakeupMethod> : std::true_type {}; } // namespace impl_ struct JsonRawString { - explicit JsonRawString(string &s) noexcept - : str(s) {} - string &str; + explicit JsonRawString(string& s) noexcept : str(s) {} + string& str; }; diff --git a/runtime-common/stdlib/serialization/json-writer.cpp b/runtime-common/stdlib/serialization/json-writer.cpp index 1487d89dce..bc99b25855 100644 --- a/runtime-common/stdlib/serialization/json-writer.cpp +++ b/runtime-common/stdlib/serialization/json-writer.cpp @@ -10,57 +10,53 @@ // for untyped json_encode() and json_decode(), see json-functions.cpp namespace impl_ { -static void escape_json_string(string_buffer &buffer, std::string_view s) noexcept { +static void escape_json_string(string_buffer& buffer, std::string_view s) noexcept { for (auto c : s) { switch (c) { - case '"': - buffer.append_char('\\'); - buffer.append_char('"'); - break; - case '\\': - buffer.append_char('\\'); - buffer.append_char('\\'); - break; - case '/': - buffer.append_char('\\'); - buffer.append_char('/'); - break; - case '\b': - buffer.append_char('\\'); - buffer.append_char('b'); - break; - case '\f': - buffer.append_char('\\'); - buffer.append_char('f'); - break; - case '\n': - buffer.append_char('\\'); - buffer.append_char('n'); - break; - case '\r': - buffer.append_char('\\'); - buffer.append_char('r'); - break; - case '\t': - buffer.append_char('\\'); - buffer.append_char('t'); - break; - default: - buffer.append_char(c); - break; + case '"': + buffer.append_char('\\'); + buffer.append_char('"'); + break; + case '\\': + buffer.append_char('\\'); + buffer.append_char('\\'); + break; + case '/': + buffer.append_char('\\'); + buffer.append_char('/'); + break; + case '\b': + buffer.append_char('\\'); + buffer.append_char('b'); + break; + case '\f': + buffer.append_char('\\'); + buffer.append_char('f'); + break; + case '\n': + buffer.append_char('\\'); + buffer.append_char('n'); + break; + case '\r': + buffer.append_char('\\'); + buffer.append_char('r'); + break; + case '\t': + buffer.append_char('\\'); + buffer.append_char('t'); + break; + default: + buffer.append_char(c); + break; } } } -JsonWriter::JsonWriter(bool pretty_print, bool preserve_zero_fraction) noexcept - : pretty_print_(pretty_print) - , preserve_zero_fraction_(preserve_zero_fraction) { +JsonWriter::JsonWriter(bool pretty_print, bool preserve_zero_fraction) noexcept : pretty_print_(pretty_print), preserve_zero_fraction_(preserve_zero_fraction) { runtime_context_buffer.clean(); } -JsonWriter::~JsonWriter() noexcept { - runtime_context_buffer.clean(); -} +JsonWriter::~JsonWriter() noexcept { runtime_context_buffer.clean(); } bool JsonWriter::write_bool(bool b) noexcept { if (!register_value()) { @@ -98,7 +94,7 @@ bool JsonWriter::write_double(double d) noexcept { return true; } -bool JsonWriter::write_string(const string &s) noexcept { +bool JsonWriter::write_string(const string& s) noexcept { if (!register_value()) { return false; } @@ -109,7 +105,7 @@ bool JsonWriter::write_string(const string &s) noexcept { return true; } -bool JsonWriter::write_raw_string(const string &s) noexcept { +bool JsonWriter::write_raw_string(const string& s) noexcept { if (!register_value()) { return false; } @@ -151,33 +147,19 @@ bool JsonWriter::write_key(std::string_view key, bool escape) noexcept { return true; } -bool JsonWriter::start_object() noexcept { - return new_level(false); -} +bool JsonWriter::start_object() noexcept { return new_level(false); } -bool JsonWriter::end_object() noexcept { - return exit_level(false); -} +bool JsonWriter::end_object() noexcept { return exit_level(false); } -bool JsonWriter::start_array() noexcept { - return new_level(true); -} +bool JsonWriter::start_array() noexcept { return new_level(true); } -bool JsonWriter::end_array() noexcept { - return exit_level(true); -} +bool JsonWriter::end_array() noexcept { return exit_level(true); } -bool JsonWriter::is_complete() const noexcept { - return error_.empty() && stack_.empty() && has_root_; -} +bool JsonWriter::is_complete() const noexcept { return error_.empty() && stack_.empty() && has_root_; } -string JsonWriter::get_error() const noexcept { - return error_; -} +string JsonWriter::get_error() const noexcept { return error_; } -string JsonWriter::get_final_json() const noexcept { - return runtime_context_buffer.str(); -} +string JsonWriter::get_final_json() const noexcept { return runtime_context_buffer.str(); } bool JsonWriter::new_level(bool is_array) noexcept { if (!register_value()) { @@ -224,7 +206,7 @@ bool JsonWriter::register_value() noexcept { has_root_ = true; return true; } - auto &top = stack_.back(); + auto& top = stack_.back(); if (top.in_array) { if (top.values_count) { runtime_context_buffer << ','; diff --git a/runtime-common/stdlib/serialization/json-writer.h b/runtime-common/stdlib/serialization/json-writer.h index 9caf1a7b7e..fe0ee73062 100644 --- a/runtime-common/stdlib/serialization/json-writer.h +++ b/runtime-common/stdlib/serialization/json-writer.h @@ -22,8 +22,8 @@ class JsonWriter : vk::not_copyable { bool write_bool(bool b) noexcept; bool write_int(int64_t i) noexcept; bool write_double(double d) noexcept; - bool write_string(const string &s) noexcept; - bool write_raw_string(const string &s) noexcept; + bool write_string(const string& s) noexcept; + bool write_raw_string(const string& s) noexcept; bool write_null() noexcept; bool write_key(std::string_view key, bool escape = false) noexcept; @@ -32,9 +32,7 @@ class JsonWriter : vk::not_copyable { bool start_array() noexcept; bool end_array() noexcept; - void set_double_precision(std::size_t precision) noexcept { - double_precision_ = precision; - } + void set_double_precision(std::size_t precision) noexcept { double_precision_ = precision; } bool is_complete() const noexcept; string get_error() const noexcept; @@ -59,7 +57,7 @@ class JsonWriter : vk::not_copyable { bool has_root_{false}; std::size_t indent_{0}; - string_buffer &runtime_context_buffer{RuntimeContext::get().static_SB}; + string_buffer& runtime_context_buffer{RuntimeContext::get().static_SB}; }; } // namespace impl_ diff --git a/runtime-common/stdlib/serialization/serialization-context.h b/runtime-common/stdlib/serialization/serialization-context.h index a4920b061d..246f3d81e4 100644 --- a/runtime-common/stdlib/serialization/serialization-context.h +++ b/runtime-common/stdlib/serialization/serialization-context.h @@ -10,5 +10,5 @@ struct SerializationLibContext final : private vk::not_copyable { string last_json_processor_error; - static SerializationLibContext &get() noexcept; + static SerializationLibContext& get() noexcept; }; diff --git a/runtime-common/stdlib/serialization/serialize-functions.cpp b/runtime-common/stdlib/serialization/serialize-functions.cpp index d5fe1b668c..7ce7b8c17b 100644 --- a/runtime-common/stdlib/serialization/serialize-functions.cpp +++ b/runtime-common/stdlib/serialization/serialize-functions.cpp @@ -7,7 +7,7 @@ #include "runtime-common/core/runtime-core.h" void impl_::PhpSerializer::serialize(bool b) noexcept { - auto &static_SB{RuntimeContext::get().static_SB}; + auto& static_SB{RuntimeContext::get().static_SB}; static_SB.reserve(4); static_SB.append_char('b'); static_SB.append_char(':'); @@ -16,7 +16,7 @@ void impl_::PhpSerializer::serialize(bool b) noexcept { } void impl_::PhpSerializer::serialize(int64_t i) noexcept { - auto &static_SB{RuntimeContext::get().static_SB}; + auto& static_SB{RuntimeContext::get().static_SB}; static_SB.reserve(24); static_SB.append_char('i'); static_SB.append_char(':'); @@ -25,13 +25,13 @@ void impl_::PhpSerializer::serialize(int64_t i) noexcept { } void impl_::PhpSerializer::serialize(double d) noexcept { - auto &static_SB{RuntimeContext::get().static_SB}; + auto& static_SB{RuntimeContext::get().static_SB}; static_SB.append("d:", 2); static_SB << d << ';'; } -void impl_::PhpSerializer::serialize(const string &s) noexcept { - auto &static_SB{RuntimeContext::get().static_SB}; +void impl_::PhpSerializer::serialize(const string& s) noexcept { + auto& static_SB{RuntimeContext::get().static_SB}; string::size_type len = s.size(); static_SB.reserve(25 + len); static_SB.append_char('s'); @@ -45,215 +45,215 @@ void impl_::PhpSerializer::serialize(const string &s) noexcept { } void impl_::PhpSerializer::serialize_null() noexcept { - auto &static_SB{RuntimeContext::get().static_SB}; + auto& static_SB{RuntimeContext::get().static_SB}; static_SB.reserve(2); static_SB.append_char('N'); static_SB.append_char(';'); } -void impl_::PhpSerializer::serialize(const mixed &v) noexcept { +void impl_::PhpSerializer::serialize(const mixed& v) noexcept { switch (v.get_type()) { - case mixed::type::NUL: - return serialize_null(); - case mixed::type::BOOLEAN: - return serialize(v.as_bool()); - case mixed::type::INTEGER: - return serialize(v.as_int()); - case mixed::type::FLOAT: - return serialize(v.as_double()); - case mixed::type::STRING: - return serialize(v.as_string()); - case mixed::type::ARRAY: - return serialize(v.as_array()); - case mixed::type::OBJECT: - php_warning("Cannot serialize object of type %s", v.get_type_or_class_name()); - return; - default: - __builtin_unreachable(); + case mixed::type::NUL: + return serialize_null(); + case mixed::type::BOOLEAN: + return serialize(v.as_bool()); + case mixed::type::INTEGER: + return serialize(v.as_int()); + case mixed::type::FLOAT: + return serialize(v.as_double()); + case mixed::type::STRING: + return serialize(v.as_string()); + case mixed::type::ARRAY: + return serialize(v.as_array()); + case mixed::type::OBJECT: + php_warning("Cannot serialize object of type %s", v.get_type_or_class_name()); + return; + default: + __builtin_unreachable(); } } namespace { -int do_unserialize(const char *s, int s_len, mixed &out_var_value) noexcept { +int do_unserialize(const char* s, int s_len, mixed& out_var_value) noexcept { if (!out_var_value.is_null()) { out_var_value = mixed{}; } switch (s[0]) { - case 'N': - if (s[1] == ';') { - return 2; + case 'N': + if (s[1] == ';') { + return 2; + } + break; + case 'b': + if (s[1] == ':' && (static_cast(s[2] - '0') < 2u) && s[3] == ';') { + out_var_value = static_cast(s[2] - '0'); + return 4; + } + break; + case 'd': + if (s[1] == ':') { + s += 2; + char* end_ptr = nullptr; + double floatval = strtod(s, &end_ptr); + if (*end_ptr == ';' && end_ptr > s) { + out_var_value = floatval; + return static_cast(end_ptr - s + 3); } - break; - case 'b': - if (s[1] == ':' && (static_cast(s[2] - '0') < 2u) && s[3] == ';') { - out_var_value = static_cast(s[2] - '0'); - return 4; - } - break; - case 'd': - if (s[1] == ':') { - s += 2; - char *end_ptr = nullptr; - double floatval = strtod(s, &end_ptr); - if (*end_ptr == ';' && end_ptr > s) { - out_var_value = floatval; - return static_cast(end_ptr - s + 3); - } - } - break; - case 'i': - if (s[1] == ':') { - s += 2; - int j = 0; - while (s[j]) { - if (s[j] == ';') { - int64_t intval = 0; - if (php_try_to_int(s, j, &intval)) { - s += j + 1; - out_var_value = intval; - return j + 3; - } + } + break; + case 'i': + if (s[1] == ':') { + s += 2; + int j = 0; + while (s[j]) { + if (s[j] == ';') { + int64_t intval = 0; + if (php_try_to_int(s, j, &intval)) { + s += j + 1; + out_var_value = intval; + return j + 3; + } - int k = 0; - if (s[k] == '-' || s[k] == '+') { - k++; - } - while ('0' <= s[k] && s[k] <= '9') { - k++; - } - if (k == j) { - out_var_value = mixed(s, j); - return j + 3; - } - return 0; + int k = 0; + if (s[k] == '-' || s[k] == '+') { + k++; + } + while ('0' <= s[k] && s[k] <= '9') { + k++; + } + if (k == j) { + out_var_value = mixed(s, j); + return j + 3; } - j++; + return 0; } + j++; } - break; - case 's': - if (s[1] == ':') { - s += 2; - uint32_t j = 0; - uint32_t len = 0; - while ('0' <= s[j] && s[j] <= '9') { - len = len * 10 + s[j++] - '0'; - } - if (j > 0 && s[j] == ':' && s[j + 1] == '"' && len < string::max_size() && j + 2 + len < s_len) { - s += j + 2; + } + break; + case 's': + if (s[1] == ':') { + s += 2; + uint32_t j = 0; + uint32_t len = 0; + while ('0' <= s[j] && s[j] <= '9') { + len = len * 10 + s[j++] - '0'; + } + if (j > 0 && s[j] == ':' && s[j + 1] == '"' && len < string::max_size() && j + 2 + len < s_len) { + s += j + 2; - if (s[len] == '"' && s[len + 1] == ';') { - out_var_value = mixed(s, len); - return len + 6 + j; - } + if (s[len] == '"' && s[len + 1] == ';') { + out_var_value = mixed(s, len); + return len + 6 + j; } } - break; - case 'a': - if (s[1] == ':') { - const char *s_begin = s; - s += 2; - int j = 0; - int len = 0; - while ('0' <= s[j] && s[j] <= '9') { - len = len * 10 + s[j++] - '0'; - } - if (j > 0 && len >= 0 && s[j] == ':' && s[j + 1] == '{') { - s += j + 2; - s_len -= j + 4; - - array_size size(len, false); - if (s[0] == 'i') { // try to cheat - size = array_size(len, s[1] == ':' && s[2] == '0' && s[3] == ';'); - } - array res(size); + } + break; + case 'a': + if (s[1] == ':') { + const char* s_begin = s; + s += 2; + int j = 0; + int len = 0; + while ('0' <= s[j] && s[j] <= '9') { + len = len * 10 + s[j++] - '0'; + } + if (j > 0 && len >= 0 && s[j] == ':' && s[j + 1] == '{') { + s += j + 2; + s_len -= j + 4; - while (len-- > 0) { - if (s[0] == 'i' && s[1] == ':') { - s += 2; - int k = 0; - while (s[k]) { - if (s[k] == ';') { - int64_t intval = 0; - if (php_try_to_int(s, k, &intval)) { - s += k + 1; - s_len -= k + 3; - int length = do_unserialize(s, s_len, res[intval]); - if (!length) { - return 0; - } - s += length; - s_len -= length; - break; - } + array_size size(len, false); + if (s[0] == 'i') { // try to cheat + size = array_size(len, s[1] == ':' && s[2] == '0' && s[3] == ';'); + } + array res(size); - int q = 0; - if (s[q] == '-' || s[q] == '+') { - q++; - } - while ('0' <= s[q] && s[q] <= '9') { - q++; - } - if (q == k) { - string key(s, k); - s += k + 1; - s_len -= k + 3; - int length = do_unserialize(s, s_len, res[key]); - if (!length) { - return 0; - } - s += length; - s_len -= length; - break; + while (len-- > 0) { + if (s[0] == 'i' && s[1] == ':') { + s += 2; + int k = 0; + while (s[k]) { + if (s[k] == ';') { + int64_t intval = 0; + if (php_try_to_int(s, k, &intval)) { + s += k + 1; + s_len -= k + 3; + int length = do_unserialize(s, s_len, res[intval]); + if (!length) { + return 0; } - return 0; + s += length; + s_len -= length; + break; } - k++; - } - } else if (s[0] == 's' && s[1] == ':') { - s += 2; - uint32_t k = 0; - uint32_t str_len = 0; - while ('0' <= s[k] && s[k] <= '9') { - str_len = str_len * 10 + s[k++] - '0'; - } - if (k > 0 && s[k] == ':' && s[k + 1] == '"' && str_len < string::max_size() && k + 2 + str_len < s_len) { - s += k + 2; - if (s[str_len] == '"' && s[str_len + 1] == ';') { - string key(s, str_len); - s += str_len + 2; - s_len -= str_len + 6 + k; + int q = 0; + if (s[q] == '-' || s[q] == '+') { + q++; + } + while ('0' <= s[q] && s[q] <= '9') { + q++; + } + if (q == k) { + string key(s, k); + s += k + 1; + s_len -= k + 3; int length = do_unserialize(s, s_len, res[key]); if (!length) { return 0; } s += length; s_len -= length; + break; } - } else { return 0; } + k++; + } + } else if (s[0] == 's' && s[1] == ':') { + s += 2; + uint32_t k = 0; + uint32_t str_len = 0; + while ('0' <= s[k] && s[k] <= '9') { + str_len = str_len * 10 + s[k++] - '0'; + } + if (k > 0 && s[k] == ':' && s[k + 1] == '"' && str_len < string::max_size() && k + 2 + str_len < s_len) { + s += k + 2; + + if (s[str_len] == '"' && s[str_len + 1] == ';') { + string key(s, str_len); + s += str_len + 2; + s_len -= str_len + 6 + k; + int length = do_unserialize(s, s_len, res[key]); + if (!length) { + return 0; + } + s += length; + s_len -= length; + } } else { return 0; } + } else { + return 0; } + } - if (s[0] == '}') { - out_var_value = std::move(res); - return static_cast(s - s_begin + 1); - } + if (s[0] == '}') { + out_var_value = std::move(res); + return static_cast(s - s_begin + 1); } } - break; + } + break; } return 0; } } // namespace -mixed unserialize_raw(const char *v, int32_t v_len) noexcept { +mixed unserialize_raw(const char* v, int32_t v_len) noexcept { mixed result; if (do_unserialize(v, v_len, result) == v_len) { @@ -263,6 +263,4 @@ mixed unserialize_raw(const char *v, int32_t v_len) noexcept { return false; } -mixed f$unserialize(const string &v) noexcept { - return unserialize_raw(v.c_str(), v.size()); -} +mixed f$unserialize(const string& v) noexcept { return unserialize_raw(v.c_str(), v.size()); } diff --git a/runtime-common/stdlib/serialization/serialize-functions.h b/runtime-common/stdlib/serialization/serialize-functions.h index dd1fd64701..2386f0fb10 100644 --- a/runtime-common/stdlib/serialization/serialize-functions.h +++ b/runtime-common/stdlib/serialization/serialize-functions.h @@ -14,22 +14,22 @@ class PhpSerializer : vk::not_copyable { static void serialize(bool b) noexcept; static void serialize(int64_t i) noexcept; static void serialize(double d) noexcept; - static void serialize(const string &s) noexcept; - static void serialize(const mixed &v) noexcept; + static void serialize(const string& s) noexcept; + static void serialize(const mixed& v) noexcept; - template - static void serialize(const array &arr) noexcept; + template + static void serialize(const array& arr) noexcept; - template - static void serialize(const Optional &opt) noexcept; + template + static void serialize(const Optional& opt) noexcept; private: static void serialize_null() noexcept; }; -template -void PhpSerializer::serialize(const array &arr) noexcept { - auto &static_SB{RuntimeContext::get().static_SB}; +template +void PhpSerializer::serialize(const array& arr) noexcept { + auto& static_SB{RuntimeContext::get().static_SB}; static_SB.append("a:", 2); static_SB << arr.count(); static_SB.append(":{", 2); @@ -45,28 +45,28 @@ void PhpSerializer::serialize(const array &arr) noexcept { static_SB << '}'; } -template -void PhpSerializer::serialize(const Optional &opt) noexcept { +template +void PhpSerializer::serialize(const Optional& opt) noexcept { switch (opt.value_state()) { - case OptionalState::has_value: - return serialize(opt.val()); - case OptionalState::false_value: - return serialize(false); - case OptionalState::null_value: - return serialize_null(); + case OptionalState::has_value: + return serialize(opt.val()); + case OptionalState::false_value: + return serialize(false); + case OptionalState::null_value: + return serialize_null(); } } } // namespace impl_ -template -string f$serialize(const T &v) noexcept { - auto &static_SB{RuntimeContext::get().static_SB}; +template +string f$serialize(const T& v) noexcept { + auto& static_SB{RuntimeContext::get().static_SB}; static_SB.clean(); impl_::PhpSerializer::serialize(v); return static_SB.str(); } -mixed f$unserialize(const string &v) noexcept; +mixed f$unserialize(const string& v) noexcept; -mixed unserialize_raw(const char *v, int32_t v_len) noexcept; +mixed unserialize_raw(const char* v, int32_t v_len) noexcept; diff --git a/runtime-common/stdlib/serialization/to-json-processor.h b/runtime-common/stdlib/serialization/to-json-processor.h index 4bb000f32b..7d3bb54be4 100644 --- a/runtime-common/stdlib/serialization/to-json-processor.h +++ b/runtime-common/stdlib/serialization/to-json-processor.h @@ -10,16 +10,14 @@ #include "runtime-common/stdlib/serialization/json-writer.h" #include "runtime-common/stdlib/serialization/serialization-context.h" -template +template class ToJsonVisitor { public: - explicit ToJsonVisitor(impl_::JsonWriter &writer, bool flatten_class, std::size_t depth) noexcept - : writer_(writer) - , flatten_class_(flatten_class) - , depth_(flatten_class ? depth : ++depth) {} + explicit ToJsonVisitor(impl_::JsonWriter& writer, bool flatten_class, std::size_t depth) noexcept + : writer_(writer), flatten_class_(flatten_class), depth_(flatten_class ? depth : ++depth) {} - template - void operator()(const char *key, const T &value, bool array_as_hashmap = false) noexcept { + template + void operator()(const char* key, const T& value, bool array_as_hashmap = false) noexcept { array_as_hashmap_ = array_as_hashmap; if (!flatten_class_) { writer_.write_key(key); @@ -27,117 +25,101 @@ class ToJsonVisitor { process_impl(value); } - void set_precision(std::size_t precision) noexcept { - writer_.set_double_precision(precision); - } + void set_precision(std::size_t precision) noexcept { writer_.set_double_precision(precision); } - void restore_precision() noexcept { - writer_.set_double_precision(0); - } + void restore_precision() noexcept { writer_.set_double_precision(0); } private: - template - void process_impl(const T &value) noexcept { + template + void process_impl(const T& value) noexcept { add_value(value); } - template - void process_impl(const Optional &value) noexcept { - auto process_impl_lambda = [this](const auto &val) { return this->process_impl(val); }; + template + void process_impl(const Optional& value) noexcept { + auto process_impl_lambda = [this](const auto& val) { return this->process_impl(val); }; call_fun_on_optional_value(process_impl_lambda, value); } - template - void process_impl(const class_instance &instance) noexcept; + template + void process_impl(const class_instance& instance) noexcept; - template - void process_vector(const array &array) noexcept { + template + void process_vector(const array& array) noexcept { writer_.start_array(); - for (const auto &elem : array) { + for (const auto& elem : array) { process_impl(elem.get_value()); } writer_.end_array(); } - template - void process_map(const array &array) noexcept { + template + void process_map(const array& array) noexcept { writer_.start_object(); - for (const auto &elem : array) { - const auto &key = elem.get_key().to_string(); + for (const auto& elem : array) { + const auto& key = elem.get_key().to_string(); writer_.write_key({key.c_str(), key.size()}, true); process_impl(elem.get_value()); } writer_.end_object(); } - template - void process_impl(const array &array) noexcept { + template + void process_impl(const array& array) noexcept { // use array_as_hashmap_ only for top level of current array field, don't propagate it further bool as_hashmap = std::exchange(array_as_hashmap_, false); (array.is_vector() || array.is_pseudo_vector()) && !as_hashmap ? process_vector(array) : process_map(array); } // support of array compilation - void process_impl(const Unknown & /*elem*/) noexcept {} + void process_impl(const Unknown& /*elem*/) noexcept {} - void process_impl(const mixed &value) noexcept { + void process_impl(const mixed& value) noexcept { switch (value.get_type()) { - case mixed::type::NUL: - add_null_value(); - break; - case mixed::type::BOOLEAN: - add_value(value.as_bool()); - break; - case mixed::type::INTEGER: - add_value(value.as_int()); - break; - case mixed::type::FLOAT: - add_value(value.as_double()); - break; - case mixed::type::STRING: - add_value(value.as_string()); - break; - case mixed::type::ARRAY: - process_impl(value.as_array()); - break; - case mixed::type::OBJECT: - php_warning("Objects (%s) in mixed cannot be written in JSON", value.get_type_or_class_name()); - break; + case mixed::type::NUL: + add_null_value(); + break; + case mixed::type::BOOLEAN: + add_value(value.as_bool()); + break; + case mixed::type::INTEGER: + add_value(value.as_int()); + break; + case mixed::type::FLOAT: + add_value(value.as_double()); + break; + case mixed::type::STRING: + add_value(value.as_string()); + break; + case mixed::type::ARRAY: + process_impl(value.as_array()); + break; + case mixed::type::OBJECT: + php_warning("Objects (%s) in mixed cannot be written in JSON", value.get_type_or_class_name()); + break; } } - void add_value(const string &value) noexcept { - writer_.write_string(value); - } + void add_value(const string& value) noexcept { writer_.write_string(value); } - void add_value(const JsonRawString &value) noexcept { - writer_.write_raw_string(value.str); - } + void add_value(const JsonRawString& value) noexcept { writer_.write_raw_string(value.str); } - void add_value(std::int64_t value) noexcept { - writer_.write_int(value); - } + void add_value(std::int64_t value) noexcept { writer_.write_int(value); } - void add_value(bool value) noexcept { - writer_.write_bool(value); - } + void add_value(bool value) noexcept { writer_.write_bool(value); } - void add_value(double value) noexcept { - writer_.write_double(value); - } + void add_value(double value) noexcept { writer_.write_double(value); } - void add_null_value() noexcept { - writer_.write_null(); - } + void add_null_value() noexcept { writer_.write_null(); } - impl_::JsonWriter &writer_; + impl_::JsonWriter& writer_; const bool flatten_class_{false}; bool array_as_hashmap_{false}; std::size_t depth_{0}; }; -template -void to_json_impl(const class_instance &klass, impl_::JsonWriter &writer, const array &more, std::size_t depth = 0) noexcept { +template +void to_json_impl(const class_instance& klass, impl_::JsonWriter& writer, const array& more, std::size_t depth = 0) noexcept { if (depth > 64) { SerializationLibContext::get().last_json_processor_error.assign("allowed depth=64 of json object exceeded"); return; @@ -158,7 +140,7 @@ void to_json_impl(const class_instance &klass, impl_::JsonWriter &writer, con } for (auto elem : more) { - const auto &key = elem.get_key().to_string(); + const auto& key = elem.get_key().to_string(); visitor(key.c_str(), elem.get_value()); } @@ -167,19 +149,19 @@ void to_json_impl(const class_instance &klass, impl_::JsonWriter &writer, con } } -template -template -void ToJsonVisitor::process_impl(const class_instance &instance) noexcept { +template +template +void ToJsonVisitor::process_impl(const class_instance& instance) noexcept { to_json_impl(instance, writer_, {}, depth_); } -template -string f$JsonEncoder$$to_json_impl(Tag /*tag*/, const class_instance &klass, int64_t flags = 0, const array &more = {}) noexcept { +template +string f$JsonEncoder$$to_json_impl(Tag /*tag*/, const class_instance& klass, int64_t flags = 0, const array& more = {}) noexcept { const bool has_unsupported_option = static_cast(flags & ~JSON_AVAILABLE_FLAGS_TYPED); if (unlikely(has_unsupported_option)) { php_warning("Wrong parameter flags = %" PRIi64 " in function JsonEncoder::encode", flags); } - auto &error_msg = SerializationLibContext::get().last_json_processor_error; + auto& error_msg = SerializationLibContext::get().last_json_processor_error; error_msg = {}; impl_::JsonWriter writer{(flags & JSON_PRETTY_PRINT) > 0, (flags & JSON_PRESERVE_ZERO_FRACTION) > 0}; diff --git a/runtime-common/stdlib/server/url-functions.cpp b/runtime-common/stdlib/server/url-functions.cpp index d9b3796c2a..58dc780ce5 100644 --- a/runtime-common/stdlib/server/url-functions.cpp +++ b/runtime-common/stdlib/server/url-functions.cpp @@ -19,16 +19,14 @@ namespace { -constexpr std::array base64_reverse_table = {-2, -2, -2, -2, -2, -2, -2, -2, -2, -1, -1, -2, -2, -1, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, - -2, -2, -2, -2, -2, -2, -1, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, 62, -2, -2, -2, 63, 52, 53, 54, 55, - 56, 57, 58, 59, 60, 61, -2, -2, -2, -2, -2, -2, -2, 0, 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, -2, -2, -2, -2, -2, -2, 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, -2, -2, -2, -2, -2, -2, -2, - -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, - -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, - -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, - -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, - -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2}; +constexpr std::array base64_reverse_table = { + -2, -2, -2, -2, -2, -2, -2, -2, -2, -1, -1, -2, -2, -1, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -1, -2, -2, -2, -2, + -2, -2, -2, -2, -2, -2, 62, -2, -2, -2, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -2, -2, -2, -2, -2, -2, -2, 0, 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, -2, -2, -2, -2, -2, -2, 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, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, + -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, + -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, + -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2}; constexpr std::string_view good_url_symbols_mask = "00000000000000000000000000000000" "00000000000001101111111111000000" @@ -39,10 +37,10 @@ constexpr std::string_view good_url_symbols_mask = "0000000000000000000000000000 "00000000000000000000000000000000" "00000000000000000000000000000000"; //[0-9a-zA-Z-_.] -int32_t base64_encode(const unsigned char *input, int32_t ilen, char *output, int32_t olen) noexcept { +int32_t base64_encode(const unsigned char* input, int32_t ilen, char* output, int32_t olen) noexcept { static constexpr std::string_view symbols64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; - auto next_input_uchar = [input, ilen](int32_t &i) { + auto next_input_uchar = [input, ilen](int32_t& i) { if (i >= ilen) { return static_cast(0); } @@ -83,16 +81,16 @@ int32_t base64_encode(const unsigned char *input, int32_t ilen, char *output, in } // returns associative array like [host=> path=>] or empty array if str is not a valid url -array php_url_parse_ex(const char *str, string::size_type length) noexcept { +array php_url_parse_ex(const char* str, string::size_type length) noexcept { array result; - const char *s = str; - const char *e = nullptr; - const char *p = nullptr; - const char *pp = nullptr; - const char *ue = str + length; + const char* s = str; + const char* e = nullptr; + const char* p = nullptr; + const char* pp = nullptr; + const char* ue = str + length; /* parse scheme */ - if ((e = static_cast(memchr(s, ':', length))) && e != s) { + if ((e = static_cast(memchr(s, ':', length))) && e != s) { /* validate scheme */ p = s; while (p < e) { @@ -190,19 +188,19 @@ array php_url_parse_ex(const char *str, string::size_type length) noexcep parse_host: /* Binary-safe strcspn(s, "/?#") */ e = ue; - if ((p = static_cast(memchr(s, '/', e - s)))) { + if ((p = static_cast(memchr(s, '/', e - s)))) { e = p; } - if ((p = static_cast(memchr(s, '?', e - s)))) { + if ((p = static_cast(memchr(s, '?', e - s)))) { e = p; } - if ((p = static_cast(memchr(s, '#', e - s)))) { + if ((p = static_cast(memchr(s, '#', e - s)))) { e = p; } /* check for login and password */ - if ((p = static_cast(memrchr(s, '@', (e - s))))) { - if ((pp = static_cast(memchr(s, ':', (p - s))))) { + if ((p = static_cast(memrchr(s, '@', (e - s))))) { + if ((pp = static_cast(memchr(s, ':', (p - s))))) { result.set_value(string("user", 4), string(s, static_cast(pp - s))); pp++; result.set_value(string("pass", 4), string(pp, static_cast(p - pp))); @@ -218,7 +216,7 @@ array php_url_parse_ex(const char *str, string::size_type length) noexcep /* Short circuit portscan, we're dealing with an IPv6 embedded address */ p = nullptr; } else { - p = static_cast(memrchr(s, ':', (e - s))); + p = static_cast(memrchr(s, ':', (e - s))); } if (p) { @@ -255,7 +253,7 @@ array php_url_parse_ex(const char *str, string::size_type length) noexcep just_path: e = ue; - p = static_cast(memchr(s, '#', (e - s))); + p = static_cast(memchr(s, '#', (e - s))); if (p) { p++; if (p < e) { @@ -264,7 +262,7 @@ array php_url_parse_ex(const char *str, string::size_type length) noexcep e = p - 1; } - p = static_cast(memchr(s, '?', (e - s))); + p = static_cast(memchr(s, '?', (e - s))); if (p) { p++; if (p < e) { @@ -280,9 +278,9 @@ array php_url_parse_ex(const char *str, string::size_type length) noexcep return result; } -void parse_str_set_array_value(mixed &arr, const char *left_br_pos, int key_len, const string &value) noexcept { +void parse_str_set_array_value(mixed& arr, const char* left_br_pos, int key_len, const string& value) noexcept { php_assert(*left_br_pos == '['); - const char *right_br_pos = static_cast(memchr(left_br_pos + 1, ']', key_len - 1)); + const char* right_br_pos = static_cast(memchr(left_br_pos + 1, ']', key_len - 1)); if (right_br_pos != nullptr) { string next_key(left_br_pos + 1, static_cast(right_br_pos - left_br_pos - 1)); if (!arr.is_array()) { @@ -305,10 +303,10 @@ void parse_str_set_array_value(mixed &arr, const char *left_br_pos, int key_len, } // namespace -string f$base64_encode(const string &s) noexcept { +string f$base64_encode(const string& s) noexcept { int32_t result_len = (s.size() + 2) / 3 * 4; string res(result_len, false); - result_len = base64_encode(reinterpret_cast(s.c_str()), static_cast(s.size()), res.buffer(), result_len + 1); + result_len = base64_encode(reinterpret_cast(s.c_str()), static_cast(s.size()), res.buffer(), result_len + 1); if (result_len != 0) { return {}; @@ -320,7 +318,7 @@ string f$base64_encode(const string &s) noexcept { /* Function f$base64_decode ported from https://github.com/php/php-src/blob/master/ext/standard/base64.c#L130 * "This product includes PHP software, freely available from ". */ -Optional f$base64_decode(const string &s, bool strict) noexcept { +Optional f$base64_decode(const string& s, bool strict) noexcept { /* run through the whole string, converting as we go */ string::size_type result_len = (s.size() + 3) / 4 * 3; string result(result_len, false); @@ -352,21 +350,21 @@ Optional f$base64_decode(const string &s, bool strict) noexcept { } switch (i % 4) { - case 0: - result[j] = static_cast(ch << 2); - break; - case 1: - result[j] = static_cast(result[j] | (ch >> 4)); - result[++j] = static_cast((ch & 0x0f) << 4); - break; - case 2: - result[j] = static_cast(result[j] | (ch >> 2)); - result[++j] = static_cast((ch & 0x03) << 6); - break; - case 3: - result[j] = static_cast(result[j] | ch); - ++j; - break; + case 0: + result[j] = static_cast(ch << 2); + break; + case 1: + result[j] = static_cast(result[j] | (ch >> 4)); + result[++j] = static_cast((ch & 0x0f) << 4); + break; + case 2: + result[j] = static_cast(result[j] | (ch >> 2)); + result[++j] = static_cast((ch & 0x03) << 6); + break; + case 3: + result[j] = static_cast(result[j] | ch); + ++j; + break; } i++; } @@ -385,11 +383,11 @@ Optional f$base64_decode(const string &s, bool strict) noexcept { return result; } -string f$rawurlencode(const string &s) noexcept { - auto &runtime_ctx{RuntimeContext::get()}; +string f$rawurlencode(const string& s) noexcept { + auto& runtime_ctx{RuntimeContext::get()}; runtime_ctx.static_SB.clean().reserve(3 * s.size()); - const auto &string_lib_constants{StringLibConstants::get()}; + const auto& string_lib_constants{StringLibConstants::get()}; for (string::size_type i = 0; i < s.size(); ++i) { if (good_url_symbols_mask[static_cast(s[i])] == '1') { runtime_ctx.static_SB.append_char(s[i]); @@ -402,8 +400,8 @@ string f$rawurlencode(const string &s) noexcept { return runtime_ctx.static_SB.str(); } -string f$rawurldecode(const string &s) noexcept { - auto &runtime_ctx{RuntimeContext::get()}; +string f$rawurldecode(const string& s) noexcept { + auto& runtime_ctx{RuntimeContext::get()}; runtime_ctx.static_SB.clean().reserve(s.size()); for (string::size_type i = 0; i < s.size(); ++i) { @@ -421,11 +419,11 @@ string f$rawurldecode(const string &s) noexcept { return runtime_ctx.static_SB.str(); } -string f$urlencode(const string &s) noexcept { - auto &runtime_ctx{RuntimeContext::get()}; +string f$urlencode(const string& s) noexcept { + auto& runtime_ctx{RuntimeContext::get()}; runtime_ctx.static_SB.clean().reserve(3 * s.size()); - const auto &string_lib_constants{StringLibConstants::get()}; + const auto& string_lib_constants{StringLibConstants::get()}; for (string::size_type i = 0; i < s.size(); ++i) { if (good_url_symbols_mask[static_cast(s[i])] == '1') { runtime_ctx.static_SB.append_char(s[i]); @@ -440,8 +438,8 @@ string f$urlencode(const string &s) noexcept { return runtime_ctx.static_SB.str(); } -string f$urldecode(const string &s) noexcept { - auto &runtime_ctx{RuntimeContext::get()}; +string f$urldecode(const string& s) noexcept { + auto& runtime_ctx{RuntimeContext::get()}; runtime_ctx.static_SB.clean().reserve(s.size()); for (string::size_type i = 0; i < s.size(); ++i) { @@ -463,7 +461,7 @@ string f$urldecode(const string &s) noexcept { } // returns var, as array|false|null (null if component doesn't exist) -mixed f$parse_url(const string &s, int64_t component) noexcept { +mixed f$parse_url(const string& s, int64_t component) noexcept { array url_as_array = php_url_parse_ex(s.c_str(), s.size()); if (url_as_array.empty()) { @@ -472,34 +470,34 @@ mixed f$parse_url(const string &s, int64_t component) noexcept { if (component != -1) { switch (component) { - case 0: // PHP_URL_SCHEME - return url_as_array.get_value(string("scheme", 6)); - case 1: // PHP_URL_HOST - return url_as_array.get_value(string("host", 4)); - case 2: // PHP_URL_PORT - return url_as_array.get_value(string("port", 4)); - case 3: // PHP_URL_USER - return url_as_array.get_value(string("user", 4)); - case 4: // PHP_URL_PASS - return url_as_array.get_value(string("pass", 4)); - case 5: // PHP_URL_PATH - return url_as_array.get_value(string("path", 4)); - case 6: // PHP_URL_QUERY - return url_as_array.get_value(string("query", 5)); - case 7: // PHP_URL_FRAGMENT - return url_as_array.get_value(string("fragment", 8)); - default: - php_warning("Wrong parameter component = %" PRIi64 " in function parse_url", component); - return false; + case 0: // PHP_URL_SCHEME + return url_as_array.get_value(string("scheme", 6)); + case 1: // PHP_URL_HOST + return url_as_array.get_value(string("host", 4)); + case 2: // PHP_URL_PORT + return url_as_array.get_value(string("port", 4)); + case 3: // PHP_URL_USER + return url_as_array.get_value(string("user", 4)); + case 4: // PHP_URL_PASS + return url_as_array.get_value(string("pass", 4)); + case 5: // PHP_URL_PATH + return url_as_array.get_value(string("path", 4)); + case 6: // PHP_URL_QUERY + return url_as_array.get_value(string("query", 5)); + case 7: // PHP_URL_FRAGMENT + return url_as_array.get_value(string("fragment", 8)); + default: + php_warning("Wrong parameter component = %" PRIi64 " in function parse_url", component); + return false; } } return url_as_array; } -void parse_str_set_value(mixed &arr, const string &key, const string &value) noexcept { - const char *key_c = key.c_str(); - const char *left_br_pos = static_cast(std::memchr(key_c, '[', key.size())); +void parse_str_set_value(mixed& arr, const string& key, const string& value) noexcept { + const char* key_c = key.c_str(); + const char* left_br_pos = static_cast(std::memchr(key_c, '[', key.size())); if (left_br_pos != nullptr) { return parse_str_set_array_value(arr[string(key_c, static_cast(left_br_pos - key_c))], left_br_pos, static_cast(key_c + key.size() - left_br_pos), value); @@ -508,7 +506,7 @@ void parse_str_set_value(mixed &arr, const string &key, const string &value) noe arr.set_value(key, value); } -void f$parse_str(const string &str, mixed &arr) noexcept { +void f$parse_str(const string& str, mixed& arr) noexcept { if (f$trim(str).empty()) { arr = array(); return; @@ -519,8 +517,8 @@ void f$parse_str(const string &str, mixed &arr) noexcept { array par = explode('&', str, std::numeric_limits::max()); int64_t len = par.count(); for (int64_t i = 0; i < len; i++) { - const char *cur = par.get_value(i).c_str(); - const char *eq_pos = strchrnul(cur, '='); + const char* cur = par.get_value(i).c_str(); + const char* eq_pos = strchrnul(cur, '='); string value; if (*eq_pos) { value = f$urldecode(string(eq_pos + 1)); diff --git a/runtime-common/stdlib/server/url-functions.h b/runtime-common/stdlib/server/url-functions.h index 1f60ba301a..c153908d06 100644 --- a/runtime-common/stdlib/server/url-functions.h +++ b/runtime-common/stdlib/server/url-functions.h @@ -6,20 +6,20 @@ #include "runtime-common/core/runtime-core.h" -string f$base64_encode(const string &s) noexcept; +string f$base64_encode(const string& s) noexcept; -Optional f$base64_decode(const string &s, bool strict = false) noexcept; +Optional f$base64_decode(const string& s, bool strict = false) noexcept; -string f$rawurlencode(const string &s) noexcept; +string f$rawurlencode(const string& s) noexcept; -string f$rawurldecode(const string &s) noexcept; +string f$rawurldecode(const string& s) noexcept; -string f$urlencode(const string &s) noexcept; +string f$urlencode(const string& s) noexcept; -string f$urldecode(const string &s) noexcept; +string f$urldecode(const string& s) noexcept; -mixed f$parse_url(const string &s, int64_t component = -1) noexcept; +mixed f$parse_url(const string& s, int64_t component = -1) noexcept; -void parse_str_set_value(mixed &arr, const string &key, const string &value) noexcept; +void parse_str_set_value(mixed& arr, const string& key, const string& value) noexcept; -void f$parse_str(const string &str, mixed &arr) noexcept; +void f$parse_str(const string& str, mixed& arr) noexcept; diff --git a/runtime-common/stdlib/string/mbstring-functions.cpp b/runtime-common/stdlib/string/mbstring-functions.cpp index cbe8887beb..6c91852e5c 100644 --- a/runtime-common/stdlib/string/mbstring-functions.cpp +++ b/runtime-common/stdlib/string/mbstring-functions.cpp @@ -9,8 +9,8 @@ #include "runtime-common/stdlib/string/string-context.h" #include "runtime-common/stdlib/string/string-functions.h" -int mb_detect_encoding_new(const string &encoding) noexcept { - const auto *encoding_name = f$strtolower(encoding).c_str(); +int mb_detect_encoding_new(const string& encoding) noexcept { + const auto* encoding_name = f$strtolower(encoding).c_str(); if (!strcmp(encoding_name, "cp1251") || !strcmp(encoding_name, "cp-1251") || !strcmp(encoding_name, "windows-1251")) { return 1251; @@ -23,7 +23,7 @@ int mb_detect_encoding_new(const string &encoding) noexcept { return -1; } -int mb_detect_encoding(const string &encoding) noexcept { +int mb_detect_encoding(const string& encoding) noexcept { const int result_new = mb_detect_encoding_new(encoding); const auto detect_incorrect_encoding_names = StringLibContext::get().detect_incorrect_encoding_names; @@ -46,7 +46,7 @@ int mb_detect_encoding(const string &encoding) noexcept { return -1; } -int64_t mb_UTF8_strlen(const char *s) { +int64_t mb_UTF8_strlen(const char* s) { int64_t res = 0; for (int64_t i = 0; s[i]; i++) { if (((static_cast(s[i])) & 0xc0) != 0x80) { @@ -56,7 +56,7 @@ int64_t mb_UTF8_strlen(const char *s) { return res; } -int64_t mb_UTF8_advance(const char *s, int64_t cnt) { +int64_t mb_UTF8_advance(const char* s, int64_t cnt) { php_assert(cnt >= 0); int64_t i = 0; for (i = 0; s[i] && cnt >= 0; i++) { @@ -70,7 +70,7 @@ int64_t mb_UTF8_advance(const char *s, int64_t cnt) { return i; } -int64_t mb_UTF8_get_offset(const char *s, int64_t pos) { +int64_t mb_UTF8_get_offset(const char* s, int64_t pos) { int64_t res = 0; for (int64_t i = 0; i < pos && s[i]; i++) { if (((static_cast(s[i])) & 0xc0) != 0x80) { @@ -80,7 +80,7 @@ int64_t mb_UTF8_get_offset(const char *s, int64_t pos) { return res; } -bool mb_UTF8_check(const char *s) noexcept { +bool mb_UTF8_check(const char* s) noexcept { do { #define CHECK(condition) \ if (!(condition)) { \ @@ -126,7 +126,7 @@ bool mb_UTF8_check(const char *s) noexcept { php_assert(0); } -bool f$mb_check_encoding(const string &str, const string &encoding) noexcept { +bool f$mb_check_encoding(const string& str, const string& encoding) noexcept { int encoding_num = mb_detect_encoding(encoding); if (encoding_num < 0) { php_critical_error("encoding \"%s\" doesn't supported in mb_check_encoding", encoding.c_str()); @@ -140,7 +140,7 @@ bool f$mb_check_encoding(const string &str, const string &encoding) noexcept { return mb_UTF8_check(str.c_str()); } -int64_t f$mb_strlen(const string &str, const string &encoding) noexcept { +int64_t f$mb_strlen(const string& str, const string& encoding) noexcept { int encoding_num = mb_detect_encoding(encoding); if (encoding_num < 0) { php_critical_error("encoding \"%s\" doesn't supported in mb_strlen", encoding.c_str()); @@ -154,7 +154,7 @@ int64_t f$mb_strlen(const string &str, const string &encoding) noexcept { return mb_UTF8_strlen(str.c_str()); } -string f$mb_strtolower(const string &str, const string &encoding) noexcept { +string f$mb_strtolower(const string& str, const string& encoding) noexcept { int encoding_num = mb_detect_encoding(encoding); if (encoding_num < 0) { php_critical_error("encoding \"%s\" doesn't supported in mb_strtolower", encoding.c_str()); @@ -166,43 +166,43 @@ string f$mb_strtolower(const string &str, const string &encoding) noexcept { string res(len, false); for (int i = 0; i < len; i++) { switch (static_cast(str[i])) { - case 'A' ... 'Z': - res[i] = static_cast(str[i] + 'a' - 'A'); - break; - case 0xC0 ... 0xDF: - res[i] = static_cast(str[i] + 32); - break; - case 0x81: - res[i] = static_cast(0x83); - break; - case 0xA3: - res[i] = static_cast(0xBC); - break; - case 0xA5: - res[i] = static_cast(0xB4); - break; - case 0xA1: - case 0xB2: - case 0xBD: - res[i] = static_cast(str[i] + 1); - break; - case 0x80: - case 0x8A: - case 0x8C ... 0x8F: - case 0xA8: - case 0xAA: - case 0xAF: - res[i] = static_cast(str[i] + 16); - break; - default: - res[i] = str[i]; + case 'A' ... 'Z': + res[i] = static_cast(str[i] + 'a' - 'A'); + break; + case 0xC0 ... 0xDF: + res[i] = static_cast(str[i] + 32); + break; + case 0x81: + res[i] = static_cast(0x83); + break; + case 0xA3: + res[i] = static_cast(0xBC); + break; + case 0xA5: + res[i] = static_cast(0xB4); + break; + case 0xA1: + case 0xB2: + case 0xBD: + res[i] = static_cast(str[i] + 1); + break; + case 0x80: + case 0x8A: + case 0x8C ... 0x8F: + case 0xA8: + case 0xAA: + case 0xAF: + res[i] = static_cast(str[i] + 16); + break; + default: + res[i] = str[i]; } } return res; } else { string res(len * 3, false); - const char *s = str.c_str(); + const char* s = str.c_str(); int res_len = 0; int p = 0; int ch = 0; @@ -219,7 +219,7 @@ string f$mb_strtolower(const string &str, const string &encoding) noexcept { } } -string f$mb_strtoupper(const string &str, const string &encoding) noexcept { +string f$mb_strtoupper(const string& str, const string& encoding) noexcept { int encoding_num = mb_detect_encoding(encoding); if (encoding_num < 0) { php_critical_error("encoding \"%s\" doesn't supported in mb_strtoupper", encoding.c_str()); @@ -231,48 +231,48 @@ string f$mb_strtoupper(const string &str, const string &encoding) noexcept { string res(len, false); for (int i = 0; i < len; i++) { switch (static_cast(str[i])) { - case 'a' ... 'z': - res[i] = static_cast(str[i] + 'A' - 'a'); - break; - case 0xE0 ... 0xFF: - res[i] = static_cast(str[i] - 32); - break; - case 0x83: - res[i] = static_cast(0x81); - break; - case 0xBC: - res[i] = static_cast(0xA3); - break; - case 0xB4: - res[i] = static_cast(0xA5); - break; - case 0xA2: - case 0xB3: - case 0xBE: - res[i] = static_cast(str[i] - 1); - break; - case 0x98: - case 0xA0: - case 0xAD: - res[i] = ' '; - break; - case 0x90: - case 0x9A: - case 0x9C ... 0x9F: - case 0xB8: - case 0xBA: - case 0xBF: - res[i] = static_cast(str[i] - 16); - break; - default: - res[i] = str[i]; + case 'a' ... 'z': + res[i] = static_cast(str[i] + 'A' - 'a'); + break; + case 0xE0 ... 0xFF: + res[i] = static_cast(str[i] - 32); + break; + case 0x83: + res[i] = static_cast(0x81); + break; + case 0xBC: + res[i] = static_cast(0xA3); + break; + case 0xB4: + res[i] = static_cast(0xA5); + break; + case 0xA2: + case 0xB3: + case 0xBE: + res[i] = static_cast(str[i] - 1); + break; + case 0x98: + case 0xA0: + case 0xAD: + res[i] = ' '; + break; + case 0x90: + case 0x9A: + case 0x9C ... 0x9F: + case 0xB8: + case 0xBA: + case 0xBF: + res[i] = static_cast(str[i] - 16); + break; + default: + res[i] = str[i]; } } return res; } else { string res(len * 3, false); - const char *s = str.c_str(); + const char* s = str.c_str(); int res_len = 0; int p = 0; int ch = 0; @@ -291,7 +291,7 @@ string f$mb_strtoupper(const string &str, const string &encoding) noexcept { namespace { -int check_strpos_agrs(const char *func_name, const string &needle, int64_t offset, const string &encoding) noexcept { +int check_strpos_agrs(const char* func_name, const string& needle, int64_t offset, const string& encoding) noexcept { if (unlikely(offset < 0)) { php_warning("Wrong offset = %" PRIi64 " in function %s()", offset, func_name); return 0; @@ -309,13 +309,13 @@ int check_strpos_agrs(const char *func_name, const string &needle, int64_t offse return encoding_num; } -Optional mp_strpos_impl(const string &haystack, const string &needle, int64_t offset, int encoding_num) noexcept { +Optional mp_strpos_impl(const string& haystack, const string& needle, int64_t offset, int encoding_num) noexcept { if (encoding_num == 1251) { return f$strpos(haystack, needle, offset); } int64_t UTF8_offset = mb_UTF8_advance(haystack.c_str(), offset); - const char *s = static_cast(memmem(haystack.c_str() + UTF8_offset, haystack.size() - UTF8_offset, needle.c_str(), needle.size())); + const char* s = static_cast(memmem(haystack.c_str() + UTF8_offset, haystack.size() - UTF8_offset, needle.c_str(), needle.size())); if (unlikely(s == nullptr)) { return false; } @@ -324,21 +324,21 @@ Optional mp_strpos_impl(const string &haystack, const string &needle, i } // namespace -Optional f$mb_strpos(const string &haystack, const string &needle, int64_t offset, const string &encoding) noexcept { +Optional f$mb_strpos(const string& haystack, const string& needle, int64_t offset, const string& encoding) noexcept { if (const int encoding_num = check_strpos_agrs("mb_strpos", needle, offset, encoding)) { return mp_strpos_impl(haystack, needle, offset, encoding_num); } return false; } -Optional f$mb_stripos(const string &haystack, const string &needle, int64_t offset, const string &encoding) noexcept { +Optional f$mb_stripos(const string& haystack, const string& needle, int64_t offset, const string& encoding) noexcept { if (const int encoding_num = check_strpos_agrs("mb_stripos", needle, offset, encoding)) { return mp_strpos_impl(f$mb_strtolower(haystack, encoding), f$mb_strtolower(needle, encoding), offset, encoding_num); } return false; } -string f$mb_substr(const string &str, int64_t start, const mixed &length_var, const string &encoding) noexcept { +string f$mb_substr(const string& str, int64_t start, const mixed& length_var, const string& encoding) noexcept { int encoding_num = mb_detect_encoding(encoding); if (encoding_num < 0) { php_critical_error("encoding \"%s\" doesn't supported in mb_substr", encoding.c_str()); diff --git a/runtime-common/stdlib/string/mbstring-functions.h b/runtime-common/stdlib/string/mbstring-functions.h index 374422f8f7..8602b98f98 100644 --- a/runtime-common/stdlib/string/mbstring-functions.h +++ b/runtime-common/stdlib/string/mbstring-functions.h @@ -9,29 +9,25 @@ #include "runtime-common/core/runtime-core.h" #include "runtime-common/stdlib/string/string-context.h" -bool mb_UTF8_check(const char *s) noexcept; +bool mb_UTF8_check(const char* s) noexcept; -bool f$mb_check_encoding(const string &str, const string &encoding = StringLibConstants::get().CP1251_STR) noexcept; +bool f$mb_check_encoding(const string& str, const string& encoding = StringLibConstants::get().CP1251_STR) noexcept; -int64_t f$mb_strlen(const string &str, const string &encoding = StringLibConstants::get().CP1251_STR) noexcept; +int64_t f$mb_strlen(const string& str, const string& encoding = StringLibConstants::get().CP1251_STR) noexcept; -string f$mb_strtolower(const string &str, const string &encoding = StringLibConstants::get().CP1251_STR) noexcept; +string f$mb_strtolower(const string& str, const string& encoding = StringLibConstants::get().CP1251_STR) noexcept; -string f$mb_strtoupper(const string &str, const string &encoding = StringLibConstants::get().CP1251_STR) noexcept; +string f$mb_strtoupper(const string& str, const string& encoding = StringLibConstants::get().CP1251_STR) noexcept; -Optional f$mb_strpos(const string &haystack, const string &needle, int64_t offset = 0, - const string &encoding = StringLibConstants::get().CP1251_STR) noexcept; +Optional f$mb_strpos(const string& haystack, const string& needle, int64_t offset = 0, + const string& encoding = StringLibConstants::get().CP1251_STR) noexcept; -Optional f$mb_stripos(const string &haystack, const string &needle, int64_t offset = 0, - const string &encoding = StringLibConstants::get().CP1251_STR) noexcept; +Optional f$mb_stripos(const string& haystack, const string& needle, int64_t offset = 0, + const string& encoding = StringLibConstants::get().CP1251_STR) noexcept; -string f$mb_substr(const string &str, int64_t start, const mixed &length = std::numeric_limits::max(), - const string &encoding = StringLibConstants::get().CP1251_STR) noexcept; +string f$mb_substr(const string& str, int64_t start, const mixed& length = std::numeric_limits::max(), + const string& encoding = StringLibConstants::get().CP1251_STR) noexcept; -inline void f$set_detect_incorrect_encoding_names_warning(bool show) noexcept { - StringLibContext::get().detect_incorrect_encoding_names = show; -} +inline void f$set_detect_incorrect_encoding_names_warning(bool show) noexcept { StringLibContext::get().detect_incorrect_encoding_names = show; } -inline void free_detect_incorrect_encoding_names() noexcept { - StringLibContext::get().detect_incorrect_encoding_names = false; -} +inline void free_detect_incorrect_encoding_names() noexcept { StringLibContext::get().detect_incorrect_encoding_names = false; } diff --git a/runtime-common/stdlib/string/regex-functions.cpp b/runtime-common/stdlib/string/regex-functions.cpp index c6b1629b68..1a44b29118 100644 --- a/runtime-common/stdlib/string/regex-functions.cpp +++ b/runtime-common/stdlib/string/regex-functions.cpp @@ -6,49 +6,49 @@ #include "runtime-common/core/runtime-core.h" -string f$preg_quote(const string &str, const string &delimiter) noexcept { - auto &static_SB{RuntimeContext::get().static_SB}; +string f$preg_quote(const string& str, const string& delimiter) noexcept { + auto& static_SB{RuntimeContext::get().static_SB}; const string::size_type len{str.size()}; static_SB.clean().reserve(4 * len); for (string::size_type i = 0; i < len; i++) { switch (str[i]) { - case '.': - case '\\': - case '+': - case '*': - case '?': - case '[': - case '^': - case ']': - case '$': - case '(': - case ')': - case '{': - case '}': - case '=': - case '!': - case '>': - case '<': - case '|': - case ':': - case '-': - case '#': + case '.': + case '\\': + case '+': + case '*': + case '?': + case '[': + case '^': + case ']': + case '$': + case '(': + case ')': + case '{': + case '}': + case '=': + case '!': + case '>': + case '<': + case '|': + case ':': + case '-': + case '#': + static_SB.append_char('\\'); + static_SB.append_char(str[i]); + break; + case '\0': + static_SB.append_char('\\'); + static_SB.append_char('0'); + static_SB.append_char('0'); + static_SB.append_char('0'); + break; + default: + if (!delimiter.empty() && str[i] == delimiter[0]) { static_SB.append_char('\\'); - static_SB.append_char(str[i]); - break; - case '\0': - static_SB.append_char('\\'); - static_SB.append_char('0'); - static_SB.append_char('0'); - static_SB.append_char('0'); - break; - default: - if (!delimiter.empty() && str[i] == delimiter[0]) { - static_SB.append_char('\\'); - } - static_SB.append_char(str[i]); - break; + } + static_SB.append_char(str[i]); + break; } } diff --git a/runtime-common/stdlib/string/regex-functions.h b/runtime-common/stdlib/string/regex-functions.h index a958b67d8b..b8ca0d12cc 100644 --- a/runtime-common/stdlib/string/regex-functions.h +++ b/runtime-common/stdlib/string/regex-functions.h @@ -6,4 +6,4 @@ #include "runtime-common/core/runtime-core.h" -string f$preg_quote(const string &str, const string &delimiter = {}) noexcept; +string f$preg_quote(const string& str, const string& delimiter = {}) noexcept; diff --git a/runtime-common/stdlib/string/string-context.h b/runtime-common/stdlib/string/string-context.h index d655fc18fe..1eff6b4f1e 100644 --- a/runtime-common/stdlib/string/string-context.h +++ b/runtime-common/stdlib/string/string-context.h @@ -45,7 +45,7 @@ class StringLibContext final : vk::not_copyable { // mb_string context bool detect_incorrect_encoding_names{}; - static StringLibContext &get() noexcept; + static StringLibContext& get() noexcept; }; struct StringLibConstants final : vk::not_copyable { @@ -87,5 +87,5 @@ struct StringLibConstants final : vk::not_copyable { PERCENT_STR.set_reference_counter_to(ExtraRefCnt::for_global_const); } - static const StringLibConstants &get() noexcept; + static const StringLibConstants& get() noexcept; }; diff --git a/runtime-common/stdlib/string/string-functions.cpp b/runtime-common/stdlib/string/string-functions.cpp index 0c76c9567c..e466b93f11 100644 --- a/runtime-common/stdlib/string/string-functions.cpp +++ b/runtime-common/stdlib/string/string-functions.cpp @@ -15,8 +15,8 @@ #include "runtime-common/core/runtime-core.h" #include "runtime-common/stdlib/string/string-context.h" -const char *get_mask(const string &what) noexcept { - auto &mask{StringLibContext::get().mask_buffer}; +const char* get_mask(const string& what) noexcept { + auto& mask{StringLibContext::get().mask_buffer}; std::memset(mask.data(), 0, mask.size()); int len = what.size(); @@ -35,11 +35,11 @@ const char *get_mask(const string &what) noexcept { return mask.data(); } -string f$addcslashes(const string &str, const string &what) noexcept { - const char *mask = get_mask(what); +string f$addcslashes(const string& str, const string& what) noexcept { + const char* mask = get_mask(what); int len = str.size(); - auto &static_SB = RuntimeContext::get().static_SB; + auto& static_SB = RuntimeContext::get().static_SB; static_SB.clean().reserve(4 * len); for (int i = 0; i < len; i++) { @@ -48,31 +48,31 @@ string f$addcslashes(const string &str, const string &what) noexcept { static_SB.append_char('\\'); if (c < 32 || c > 126) { switch (c) { - case '\n': - static_SB.append_char('n'); - break; - case '\t': - static_SB.append_char('t'); - break; - case '\r': - static_SB.append_char('r'); - break; - case '\a': - static_SB.append_char('a'); - break; - case '\v': - static_SB.append_char('v'); - break; - case '\b': - static_SB.append_char('b'); - break; - case '\f': - static_SB.append_char('f'); - break; - default: - static_SB.append_char(static_cast((c >> 6) + '0')); - static_SB.append_char(static_cast(((c >> 3) & 7) + '0')); - static_SB.append_char(static_cast((c & 7) + '0')); + case '\n': + static_SB.append_char('n'); + break; + case '\t': + static_SB.append_char('t'); + break; + case '\r': + static_SB.append_char('r'); + break; + case '\a': + static_SB.append_char('a'); + break; + case '\v': + static_SB.append_char('v'); + break; + case '\b': + static_SB.append_char('b'); + break; + case '\f': + static_SB.append_char('f'); + break; + default: + static_SB.append_char(static_cast((c >> 6) + '0')); + static_SB.append_char(static_cast(((c >> 3) & 7) + '0')); + static_SB.append_char(static_cast((c & 7) + '0')); } } else { static_SB.append_char(c); @@ -84,58 +84,56 @@ string f$addcslashes(const string &str, const string &what) noexcept { return static_SB.str(); } -string f$addslashes(const string &str) noexcept { +string f$addslashes(const string& str) noexcept { int len = str.size(); - auto &static_SB = RuntimeContext::get().static_SB; + auto& static_SB = RuntimeContext::get().static_SB; static_SB.clean().reserve(2 * len); for (int i = 0; i < len; i++) { switch (str[i]) { - case '\0': - static_SB.append_char('\\'); - static_SB.append_char('0'); - break; - case '\'': - case '\"': - case '\\': - static_SB.append_char('\\'); - /* fallthrough */ - default: - static_SB.append_char(str[i]); + case '\0': + static_SB.append_char('\\'); + static_SB.append_char('0'); + break; + case '\'': + case '\"': + case '\\': + static_SB.append_char('\\'); + /* fallthrough */ + default: + static_SB.append_char(str[i]); } } return static_SB.str(); } -constexpr unsigned char win_to_koi[] = {0, 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, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, - 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 154, 174, 190, 46, 159, 189, 46, 46, - 179, 191, 180, 157, 46, 46, 156, 183, 46, 46, 182, 166, 173, 46, 46, 158, 163, 152, 164, 155, 46, 46, 46, 167, - 225, 226, 247, 231, 228, 229, 246, 250, 233, 234, 235, 236, 237, 238, 239, 240, 242, 243, 244, 245, 230, 232, 227, 254, - 251, 253, 255, 249, 248, 252, 224, 241, 193, 194, 215, 199, 196, 197, 214, 218, 201, 202, 203, 204, 205, 206, 207, 208, - 210, 211, 212, 213, 198, 200, 195, 222, 219, 221, 223, 217, 216, 220, 192, 209}; - -constexpr unsigned char koi_to_win[] = {0, 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, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, - 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 184, 186, 32, 179, 191, - 32, 32, 32, 32, 32, 180, 162, 32, 32, 32, 32, 168, 170, 32, 178, 175, 32, 32, 32, 32, 32, 165, 161, 169, - 254, 224, 225, 246, 228, 229, 244, 227, 245, 232, 233, 234, 235, 236, 237, 238, 239, 255, 240, 241, 242, 243, 230, 226, - 252, 251, 231, 248, 253, 249, 247, 250, 222, 192, 193, 214, 196, 197, 212, 195, 213, 200, 201, 202, 203, 204, 205, 206, - 207, 223, 208, 209, 210, 211, 198, 194, 220, 219, 199, 216, 221, 217, 215, 218}; - -string f$convert_cyr_string(const string &str, const string &from_s, const string &to_s) noexcept { +constexpr unsigned char win_to_koi[] = { + 0, 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, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, + 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 154, 174, 190, 46, 159, 189, 46, 46, 179, 191, 180, 157, 46, 46, + 156, 183, 46, 46, 182, 166, 173, 46, 46, 158, 163, 152, 164, 155, 46, 46, 46, 167, 225, 226, 247, 231, 228, 229, 246, 250, 233, 234, 235, + 236, 237, 238, 239, 240, 242, 243, 244, 245, 230, 232, 227, 254, 251, 253, 255, 249, 248, 252, 224, 241, 193, 194, 215, 199, 196, 197, 214, 218, + 201, 202, 203, 204, 205, 206, 207, 208, 210, 211, 212, 213, 198, 200, 195, 222, 219, 221, 223, 217, 216, 220, 192, 209}; + +constexpr unsigned char koi_to_win[] = { + 0, 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, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, + 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 184, 186, 32, 179, 191, 32, 32, 32, 32, 32, 180, + 162, 32, 32, 32, 32, 168, 170, 32, 178, 175, 32, 32, 32, 32, 32, 165, 161, 169, 254, 224, 225, 246, 228, 229, 244, 227, 245, 232, 233, + 234, 235, 236, 237, 238, 239, 255, 240, 241, 242, 243, 230, 226, 252, 251, 231, 248, 253, 249, 247, 250, 222, 192, 193, 214, 196, 197, 212, 195, + 213, 200, 201, 202, 203, 204, 205, 206, 207, 223, 208, 209, 210, 211, 198, 194, 220, 219, 199, 216, 221, 217, 215, 218}; + +string f$convert_cyr_string(const string& str, const string& from_s, const string& to_s) noexcept { char from = static_cast(toupper(from_s[0])); char to = static_cast(toupper(to_s[0])); - const unsigned char *table = nullptr; + const unsigned char* table = nullptr; if (from == 'W' && to == 'K') { table = win_to_koi; } @@ -155,7 +153,7 @@ string f$convert_cyr_string(const string &str, const string &from_s, const strin return result; } -mixed f$count_chars(const string &str, int64_t mode) noexcept { +mixed f$count_chars(const string& str, int64_t mode) noexcept { int64_t chars[256] = {0}; if (static_cast(mode) > 4U) { @@ -187,7 +185,7 @@ mixed f$count_chars(const string &str, int64_t mode) noexcept { return result; } -string f$hex2bin(const string &str) noexcept { +string f$hex2bin(const string& str) noexcept { int len = str.size(); if (len & 1) { php_warning("Wrong argument \"%s\" supplied for function hex2bin", str.c_str()); @@ -210,39 +208,37 @@ string f$hex2bin(const string &str) noexcept { constexpr int entities_size = 251; -static const char *const ent_to_num_s[entities_size] = - {"AElig", "Aacute", "Acirc", "Agrave", "Alpha", "Aring", "Atilde", "Auml", "Beta", "Ccedil", "Chi", "Dagger", "Delta", "ETH", "Eacute", - "Ecirc", "Egrave", "Epsilon", "Eta", "Euml", "Gamma", "Iacute", "Icirc", "Igrave", "Iota", "Iuml", "Kappa", "Lambda", "Mu", "Ntilde", - "Nu", "OElig", "Oacute", "Ocirc", "Ograve", "Omega", "Omicron", "Oslash", "Otilde", "Ouml", "Phi", "Pi", "Prime", "Psi", "Rho", - "Scaron", "Sigma", "THORN", "Tau", "Theta", "Uacute", "Ucirc", "Ugrave", "Upsilon", "Uuml", "Xi", "Yacute", "Yuml", "Zeta", "aacute", - "acirc", "acute", "aelig", "agrave", "alefsym", "alpha", "amp", "and", "ang", "aring", "asymp", "atilde", "auml", "bdquo", "beta", - "brvbar", "bull", "cap", "ccedil", "cedil", "cent", "chi", "circ", "clubs", "cong", "copy", "crarr", "cup", "curren", "dArr", - "dagger", "darr", "deg", "delta", "diams", "divide", "eacute", "ecirc", "egrave", "empty", "emsp", "ensp", "epsilon", "equiv", "eta", - "eth", "euml", "euro", "exist", "fnof", "forall", "frac12", "frac14", "frac34", "frasl", "gamma", "ge", "gt", "hArr", "harr", - "hearts", "hellip", "iacute", "icirc", "iexcl", "igrave", "image", "infin", "int", "iota", "iquest", "isin", "iuml", "kappa", "lArr", - "lambda", "lang", "laquo", "larr", "lceil", "ldquo", "le", "lfloor", "lowast", "loz", "lrm", "lsaquo", "lsquo", "lt", "macr", - "mdash", "micro", "middot", "minus", "mu", "nabla", "nbsp", "ndash", "ne", "ni", "not", "notin", "nsub", "ntilde", "nu", - "oacute", "ocirc", "oelig", "ograve", "oline", "omega", "omicron", "oplus", "or", "ordf", "ordm", "oslash", "otilde", "otimes", "ouml", - "para", "part", "permil", "perp", "phi", "pi", "piv", "plusmn", "pound", "prime", "prod", "prop", "psi", "rArr", "radic", - "rang", "raquo", "rarr", "rceil", "rdquo", "real", "reg", "rfloor", "rho", "rlm", "rsaquo", "rsquo", "sbquo", "scaron", "sdot", - "sect", "shy", "sigma", "sigmaf", "sim", "spades", "sub", "sube", "sum", "sup", "sup1", "sup2", "sup3", "supe", "szlig", - "tau", "there4", "theta", "thetasym", "thinsp", "thorn", "tilde", "times", "trade", "uArr", "uacute", "uarr", "ucirc", "ugrave", "uml", - "upsih", "upsilon", "uuml", "weierp", "xi", "yacute", "yen", "yuml", "zeta", "zwj", "zwnj"}; - -constexpr int32_t ent_to_num_i[entities_size] = {198, 193, 194, 192, 913, 197, 195, 196, 914, 199, 935, 8225, 916, 208, 201, 202, 200, 917, - 919, 203, 915, 205, 206, 204, 921, 207, 922, 923, 924, 209, 925, 338, 211, 212, 210, 937, - 927, 216, 213, 214, 934, 928, 8243, 936, 929, 352, 931, 222, 932, 920, 218, 219, 217, 933, - 220, 926, 221, 376, 918, 225, 226, 180, 230, 224, 8501, 945, 38, 8743, 8736, 229, 8776, 227, - 228, 8222, 946, 166, 8226, 8745, 231, 184, 162, 967, 710, 9827, 8773, 169, 8629, 8746, 164, 8659, - 8224, 8595, 176, 948, 9830, 247, 233, 234, 232, 8709, 8195, 8194, 949, 8801, 951, 240, 235, 8364, - 8707, 402, 8704, 189, 188, 190, 8260, 947, 8805, 62, 8660, 8596, 9829, 8230, 237, 238, 161, 236, - 8465, 8734, 8747, 953, 191, 8712, 239, 954, 8656, 955, 9001, 171, 8592, 8968, 8220, 8804, 8970, 8727, - 9674, 8206, 8249, 8216, 60, 175, 8212, 181, 183, 8722, 956, 8711, 160, 8211, 8800, 8715, 172, 8713, - 8836, 241, 957, 243, 244, 339, 242, 8254, 969, 959, 8853, 8744, 170, 186, 248, 245, 8855, 246, - 182, 8706, 8240, 8869, 966, 960, 982, 177, 163, 8242, 8719, 8733, 968, 8658, 8730, 9002, 187, 8594, - 8969, 8221, 8476, 174, 8971, 961, 8207, 8250, 8217, 8218, 353, 8901, 167, 173, 963, 962, 8764, 9824, - 8834, 8838, 8721, 8835, 185, 178, 179, 8839, 223, 964, 8756, 952, 977, 8201, 254, 732, 215, 8482, - 8657, 250, 8593, 251, 249, 168, 978, 965, 252, 8472, 958, 253, 165, 255, 950, 8205, 8204}; +static const char* const ent_to_num_s[entities_size] = { + "AElig", "Aacute", "Acirc", "Agrave", "Alpha", "Aring", "Atilde", "Auml", "Beta", "Ccedil", "Chi", "Dagger", "Delta", "ETH", + "Eacute", "Ecirc", "Egrave", "Epsilon", "Eta", "Euml", "Gamma", "Iacute", "Icirc", "Igrave", "Iota", "Iuml", "Kappa", "Lambda", + "Mu", "Ntilde", "Nu", "OElig", "Oacute", "Ocirc", "Ograve", "Omega", "Omicron", "Oslash", "Otilde", "Ouml", "Phi", "Pi", + "Prime", "Psi", "Rho", "Scaron", "Sigma", "THORN", "Tau", "Theta", "Uacute", "Ucirc", "Ugrave", "Upsilon", "Uuml", "Xi", + "Yacute", "Yuml", "Zeta", "aacute", "acirc", "acute", "aelig", "agrave", "alefsym", "alpha", "amp", "and", "ang", "aring", + "asymp", "atilde", "auml", "bdquo", "beta", "brvbar", "bull", "cap", "ccedil", "cedil", "cent", "chi", "circ", "clubs", + "cong", "copy", "crarr", "cup", "curren", "dArr", "dagger", "darr", "deg", "delta", "diams", "divide", "eacute", "ecirc", + "egrave", "empty", "emsp", "ensp", "epsilon", "equiv", "eta", "eth", "euml", "euro", "exist", "fnof", "forall", "frac12", + "frac14", "frac34", "frasl", "gamma", "ge", "gt", "hArr", "harr", "hearts", "hellip", "iacute", "icirc", "iexcl", "igrave", + "image", "infin", "int", "iota", "iquest", "isin", "iuml", "kappa", "lArr", "lambda", "lang", "laquo", "larr", "lceil", + "ldquo", "le", "lfloor", "lowast", "loz", "lrm", "lsaquo", "lsquo", "lt", "macr", "mdash", "micro", "middot", "minus", + "mu", "nabla", "nbsp", "ndash", "ne", "ni", "not", "notin", "nsub", "ntilde", "nu", "oacute", "ocirc", "oelig", + "ograve", "oline", "omega", "omicron", "oplus", "or", "ordf", "ordm", "oslash", "otilde", "otimes", "ouml", "para", "part", + "permil", "perp", "phi", "pi", "piv", "plusmn", "pound", "prime", "prod", "prop", "psi", "rArr", "radic", "rang", + "raquo", "rarr", "rceil", "rdquo", "real", "reg", "rfloor", "rho", "rlm", "rsaquo", "rsquo", "sbquo", "scaron", "sdot", + "sect", "shy", "sigma", "sigmaf", "sim", "spades", "sub", "sube", "sum", "sup", "sup1", "sup2", "sup3", "supe", + "szlig", "tau", "there4", "theta", "thetasym", "thinsp", "thorn", "tilde", "times", "trade", "uArr", "uacute", "uarr", "ucirc", + "ugrave", "uml", "upsih", "upsilon", "uuml", "weierp", "xi", "yacute", "yen", "yuml", "zeta", "zwj", "zwnj"}; + +constexpr int32_t ent_to_num_i[entities_size] = { + 198, 193, 194, 192, 913, 197, 195, 196, 914, 199, 935, 8225, 916, 208, 201, 202, 200, 917, 919, 203, 915, 205, 206, 204, 921, 207, + 922, 923, 924, 209, 925, 338, 211, 212, 210, 937, 927, 216, 213, 214, 934, 928, 8243, 936, 929, 352, 931, 222, 932, 920, 218, 219, + 217, 933, 220, 926, 221, 376, 918, 225, 226, 180, 230, 224, 8501, 945, 38, 8743, 8736, 229, 8776, 227, 228, 8222, 946, 166, 8226, 8745, + 231, 184, 162, 967, 710, 9827, 8773, 169, 8629, 8746, 164, 8659, 8224, 8595, 176, 948, 9830, 247, 233, 234, 232, 8709, 8195, 8194, 949, 8801, + 951, 240, 235, 8364, 8707, 402, 8704, 189, 188, 190, 8260, 947, 8805, 62, 8660, 8596, 9829, 8230, 237, 238, 161, 236, 8465, 8734, 8747, 953, + 191, 8712, 239, 954, 8656, 955, 9001, 171, 8592, 8968, 8220, 8804, 8970, 8727, 9674, 8206, 8249, 8216, 60, 175, 8212, 181, 183, 8722, 956, 8711, + 160, 8211, 8800, 8715, 172, 8713, 8836, 241, 957, 243, 244, 339, 242, 8254, 969, 959, 8853, 8744, 170, 186, 248, 245, 8855, 246, 182, 8706, + 8240, 8869, 966, 960, 982, 177, 163, 8242, 8719, 8733, 968, 8658, 8730, 9002, 187, 8594, 8969, 8221, 8476, 174, 8971, 961, 8207, 8250, 8217, 8218, + 353, 8901, 167, 173, 963, 962, 8764, 9824, 8834, 8838, 8721, 8835, 185, 178, 179, 8839, 223, 964, 8756, 952, 977, 8201, 254, 732, 215, 8482, + 8657, 250, 8593, 251, 249, 168, 978, 965, 252, 8472, 958, 253, 165, 255, 950, 8205, 8204}; /* static int cp1251_to_utf8[128] = { 0x402, 0x403, 0x201A, 0x453, 0x201E, 0x2026, 0x2020, 0x2021, 0x20AC, 0x2030, 0x409, 0x2039, 0x40A, 0x40C, 0x40B, 0x40F, @@ -254,66 +250,66 @@ static int cp1251_to_utf8[128] = { 0x430, 0x431, 0x432, 0x433, 0x434, 0x435, 0x436, 0x437, 0x438, 0x439, 0x43A, 0x43B, 0x43C, 0x43D, 0x43E, 0x43F, 0x440, 0x441, 0x442, 0x443, 0x444, 0x445, 0x446, 0x447, 0x448, 0x449, 0x44A, 0x44B, 0x44C, 0x44D, 0x44E, 0x44F}; */ -static const char *const cp1251_to_utf8_str[128] = - {"Ђ", "Ѓ", "‚", "ѓ", "„", "…", "†", "‡", "€", "‰", "Љ", "‹", "Њ", - "Ќ", "Ћ", "Џ", "ђ", "‘", "’", "‛", "“", "•", "–", "—", "", "™", - "љ", "›", "њ", "ќ", "ћ", "џ", " ", "Ў", "ў", "Ј", "¤", "Ґ", "¦", - "§", "Ё", "©", "Є", "«", "¬", "­", "®", "Ї", "°", "±", "І", "і", - "ґ", "µ", "¶", "·", "ё", "№", "є", "»", "ј", "Ѕ", "ѕ", "ї", "А", - "Б", "В", "Г", "Д", "Е", "Ж", "З", "И", "Й", "К", "Л", "М", "Н", - "О", "П", "Р", "С", "Т", "У", "Ф", "Х", "Ц", "Ч", "Ш", "Щ", "Ъ", - "Ы", "Ь", "Э", "Ю", "Я", "а", "б", "в", "г", "д", "е", "ж", "з", - "и", "й", "к", "л", "м", "н", "о", "п", "р", "с", "т", "у", "ф", - "х", "ц", "ч", "ш", "щ", "ъ", "ы", "ь", "э", "ю", "я"}; - -string f$htmlentities(const string &str) noexcept { +static const char* const cp1251_to_utf8_str[128] = { + "Ђ", "Ѓ", "‚", "ѓ", "„", "…", "†", "‡", "€", "‰", "Љ", "‹", "Њ", + "Ќ", "Ћ", "Џ", "ђ", "‘", "’", "‛", "“", "•", "–", "—", "", "™", + "љ", "›", "њ", "ќ", "ћ", "џ", " ", "Ў", "ў", "Ј", "¤", "Ґ", "¦", + "§", "Ё", "©", "Є", "«", "¬", "­", "®", "Ї", "°", "±", "І", "і", + "ґ", "µ", "¶", "·", "ё", "№", "є", "»", "ј", "Ѕ", "ѕ", "ї", "А", + "Б", "В", "Г", "Д", "Е", "Ж", "З", "И", "Й", "К", "Л", "М", "Н", + "О", "П", "Р", "С", "Т", "У", "Ф", "Х", "Ц", "Ч", "Ш", "Щ", "Ъ", + "Ы", "Ь", "Э", "Ю", "Я", "а", "б", "в", "г", "д", "е", "ж", "з", + "и", "й", "к", "л", "м", "н", "о", "п", "р", "с", "т", "у", "ф", + "х", "ц", "ч", "ш", "щ", "ъ", "ы", "ь", "э", "ю", "я"}; + +string f$htmlentities(const string& str) noexcept { int len = static_cast(str.size()); - auto &static_SB = RuntimeContext::get().static_SB; + auto& static_SB = RuntimeContext::get().static_SB; static_SB.clean().reserve(8 * len); for (int i = 0; i < len; i++) { switch (str[i]) { - case '&': - static_SB.append_char('&'); - static_SB.append_char('a'); - static_SB.append_char('m'); - static_SB.append_char('p'); - static_SB.append_char(';'); - break; - case '"': - static_SB.append_char('&'); - static_SB.append_char('q'); - static_SB.append_char('u'); - static_SB.append_char('o'); - static_SB.append_char('t'); - static_SB.append_char(';'); - break; - case '<': - static_SB.append_char('&'); - static_SB.append_char('l'); - static_SB.append_char('t'); - static_SB.append_char(';'); - break; - case '>': - static_SB.append_char('&'); - static_SB.append_char('g'); - static_SB.append_char('t'); - static_SB.append_char(';'); - break; - default: - if (str[i] < 0) { - const char *utf8_str = cp1251_to_utf8_str[128 + str[i]]; - static_SB.append_unsafe(utf8_str, static_cast(strlen(utf8_str))); - } else { - static_SB.append_char(str[i]); - } + case '&': + static_SB.append_char('&'); + static_SB.append_char('a'); + static_SB.append_char('m'); + static_SB.append_char('p'); + static_SB.append_char(';'); + break; + case '"': + static_SB.append_char('&'); + static_SB.append_char('q'); + static_SB.append_char('u'); + static_SB.append_char('o'); + static_SB.append_char('t'); + static_SB.append_char(';'); + break; + case '<': + static_SB.append_char('&'); + static_SB.append_char('l'); + static_SB.append_char('t'); + static_SB.append_char(';'); + break; + case '>': + static_SB.append_char('&'); + static_SB.append_char('g'); + static_SB.append_char('t'); + static_SB.append_char(';'); + break; + default: + if (str[i] < 0) { + const char* utf8_str = cp1251_to_utf8_str[128 + str[i]]; + static_SB.append_unsafe(utf8_str, static_cast(strlen(utf8_str))); + } else { + static_SB.append_char(str[i]); + } } } return static_SB.str(); } -string f$html_entity_decode(const string &str, int64_t flags, const string &encoding) noexcept { +string f$html_entity_decode(const string& str, int64_t flags, const string& encoding) noexcept { if (flags >= 3) { php_critical_error("unsupported parameter flags = %" PRIi64 " in function html_entity_decode", flags); } @@ -326,7 +322,7 @@ string f$html_entity_decode(const string &str, int64_t flags, const string &enco int len = str.size(); string res(len * 7 / 4 + 4, false); - char *p = &res[0]; + char* p = &res[0]; for (int i = 0; i < len; i++) { if (str[i] == '&') { int j = i + 1; @@ -400,87 +396,87 @@ string f$html_entity_decode(const string &str, int64_t flags, const string &enco return res; } -string f$htmlspecialchars(const string &str, int64_t flags) noexcept { +string f$htmlspecialchars(const string& str, int64_t flags) noexcept { if (flags >= 3) { php_critical_error("unsupported parameter flags = %" PRIi64 " in function htmlspecialchars", flags); } const string::size_type len = str.size(); - auto &static_SB = RuntimeContext::get().static_SB; + auto& static_SB = RuntimeContext::get().static_SB; static_SB.clean().reserve(6 * len); for (string::size_type i = 0; i < len; i++) { switch (str[i]) { - case '&': - static_SB.append_char('&'); - static_SB.append_char('a'); - static_SB.append_char('m'); - static_SB.append_char('p'); - static_SB.append_char(';'); - break; - case '"': - if (!(flags & StringLibConstants::ENT_NOQUOTES)) { - static_SB.append_char('&'); - static_SB.append_char('q'); - static_SB.append_char('u'); - static_SB.append_char('o'); - static_SB.append_char('t'); - static_SB.append_char(';'); - } else { - static_SB.append_char('"'); - } - break; - case '\'': - if (flags & StringLibConstants::ENT_QUOTES) { - static_SB.append_char('&'); - static_SB.append_char('#'); - static_SB.append_char('0'); - static_SB.append_char('3'); - static_SB.append_char('9'); - static_SB.append_char(';'); - } else { - static_SB.append_char('\''); - } - break; - case '<': + case '&': + static_SB.append_char('&'); + static_SB.append_char('a'); + static_SB.append_char('m'); + static_SB.append_char('p'); + static_SB.append_char(';'); + break; + case '"': + if (!(flags & StringLibConstants::ENT_NOQUOTES)) { static_SB.append_char('&'); - static_SB.append_char('l'); + static_SB.append_char('q'); + static_SB.append_char('u'); + static_SB.append_char('o'); static_SB.append_char('t'); static_SB.append_char(';'); - break; - case '>': + } else { + static_SB.append_char('"'); + } + break; + case '\'': + if (flags & StringLibConstants::ENT_QUOTES) { static_SB.append_char('&'); - static_SB.append_char('g'); - static_SB.append_char('t'); + static_SB.append_char('#'); + static_SB.append_char('0'); + static_SB.append_char('3'); + static_SB.append_char('9'); static_SB.append_char(';'); - break; - default: - static_SB.append_char(str[i]); + } else { + static_SB.append_char('\''); + } + break; + case '<': + static_SB.append_char('&'); + static_SB.append_char('l'); + static_SB.append_char('t'); + static_SB.append_char(';'); + break; + case '>': + static_SB.append_char('&'); + static_SB.append_char('g'); + static_SB.append_char('t'); + static_SB.append_char(';'); + break; + default: + static_SB.append_char(str[i]); } } return static_SB.str(); } -string f$htmlspecialchars_decode(const string &str, int64_t flags) noexcept { +string f$htmlspecialchars_decode(const string& str, int64_t flags) noexcept { if (flags >= 3) { php_critical_error("unsupported parameter flags = %" PRIi64 " in function htmlspecialchars_decode", flags); } int len = str.size(); string res(len, false); - char *p = &res[0]; + char* p = &res[0]; for (int i = 0; i < len;) { if (str[i] == '&') { if (str[i + 1] == 'a' && str[i + 2] == 'm' && str[i + 3] == 'p' && str[i + 4] == ';') { *p++ = '&'; i += 5; - } else if (str[i + 1] == 'q' && str[i + 2] == 'u' && str[i + 3] == 'o' && str[i + 4] == 't' && str[i + 5] == ';' - && !(flags & StringLibConstants::ENT_NOQUOTES)) { + } else if (str[i + 1] == 'q' && str[i + 2] == 'u' && str[i + 3] == 'o' && str[i + 4] == 't' && str[i + 5] == ';' && + !(flags & StringLibConstants::ENT_NOQUOTES)) { *p++ = '"'; i += 6; - } else if (str[i + 1] == '#' && str[i + 2] == '0' && str[i + 3] == '3' && str[i + 4] == '9' && str[i + 5] == ';' - && (flags & StringLibConstants::ENT_QUOTES)) { + } else if (str[i + 1] == '#' && str[i + 2] == '0' && str[i + 3] == '3' && str[i + 4] == '9' && str[i + 5] == ';' && + (flags & StringLibConstants::ENT_QUOTES)) { *p++ = '\''; i += 6; } else if (str[i + 1] == 'l' && str[i + 2] == 't' && str[i + 3] == ';') { @@ -503,7 +499,7 @@ string f$htmlspecialchars_decode(const string &str, int64_t flags) noexcept { return res; } -int64_t f$levenshtein(const string &str1, const string &str2) noexcept { +int64_t f$levenshtein(const string& str1, const string& str2) noexcept { string::size_type len1 = str1.size(); string::size_type len2 = str2.size(); @@ -544,34 +540,34 @@ int64_t f$levenshtein(const string &str1, const string &str2) noexcept { return dp[len1 & 1][len2]; } -string f$mysql_escape_string(const string &str) noexcept { +string f$mysql_escape_string(const string& str) noexcept { int len = str.size(); - auto &static_SB = RuntimeContext::get().static_SB; + auto& static_SB = RuntimeContext::get().static_SB; static_SB.clean().reserve(2 * len); for (int i = 0; i < len; i++) { switch (str[i]) { - case '\0': - case '\n': - case '\r': - case 26: - case '\'': - case '\"': - case '\\': - static_SB.append_char('\\'); - /* fallthrough */ - default: - static_SB.append_char(str[i]); + case '\0': + case '\n': + case '\r': + case 26: + case '\'': + case '\"': + case '\\': + static_SB.append_char('\\'); + /* fallthrough */ + default: + static_SB.append_char(str[i]); } } return static_SB.str(); } -string f$nl2br(const string &str, bool is_xhtml) noexcept { - const char *br = is_xhtml ? "
" : "
"; +string f$nl2br(const string& str, bool is_xhtml) noexcept { + const char* br = is_xhtml ? "
" : "
"; int br_len = static_cast(strlen(br)); int len = str.size(); - auto &static_SB = RuntimeContext::get().static_SB; + auto& static_SB = RuntimeContext::get().static_SB; static_SB.clean().reserve((br_len + 1) * len); for (int i = 0; i < len;) { @@ -587,8 +583,8 @@ string f$nl2br(const string &str, bool is_xhtml) noexcept { return static_SB.str(); } -string f$number_format(double number, int64_t decimals, const string &dec_point, const string &thousands_sep) noexcept { - char *result_begin = StringLibContext::get().static_buf.data() + StringLibContext::STATIC_BUFFER_LENGTH; +string f$number_format(double number, int64_t decimals, const string& dec_point, const string& thousands_sep) noexcept { + char* result_begin = StringLibContext::get().static_buf.data() + StringLibContext::STATIC_BUFFER_LENGTH; if (decimals < 0 || decimals > 100) { php_warning("Wrong parameter decimals (%" PRIi64 ") in function number_format", decimals); @@ -672,8 +668,8 @@ static double float64_from_bits(uint64_t bits) { return f; } -string f$pack(const string &pattern, const array &a) noexcept { - auto &static_SB = RuntimeContext::get().static_SB; +string f$pack(const string& pattern, const array& a) noexcept { + auto& static_SB = RuntimeContext::get().static_SB; static_SB.clean(); int cur_arg = 0; for (int i = 0; i < static_cast(pattern.size());) { @@ -721,144 +717,144 @@ string f$pack(const string &pattern, const array &a) noexcept { char filler = 0; switch (format) { - case 'A': - filler = ' '; - /* fallthrough */ - case 'a': { - string arg_str = arg.to_string(); - int len = arg_str.size(); - if (!cnt) { - cnt = len; - i++; + case 'A': + filler = ' '; + /* fallthrough */ + case 'a': { + string arg_str = arg.to_string(); + int len = arg_str.size(); + if (!cnt) { + cnt = len; + i++; + } + static_SB.append(arg_str.c_str(), static_cast(min(cnt, len))); + while (cnt > len) { + static_SB << filler; + cnt--; + } + break; + } + case 'h': + case 'H': { + string arg_str = arg.to_string(); + int len = arg_str.size(); + if (!cnt) { + cnt = len; + i++; + } + for (int j = 0; cnt > 0 && j < len; j += 2) { + int num_high = hex_to_int(arg_str[j]); + int num_low = cnt > 1 ? hex_to_int(arg_str[j + 1]) : 0; + cnt -= 2; + if (num_high == 16 || num_low == 16) { + php_warning("Wrong argument \"%s\" supplied for format '%c' in function pack", arg_str.c_str(), format); + return {}; } - static_SB.append(arg_str.c_str(), static_cast(min(cnt, len))); - while (cnt > len) { - static_SB << filler; - cnt--; + if (format == 'H') { + static_SB << static_cast((num_high << 4) + num_low); + } else { + static_SB << static_cast((num_low << 4) + num_high); } - break; } - case 'h': - case 'H': { - string arg_str = arg.to_string(); - int len = arg_str.size(); - if (!cnt) { - cnt = len; - i++; + if (cnt > 0) { + php_warning("Type %c: not enough characters in string \"%s\" in function pack", format, arg_str.c_str()); + } + break; + } + + default: + do { + switch (format) { + case 'c': + case 'C': + static_SB << static_cast(arg.to_int()); + break; + case 's': + case 'S': + case 'v': { + unsigned short value = static_cast(arg.to_int()); + static_SB.append(reinterpret_cast(&value), 2); + break; } - for (int j = 0; cnt > 0 && j < len; j += 2) { - int num_high = hex_to_int(arg_str[j]); - int num_low = cnt > 1 ? hex_to_int(arg_str[j + 1]) : 0; - cnt -= 2; - if (num_high == 16 || num_low == 16) { - php_warning("Wrong argument \"%s\" supplied for format '%c' in function pack", arg_str.c_str(), format); - return {}; + case 'n': { + unsigned short value = static_cast(arg.to_int()); + static_SB << static_cast(value >> 8) << static_cast(value & 255); + break; + } + case 'i': + case 'I': + case 'l': + case 'L': + case 'V': { + auto value = static_cast(arg.to_int()); + static_SB.append(reinterpret_cast(&value), 4); + break; + } + case 'N': { + auto value = static_cast(arg.to_int()); + static_SB << static_cast(value >> 24) << static_cast((value >> 16) & 255) << static_cast((value >> 8) & 255) + << static_cast(value & 255); + break; + } + case 'f': { + auto value = static_cast(arg.to_float()); + static_SB.append(reinterpret_cast(&value), sizeof(float)); + break; + } + case 'e': + case 'E': + case 'd': { + double value = arg.to_float(); + uint64_t value_byteordered = float64_bits(value); + if (format == 'e') { + value_byteordered = htole64(value_byteordered); + } else if (format == 'E') { + value_byteordered = htobe64(value_byteordered); } - if (format == 'H') { - static_SB << static_cast((num_high << 4) + num_low); - } else { - static_SB << static_cast((num_low << 4) + num_high); + static_SB.append(reinterpret_cast(&value_byteordered), sizeof(uint64_t)); + break; + } + case 'J': + case 'P': + case 'Q': { + // stored in the host machine order by the default (Q flag) + unsigned long long value_byteordered = static_cast(arg.to_string().to_int()); + if (format == 'P') { + // for P encode in little endian order + value_byteordered = htole64(value_byteordered); + } else if (format == 'J') { + // for J encode in big endian order + value_byteordered = htobe64(value_byteordered); } + + static_SB.append(reinterpret_cast(&value_byteordered), sizeof(unsigned long long)); + break; } - if (cnt > 0) { - php_warning("Type %c: not enough characters in string \"%s\" in function pack", format, arg_str.c_str()); + case 'q': { + int64_t value = arg.to_string().to_int(); + static_SB.append(reinterpret_cast(&value), sizeof(long long)); + break; + } + default: + php_warning("Format code \"%c\" not supported", format); + return {}; } - break; - } - - default: - do { - switch (format) { - case 'c': - case 'C': - static_SB << static_cast(arg.to_int()); - break; - case 's': - case 'S': - case 'v': { - unsigned short value = static_cast(arg.to_int()); - static_SB.append(reinterpret_cast(&value), 2); - break; - } - case 'n': { - unsigned short value = static_cast(arg.to_int()); - static_SB << static_cast(value >> 8) << static_cast(value & 255); - break; - } - case 'i': - case 'I': - case 'l': - case 'L': - case 'V': { - auto value = static_cast(arg.to_int()); - static_SB.append(reinterpret_cast(&value), 4); - break; - } - case 'N': { - auto value = static_cast(arg.to_int()); - static_SB << static_cast(value >> 24) << static_cast((value >> 16) & 255) << static_cast((value >> 8) & 255) - << static_cast(value & 255); - break; - } - case 'f': { - auto value = static_cast(arg.to_float()); - static_SB.append(reinterpret_cast(&value), sizeof(float)); - break; - } - case 'e': - case 'E': - case 'd': { - double value = arg.to_float(); - uint64_t value_byteordered = float64_bits(value); - if (format == 'e') { - value_byteordered = htole64(value_byteordered); - } else if (format == 'E') { - value_byteordered = htobe64(value_byteordered); - } - static_SB.append(reinterpret_cast(&value_byteordered), sizeof(uint64_t)); - break; - } - case 'J': - case 'P': - case 'Q': { - // stored in the host machine order by the default (Q flag) - unsigned long long value_byteordered = static_cast(arg.to_string().to_int()); - if (format == 'P') { - // for P encode in little endian order - value_byteordered = htole64(value_byteordered); - } else if (format == 'J') { - // for J encode in big endian order - value_byteordered = htobe64(value_byteordered); - } - static_SB.append(reinterpret_cast(&value_byteordered), sizeof(unsigned long long)); - break; - } - case 'q': { - int64_t value = arg.to_string().to_int(); - static_SB.append(reinterpret_cast(&value), sizeof(long long)); - break; - } - default: - php_warning("Format code \"%c\" not supported", format); - return {}; + if (cnt > 1) { + arg_num = cur_arg++; + if (arg_num >= a.count()) { + php_warning("Not enough parameters to call function pack"); + return {}; } - if (cnt > 1) { - arg_num = cur_arg++; - if (arg_num >= a.count()) { - php_warning("Not enough parameters to call function pack"); - return {}; - } - - arg = a.get_value(arg_num); + arg = a.get_value(arg_num); - if (arg.is_array()) { - php_warning("Argument %d of function pack is array", arg_num); - return {}; - } + if (arg.is_array()) { + php_warning("Argument %d of function pack is array", arg_num); + return {}; } - } while (--cnt > 0); + } + } while (--cnt > 0); } } @@ -870,8 +866,8 @@ string f$pack(const string &pattern, const array &a) noexcept { return static_SB.str(); } -string f$ltrim(const string &s, const string &what) noexcept { - const char *mask = get_mask(what); +string f$ltrim(const string& s, const string& what) noexcept { + const char* mask = get_mask(what); int len = static_cast(s.size()); if (len == 0 || !mask[static_cast(s[0])]) { @@ -885,8 +881,8 @@ string f$ltrim(const string &s, const string &what) noexcept { return {s.c_str() + l, static_cast(len - l)}; } -string f$rtrim(const string &s, const string &what) noexcept { - const char *mask = get_mask(what); +string f$rtrim(const string& s, const string& what) noexcept { + const char* mask = get_mask(what); int len = static_cast(s.size()) - 1; if (len == -1 || !mask[static_cast(s[len])]) { @@ -900,8 +896,8 @@ string f$rtrim(const string &s, const string &what) noexcept { return {s.c_str(), static_cast(len)}; } -string f$sprintf(const string &format, const array &a) noexcept { - auto &static_SB = RuntimeContext::get().static_SB; +string f$sprintf(const string& format, const array& a) noexcept { + auto& static_SB = RuntimeContext::get().static_SB; string result; result.reserve_at_least(format.size()); int cur_arg = 0; @@ -985,7 +981,7 @@ string f$sprintf(const string &format, const array &a) noexcept { return {}; } - const mixed &arg = a.get_value(arg_num); + const mixed& arg = a.get_value(arg_num); if (arg.is_array()) { php_warning("Argument %d of function sprintf is array", arg_num); @@ -993,113 +989,113 @@ string f$sprintf(const string &format, const array &a) noexcept { } switch (format[i]) { - case 'b': { - auto arg_int = static_cast(arg.to_int()); - int cur_pos = 70; - do { - StringLibContext::get().static_buf[--cur_pos] = static_cast((arg_int & 1) + '0'); - arg_int >>= 1; - } while (arg_int > 0); - piece.assign(StringLibContext::get().static_buf.data() + cur_pos, 70 - cur_pos); - break; + case 'b': { + auto arg_int = static_cast(arg.to_int()); + int cur_pos = 70; + do { + StringLibContext::get().static_buf[--cur_pos] = static_cast((arg_int & 1) + '0'); + arg_int >>= 1; + } while (arg_int > 0); + piece.assign(StringLibContext::get().static_buf.data() + cur_pos, 70 - cur_pos); + break; + } + case 'c': { + int64_t arg_int = arg.to_int(); + if (arg_int <= -128 || arg_int > 255) { + php_warning("Wrong parameter for specifier %%c in function sprintf with format \"%s\"", format.c_str()); } - case 'c': { - int64_t arg_int = arg.to_int(); - if (arg_int <= -128 || arg_int > 255) { - php_warning("Wrong parameter for specifier %%c in function sprintf with format \"%s\"", format.c_str()); - } - piece.assign(1, static_cast(arg_int)); - break; + piece.assign(1, static_cast(arg_int)); + break; + } + case 'd': { + int64_t arg_int = arg.to_int(); + if (sign == '+' && arg_int >= 0) { + piece = (static_SB.clean() << "+" << arg_int).str(); + } else { + piece = string(arg_int); } - case 'd': { - int64_t arg_int = arg.to_int(); - if (sign == '+' && arg_int >= 0) { - piece = (static_SB.clean() << "+" << arg_int).str(); - } else { - piece = string(arg_int); - } - break; + break; + } + case 'u': { + auto arg_int = static_cast(arg.to_int()); + int cur_pos = 70; + do { + StringLibContext::get().static_buf[--cur_pos] = static_cast(arg_int % 10 + '0'); + arg_int /= 10; + } while (arg_int > 0); + piece.assign(StringLibContext::get().static_buf.data() + cur_pos, 70 - cur_pos); + break; + } + case 'e': + case 'E': + case 'f': + case 'F': + case 'g': + case 'G': { + double arg_float = arg.to_float(); + + static_SB.clean() << '%'; + if (sign) { + static_SB << sign; } - case 'u': { - auto arg_int = static_cast(arg.to_int()); - int cur_pos = 70; - do { - StringLibContext::get().static_buf[--cur_pos] = static_cast(arg_int % 10 + '0'); - arg_int /= 10; - } while (arg_int > 0); - piece.assign(StringLibContext::get().static_buf.data() + cur_pos, 70 - cur_pos); - break; + if (precision >= 0) { + static_SB << '.' << precision; } - case 'e': - case 'E': - case 'f': - case 'F': - case 'g': - case 'G': { - double arg_float = arg.to_float(); - - static_SB.clean() << '%'; - if (sign) { - static_SB << sign; - } - if (precision >= 0) { - static_SB << '.' << precision; - } - static_SB << format[i]; + static_SB << format[i]; - int len = snprintf(StringLibContext::get().static_buf.data(), StringLibContext::STATIC_BUFFER_LENGTH, static_SB.c_str(), arg_float); - if (len >= StringLibContext::STATIC_BUFFER_LENGTH) { - error_too_big = true; - break; - } - - piece.assign(StringLibContext::get().static_buf.data(), len); - break; - } - case 'o': { - auto arg_int = static_cast(arg.to_int()); - int cur_pos = 70; - do { - StringLibContext::get().static_buf[--cur_pos] = static_cast((arg_int & 7) + '0'); - arg_int >>= 3; - } while (arg_int > 0); - piece.assign(StringLibContext::get().static_buf.data() + cur_pos, 70 - cur_pos); + int len = snprintf(StringLibContext::get().static_buf.data(), StringLibContext::STATIC_BUFFER_LENGTH, static_SB.c_str(), arg_float); + if (len >= StringLibContext::STATIC_BUFFER_LENGTH) { + error_too_big = true; break; } - case 's': { - string arg_string = arg.to_string(); - - static_SB.clean() << '%'; - if (precision >= 0) { - static_SB << '.' << precision; - } - static_SB << 's'; - int len = snprintf(StringLibContext::get().static_buf.data(), StringLibContext::STATIC_BUFFER_LENGTH, static_SB.c_str(), arg_string.c_str()); - if (len >= StringLibContext::STATIC_BUFFER_LENGTH) { - error_too_big = true; - break; - } + piece.assign(StringLibContext::get().static_buf.data(), len); + break; + } + case 'o': { + auto arg_int = static_cast(arg.to_int()); + int cur_pos = 70; + do { + StringLibContext::get().static_buf[--cur_pos] = static_cast((arg_int & 7) + '0'); + arg_int >>= 3; + } while (arg_int > 0); + piece.assign(StringLibContext::get().static_buf.data() + cur_pos, 70 - cur_pos); + break; + } + case 's': { + string arg_string = arg.to_string(); - piece.assign(StringLibContext::get().static_buf.data(), len); - break; + static_SB.clean() << '%'; + if (precision >= 0) { + static_SB << '.' << precision; } - case 'x': - case 'X': { - const char *hex_digits = (format[i] == 'x' ? StringLibConstants::get().lhex_digits : StringLibConstants::get().uhex_digits); - auto arg_int = static_cast(arg.to_int()); - - int cur_pos = 70; - do { - StringLibContext::get().static_buf[--cur_pos] = hex_digits[arg_int & 15]; - arg_int >>= 4; - } while (arg_int > 0); - piece.assign(StringLibContext::get().static_buf.data() + cur_pos, 70 - cur_pos); + static_SB << 's'; + + int len = snprintf(StringLibContext::get().static_buf.data(), StringLibContext::STATIC_BUFFER_LENGTH, static_SB.c_str(), arg_string.c_str()); + if (len >= StringLibContext::STATIC_BUFFER_LENGTH) { + error_too_big = true; break; } - default: - php_warning("Unsupported specifier %%%c in sprintf with format \"%s\"", format[i], format.c_str()); - return {}; + + piece.assign(StringLibContext::get().static_buf.data(), len); + break; + } + case 'x': + case 'X': { + const char* hex_digits = (format[i] == 'x' ? StringLibConstants::get().lhex_digits : StringLibConstants::get().uhex_digits); + auto arg_int = static_cast(arg.to_int()); + + int cur_pos = 70; + do { + StringLibContext::get().static_buf[--cur_pos] = hex_digits[arg_int & 15]; + arg_int >>= 4; + } while (arg_int > 0); + piece.assign(StringLibContext::get().static_buf.data() + cur_pos, 70 - cur_pos); + break; + } + default: + php_warning("Unsupported specifier %%%c in sprintf with format \"%s\"", format[i], format.c_str()); + return {}; } } @@ -1114,7 +1110,7 @@ string f$sprintf(const string &format, const array &a) noexcept { return result; } -string f$stripcslashes(const string &str) noexcept { +string f$stripcslashes(const string& str) noexcept { if (str.empty()) { return str; } @@ -1124,7 +1120,7 @@ string f$stripcslashes(const string &str) noexcept { auto len = str.size(); auto new_len = len; string result(len, false); - char *result_c_str = &result[0]; + char* result_c_str = &result[0]; char num_tmp[4]; // we need up to three digits + a space for null-terminator int j = 0; @@ -1134,73 +1130,73 @@ string f$stripcslashes(const string &str) noexcept { } else { i++; // step over a backslash switch (str[i]) { - case 'n': - *result_c_str++ = '\n'; - new_len--; - break; - case 'r': - *result_c_str++ = '\r'; - new_len--; - break; - case 'a': - *result_c_str++ = '\a'; - new_len--; - break; - case 't': - *result_c_str++ = '\t'; - new_len--; - break; - case 'v': - *result_c_str++ = '\v'; - new_len--; - break; - case 'b': - *result_c_str++ = '\b'; - new_len--; - break; - case 'f': - *result_c_str++ = '\f'; - new_len--; - break; - case '\\': - *result_c_str++ = '\\'; - new_len--; - break; - case 'x': // \\xN or \\xNN - // collect up to two hex digits and interpret them as char + case 'n': + *result_c_str++ = '\n'; + new_len--; + break; + case 'r': + *result_c_str++ = '\r'; + new_len--; + break; + case 'a': + *result_c_str++ = '\a'; + new_len--; + break; + case 't': + *result_c_str++ = '\t'; + new_len--; + break; + case 'v': + *result_c_str++ = '\v'; + new_len--; + break; + case 'b': + *result_c_str++ = '\b'; + new_len--; + break; + case 'f': + *result_c_str++ = '\f'; + new_len--; + break; + case '\\': + *result_c_str++ = '\\'; + new_len--; + break; + case 'x': // \\xN or \\xNN + // collect up to two hex digits and interpret them as char + if (i + 1 < len && isxdigit(static_cast(str[i + 1]))) { + num_tmp[0] = str[++i]; if (i + 1 < len && isxdigit(static_cast(str[i + 1]))) { - num_tmp[0] = str[++i]; - if (i + 1 < len && isxdigit(static_cast(str[i + 1]))) { - num_tmp[1] = str[++i]; - num_tmp[2] = '\0'; - new_len -= 3; - } else { - num_tmp[1] = '\0'; - new_len -= 2; - } - *result_c_str++ = static_cast(strtol(num_tmp, nullptr, 16)); + num_tmp[1] = str[++i]; + num_tmp[2] = '\0'; + new_len -= 3; } else { - // not a hex literal, just copy a char as i - *result_c_str++ = str[i]; - new_len--; - } - break; - default: // \N \NN \NNN - // collect up to three octal digits and interpret them as char - j = 0; - while (i < len && str[i] >= '0' && str[i] <= '7' && j < 3) { - num_tmp[j++] = str[i++]; - } - if (j) { - num_tmp[j] = '\0'; - *result_c_str++ = static_cast(strtol(num_tmp, nullptr, 8)); - new_len -= j; - i--; - } else { - // not an octal literal, just copy a char as is - *result_c_str++ = str[i]; - new_len--; + num_tmp[1] = '\0'; + new_len -= 2; } + *result_c_str++ = static_cast(strtol(num_tmp, nullptr, 16)); + } else { + // not a hex literal, just copy a char as i + *result_c_str++ = str[i]; + new_len--; + } + break; + default: // \N \NN \NNN + // collect up to three octal digits and interpret them as char + j = 0; + while (i < len && str[i] >= '0' && str[i] <= '7' && j < 3) { + num_tmp[j++] = str[i++]; + } + if (j) { + num_tmp[j] = '\0'; + *result_c_str++ = static_cast(strtol(num_tmp, nullptr, 8)); + new_len -= j; + i--; + } else { + // not an octal literal, just copy a char as is + *result_c_str++ = str[i]; + new_len--; + } } } } @@ -1212,12 +1208,12 @@ string f$stripcslashes(const string &str) noexcept { return result; } -string f$stripslashes(const string &str) noexcept { +string f$stripslashes(const string& str) noexcept { int len = str.size(); int i = 0; string result(len, false); - char *result_c_str = &result[0]; + char* result_c_str = &result[0]; for (i = 0; i + 1 < len; i++) { if (str[i] == '\\') { i++; @@ -1236,7 +1232,7 @@ string f$stripslashes(const string &str) noexcept { return result; } -Optional f$stripos(const string &haystack, const string &needle, int64_t offset) noexcept { +Optional f$stripos(const string& haystack, const string& needle, int64_t offset) noexcept { if (offset < 0) { php_warning("Wrong offset = %" PRIi64 " in function stripos", offset); return false; @@ -1249,14 +1245,14 @@ Optional f$stripos(const string &haystack, const string &needle, int64_ return false; } - const char *s = strcasestr(haystack.c_str() + offset, needle.c_str()); + const char* s = strcasestr(haystack.c_str() + offset, needle.c_str()); if (s == nullptr) { return false; } return s - haystack.c_str(); } -static bool php_tag_find(const string &tag, const string &allow) { +static bool php_tag_find(const string& tag, const string& allow) { if (tag.empty() || allow.empty()) { return false; } @@ -1267,43 +1263,43 @@ static bool php_tag_find(const string &tag, const string &allow) { for (int i = 0; tag[i] && !done; i++) { char c = static_cast(tolower(tag[i])); switch (c) { - case '<': - norm.push_back(c); - break; - case '>': - done = 1; - break; - default: - if (!isspace(c)) { - // since PHP5.3.4, self-closing tags are interpreted as normal tags, - // so normalized
=
; note that tags from $allow are not normalized - if (c != '/') { - norm.push_back(c); - } - if (state == 0) { - state = 1; - } - } else { - if (state == 1) { - done = 1; - } + case '<': + norm.push_back(c); + break; + case '>': + done = 1; + break; + default: + if (!isspace(c)) { + // since PHP5.3.4, self-closing tags are interpreted as normal tags, + // so normalized
=
; note that tags from $allow are not normalized + if (c != '/') { + norm.push_back(c); } - break; + if (state == 0) { + state = 1; + } + } else { + if (state == 1) { + done = 1; + } + } + break; } } norm.push_back('>'); return memmem(allow.c_str(), allow.size(), norm.c_str(), norm.size()) != nullptr; } -string f$strip_tags(const string &str, const string &allow) { +string f$strip_tags(const string& str, const string& allow) { int br = 0; int depth = 0; int in_q = 0; int state = 0; const string allow_low = f$strtolower(allow); - auto &static_SB = RuntimeContext::get().static_SB; - auto &static_SB_spare = RuntimeContext::get().static_SB_spare; + auto& static_SB = RuntimeContext::get().static_SB; + auto& static_SB_spare = RuntimeContext::get().static_SB_spare; static_SB.clean(); static_SB_spare.clean(); char lc = 0; @@ -1311,187 +1307,187 @@ string f$strip_tags(const string &str, const string &allow) { for (int i = 0; i < len; i++) { char c = str[i]; switch (c) { - case '\0': - break; - case '<': - if (!in_q) { - if (isspace(str[i + 1])) { - if (state == 0) { - static_SB << c; - } else if (state == 1) { - static_SB_spare << c; - } - } else if (state == 0) { - lc = '<'; - state = 1; - static_SB_spare << '<'; + case '\0': + break; + case '<': + if (!in_q) { + if (isspace(str[i + 1])) { + if (state == 0) { + static_SB << c; } else if (state == 1) { - depth++; - } - } - break; - case '(': - if (state == 2) { - if (lc != '"' && lc != '\'') { - lc = '('; - br++; + static_SB_spare << c; } - } else if (state == 1) { - static_SB_spare << c; } else if (state == 0) { - static_SB << c; - } - break; - case ')': - if (state == 2) { - if (lc != '"' && lc != '\'') { - lc = ')'; - br--; - } + lc = '<'; + state = 1; + static_SB_spare << '<'; } else if (state == 1) { - static_SB_spare << c; - } else if (state == 0) { - static_SB << c; + depth++; } - break; - case '>': - if (depth) { - depth--; - break; + } + break; + case '(': + if (state == 2) { + if (lc != '"' && lc != '\'') { + lc = '('; + br++; } - - if (in_q) { - break; + } else if (state == 1) { + static_SB_spare << c; + } else if (state == 0) { + static_SB << c; + } + break; + case ')': + if (state == 2) { + if (lc != '"' && lc != '\'') { + lc = ')'; + br--; } + } else if (state == 1) { + static_SB_spare << c; + } else if (state == 0) { + static_SB << c; + } + break; + case '>': + if (depth) { + depth--; + break; + } - switch (state) { - case 1: /* HTML/XML */ - lc = '>'; - in_q = state = 0; - static_SB_spare << '>'; - if (php_tag_find(static_SB_spare.str(), allow_low)) { - static_SB << static_SB_spare.c_str(); - } - static_SB_spare.clean(); - break; - case 2: /* PHP */ - if (!br && lc != '\"' && str[i - 1] == '?') { - in_q = state = 0; - static_SB_spare.clean(); - } - break; - case 3: - in_q = state = 0; - static_SB_spare.clean(); - break; - case 4: /* JavaScript/CSS/etc... */ - if (i >= 2 && str[i - 1] == '-' && str[i - 2] == '-') { - in_q = state = 0; - static_SB_spare.clean(); - } - break; - default: - static_SB << c; - break; - } + if (in_q) { break; + } - case '"': - case '\'': - if (state == 4) { - /* Inside */ - break; - } else if (state == 2 && str[i - 1] != '\\') { - if (lc == c) { - lc = 0; - } else if (lc != '\\') { - lc = c; - } - } else if (state == 0) { - static_SB << c; - } else if (state == 1) { - static_SB_spare << c; - } - if (state && i > 0 && (state == 1 || str[i - 1] != '\\') && (!in_q || c == in_q)) { - if (in_q) { - in_q = 0; - } else { - in_q = c; - } + switch (state) { + case 1: /* HTML/XML */ + lc = '>'; + in_q = state = 0; + static_SB_spare << '>'; + if (php_tag_find(static_SB_spare.str(), allow_low)) { + static_SB << static_SB_spare.c_str(); } + static_SB_spare.clean(); break; - case '!': - /* JavaScript & Other HTML scripting languages */ - if (state == 1 && str[i - 1] == '<') { - state = 3; - lc = c; - } else { - if (state == 0) { - static_SB << c; - } else if (state == 1) { - static_SB_spare << c; - } + case 2: /* PHP */ + if (!br && lc != '\"' && str[i - 1] == '?') { + in_q = state = 0; + static_SB_spare.clean(); } break; - case '-': - if (state == 3 && i >= 2 && str[i - 1] == '-' && str[i - 2] == '!') { - state = 4; - } else { - if (state == 0) { - static_SB << c; - } else if (state == 1) { - static_SB_spare << c; - } + case 3: + in_q = state = 0; + static_SB_spare.clean(); + break; + case 4: /* JavaScript/CSS/etc... */ + if (i >= 2 && str[i - 1] == '-' && str[i - 2] == '-') { + in_q = state = 0; + static_SB_spare.clean(); } break; - case '?': - if (state == 1 && str[i - 1] == '<') { - br = 0; - state = 2; - break; + default: + static_SB << c; + break; + } + break; + + case '"': + case '\'': + if (state == 4) { + /* Inside */ + break; + } else if (state == 2 && str[i - 1] != '\\') { + if (lc == c) { + lc = 0; + } else if (lc != '\\') { + lc = c; } - /* fall-through */ - case 'E': - case 'e': - /* !DOCTYPE exception */ - if (state == 3 && i > 6 && tolower(str[i - 1]) == 'p' && tolower(str[i - 2]) == 'y' && tolower(str[i - 3]) == 't' && tolower(str[i - 4]) == 'c' - && tolower(str[i - 5]) == 'o' && tolower(str[i - 6]) == 'd') { - state = 1; - break; + } else if (state == 0) { + static_SB << c; + } else if (state == 1) { + static_SB_spare << c; + } + if (state && i > 0 && (state == 1 || str[i - 1] != '\\') && (!in_q || c == in_q)) { + if (in_q) { + in_q = 0; + } else { + in_q = c; } - /* fall-through */ - case 'l': - case 'L': - /* swm: If we encounter ' 2 && tolower(str[i - 1]) == 'm' && tolower(str[i - 2]) == 'x') { - state = 1; - break; + } + break; + case '!': + /* JavaScript & Other HTML scripting languages */ + if (state == 1 && str[i - 1] == '<') { + state = 3; + lc = c; + } else { + if (state == 0) { + static_SB << c; + } else if (state == 1) { + static_SB_spare << c; } - - /* fall-through */ - default: + } + break; + case '-': + if (state == 3 && i >= 2 && str[i - 1] == '-' && str[i - 2] == '!') { + state = 4; + } else { if (state == 0) { static_SB << c; } else if (state == 1) { static_SB_spare << c; } + } + break; + case '?': + if (state == 1 && str[i - 1] == '<') { + br = 0; + state = 2; + break; + } + /* fall-through */ + case 'E': + case 'e': + /* !DOCTYPE exception */ + if (state == 3 && i > 6 && tolower(str[i - 1]) == 'p' && tolower(str[i - 2]) == 'y' && tolower(str[i - 3]) == 't' && tolower(str[i - 4]) == 'c' && + tolower(str[i - 5]) == 'o' && tolower(str[i - 6]) == 'd') { + state = 1; break; + } + /* fall-through */ + case 'l': + case 'L': + /* swm: If we encounter ' 2 && tolower(str[i - 1]) == 'm' && tolower(str[i - 2]) == 'x') { + state = 1; + break; + } + + /* fall-through */ + default: + if (state == 0) { + static_SB << c; + } else if (state == 1) { + static_SB_spare << c; + } + break; } } return static_SB.str(); } -template -string strip_tags_string(const array &list) { +template +string strip_tags_string(const array& list) { string allow_str; if (!list.empty()) { allow_str.reserve_at_least(list.count() * strlen("
")); - for (const auto &it : list) { - const auto &s = it.get_value(); + for (const auto& it : list) { + const auto& s = it.get_value(); if (!s.empty()) { allow_str.push_back('<'); allow_str.append(f$strval(s)); @@ -1502,7 +1498,7 @@ string strip_tags_string(const array &list) { return allow_str; } -string f$strip_tags(const string &str, const mixed &allow) { +string f$strip_tags(const string& str, const mixed& allow) { if (!allow.is_array()) { return f$strip_tags(str, allow.to_string()); } @@ -1510,17 +1506,15 @@ string f$strip_tags(const string &str, const mixed &allow) { return f$strip_tags(str, strip_tags_string(allow_list)); } -string f$strip_tags(const string &str, const array &allow_list) { - return f$strip_tags(str, strip_tags_string(allow_list)); -} +string f$strip_tags(const string& str, const array& allow_list) { return f$strip_tags(str, strip_tags_string(allow_list)); } -Optional f$stristr(const string &haystack, const string &needle, bool before_needle) noexcept { +Optional f$stristr(const string& haystack, const string& needle, bool before_needle) noexcept { if (static_cast(needle.size()) == 0) { php_warning("Parameter needle is empty in function stristr"); return false; } - const char *s = strcasestr(haystack.c_str(), needle.c_str()); + const char* s = strcasestr(haystack.c_str(), needle.c_str()); if (s == nullptr) { return false; } @@ -1532,7 +1526,7 @@ Optional f$stristr(const string &haystack, const string &needle, bool be return haystack.substr(pos, haystack.size() - pos); } -Optional f$strrchr(const string &haystack, const string &needle) noexcept { +Optional f$strrchr(const string& haystack, const string& needle) noexcept { if (needle.empty()) { php_warning("Parameter needle is empty in function strrchr"); return false; @@ -1573,7 +1567,7 @@ Optional f$strrchr(const string &haystack, const string &needle) noexcep 3. This notice may not be removed or altered from any source distribution. */ -static int64_t compare_right(char const **a, char const *aend, char const **b, char const *bend) { +static int64_t compare_right(char const** a, char const* aend, char const** b, char const* bend) { int64_t bias = 0; /* The longest run of digits wins. That aside, the greatest @@ -1581,8 +1575,8 @@ static int64_t compare_right(char const **a, char const *aend, char const **b, c both numbers to know that they have the same magnitude, so we remember it in BIAS. */ for (;; (*a)++, (*b)++) { - if ((*a == aend || !isdigit(static_cast(static_cast(**a)))) - && (*b == bend || !isdigit(static_cast(static_cast(**b))))) { + if ((*a == aend || !isdigit(static_cast(static_cast(**a)))) && + (*b == bend || !isdigit(static_cast(static_cast(**b))))) { return bias; } else if (*a == aend || !isdigit(static_cast(static_cast(**a)))) { return -1; @@ -1602,12 +1596,12 @@ static int64_t compare_right(char const **a, char const *aend, char const **b, c return 0; } -static int64_t compare_left(char const **a, char const *aend, char const **b, char const *bend) { +static int64_t compare_left(char const** a, char const* aend, char const** b, char const* bend) { /* Compare two left-aligned numbers: the first to have a different value wins. */ for (;; (*a)++, (*b)++) { - if ((*a == aend || !isdigit(static_cast(static_cast(**a)))) - && (*b == bend || !isdigit(static_cast(static_cast(**b))))) { + if ((*a == aend || !isdigit(static_cast(static_cast(**a)))) && + (*b == bend || !isdigit(static_cast(static_cast(**b))))) { return 0; } else if (*a == aend || !isdigit(static_cast(static_cast(**a)))) { return -1; @@ -1623,13 +1617,13 @@ static int64_t compare_left(char const **a, char const *aend, char const **b, ch return 0; } -static int64_t strnatcmp_ex(char const *a, size_t a_len, char const *b, size_t b_len, int64_t fold_case) { +static int64_t strnatcmp_ex(char const* a, size_t a_len, char const* b, size_t b_len, int64_t fold_case) { unsigned char ca = 0; unsigned char cb = 0; - char const *ap = nullptr; - char const *bp = nullptr; - char const *aend = a + a_len; - char const *bend = b + b_len; + char const* ap = nullptr; + char const* bp = nullptr; + char const* aend = a + a_len; + char const* bend = b + b_len; bool fractional = false; int64_t result = 0; short leading = 1; @@ -1713,15 +1707,11 @@ static int64_t strnatcmp_ex(char const *a, size_t a_len, char const *b, size_t b } } -int64_t f$strcmp(const string &lhs, const string &rhs) noexcept { - return lhs.compare(rhs); -} +int64_t f$strcmp(const string& lhs, const string& rhs) noexcept { return lhs.compare(rhs); } -int64_t f$strnatcmp(const string &lhs, const string &rhs) noexcept { - return strnatcmp_ex(lhs.c_str(), lhs.size(), rhs.c_str(), rhs.size(), 0); -} +int64_t f$strnatcmp(const string& lhs, const string& rhs) noexcept { return strnatcmp_ex(lhs.c_str(), lhs.size(), rhs.c_str(), rhs.size(), 0); } -Optional f$strpos(const string &haystack, const string &needle, int64_t offset) noexcept { +Optional f$strpos(const string& haystack, const string& needle, int64_t offset) noexcept { if (offset < 0) { php_warning("Wrong offset = %" PRIi64 " in function strpos", offset); return false; @@ -1735,22 +1725,22 @@ Optional f$strpos(const string &haystack, const string &needle, int64_t return false; } - const char *s = static_cast(memchr(haystack.c_str() + offset, needle[0], haystack.size() - offset)); + const char* s = static_cast(memchr(haystack.c_str() + offset, needle[0], haystack.size() - offset)); if (s == nullptr) { return false; } return s - haystack.c_str(); } - const char *s = static_cast(memmem(haystack.c_str() + offset, haystack.size() - offset, needle.c_str(), needle.size())); + const char* s = static_cast(memmem(haystack.c_str() + offset, haystack.size() - offset, needle.c_str(), needle.size())); if (s == nullptr) { return false; } return s - haystack.c_str(); } -Optional f$strrpos(const string &haystack, const string &needle, int64_t offset) noexcept { - const char *end = haystack.c_str() + haystack.size(); +Optional f$strrpos(const string& haystack, const string& needle, int64_t offset) noexcept { + const char* end = haystack.c_str() + haystack.size(); if (offset < 0) { offset += haystack.size() + 1; if (offset < 0) { @@ -1768,19 +1758,19 @@ Optional f$strrpos(const string &haystack, const string &needle, int64_ return false; } - const char *s = static_cast(memmem(haystack.c_str() + offset, haystack.size() - offset, needle.c_str(), needle.size())); - const char *t = nullptr; + const char* s = static_cast(memmem(haystack.c_str() + offset, haystack.size() - offset, needle.c_str(), needle.size())); + const char* t = nullptr; if (s == nullptr || s >= end) { return false; } - while ((t = static_cast(memmem(s + 1, haystack.c_str() + haystack.size() - s - 1, needle.c_str(), needle.size()))) != nullptr && t < end) { + while ((t = static_cast(memmem(s + 1, haystack.c_str() + haystack.size() - s - 1, needle.c_str(), needle.size()))) != nullptr && t < end) { s = t; } return s - haystack.c_str(); } -Optional f$strripos(const string &haystack, const string &needle, int64_t offset) noexcept { - const char *end = haystack.c_str() + haystack.size(); +Optional f$strripos(const string& haystack, const string& needle, int64_t offset) noexcept { + const char* end = haystack.c_str() + haystack.size(); if (offset < 0) { offset += haystack.size() + 1; if (offset < 0) { @@ -1798,8 +1788,8 @@ Optional f$strripos(const string &haystack, const string &needle, int64 return false; } - const char *s = strcasestr(haystack.c_str() + offset, needle.c_str()); - const char *t = nullptr; + const char* s = strcasestr(haystack.c_str() + offset, needle.c_str()); + const char* t = nullptr; if (s == nullptr || s >= end) { return false; } @@ -1809,13 +1799,13 @@ Optional f$strripos(const string &haystack, const string &needle, int64 return s - haystack.c_str(); } -Optional f$strstr(const string &haystack, const string &needle, bool before_needle) noexcept { +Optional f$strstr(const string& haystack, const string& needle, bool before_needle) noexcept { if (static_cast(needle.size()) == 0) { php_warning("Parameter needle is empty in function strstr"); return false; } - const char *s = static_cast(memmem(haystack.c_str(), haystack.size(), needle.c_str(), needle.size())); + const char* s = static_cast(memmem(haystack.c_str(), haystack.size(), needle.c_str(), needle.size())); if (s == nullptr) { return false; } @@ -1827,7 +1817,7 @@ Optional f$strstr(const string &haystack, const string &needle, bool bef return haystack.substr(pos, haystack.size() - pos); } -string f$strtolower(const string &str) noexcept { +string f$strtolower(const string& str) noexcept { int n = str.size(); // if there is no upper case char inside the string, we can @@ -1836,8 +1826,8 @@ string f$strtolower(const string &str) noexcept { // use memcpy to copy everything before that pos; // note: do not use islower() here, the compiler does not inline that function call; // it could be beneficial to use 256-byte LUT here, but SIMD approach could be even better - const char *end = str.c_str() + n; - const char *uppercase_pos = std::find_if(str.c_str(), end, [](unsigned char ch) { return ch >= 'A' && ch <= 'Z'; }); + const char* end = str.c_str() + n; + const char* uppercase_pos = std::find_if(str.c_str(), end, [](unsigned char ch) { return ch >= 'A' && ch <= 'Z'; }); if (uppercase_pos == end) { return str; } @@ -1854,12 +1844,12 @@ string f$strtolower(const string &str) noexcept { return res; } -string f$strtoupper(const string &str) noexcept { +string f$strtoupper(const string& str) noexcept { int n = str.size(); // same optimization as in strtolower - const char *end = str.c_str() + n; - const char *lowercase_pos = std::find_if(str.c_str(), end, [](unsigned char ch) { return ch >= 'a' && ch <= 'z'; }); + const char* end = str.c_str() + n; + const char* lowercase_pos = std::find_if(str.c_str(), end, [](unsigned char ch) { return ch >= 'a' && ch <= 'z'; }); if (lowercase_pos == end) { return str; } @@ -1876,12 +1866,12 @@ string f$strtoupper(const string &str) noexcept { return res; } -string f$strtr(const string &subject, const string &from, const string &to) noexcept { +string f$strtr(const string& subject, const string& from, const string& to) noexcept { int n = subject.size(); string result(n, false); for (int i = 0; i < n; i++) { - const char *p = static_cast( - memchr(static_cast(from.c_str()), static_cast(static_cast(subject[i])), static_cast(from.size()))); + const char* p = static_cast( + memchr(static_cast(from.c_str()), static_cast(static_cast(subject[i])), static_cast(from.size()))); if (p == nullptr || static_cast(p - from.c_str()) >= to.size()) { result[i] = subject[i]; } else { @@ -1891,7 +1881,7 @@ string f$strtr(const string &subject, const string &from, const string &to) noex return result; } -string f$str_pad(const string &input, int64_t len, const string &pad_str, int64_t pad_type) noexcept { +string f$str_pad(const string& input, int64_t len, const string& pad_str, int64_t pad_type) noexcept { string::size_type old_len = input.size(); if (len <= old_len) { return input; @@ -1934,7 +1924,7 @@ string f$str_pad(const string &input, int64_t len, const string &pad_str, int64_ return res; } -string f$str_repeat(const string &s, int64_t multiplier) noexcept { +string f$str_repeat(const string& s, int64_t multiplier) noexcept { const string::size_type len = s.size(); if (multiplier <= 0 || len == 0) { return {}; @@ -1964,10 +1954,10 @@ string f$str_repeat(const string &s, int64_t multiplier) noexcept { return result; } -static string str_replace_char(char c, const string &replace, const string &subject, int64_t &replace_count, bool with_case) { +static string str_replace_char(char c, const string& replace, const string& subject, int64_t& replace_count, bool with_case) { int count = 0; - const char *piece = subject.c_str(); - const char *piece_end = subject.c_str() + subject.size(); + const char* piece = subject.c_str(); + const char* piece_end = subject.c_str() + subject.size(); string result; if (!replace.empty()) { @@ -1975,9 +1965,9 @@ static string str_replace_char(char c, const string &replace, const string &subj } while (true) { - const char *pos = nullptr; + const char* pos = nullptr; if (with_case) { - pos = static_cast(memchr(piece, c, piece_end - piece)); + pos = static_cast(memchr(piece, c, piece_end - piece)); } else { const char needle[] = {c, '\0'}; pos = strcasestr(piece, needle); @@ -2003,15 +1993,15 @@ static string str_replace_char(char c, const string &replace, const string &subj return {}; } -static const char *find_substr(const char *where, const char *where_end, const string &what, bool with_case) { +static const char* find_substr(const char* where, const char* where_end, const string& what, bool with_case) { if (with_case) { - return static_cast(memmem(where, where_end - where, what.c_str(), what.size())); + return static_cast(memmem(where, where_end - where, what.c_str(), what.size())); } return strcasestr(where, what.c_str()); } -void str_replace_inplace(const string &search, const string &replace, string &subject, int64_t &replace_count, bool with_case) noexcept { +void str_replace_inplace(const string& search, const string& replace, string& subject, int64_t& replace_count, bool with_case) noexcept { if (search.empty()) { php_warning("Parameter search is empty in function str_replace"); return; @@ -2020,14 +2010,14 @@ void str_replace_inplace(const string &search, const string &replace, string &su subject.make_not_shared(); int count = 0; - const char *piece = subject.c_str(); - const char *piece_end = subject.c_str() + subject.size(); + const char* piece = subject.c_str(); + const char* piece_end = subject.c_str() + subject.size(); - char *output = subject.buffer(); + char* output = subject.buffer(); bool length_no_change = search.size() == replace.size(); while (true) { - const char *pos = find_substr(piece, piece_end, search, with_case); + const char* pos = find_substr(piece, piece_end, search, with_case); if (pos == nullptr) { if (count == 0) { return; @@ -2057,19 +2047,19 @@ void str_replace_inplace(const string &search, const string &replace, string &su php_assert(0); // unreachable } -string str_replace(const string &search, const string &replace, const string &subject, int64_t &replace_count, bool with_case) noexcept { +string str_replace(const string& search, const string& replace, const string& subject, int64_t& replace_count, bool with_case) noexcept { if (search.empty()) { php_warning("Parameter search is empty in function str_replace"); return subject; } int count = 0; - const char *piece = subject.c_str(); - const char *piece_end = subject.c_str() + subject.size(); + const char* piece = subject.c_str(); + const char* piece_end = subject.c_str() + subject.size(); string result; while (true) { - const char *pos = find_substr(piece, piece_end, search, with_case); + const char* pos = find_substr(piece, piece_end, search, with_case); if (pos == nullptr) { if (count == 0) { return subject; @@ -2091,17 +2081,17 @@ string str_replace(const string &search, const string &replace, const string &su } // common for f$str_replace(string) and f$str_ireplace(string) -string str_replace_gen(const string &search, const string &replace, const string &subject, int64_t &replace_count, bool with_case); +string str_replace_gen(const string& search, const string& replace, const string& subject, int64_t& replace_count, bool with_case); -string str_replace_string(const mixed &search, const mixed &replace, const string &subject, int64_t &replace_count, bool with_case) { +string str_replace_string(const mixed& search, const mixed& replace, const string& subject, int64_t& replace_count, bool with_case) { if (search.is_array() && replace.is_array()) { return str_replace_string_array(search.as_array(""), replace.as_array(""), subject, replace_count, with_case); } else if (search.is_array()) { string result = subject; - const string &replace_value = replace.to_string(); + const string& replace_value = replace.to_string(); for (array::const_iterator it = search.begin(); it != search.end(); ++it) { - const string &search_string = f$strval(it.get_value()); + const string& search_string = f$strval(it.get_value()); if (search_string.size() >= replace_value.size()) { str_replace_inplace(search_string, replace_value, result, replace_count, with_case); } else { @@ -2120,7 +2110,7 @@ string str_replace_string(const mixed &search, const mixed &replace, const strin } // common for f$str_replace(string) and f$str_ireplace(string) -string str_replace_gen(const string &search, const string &replace, const string &subject, int64_t &replace_count, bool with_case) { +string str_replace_gen(const string& search, const string& replace, const string& subject, int64_t& replace_count, bool with_case) { replace_count = 0; if (search.size() == 1) { return str_replace_char(search[0], replace, subject, replace_count, with_case); @@ -2129,24 +2119,24 @@ string str_replace_gen(const string &search, const string &replace, const string } } -string f$str_replace(const string &search, const string &replace, const string &subject, int64_t &replace_count) noexcept { +string f$str_replace(const string& search, const string& replace, const string& subject, int64_t& replace_count) noexcept { return str_replace_gen(search, replace, subject, replace_count, true); } -string f$str_ireplace(const string &search, const string &replace, const string &subject, int64_t &replace_count) noexcept { +string f$str_ireplace(const string& search, const string& replace, const string& subject, int64_t& replace_count) noexcept { return str_replace_gen(search, replace, subject, replace_count, false); } -string f$str_replace(const mixed &search, const mixed &replace, const string &subject, int64_t &replace_count) noexcept { +string f$str_replace(const mixed& search, const mixed& replace, const string& subject, int64_t& replace_count) noexcept { return str_replace_string(search, replace, subject, replace_count, true); } -string f$str_ireplace(const mixed &search, const mixed &replace, const string &subject, int64_t &replace_count) noexcept { +string f$str_ireplace(const mixed& search, const mixed& replace, const string& subject, int64_t& replace_count) noexcept { return str_replace_string(search, replace, subject, replace_count, false); } // common for f$str_replace(mixed) and f$str_ireplace(mixed) -mixed str_replace_gen(const mixed &search, const mixed &replace, const mixed &subject, int64_t &replace_count, bool with_case) { +mixed str_replace_gen(const mixed& search, const mixed& replace, const mixed& subject, int64_t& replace_count, bool with_case) { replace_count = 0; if (subject.is_array()) { array result; @@ -2162,15 +2152,15 @@ mixed str_replace_gen(const mixed &search, const mixed &replace, const mixed &su } } -mixed f$str_replace(const mixed &search, const mixed &replace, const mixed &subject, int64_t &replace_count) noexcept { +mixed f$str_replace(const mixed& search, const mixed& replace, const mixed& subject, int64_t& replace_count) noexcept { return str_replace_gen(search, replace, subject, replace_count, true); } -mixed f$str_ireplace(const mixed &search, const mixed &replace, const mixed &subject, int64_t &replace_count) noexcept { +mixed f$str_ireplace(const mixed& search, const mixed& replace, const mixed& subject, int64_t& replace_count) noexcept { return str_replace_gen(search, replace, subject, replace_count, false); } -array f$str_split(const string &str, int64_t split_length) noexcept { +array f$str_split(const string& str, int64_t split_length) noexcept { if (split_length <= 0) { php_warning("Wrong parameter split_length = %" PRIi64 " in function str_split", split_length); array result(array_size(1, true)); @@ -2189,7 +2179,7 @@ array f$str_split(const string &str, int64_t split_length) noexcept { return result; } -int64_t f$substr_count(const string &haystack, const string &needle, int64_t offset, int64_t length) noexcept { +int64_t f$substr_count(const string& haystack, const string& needle, int64_t offset, int64_t length) noexcept { offset = haystack.get_correct_offset(offset); if (offset >= haystack.size()) { return 0; @@ -2199,15 +2189,15 @@ int64_t f$substr_count(const string &haystack, const string &needle, int64_t off } int64_t ans = 0; - const char *s = haystack.c_str() + offset; - const char *end = haystack.c_str() + offset + length; + const char* s = haystack.c_str() + offset; + const char* end = haystack.c_str() + offset + length; if (needle.empty()) { php_warning("Needle is empty in function substr_count"); return end - s; } do { - s = static_cast( - memmem(static_cast(s), static_cast(end - s), static_cast(needle.c_str()), static_cast(needle.size()))); + s = static_cast( + memmem(static_cast(s), static_cast(end - s), static_cast(needle.c_str()), static_cast(needle.size()))); if (s == nullptr) { return ans; } @@ -2216,7 +2206,7 @@ int64_t f$substr_count(const string &haystack, const string &needle, int64_t off } while (true); } -string f$substr_replace(const string &str, const string &replacement, int64_t start, int64_t length) noexcept { +string f$substr_replace(const string& str, const string& replacement, int64_t start, int64_t length) noexcept { int64_t str_len = str.size(); // if $start is negative, count $start from the end of the string @@ -2245,7 +2235,7 @@ string f$substr_replace(const string &str, const string &replacement, int64_t st return result; } -Optional f$substr_compare(const string &main_str, const string &str, int64_t offset, int64_t length, bool case_insensitivity) noexcept { +Optional f$substr_compare(const string& main_str, const string& str, int64_t offset, int64_t length, bool case_insensitivity) noexcept { int64_t str_len = main_str.size(); if (length < 0) { @@ -2268,8 +2258,8 @@ Optional f$substr_compare(const string &main_str, const string &str, in } } -tmp_string trim_impl(const char *s, string::size_type s_len, const string &what) { - const char *mask = get_mask(what); +tmp_string trim_impl(const char* s, string::size_type s_len, const string& what) { + const char* mask = get_mask(what); int len = s_len; if (len == 0 || (!mask[static_cast(s[len - 1])] && !mask[static_cast(s[0])])) { @@ -2291,19 +2281,13 @@ tmp_string trim_impl(const char *s, string::size_type s_len, const string &what) return {s + l, static_cast(len - l)}; } -tmp_string f$_tmp_trim(tmp_string s, const string &what) noexcept { - return trim_impl(s.data, s.size, what); -} +tmp_string f$_tmp_trim(tmp_string s, const string& what) noexcept { return trim_impl(s.data, s.size, what); } -tmp_string f$_tmp_trim(const string &s, const string &what) noexcept { - return trim_impl(s.c_str(), s.size(), what); -} +tmp_string f$_tmp_trim(const string& s, const string& what) noexcept { return trim_impl(s.c_str(), s.size(), what); } -string f$trim(tmp_string s, const string &what) noexcept { - return materialize_tmp_string(trim_impl(s.data, s.size, what)); -} +string f$trim(tmp_string s, const string& what) noexcept { return materialize_tmp_string(trim_impl(s.data, s.size, what)); } -string f$trim(const string &s, const string &what) noexcept { +string f$trim(const string& s, const string& what) noexcept { tmp_string result = trim_impl(s.c_str(), s.size(), what); if (result.data == s.c_str() && result.size == s.size()) { return s; @@ -2311,7 +2295,7 @@ string f$trim(const string &s, const string &what) noexcept { return materialize_tmp_string(result); } -string f$ucwords(const string &str) noexcept { +string f$ucwords(const string& str) noexcept { int n = str.size(); bool in_word = false; @@ -2334,7 +2318,7 @@ string f$ucwords(const string &str) noexcept { return res; } -Optional> f$unpack(const string &pattern, const string &data) noexcept { +Optional> f$unpack(const string& pattern, const string& data) noexcept { array result; int data_len = data.size(); @@ -2364,7 +2348,7 @@ Optional> f$unpack(const string &pattern, const string &data) noexc return result; } - const char *key_end = strchrnul(&pattern[i], '/'); + const char* key_end = strchrnul(&pattern[i], '/'); string key_prefix(pattern.c_str() + i, static_cast(key_end - pattern.c_str() - i)); i = static_cast(key_end - pattern.c_str()); if (i < static_cast(pattern.size())) { @@ -2378,235 +2362,235 @@ Optional> f$unpack(const string &pattern, const string &data) noexc char filler = 0; switch (format) { - case 'A': - filler = ' '; - /* fallthrough */ - case 'a': { - if (cnt == 0) { - cnt = data_len - data_pos; - } else if (cnt == -1) { - cnt = 1; - } - int read_len = cnt; - if (read_len + data_pos > data_len) { - php_warning("Not enough data to unpack with format \"%s\"", pattern.c_str()); - return false; - } - while (cnt > 0 && data[data_pos + cnt - 1] == filler) { - cnt--; - } + case 'A': + filler = ' '; + /* fallthrough */ + case 'a': { + if (cnt == 0) { + cnt = data_len - data_pos; + } else if (cnt == -1) { + cnt = 1; + } + int read_len = cnt; + if (read_len + data_pos > data_len) { + php_warning("Not enough data to unpack with format \"%s\"", pattern.c_str()); + return false; + } + while (cnt > 0 && data[data_pos + cnt - 1] == filler) { + cnt--; + } - if (key_prefix.empty()) { - key_prefix = StringLibConstants::get().ONE_STR; - } + if (key_prefix.empty()) { + key_prefix = StringLibConstants::get().ONE_STR; + } - result.set_value(key_prefix, string(data.c_str() + data_pos, cnt)); + result.set_value(key_prefix, string(data.c_str() + data_pos, cnt)); - data_pos += read_len; - break; + data_pos += read_len; + break; + } + case 'h': + case 'H': { + if (cnt == 0) { + cnt = (data_len - data_pos) * 2; + } else if (cnt == -1) { + cnt = 1; } - case 'h': - case 'H': { - if (cnt == 0) { - cnt = (data_len - data_pos) * 2; - } else if (cnt == -1) { - cnt = 1; - } - int read_len = (cnt + 1) / 2; - if (read_len + data_pos > data_len) { - php_warning("Not enough data to unpack with format \"%s\"", pattern.c_str()); - return false; - } - - string value(cnt, false); - for (int j = data_pos; cnt > 0; j++, cnt -= 2) { - unsigned char ch = data[j]; - char num_high = StringLibConstants::get().lhex_digits[ch >> 4]; - char num_low = StringLibConstants::get().lhex_digits[ch & 15]; - if (format == 'h') { - swap(num_high, num_low); - } + int read_len = (cnt + 1) / 2; + if (read_len + data_pos > data_len) { + php_warning("Not enough data to unpack with format \"%s\"", pattern.c_str()); + return false; + } - value[(j - data_pos) * 2] = num_high; - if (cnt > 1) { - value[(j - data_pos) * 2 + 1] = num_low; - } + string value(cnt, false); + for (int j = data_pos; cnt > 0; j++, cnt -= 2) { + unsigned char ch = data[j]; + char num_high = StringLibConstants::get().lhex_digits[ch >> 4]; + char num_low = StringLibConstants::get().lhex_digits[ch & 15]; + if (format == 'h') { + swap(num_high, num_low); } - php_assert(cnt == 0 || cnt == -1); - if (key_prefix.empty()) { - key_prefix = StringLibConstants::get().ONE_STR; + value[(j - data_pos) * 2] = num_high; + if (cnt > 1) { + value[(j - data_pos) * 2 + 1] = num_low; } + } + php_assert(cnt == 0 || cnt == -1); - result.set_value(key_prefix, value); - - data_pos += read_len; - break; + if (key_prefix.empty()) { + key_prefix = StringLibConstants::get().ONE_STR; } - default: { - if (key_prefix.empty() && cnt == -1) { - key_prefix = StringLibConstants::get().ONE_STR; + result.set_value(key_prefix, value); + + data_pos += read_len; + break; + } + + default: { + if (key_prefix.empty() && cnt == -1) { + key_prefix = StringLibConstants::get().ONE_STR; + } + int counter = 1; + do { + mixed value; + int value_int = 0; + if (data_pos >= data_len) { + php_warning("Not enough data to unpack with format \"%s\"", pattern.c_str()); + return false; } - int counter = 1; - do { - mixed value; - int value_int = 0; - if (data_pos >= data_len) { - php_warning("Not enough data to unpack with format \"%s\"", pattern.c_str()); - return false; - } - switch (format) { - case 'c': - case 'C': - value_int = static_cast(data[data_pos++]); - if (format != 'c' && value_int < 0) { - value_int += 256; - } - value = value_int; - break; - case 's': - case 'S': - case 'v': - value_int = static_cast(data[data_pos]); - if (data_pos + 1 < data_len) { - value_int |= data[data_pos + 1] << 8; - } - data_pos += 2; - if (format != 's' && value_int < 0) { - value_int += 65536; - } - value = value_int; - break; - case 'n': - value_int = static_cast(data[data_pos]) << 8; - if (data_pos + 1 < data_len) { - value_int |= static_cast(data[data_pos + 1]); - } - data_pos += 2; - value = value_int; - break; - case 'i': - case 'I': - case 'l': - case 'L': - case 'V': - value_int = static_cast(data[data_pos]); - if (data_pos + 1 < data_len) { - value_int |= static_cast(data[data_pos + 1]) << 8; - if (data_pos + 2 < data_len) { - value_int |= static_cast(data[data_pos + 2]) << 16; - if (data_pos + 3 < data_len) { - value_int |= data[data_pos + 3] << 24; - } - } - } - data_pos += 4; - value = value_int; - break; - case 'N': - value_int = static_cast(data[data_pos]) << 24; - if (data_pos + 1 < data_len) { - value_int |= static_cast(data[data_pos + 1]) << 16; - if (data_pos + 2 < data_len) { - value_int |= static_cast(data[data_pos + 2]) << 8; - if (data_pos + 3 < data_len) { - value_int |= static_cast(data[data_pos + 3]); - } - } - } - data_pos += 4; - value = value_int; - break; - case 'f': { - if (data_pos + static_cast(sizeof(float)) > data_len) { - php_warning("Not enough data to unpack with format \"%s\"", pattern.c_str()); - return false; + switch (format) { + case 'c': + case 'C': + value_int = static_cast(data[data_pos++]); + if (format != 'c' && value_int < 0) { + value_int += 256; + } + value = value_int; + break; + case 's': + case 'S': + case 'v': + value_int = static_cast(data[data_pos]); + if (data_pos + 1 < data_len) { + value_int |= data[data_pos + 1] << 8; + } + data_pos += 2; + if (format != 's' && value_int < 0) { + value_int += 65536; + } + value = value_int; + break; + case 'n': + value_int = static_cast(data[data_pos]) << 8; + if (data_pos + 1 < data_len) { + value_int |= static_cast(data[data_pos + 1]); + } + data_pos += 2; + value = value_int; + break; + case 'i': + case 'I': + case 'l': + case 'L': + case 'V': + value_int = static_cast(data[data_pos]); + if (data_pos + 1 < data_len) { + value_int |= static_cast(data[data_pos + 1]) << 8; + if (data_pos + 2 < data_len) { + value_int |= static_cast(data[data_pos + 2]) << 16; + if (data_pos + 3 < data_len) { + value_int |= data[data_pos + 3] << 24; } - value = static_cast(*(float *)(data.c_str() + data_pos)); - data_pos += static_cast(sizeof(float)); - break; } - case 'e': - case 'E': - case 'd': { - if (data_pos + static_cast(sizeof(double)) > data_len) { - php_warning("Not enough data to unpack with format \"%s\"", pattern.c_str()); - return false; - } - uint64_t value_byteordered = 0; - memcpy(&value_byteordered, data.c_str() + data_pos, sizeof(double)); - if (format == 'e') { - value_byteordered = le64toh(value_byteordered); - } else if (format == 'E') { - value_byteordered = be64toh(value_byteordered); + } + data_pos += 4; + value = value_int; + break; + case 'N': + value_int = static_cast(data[data_pos]) << 24; + if (data_pos + 1 < data_len) { + value_int |= static_cast(data[data_pos + 1]) << 16; + if (data_pos + 2 < data_len) { + value_int |= static_cast(data[data_pos + 2]) << 8; + if (data_pos + 3 < data_len) { + value_int |= static_cast(data[data_pos + 3]); } - value = float64_from_bits(value_byteordered); - data_pos += static_cast(sizeof(double)); - break; } - case 'J': - case 'P': - case 'Q': { - if (data_pos + static_cast(sizeof(unsigned long long)) > data_len) { - php_warning("Not enough data to unpack with format \"%s\"", pattern.c_str()); - return false; - } - - // stored in the host machine order by the default (Q flag) - unsigned long long value_byteordered = 0; - memcpy(&value_byteordered, data.c_str() + data_pos, sizeof(value_byteordered)); - if (format == 'P') { - // for P encode in little endian order - value_byteordered = le64toh(value_byteordered); - } else if (format == 'J') { - // for J encode in big endian order - value_byteordered = be64toh(value_byteordered); - } + } + data_pos += 4; + value = value_int; + break; + case 'f': { + if (data_pos + static_cast(sizeof(float)) > data_len) { + php_warning("Not enough data to unpack with format \"%s\"", pattern.c_str()); + return false; + } + value = static_cast(*(float*)(data.c_str() + data_pos)); + data_pos += static_cast(sizeof(float)); + break; + } + case 'e': + case 'E': + case 'd': { + if (data_pos + static_cast(sizeof(double)) > data_len) { + php_warning("Not enough data to unpack with format \"%s\"", pattern.c_str()); + return false; + } + uint64_t value_byteordered = 0; + memcpy(&value_byteordered, data.c_str() + data_pos, sizeof(double)); + if (format == 'e') { + value_byteordered = le64toh(value_byteordered); + } else if (format == 'E') { + value_byteordered = be64toh(value_byteordered); + } + value = float64_from_bits(value_byteordered); + data_pos += static_cast(sizeof(double)); + break; + } + case 'J': + case 'P': + case 'Q': { + if (data_pos + static_cast(sizeof(unsigned long long)) > data_len) { + php_warning("Not enough data to unpack with format \"%s\"", pattern.c_str()); + return false; + } - const size_t buf_size = 20; - char buf[buf_size]; - value = string{buf, static_cast(simd_uint64_to_string(value_byteordered, buf) - buf)}; - data_pos += static_cast(sizeof(unsigned long long)); - break; - } - case 'q': { - if (data_pos + static_cast(sizeof(long long)) > data_len) { - php_warning("Not enough data to unpack with format \"%s\"", pattern.c_str()); - return false; - } - long long value_ll = *reinterpret_cast(data.c_str() + data_pos); - value = f$strval(static_cast(value_ll)); - data_pos += static_cast(sizeof(long long)); - break; - } - default: - php_warning("Format code \"%c\" not supported", format); - return false; + // stored in the host machine order by the default (Q flag) + unsigned long long value_byteordered = 0; + memcpy(&value_byteordered, data.c_str() + data_pos, sizeof(value_byteordered)); + if (format == 'P') { + // for P encode in little endian order + value_byteordered = le64toh(value_byteordered); + } else if (format == 'J') { + // for J encode in big endian order + value_byteordered = be64toh(value_byteordered); } - string key = key_prefix; - if (cnt != -1) { - key.append(string(counter++)); + const size_t buf_size = 20; + char buf[buf_size]; + value = string{buf, static_cast(simd_uint64_to_string(value_byteordered, buf) - buf)}; + data_pos += static_cast(sizeof(unsigned long long)); + break; + } + case 'q': { + if (data_pos + static_cast(sizeof(long long)) > data_len) { + php_warning("Not enough data to unpack with format \"%s\"", pattern.c_str()); + return false; } + long long value_ll = *reinterpret_cast(data.c_str() + data_pos); + value = f$strval(static_cast(value_ll)); + data_pos += static_cast(sizeof(long long)); + break; + } + default: + php_warning("Format code \"%c\" not supported", format); + return false; + } + + string key = key_prefix; + if (cnt != -1) { + key.append(string(counter++)); + } - result.set_value(key, value); + result.set_value(key, value); - if (cnt == 0) { - if (data_pos >= data_len) { - return result; - } + if (cnt == 0) { + if (data_pos >= data_len) { + return result; } - } while (cnt == 0 || --cnt > 0); - } + } + } while (cnt == 0 || --cnt > 0); + } } } return result; } -string f$wordwrap(const string &str, int64_t width, const string &brk, bool cut) noexcept { +string f$wordwrap(const string& str, int64_t width, const string& brk, bool cut) noexcept { if (width <= 0) { php_warning("Wrong parameter width = %" PRIi64 " in function wordwrap", width); return str; @@ -2635,12 +2619,12 @@ string f$wordwrap(const string &str, int64_t width, const string &brk, bool cut) return result; } -string f$xor_strings(const string &s, const string &t) noexcept { +string f$xor_strings(const string& s, const string& t) noexcept { string::size_type length = min(s.size(), t.size()); string result{length, false}; - const char *s_str = s.c_str(); - const char *t_str = t.c_str(); - char *res_str = result.buffer(); + const char* s_str = s.c_str(); + const char* t_str = t.c_str(); + char* res_str = result.buffer(); for (string::size_type i = 0; i < length; i++) { *res_str = *s_str ^ *t_str; ++s_str; @@ -2653,11 +2637,11 @@ string f$xor_strings(const string &s, const string &t) noexcept { namespace impl_ { // Based on the original PHP implementation // https://github.com/php/php-src/blob/e8678fcb42c5cb1ea38ff9c6819baca74c2bb5ea/ext/standard/string.c#L3375-L3418 -inline size_t php_similar_str(vk::string_view first, vk::string_view second, size_t &pos1, size_t &pos2, size_t &count) { +inline size_t php_similar_str(vk::string_view first, vk::string_view second, size_t& pos1, size_t& pos2, size_t& count) { size_t max = 0; count = 0; - for (const char *p = first.begin(); p != first.end(); ++p) { - for (const char *q = second.begin(); q != second.end(); ++q) { + for (const char* p = first.begin(); p != first.end(); ++p) { + for (const char* q = second.begin(); q != second.end(); ++q) { size_t l = 0; for (; (p + l < first.end()) && (q + l < second.end()) && (p[l] == q[l]); ++l) { } @@ -2694,7 +2678,7 @@ size_t php_similar_char(vk::string_view first, vk::string_view second) { } // namespace impl_ -int64_t f$similar_text(const string &first, const string &second, double &percent) noexcept { +int64_t f$similar_text(const string& first, const string& second, double& percent) noexcept { if (first.empty() && second.empty()) { percent = 0.0; return 0; @@ -2704,7 +2688,7 @@ int64_t f$similar_text(const string &first, const string &second, double &percen return static_cast(sim); } -string str_concat(const string &s1, const string &s2) noexcept { +string str_concat(const string& s1, const string& s2) noexcept { // for 2 argument concatenation it's not so uncommon to have at least one empty string argument; // it happens in cases like `$prefix . $s` where $prefix could be empty depending on some condition // real-world applications analysis shows that ~17.6% of all two arguments concatenations have @@ -2737,20 +2721,20 @@ string str_concat(str_concat_arg s1, str_concat_arg s2, str_concat_arg s3) noexc string str_concat(str_concat_arg s1, str_concat_arg s2, str_concat_arg s3, str_concat_arg s4) noexcept { auto new_size = s1.size + s2.size + s3.size + s4.size; return string(new_size, true) - .append_unsafe(s1.as_tmp_string()) - .append_unsafe(s2.as_tmp_string()) - .append_unsafe(s3.as_tmp_string()) - .append_unsafe(s4.as_tmp_string()) - .finish_append(); + .append_unsafe(s1.as_tmp_string()) + .append_unsafe(s2.as_tmp_string()) + .append_unsafe(s3.as_tmp_string()) + .append_unsafe(s4.as_tmp_string()) + .finish_append(); } string str_concat(str_concat_arg s1, str_concat_arg s2, str_concat_arg s3, str_concat_arg s4, str_concat_arg s5) noexcept { auto new_size = s1.size + s2.size + s3.size + s4.size + s5.size; return string(new_size, true) - .append_unsafe(s1.as_tmp_string()) - .append_unsafe(s2.as_tmp_string()) - .append_unsafe(s3.as_tmp_string()) - .append_unsafe(s4.as_tmp_string()) - .append_unsafe(s5.as_tmp_string()) - .finish_append(); + .append_unsafe(s1.as_tmp_string()) + .append_unsafe(s2.as_tmp_string()) + .append_unsafe(s3.as_tmp_string()) + .append_unsafe(s4.as_tmp_string()) + .append_unsafe(s5.as_tmp_string()) + .finish_append(); } diff --git a/runtime-common/stdlib/string/string-functions.h b/runtime-common/stdlib/string/string-functions.h index 18ede0d20f..12449a9a05 100644 --- a/runtime-common/stdlib/string/string-functions.h +++ b/runtime-common/stdlib/string/string-functions.h @@ -12,13 +12,13 @@ #include "runtime-common/core/utils/kphp-assert-core.h" #include "runtime-common/stdlib/string/string-context.h" -string f$addcslashes(const string &str, const string &what) noexcept; +string f$addcslashes(const string& str, const string& what) noexcept; -string f$addslashes(const string &str) noexcept; +string f$addslashes(const string& str) noexcept; -string f$hex2bin(const string &str) noexcept; +string f$hex2bin(const string& str) noexcept; -inline string f$bin2hex(const string &str) noexcept { +inline string f$bin2hex(const string& str) noexcept { int len = str.size(); string result(2 * len, false); @@ -30,28 +30,24 @@ inline string f$bin2hex(const string &str) noexcept { return result; } -string f$convert_cyr_string(const string &str, const string &from_s, const string &to_s) noexcept; +string f$convert_cyr_string(const string& str, const string& from_s, const string& to_s) noexcept; -inline string f$chr(int64_t v) noexcept { - return {1, static_cast(v)}; -} +inline string f$chr(int64_t v) noexcept { return {1, static_cast(v)}; } -inline int64_t f$ord(const string &s) noexcept { - return static_cast(s[0]); -} +inline int64_t f$ord(const string& s) noexcept { return static_cast(s[0]); } -mixed f$count_chars(const string &str, int64_t mode = 0) noexcept; +mixed f$count_chars(const string& str, int64_t mode = 0) noexcept; -string f$htmlentities(const string &str) noexcept; +string f$htmlentities(const string& str) noexcept; -string f$html_entity_decode(const string &str, int64_t flags = StringLibConstants::ENT_COMPAT | StringLibConstants::ENT_HTML401, - const string &encoding = StringLibConstants::get().CP1251_STR) noexcept; +string f$html_entity_decode(const string& str, int64_t flags = StringLibConstants::ENT_COMPAT | StringLibConstants::ENT_HTML401, + const string& encoding = StringLibConstants::get().CP1251_STR) noexcept; -string f$htmlspecialchars(const string &str, int64_t flags = StringLibConstants::ENT_COMPAT | StringLibConstants::ENT_HTML401) noexcept; +string f$htmlspecialchars(const string& str, int64_t flags = StringLibConstants::ENT_COMPAT | StringLibConstants::ENT_HTML401) noexcept; -string f$htmlspecialchars_decode(const string &str, int64_t flags = StringLibConstants::ENT_COMPAT | StringLibConstants::ENT_HTML401) noexcept; +string f$htmlspecialchars_decode(const string& str, int64_t flags = StringLibConstants::ENT_COMPAT | StringLibConstants::ENT_HTML401) noexcept; -inline string f$lcfirst(const string &str) noexcept { +inline string f$lcfirst(const string& str) noexcept { int n = str.size(); if (n == 0) { return str; @@ -64,31 +60,29 @@ inline string f$lcfirst(const string &str) noexcept { return res; } -int64_t f$levenshtein(const string &str1, const string &str2) noexcept; +int64_t f$levenshtein(const string& str1, const string& str2) noexcept; -string f$ltrim(const string &s, const string &what = StringLibConstants::get().WHAT_STR) noexcept; +string f$ltrim(const string& s, const string& what = StringLibConstants::get().WHAT_STR) noexcept; -string f$mysql_escape_string(const string &str) noexcept; +string f$mysql_escape_string(const string& str) noexcept; -string f$nl2br(const string &str, bool is_xhtml = true) noexcept; +string f$nl2br(const string& str, bool is_xhtml = true) noexcept; -string f$number_format(double number, int64_t decimals, const string &dec_point, const string &thousands_sep) noexcept; +string f$number_format(double number, int64_t decimals, const string& dec_point, const string& thousands_sep) noexcept; -string f$pack(const string &pattern, const array &a) noexcept; +string f$pack(const string& pattern, const array& a) noexcept; -string f$rtrim(const string &s, const string &what = StringLibConstants::get().WHAT_STR) noexcept; +string f$rtrim(const string& s, const string& what = StringLibConstants::get().WHAT_STR) noexcept; -inline string f$chop(const string &s, const string &what = StringLibConstants::get().WHAT_STR) noexcept { - return f$rtrim(s, what); -} +inline string f$chop(const string& s, const string& what = StringLibConstants::get().WHAT_STR) noexcept { return f$rtrim(s, what); } -string f$sprintf(const string &format, const array &a) noexcept; +string f$sprintf(const string& format, const array& a) noexcept; -string f$stripcslashes(const string &str) noexcept; +string f$stripcslashes(const string& str) noexcept; -string f$stripslashes(const string &str) noexcept; +string f$stripslashes(const string& str) noexcept; -inline int64_t f$strcasecmp(const string &lhs, const string &rhs) noexcept { +inline int64_t f$strcasecmp(const string& lhs, const string& rhs) noexcept { int n = min(lhs.size(), rhs.size()); for (int i = 0; i < n; i++) { if (tolower(lhs[i]) != tolower(rhs[i])) { @@ -100,22 +94,22 @@ inline int64_t f$strcasecmp(const string &lhs, const string &rhs) noexcept { return static_cast(lhs.size()) - static_cast(rhs.size()); } -int64_t f$strcmp(const string &lhs, const string &rhs) noexcept; +int64_t f$strcmp(const string& lhs, const string& rhs) noexcept; -string f$strip_tags(const string &str, const string &allow = string{}); +string f$strip_tags(const string& str, const string& allow = string{}); -inline string f$strip_tags(const string &str, const array &allow_list) noexcept { +inline string f$strip_tags(const string& str, const array& allow_list) noexcept { php_assert(allow_list.empty()); return f$strip_tags(str, string()); } -string f$strip_tags(const string &str, const mixed &allow); +string f$strip_tags(const string& str, const mixed& allow); -string f$strip_tags(const string &str, const array &allow_list); +string f$strip_tags(const string& str, const array& allow_list); -Optional f$stripos(const string &haystack, const string &needle, int64_t offset = 0) noexcept; +Optional f$stripos(const string& haystack, const string& needle, int64_t offset = 0) noexcept; -inline Optional f$stripos(const string &haystack, const mixed &needle, int64_t offset = 0) noexcept { +inline Optional f$stripos(const string& haystack, const mixed& needle, int64_t offset = 0) noexcept { if (needle.is_string()) { return f$stripos(haystack, needle.to_string(), offset); } else { @@ -123,29 +117,29 @@ inline Optional f$stripos(const string &haystack, const mixed &needle, } } -Optional f$stristr(const string &haystack, const string &needle, bool before_needle = false) noexcept; +Optional f$stristr(const string& haystack, const string& needle, bool before_needle = false) noexcept; -Optional f$strrchr(const string &haystack, const string &needle) noexcept; +Optional f$strrchr(const string& haystack, const string& needle) noexcept; -inline int64_t f$strncmp(const string &lhs, const string &rhs, int64_t len) noexcept { +inline int64_t f$strncmp(const string& lhs, const string& rhs, int64_t len) noexcept { if (len < 0) { return 0; } return std::memcmp(lhs.c_str(), rhs.c_str(), min(int64_t{min(lhs.size(), rhs.size())} + 1, len)); } -int64_t f$strnatcmp(const string &lhs, const string &rhs) noexcept; +int64_t f$strnatcmp(const string& lhs, const string& rhs) noexcept; -inline int64_t f$strspn(const string &hayshack, const string &char_list, int64_t offset = 0) noexcept { +inline int64_t f$strspn(const string& hayshack, const string& char_list, int64_t offset = 0) noexcept { return std::strspn(hayshack.c_str() + hayshack.get_correct_offset_clamped(offset), char_list.c_str()); } -inline int64_t f$strcspn(const string &hayshack, const string &char_list, int64_t offset = 0) noexcept { +inline int64_t f$strcspn(const string& hayshack, const string& char_list, int64_t offset = 0) noexcept { return std::strcspn(hayshack.c_str() + hayshack.get_correct_offset_clamped(offset), char_list.c_str()); } -inline Optional f$strpbrk(const string &haystack, const string &char_list) noexcept { - const char *pos = std::strpbrk(haystack.c_str(), char_list.c_str()); +inline Optional f$strpbrk(const string& haystack, const string& char_list) noexcept { + const char* pos = std::strpbrk(haystack.c_str(), char_list.c_str()); if (pos == nullptr) { return false; } @@ -153,9 +147,9 @@ inline Optional f$strpbrk(const string &haystack, const string &char_lis return string(pos, static_cast(haystack.size() - (pos - haystack.c_str()))); } -Optional f$strpos(const string &haystack, const string &needle, int64_t offset = 0) noexcept; +Optional f$strpos(const string& haystack, const string& needle, int64_t offset = 0) noexcept; -inline Optional f$strpos(const string &haystack, const mixed &needle, int64_t offset = 0) noexcept { +inline Optional f$strpos(const string& haystack, const mixed& needle, int64_t offset = 0) noexcept { if (needle.is_string()) { return f$strpos(haystack, needle.to_string(), offset); } else { @@ -163,16 +157,16 @@ inline Optional f$strpos(const string &haystack, const mixed &needle, i } } -template -Optional f$strpos(const string &haystack, const Optional &needle, int64_t offset = 0) noexcept { +template +Optional f$strpos(const string& haystack, const Optional& needle, int64_t offset = 0) noexcept { return f$strpos(haystack, needle.val(), offset); } -Optional f$strrpos(const string &haystack, const string &needle, int64_t offset = 0) noexcept; +Optional f$strrpos(const string& haystack, const string& needle, int64_t offset = 0) noexcept; -Optional f$strripos(const string &haystack, const string &needle, int64_t offset = 0) noexcept; +Optional f$strripos(const string& haystack, const string& needle, int64_t offset = 0) noexcept; -inline string f$strrev(const string &str) noexcept { +inline string f$strrev(const string& str) noexcept { int n = str.size(); string res(n, false); @@ -183,31 +177,31 @@ inline string f$strrev(const string &str) noexcept { return res; } -Optional f$strstr(const string &haystack, const string &needle, bool before_needle = false) noexcept; +Optional f$strstr(const string& haystack, const string& needle, bool before_needle = false) noexcept; -string f$strtolower(const string &str) noexcept; +string f$strtolower(const string& str) noexcept; -string f$strtoupper(const string &str) noexcept; +string f$strtoupper(const string& str) noexcept; -string f$strtr(const string &subject, const string &from, const string &to) noexcept; +string f$strtr(const string& subject, const string& from, const string& to) noexcept; -string f$str_pad(const string &input, int64_t len, const string &pad_str = StringLibConstants::get().SPACE_STR, +string f$str_pad(const string& input, int64_t len, const string& pad_str = StringLibConstants::get().SPACE_STR, int64_t pad_type = StringLibConstants::STR_PAD_RIGHT) noexcept; -string f$str_repeat(const string &s, int64_t multiplier) noexcept; +string f$str_repeat(const string& s, int64_t multiplier) noexcept; -string f$str_replace(const string &search, const string &replace, const string &subject, - int64_t &replace_count = StringLibContext::get().str_replace_count_dummy) noexcept; +string f$str_replace(const string& search, const string& replace, const string& subject, + int64_t& replace_count = StringLibContext::get().str_replace_count_dummy) noexcept; -string f$str_ireplace(const string &search, const string &replace, const string &subject, - int64_t &replace_count = StringLibContext::get().str_replace_count_dummy) noexcept; +string f$str_ireplace(const string& search, const string& replace, const string& subject, + int64_t& replace_count = StringLibContext::get().str_replace_count_dummy) noexcept; -void str_replace_inplace(const string &search, const string &replace, string &subject, int64_t &replace_count, bool with_case) noexcept; +void str_replace_inplace(const string& search, const string& replace, string& subject, int64_t& replace_count, bool with_case) noexcept; -string str_replace(const string &search, const string &replace, const string &subject, int64_t &replace_count, bool with_case) noexcept; +string str_replace(const string& search, const string& replace, const string& subject, int64_t& replace_count, bool with_case) noexcept; -template -string str_replace_string_array(const array &search, const array &replace, const string &subject, int64_t &replace_count, bool with_case) noexcept { +template +string str_replace_string_array(const array& search, const array& replace, const string& subject, int64_t& replace_count, bool with_case) noexcept { string result = subject; string replace_value; typename array::const_iterator cur_replace_val = replace.begin(); @@ -220,7 +214,7 @@ string str_replace_string_array(const array &search, const array &replac replace_value = string{}; } - const string &search_string = f$strval(it.get_value()); + const string& search_string = f$strval(it.get_value()); if (search_string.size() >= replace_value.size()) { str_replace_inplace(search_string, replace_value, result, replace_count, with_case); } else { @@ -231,47 +225,47 @@ string str_replace_string_array(const array &search, const array &replac return result; }; -template -string f$str_replace(const array &search, const array &replace, const string &subject, - int64_t &replace_count = StringLibContext::get().str_replace_count_dummy) noexcept { +template +string f$str_replace(const array& search, const array& replace, const string& subject, + int64_t& replace_count = StringLibContext::get().str_replace_count_dummy) noexcept { replace_count = 0; return str_replace_string_array(search, replace, subject, replace_count, true); } -template -string f$str_ireplace(const array &search, const array &replace, const string &subject, - int64_t &replace_count = StringLibContext::get().str_replace_count_dummy) noexcept { +template +string f$str_ireplace(const array& search, const array& replace, const string& subject, + int64_t& replace_count = StringLibContext::get().str_replace_count_dummy) noexcept { replace_count = 0; return str_replace_string_array(search, replace, subject, replace_count, false); } -string f$str_replace(const mixed &search, const mixed &replace, const string &subject, - int64_t &replace_count = StringLibContext::get().str_replace_count_dummy) noexcept; +string f$str_replace(const mixed& search, const mixed& replace, const string& subject, + int64_t& replace_count = StringLibContext::get().str_replace_count_dummy) noexcept; -string f$str_ireplace(const mixed &search, const mixed &replace, const string &subject, - int64_t &replace_count = StringLibContext::get().str_replace_count_dummy) noexcept; +string f$str_ireplace(const mixed& search, const mixed& replace, const string& subject, + int64_t& replace_count = StringLibContext::get().str_replace_count_dummy) noexcept; -template> -SubjectT f$str_replace(const T1 &search, const T2 &replace, const SubjectT &subject, - int64_t &replace_count = StringLibContext::get().str_replace_count_dummy) noexcept { +template > +SubjectT f$str_replace(const T1& search, const T2& replace, const SubjectT& subject, + int64_t& replace_count = StringLibContext::get().str_replace_count_dummy) noexcept { return f$str_replace(search, replace, subject.val(), replace_count); } -template> -SubjectT f$str_ireplace(const T1 &search, const T2 &replace, const SubjectT &subject, - int64_t &replace_count = StringLibContext::get().str_replace_count_dummy) noexcept { +template > +SubjectT f$str_ireplace(const T1& search, const T2& replace, const SubjectT& subject, + int64_t& replace_count = StringLibContext::get().str_replace_count_dummy) noexcept { return f$str_ireplace(search, replace, subject.val(), replace_count); } -mixed f$str_replace(const mixed &search, const mixed &replace, const mixed &subject, - int64_t &replace_count = StringLibContext::get().str_replace_count_dummy) noexcept; +mixed f$str_replace(const mixed& search, const mixed& replace, const mixed& subject, + int64_t& replace_count = StringLibContext::get().str_replace_count_dummy) noexcept; -mixed f$str_ireplace(const mixed &search, const mixed &replace, const mixed &subject, - int64_t &replace_count = StringLibContext::get().str_replace_count_dummy) noexcept; +mixed f$str_ireplace(const mixed& search, const mixed& replace, const mixed& subject, + int64_t& replace_count = StringLibContext::get().str_replace_count_dummy) noexcept; -array f$str_split(const string &str, int64_t split_length = 1) noexcept; +array f$str_split(const string& str, int64_t split_length = 1) noexcept; -inline Optional f$substr(const string &str, int64_t start, int64_t length = std::numeric_limits::max()) noexcept { +inline Optional f$substr(const string& str, int64_t start, int64_t length = std::numeric_limits::max()) noexcept { if (!wrap_substr_args(str.size(), start, length)) { return false; } @@ -285,7 +279,7 @@ inline Optional f$substr(tmp_string str, int64_t start, int64_t length = return string(str.data + start, length); } -inline tmp_string f$_tmp_substr(const string &str, int64_t start, int64_t length = std::numeric_limits::max()) noexcept { +inline tmp_string f$_tmp_substr(const string& str, int64_t start, int64_t length = std::numeric_limits::max()) noexcept { if (!wrap_substr_args(str.size(), start, length)) { return {}; } @@ -299,30 +293,26 @@ inline tmp_string f$_tmp_substr(tmp_string str, int64_t start, int64_t length = return {str.data + start, static_cast(length)}; } -int64_t f$substr_count(const string &haystack, const string &needle, int64_t offset = 0, int64_t length = std::numeric_limits::max()) noexcept; +int64_t f$substr_count(const string& haystack, const string& needle, int64_t offset = 0, int64_t length = std::numeric_limits::max()) noexcept; -string f$substr_replace(const string &str, const string &replacement, int64_t start, int64_t length = std::numeric_limits::max()) noexcept; +string f$substr_replace(const string& str, const string& replacement, int64_t start, int64_t length = std::numeric_limits::max()) noexcept; -Optional f$substr_compare(const string &main_str, const string &str, int64_t offset, int64_t length = std::numeric_limits::max(), +Optional f$substr_compare(const string& main_str, const string& str, int64_t offset, int64_t length = std::numeric_limits::max(), bool case_insensitivity = false) noexcept; -inline bool f$str_starts_with(const string &haystack, const string &needle) noexcept { - return haystack.starts_with(needle); -} +inline bool f$str_starts_with(const string& haystack, const string& needle) noexcept { return haystack.starts_with(needle); } -inline bool f$str_ends_with(const string &haystack, const string &needle) noexcept { - return haystack.ends_with(needle); -} +inline bool f$str_ends_with(const string& haystack, const string& needle) noexcept { return haystack.ends_with(needle); } -tmp_string f$_tmp_trim(tmp_string s, const string &what = StringLibConstants::get().WHAT_STR) noexcept; +tmp_string f$_tmp_trim(tmp_string s, const string& what = StringLibConstants::get().WHAT_STR) noexcept; -tmp_string f$_tmp_trim(const string &s, const string &what = StringLibConstants::get().WHAT_STR) noexcept; +tmp_string f$_tmp_trim(const string& s, const string& what = StringLibConstants::get().WHAT_STR) noexcept; -string f$trim(tmp_string s, const string &what = StringLibConstants::get().WHAT_STR) noexcept; +string f$trim(tmp_string s, const string& what = StringLibConstants::get().WHAT_STR) noexcept; -string f$trim(const string &s, const string &what = StringLibConstants::get().WHAT_STR) noexcept; +string f$trim(const string& s, const string& what = StringLibConstants::get().WHAT_STR) noexcept; -inline string f$ucfirst(const string &str) noexcept { +inline string f$ucfirst(const string& str) noexcept { int n = str.size(); if (n == 0) { return str; @@ -335,15 +325,13 @@ inline string f$ucfirst(const string &str) noexcept { return res; } -string f$ucwords(const string &str) noexcept; +string f$ucwords(const string& str) noexcept; -Optional> f$unpack(const string &pattern, const string &data) noexcept; +Optional> f$unpack(const string& pattern, const string& data) noexcept; -inline string f$vsprintf(const string &format, const array &args) noexcept { - return f$sprintf(format, args); -} +inline string f$vsprintf(const string& format, const array& args) noexcept { return f$sprintf(format, args); } -string f$wordwrap(const string &str, int64_t width = 75, const string &brk = StringLibConstants::get().NEWLINE_STR, bool cut = false) noexcept; +string f$wordwrap(const string& str, int64_t width = 75, const string& brk = StringLibConstants::get().NEWLINE_STR, bool cut = false) noexcept; namespace hex2char_impl_ { @@ -357,10 +345,10 @@ struct Hex2CharMapMaker { } public: - template + template static constexpr auto make(std::index_sequence /*unused*/) noexcept { return std::array{{ - hex2int_char(Ints)..., + hex2int_char(Ints)..., }}; } }; @@ -376,33 +364,31 @@ inline string f$number_format(double number, int64_t decimals = 0) noexcept { return f$number_format(number, decimals, StringLibConstants::get().DOT_STR, StringLibConstants::get().COLON_STR); } -inline string f$number_format(double number, int64_t decimals, const string &dec_point) noexcept { +inline string f$number_format(double number, int64_t decimals, const string& dec_point) noexcept { return f$number_format(number, decimals, dec_point, StringLibConstants::get().COLON_STR); } -inline string f$number_format(double number, int64_t decimals, const mixed &dec_point) noexcept { +inline string f$number_format(double number, int64_t decimals, const mixed& dec_point) noexcept { return f$number_format(number, decimals, dec_point.is_null() ? StringLibConstants::get().DOT_STR : dec_point.to_string(), StringLibConstants::get().COLON_STR); } -inline string f$number_format(double number, int64_t decimals, const string &dec_point, const mixed &thousands_sep) noexcept { +inline string f$number_format(double number, int64_t decimals, const string& dec_point, const mixed& thousands_sep) noexcept { return f$number_format(number, decimals, dec_point, thousands_sep.is_null() ? StringLibConstants::get().COLON_STR : thousands_sep.to_string()); } -inline string f$number_format(double number, int64_t decimals, const mixed &dec_point, const string &thousands_sep) noexcept { +inline string f$number_format(double number, int64_t decimals, const mixed& dec_point, const string& thousands_sep) noexcept { return f$number_format(number, decimals, dec_point.is_null() ? StringLibConstants::get().DOT_STR : dec_point.to_string(), thousands_sep); } -inline string f$number_format(double number, int64_t decimals, const mixed &dec_point, const mixed &thousands_sep) noexcept { +inline string f$number_format(double number, int64_t decimals, const mixed& dec_point, const mixed& thousands_sep) noexcept { return f$number_format(number, decimals, dec_point.is_null() ? StringLibConstants::get().DOT_STR : dec_point.to_string(), thousands_sep.is_null() ? StringLibConstants::get().COLON_STR : thousands_sep.to_string()); } -inline int64_t f$strlen(const string &s) noexcept { - return s.size(); -} +inline int64_t f$strlen(const string& s) noexcept { return s.size(); } -inline Optional f$stristr(const string &haystack, const mixed &needle, bool before_needle = false) noexcept { +inline Optional f$stristr(const string& haystack, const mixed& needle, bool before_needle = false) noexcept { if (needle.is_string()) { return f$stristr(haystack, needle.to_string(), before_needle); } else { @@ -410,7 +396,7 @@ inline Optional f$stristr(const string &haystack, const mixed &needle, b } } -inline Optional f$strrpos(const string &haystack, const mixed &needle, int64_t offset = 0) noexcept { +inline Optional f$strrpos(const string& haystack, const mixed& needle, int64_t offset = 0) noexcept { if (needle.is_string()) { return f$strrpos(haystack, needle.to_string(), offset); } else { @@ -418,7 +404,7 @@ inline Optional f$strrpos(const string &haystack, const mixed &needle, } } -inline Optional f$strripos(const string &haystack, const mixed &needle, int64_t offset) noexcept { +inline Optional f$strripos(const string& haystack, const mixed& needle, int64_t offset) noexcept { if (needle.is_string()) { return f$strripos(haystack, needle.to_string(), offset); } else { @@ -426,7 +412,7 @@ inline Optional f$strripos(const string &haystack, const mixed &needle, } } -inline Optional f$strstr(const string &haystack, const mixed &needle, bool before_needle = false) noexcept { +inline Optional f$strstr(const string& haystack, const mixed& needle, bool before_needle = false) noexcept { if (needle.is_string()) { return f$strstr(haystack, needle.to_string(), before_needle); } else { @@ -434,13 +420,13 @@ inline Optional f$strstr(const string &haystack, const mixed &needle, bo } } -template -string f$strtr(const string &subject, const array &replace_pairs) noexcept { - const char *piece = subject.c_str(); - const char *piece_end = subject.c_str() + subject.size(); +template +string f$strtr(const string& subject, const array& replace_pairs) noexcept { + const char* piece = subject.c_str(); + const char* piece_end = subject.c_str() + subject.size(); string result; while (true) { - const char *best_pos = nullptr; + const char* best_pos = nullptr; int64_t best_len = -1; string replace; for (typename array::const_iterator p = replace_pairs.begin(); p != replace_pairs.end(); ++p) { @@ -449,8 +435,8 @@ string f$strtr(const string &subject, const array &replace_pairs) noexcept { if (search_len == 0) { return subject; } - const char *pos = static_cast(memmem(static_cast(piece), static_cast(piece_end - piece), - static_cast(search.c_str()), static_cast(search_len))); + const char* pos = static_cast(memmem(static_cast(piece), static_cast(piece_end - piece), + static_cast(search.c_str()), static_cast(search_len))); if (pos != nullptr && (best_pos == nullptr || best_pos > pos || (best_pos == pos && search_len > best_len))) { best_pos = pos; best_len = search_len; @@ -471,17 +457,13 @@ string f$strtr(const string &subject, const array &replace_pairs) noexcept { return result; } -inline string f$strtr(const string &subject, const mixed &from, const mixed &to) noexcept { - return f$strtr(subject, from.to_string(), to.to_string()); -} +inline string f$strtr(const string& subject, const mixed& from, const mixed& to) noexcept { return f$strtr(subject, from.to_string(), to.to_string()); } -inline string f$strtr(const string &subject, const mixed &replace_pairs) noexcept { - return f$strtr(subject, replace_pairs.as_array("strtr")); -} +inline string f$strtr(const string& subject, const mixed& replace_pairs) noexcept { return f$strtr(subject, replace_pairs.as_array("strtr")); } -string f$xor_strings(const string &s, const string &t) noexcept; +string f$xor_strings(const string& s, const string& t) noexcept; -int64_t f$similar_text(const string &first, const string &second, double &percent = StringLibContext::get().default_similar_text_percent_stub) noexcept; +int64_t f$similar_text(const string& first, const string& second, double& percent = StringLibContext::get().default_similar_text_percent_stub) noexcept; // similar_text ( string $first , string $second [, float &$percent ] ) : int @@ -491,19 +473,13 @@ int64_t f$similar_text(const string &first, const string &second, double &percen // there is a special (string, string) overloading for concat2 to // allow the empty string result optimization to kick in struct str_concat_arg { - const char *data; + const char* data; string::size_type size; - str_concat_arg(const string &s) noexcept - : data{s.c_str()} - , size{s.size()} {} - str_concat_arg(tmp_string s) noexcept - : data{s.data} - , size{s.size} {} + str_concat_arg(const string& s) noexcept : data{s.c_str()}, size{s.size()} {} + str_concat_arg(tmp_string s) noexcept : data{s.data}, size{s.size} {} - tmp_string as_tmp_string() const noexcept { - return {data, size}; - } + tmp_string as_tmp_string() const noexcept { return {data, size}; } }; // str_concat functions implement efficient string-typed `.` (concatenation) operator implementation; @@ -520,7 +496,7 @@ struct str_concat_arg { // 565: 6 args // 350: 9 args // Both 6 and 7 argument combination already look infrequent enough to not bother -string str_concat(const string &s1, const string &s2) noexcept; +string str_concat(const string& s1, const string& s2) noexcept; string str_concat(str_concat_arg s1, str_concat_arg s2) noexcept; string str_concat(str_concat_arg s1, str_concat_arg s2, str_concat_arg s3) noexcept; string str_concat(str_concat_arg s1, str_concat_arg s2, str_concat_arg s3, str_concat_arg s4) noexcept; diff --git a/runtime-common/stdlib/tracing/tracing-context.h b/runtime-common/stdlib/tracing/tracing-context.h index 119cf152c9..b4ceee126e 100644 --- a/runtime-common/stdlib/tracing/tracing-context.h +++ b/runtime-common/stdlib/tracing/tracing-context.h @@ -21,7 +21,7 @@ struct TracingContext final : private vk::not_copyable { // (same as 1, but more events with more details are written to binlog, significant overhead) int32_t cur_trace_level{-1}; - static TracingContext &get() noexcept; + static TracingContext& get() noexcept; }; } // namespace kphp_tracing diff --git a/runtime-common/stdlib/tracing/tracing-functions.h b/runtime-common/stdlib/tracing/tracing-functions.h index 9e56f6fba7..fa861f8037 100644 --- a/runtime-common/stdlib/tracing/tracing-functions.h +++ b/runtime-common/stdlib/tracing/tracing-functions.h @@ -8,8 +8,6 @@ namespace kphp_tracing { -inline bool is_turned_on() { - return TracingContext::get().cur_trace_level >= 1; -} +inline bool is_turned_on() { return TracingContext::get().cur_trace_level >= 1; } } // namespace kphp_tracing diff --git a/runtime-common/stdlib/tracing/tracing.h b/runtime-common/stdlib/tracing/tracing.h index 9c5aa65938..88bd6bad60 100644 --- a/runtime-common/stdlib/tracing/tracing.h +++ b/runtime-common/stdlib/tracing/tracing.h @@ -46,8 +46,8 @@ class KphpTracingAggregateGuard { public: KphpTracingAggregateGuard() noexcept = default; - KphpTracingAggregateGuard(const KphpTracingAggregateGuard &) = delete; - KphpTracingAggregateGuard &operator=(const KphpTracingAggregateGuard &) = delete; + KphpTracingAggregateGuard(const KphpTracingAggregateGuard&) = delete; + KphpTracingAggregateGuard& operator=(const KphpTracingAggregateGuard&) = delete; void start(int32_t call_mask) { if (unlikely(kphp_tracing::TracingContext::get().cur_trace_level >= 2)) { diff --git a/runtime-common/stdlib/visitors/common-visitors-methods.h b/runtime-common/stdlib/visitors/common-visitors-methods.h index b1d54b5be2..7a0a18bc86 100644 --- a/runtime-common/stdlib/visitors/common-visitors-methods.h +++ b/runtime-common/stdlib/visitors/common-visitors-methods.h @@ -9,5 +9,5 @@ struct CommonDefaultVisitorMethods { // for f$instance_to_array(), f$to_array_debug() // set at compiler at deeply_require_to_array_debug_visitor() - void accept(ToArrayVisitor &) noexcept {} + void accept(ToArrayVisitor&) noexcept {} }; diff --git a/runtime-light/allocator/allocator.h b/runtime-light/allocator/allocator.h index 540b6ae7b5..bb5f113b0b 100644 --- a/runtime-light/allocator/allocator.h +++ b/runtime-light/allocator/allocator.h @@ -8,7 +8,8 @@ #include "runtime-common/core/allocator/script-allocator-managed.h" -template T, typename... Args> -requires std::constructible_from auto make_unique_on_script_memory(Args &&...args) noexcept { +template T, typename... Args> +requires std::constructible_from +auto make_unique_on_script_memory(Args&&... args) noexcept { return std::make_unique(std::forward(args)...); } diff --git a/runtime-light/allocator/libc-alloc-wrapper.cpp b/runtime-light/allocator/libc-alloc-wrapper.cpp index f0f042d694..c08632f1e0 100644 --- a/runtime-light/allocator/libc-alloc-wrapper.cpp +++ b/runtime-light/allocator/libc-alloc-wrapper.cpp @@ -6,18 +6,10 @@ #include "runtime-common/core/utils/kphp-assert-core.h" -extern "C" void *__wrap_malloc([[maybe_unused]] size_t size) noexcept { - php_critical_error("unexpected use of malloc"); -} +extern "C" void* __wrap_malloc([[maybe_unused]] size_t size) noexcept { php_critical_error("unexpected use of malloc"); } -extern "C" void __wrap_free([[maybe_unused]] void *ptr) noexcept { - php_critical_error("unexpected use of free"); -} +extern "C" void __wrap_free([[maybe_unused]] void* ptr) noexcept { php_critical_error("unexpected use of free"); } -extern "C" void *__wrap_calloc([[maybe_unused]] size_t nmemb, [[maybe_unused]] size_t size) noexcept { - php_critical_error("unexpected use of calloc"); -} +extern "C" void* __wrap_calloc([[maybe_unused]] size_t nmemb, [[maybe_unused]] size_t size) noexcept { php_critical_error("unexpected use of calloc"); } -extern "C" void *__wrap_realloc([[maybe_unused]] void *ptr, [[maybe_unused]] size_t size) noexcept { - php_critical_error("unexpected use of realloc"); -} +extern "C" void* __wrap_realloc([[maybe_unused]] void* ptr, [[maybe_unused]] size_t size) noexcept { php_critical_error("unexpected use of realloc"); } diff --git a/runtime-light/allocator/runtime-light-allocator.cpp b/runtime-light/allocator/runtime-light-allocator.cpp index f884eb4c33..ca72338866 100644 --- a/runtime-light/allocator/runtime-light-allocator.cpp +++ b/runtime-light/allocator/runtime-light-allocator.cpp @@ -19,14 +19,14 @@ constexpr auto EXTRA_MEMORY_MULTIPLIER = 2; void request_extra_memory(size_t requested_size) { const size_t extra_mem_size{std::max(MIN_EXTRA_MEM_SIZE, EXTRA_MEMORY_MULTIPLIER * requested_size)}; - auto &allocator{RuntimeAllocator::get()}; - auto *extra_mem{allocator.alloc_global_memory(extra_mem_size)}; + auto& allocator{RuntimeAllocator::get()}; + auto* extra_mem{allocator.alloc_global_memory(extra_mem_size)}; allocator.memory_resource.add_extra_memory(new (extra_mem) memory_resource::extra_memory_pool{extra_mem_size}); } } // namespace -RuntimeAllocator &RuntimeAllocator::get() noexcept { +RuntimeAllocator& RuntimeAllocator::get() noexcept { if (k2::instance_state() != nullptr) [[likely]] { return InstanceState::get().allocator; } else if (k2::component_state() != nullptr) { @@ -39,29 +39,29 @@ RuntimeAllocator &RuntimeAllocator::get() noexcept { } RuntimeAllocator::RuntimeAllocator(size_t script_mem_size, size_t oom_handling_mem_size) { - void *buffer{alloc_global_memory(script_mem_size)}; + void* buffer{alloc_global_memory(script_mem_size)}; php_assert(buffer != nullptr); memory_resource.init(buffer, script_mem_size, oom_handling_mem_size); } -void RuntimeAllocator::init(void *buffer, size_t script_mem_size, size_t oom_handling_mem_size) { +void RuntimeAllocator::init(void* buffer, size_t script_mem_size, size_t oom_handling_mem_size) { php_assert(buffer != nullptr); memory_resource.init(buffer, script_mem_size, oom_handling_mem_size); } void RuntimeAllocator::free() { - auto *extra_memory{memory_resource.get_extra_memory_head()}; + auto* extra_memory{memory_resource.get_extra_memory_head()}; while (extra_memory->get_pool_payload_size() != 0) { - auto *extra_memory_to_release{extra_memory}; + auto* extra_memory_to_release{extra_memory}; extra_memory = extra_memory->next_in_chain; k2::free(extra_memory_to_release); } k2::free(memory_resource.memory_begin()); } -void *RuntimeAllocator::alloc_script_memory(size_t size) noexcept { +void* RuntimeAllocator::alloc_script_memory(size_t size) noexcept { php_assert(size > 0); - void *mem{memory_resource.allocate(size)}; + void* mem{memory_resource.allocate(size)}; if (mem == nullptr) [[unlikely]] { request_extra_memory(size); mem = memory_resource.allocate(size); @@ -70,9 +70,9 @@ void *RuntimeAllocator::alloc_script_memory(size_t size) noexcept { return mem; } -void *RuntimeAllocator::alloc0_script_memory(size_t size) noexcept { +void* RuntimeAllocator::alloc0_script_memory(size_t size) noexcept { php_assert(size > 0); - void *mem{memory_resource.allocate0(size)}; + void* mem{memory_resource.allocate0(size)}; if (mem == nullptr) [[unlikely]] { request_extra_memory(size); mem = memory_resource.allocate0(size); @@ -81,9 +81,9 @@ void *RuntimeAllocator::alloc0_script_memory(size_t size) noexcept { return mem; } -void *RuntimeAllocator::realloc_script_memory(void *old_mem, size_t new_size, size_t old_size) noexcept { +void* RuntimeAllocator::realloc_script_memory(void* old_mem, size_t new_size, size_t old_size) noexcept { php_assert(new_size > old_size); - void *new_mem{memory_resource.reallocate(old_mem, new_size, old_size)}; + void* new_mem{memory_resource.reallocate(old_mem, new_size, old_size)}; if (new_mem == nullptr) [[unlikely]] { request_extra_memory(new_size * 2); new_mem = memory_resource.reallocate(old_mem, new_size, old_size); @@ -92,21 +92,21 @@ void *RuntimeAllocator::realloc_script_memory(void *old_mem, size_t new_size, si return new_mem; } -void RuntimeAllocator::free_script_memory(void *mem, size_t size) noexcept { +void RuntimeAllocator::free_script_memory(void* mem, size_t size) noexcept { php_assert(size > 0); memory_resource.deallocate(mem, size); } -void *RuntimeAllocator::alloc_global_memory(size_t size) noexcept { - void *mem{k2::alloc(size)}; +void* RuntimeAllocator::alloc_global_memory(size_t size) noexcept { + void* mem{k2::alloc(size)}; if (mem == nullptr) [[unlikely]] { critical_error_handler(); } return mem; } -void *RuntimeAllocator::alloc0_global_memory(size_t size) noexcept { - void *mem{k2::alloc(size)}; +void* RuntimeAllocator::alloc0_global_memory(size_t size) noexcept { + void* mem{k2::alloc(size)}; if (mem == nullptr) [[unlikely]] { critical_error_handler(); } @@ -114,14 +114,12 @@ void *RuntimeAllocator::alloc0_global_memory(size_t size) noexcept { return mem; } -void *RuntimeAllocator::realloc_global_memory(void *old_mem, size_t new_size, size_t /*unused*/) noexcept { - void *mem{k2::realloc(old_mem, new_size)}; +void* RuntimeAllocator::realloc_global_memory(void* old_mem, size_t new_size, size_t /*unused*/) noexcept { + void* mem{k2::realloc(old_mem, new_size)}; if (mem == nullptr) [[unlikely]] { critical_error_handler(); } return mem; } -void RuntimeAllocator::free_global_memory(void *mem, size_t /*unused*/) noexcept { - k2::free(mem); -} +void RuntimeAllocator::free_global_memory(void* mem, size_t /*unused*/) noexcept { k2::free(mem); } diff --git a/runtime-light/core/globals/php-init-scripts.h b/runtime-light/core/globals/php-init-scripts.h index f9530da589..00b3c036bd 100644 --- a/runtime-light/core/globals/php-init-scripts.h +++ b/runtime-light/core/globals/php-init-scripts.h @@ -11,4 +11,4 @@ class PhpScriptMutableGlobals; /// Initializes const variables represented as globals C++ symbols. Definition is generated by compiler. void init_php_scripts_once_in_master() noexcept; /// Initializes mutable globals. Definition is generated by compiler. -void init_php_scripts_in_each_worker(PhpScriptMutableGlobals &php_globals, task_t &run) noexcept; +void init_php_scripts_in_each_worker(PhpScriptMutableGlobals& php_globals, task_t& run) noexcept; diff --git a/runtime-light/core/globals/php-script-globals.cpp b/runtime-light/core/globals/php-script-globals.cpp index b4ab428d81..20d76ab688 100644 --- a/runtime-light/core/globals/php-script-globals.cpp +++ b/runtime-light/core/globals/php-script-globals.cpp @@ -6,29 +6,27 @@ #include "runtime-light/state/instance-state.h" -PhpScriptMutableGlobals &PhpScriptMutableGlobals::current() noexcept { - return InstanceState::get().php_script_mutable_globals_singleton; -} +PhpScriptMutableGlobals& PhpScriptMutableGlobals::current() noexcept { return InstanceState::get().php_script_mutable_globals_singleton; } void PhpScriptMutableGlobals::once_alloc_linear_mem(unsigned int n_bytes) { php_assert(g_linear_mem == nullptr); - g_linear_mem = static_cast(RuntimeAllocator::get().alloc0_global_memory(n_bytes)); + g_linear_mem = static_cast(RuntimeAllocator::get().alloc0_global_memory(n_bytes)); } -void PhpScriptMutableGlobals::once_alloc_linear_mem(const char *lib_name, unsigned int n_bytes) { +void PhpScriptMutableGlobals::once_alloc_linear_mem(const char* lib_name, unsigned int n_bytes) { int64_t key_lib_name = string_hash(lib_name, strlen(lib_name)); php_assert(libs_linear_mem.find(key_lib_name) == libs_linear_mem.end()); - libs_linear_mem[key_lib_name] = static_cast(RuntimeAllocator::get().alloc0_global_memory(n_bytes)); + libs_linear_mem[key_lib_name] = static_cast(RuntimeAllocator::get().alloc0_global_memory(n_bytes)); } -char *PhpScriptMutableGlobals::get_linear_mem(const char *lib_name) const { +char* PhpScriptMutableGlobals::get_linear_mem(const char* lib_name) const { int64_t key_lib_name = string_hash(lib_name, strlen(lib_name)); auto found = libs_linear_mem.find(key_lib_name); php_assert(found != libs_linear_mem.end()); return found->second; } -char *PhpScriptMutableGlobals::mem_for_lib(const char *lib_name) const { +char* PhpScriptMutableGlobals::mem_for_lib(const char* lib_name) const { int64_t key_lib_name = string_hash(lib_name, strlen(lib_name)); auto found = libs_linear_mem.find(key_lib_name); php_assert(found != libs_linear_mem.end()); diff --git a/runtime-light/core/globals/php-script-globals.h b/runtime-light/core/globals/php-script-globals.h index befe859031..6fb502f07c 100644 --- a/runtime-light/core/globals/php-script-globals.h +++ b/runtime-light/core/globals/php-script-globals.h @@ -67,35 +67,27 @@ struct PhpScriptBuiltInSuperGlobals { }; class PhpScriptMutableGlobals { - template + template using unordered_map = memory_resource::stl::unordered_map; - char *g_linear_mem{nullptr}; - unordered_map libs_linear_mem; + char* g_linear_mem{nullptr}; + unordered_map libs_linear_mem; PhpScriptBuiltInSuperGlobals superglobals; public: - explicit PhpScriptMutableGlobals(memory_resource::unsynchronized_pool_resource &resource) - : libs_linear_mem(unordered_map::allocator_type{resource}) {} + explicit PhpScriptMutableGlobals(memory_resource::unsynchronized_pool_resource& resource) + : libs_linear_mem(unordered_map::allocator_type{resource}) {} - static PhpScriptMutableGlobals ¤t() noexcept; + static PhpScriptMutableGlobals& current() noexcept; void once_alloc_linear_mem(unsigned int n_bytes); - void once_alloc_linear_mem(const char *lib_name, unsigned int n_bytes); - - char *get_linear_mem() const { - return g_linear_mem; - } - char *get_linear_mem(const char *lib_name) const; - - char *mem() const { - return g_linear_mem; - } - char *mem_for_lib(const char *lib_name) const; - - PhpScriptBuiltInSuperGlobals &get_superglobals() { - return superglobals; - } - const PhpScriptBuiltInSuperGlobals &get_superglobals() const { - return superglobals; - } + void once_alloc_linear_mem(const char* lib_name, unsigned int n_bytes); + + char* get_linear_mem() const { return g_linear_mem; } + char* get_linear_mem(const char* lib_name) const; + + char* mem() const { return g_linear_mem; } + char* mem_for_lib(const char* lib_name) const; + + PhpScriptBuiltInSuperGlobals& get_superglobals() { return superglobals; } + const PhpScriptBuiltInSuperGlobals& get_superglobals() const { return superglobals; } }; diff --git a/runtime-light/core/kphp-core-impl/kphp-core-context.cpp b/runtime-light/core/kphp-core-impl/kphp-core-context.cpp index f99a2b959e..ffd1976602 100644 --- a/runtime-light/core/kphp-core-impl/kphp-core-context.cpp +++ b/runtime-light/core/kphp-core-impl/kphp-core-context.cpp @@ -8,12 +8,8 @@ constexpr string_size_type initial_minimum_string_buffer_length = 1024; constexpr string_size_type initial_maximum_string_buffer_length = (1 << 24); -RuntimeContext &RuntimeContext::get() noexcept { - return InstanceState::get().runtime_context; -} +RuntimeContext& RuntimeContext::get() noexcept { return InstanceState::get().runtime_context; } -void RuntimeContext::init() noexcept { - init_string_buffer_lib(initial_minimum_string_buffer_length, initial_maximum_string_buffer_length); -} +void RuntimeContext::init() noexcept { init_string_buffer_lib(initial_minimum_string_buffer_length, initial_maximum_string_buffer_length); } void RuntimeContext::free() noexcept {} diff --git a/runtime-light/coroutine/awaitable.h b/runtime-light/coroutine/awaitable.h index ac88c7fa60..96caa60bad 100644 --- a/runtime-light/coroutine/awaitable.h +++ b/runtime-light/coroutine/awaitable.h @@ -21,14 +21,14 @@ #include "runtime-light/state/instance-state.h" #include "runtime-light/stdlib/fork/fork-state.h" -template +template concept Awaitable = requires(T awaitable, std::coroutine_handle<> coro) { { awaitable.await_ready() } noexcept -> std::convertible_to; { awaitable.await_suspend(coro) } noexcept; { awaitable.await_resume() } noexcept; }; -template +template concept CancellableAwaitable = Awaitable && requires(T awaitable) { // semantics: returns 'true' if it's safe to call 'await_resume', 'false' otherwise. { awaitable.resumable() } noexcept -> std::convertible_to; @@ -50,9 +50,7 @@ class fork_id_watcher_t { int64_t fork_id{ForkInstanceState::get().running_fork_id}; protected: - void await_resume() const noexcept { - ForkInstanceState::get().running_fork_id = fork_id; - } + void await_resume() const noexcept { ForkInstanceState::get().running_fork_id = fork_id; } }; } // namespace awaitable_impl_ @@ -64,17 +62,16 @@ class wait_for_update_t : public awaitable_impl_::fork_id_watcher_t { public: explicit wait_for_update_t(uint64_t stream_d_) noexcept - : stream_d(stream_d_) - , suspend_token(std::noop_coroutine(), WaitEvent::UpdateOnStream{.stream_d = stream_d}) {} + : stream_d(stream_d_), suspend_token(std::noop_coroutine(), WaitEvent::UpdateOnStream{.stream_d = stream_d}) {} - wait_for_update_t(wait_for_update_t &&other) noexcept - : stream_d(std::exchange(other.stream_d, k2::INVALID_PLATFORM_DESCRIPTOR)) - , suspend_token(std::exchange(other.suspend_token, std::make_pair(std::noop_coroutine(), WaitEvent::Rechedule{}))) - , state(std::exchange(other.state, awaitable_impl_::State::End)) {} + wait_for_update_t(wait_for_update_t&& other) noexcept + : stream_d(std::exchange(other.stream_d, k2::INVALID_PLATFORM_DESCRIPTOR)), + suspend_token(std::exchange(other.suspend_token, std::make_pair(std::noop_coroutine(), WaitEvent::Rechedule{}))), + state(std::exchange(other.state, awaitable_impl_::State::End)) {} - wait_for_update_t(const wait_for_update_t &) = delete; - wait_for_update_t &operator=(const wait_for_update_t &) = delete; - wait_for_update_t &operator=(wait_for_update_t &&) = delete; + wait_for_update_t(const wait_for_update_t&) = delete; + wait_for_update_t& operator=(const wait_for_update_t&) = delete; + wait_for_update_t& operator=(wait_for_update_t&&) = delete; ~wait_for_update_t() { if (state == awaitable_impl_::State::Suspend) { @@ -118,13 +115,13 @@ class wait_for_incoming_stream_t : awaitable_impl_::fork_id_watcher_t { public: wait_for_incoming_stream_t() noexcept = default; - wait_for_incoming_stream_t(wait_for_incoming_stream_t &&other) noexcept - : suspend_token(std::exchange(other.suspend_token, std::make_pair(std::noop_coroutine(), WaitEvent::Rechedule{}))) - , state(std::exchange(other.state, awaitable_impl_::State::End)) {} + wait_for_incoming_stream_t(wait_for_incoming_stream_t&& other) noexcept + : suspend_token(std::exchange(other.suspend_token, std::make_pair(std::noop_coroutine(), WaitEvent::Rechedule{}))), + state(std::exchange(other.state, awaitable_impl_::State::End)) {} - wait_for_incoming_stream_t(const wait_for_incoming_stream_t &) = delete; - wait_for_incoming_stream_t &operator=(const wait_for_incoming_stream_t &) = delete; - wait_for_incoming_stream_t &operator=(wait_for_incoming_stream_t &&) = delete; + wait_for_incoming_stream_t(const wait_for_incoming_stream_t&) = delete; + wait_for_incoming_stream_t& operator=(const wait_for_incoming_stream_t&) = delete; + wait_for_incoming_stream_t& operator=(wait_for_incoming_stream_t&&) = delete; ~wait_for_incoming_stream_t() { if (state == awaitable_impl_::State::Suspend) { @@ -171,13 +168,13 @@ class wait_for_reschedule_t : awaitable_impl_::fork_id_watcher_t { public: wait_for_reschedule_t() noexcept = default; - wait_for_reschedule_t(wait_for_reschedule_t &&other) noexcept - : suspend_token(std::exchange(other.suspend_token, std::make_pair(std::noop_coroutine(), WaitEvent::Rechedule{}))) - , state(std::exchange(other.state, awaitable_impl_::State::End)) {} + wait_for_reschedule_t(wait_for_reschedule_t&& other) noexcept + : suspend_token(std::exchange(other.suspend_token, std::make_pair(std::noop_coroutine(), WaitEvent::Rechedule{}))), + state(std::exchange(other.state, awaitable_impl_::State::End)) {} - wait_for_reschedule_t(const wait_for_reschedule_t &) = delete; - wait_for_reschedule_t &operator=(const wait_for_reschedule_t &) = delete; - wait_for_reschedule_t &operator=(wait_for_reschedule_t &&) = delete; + wait_for_reschedule_t(const wait_for_reschedule_t&) = delete; + wait_for_reschedule_t& operator=(const wait_for_reschedule_t&) = delete; + wait_for_reschedule_t& operator=(wait_for_reschedule_t&&) = delete; ~wait_for_reschedule_t() { if (state == awaitable_impl_::State::Suspend) { @@ -201,9 +198,7 @@ class wait_for_reschedule_t : awaitable_impl_::fork_id_watcher_t { fork_id_watcher_t::await_resume(); } - bool resumable() const noexcept { - return state == awaitable_impl_::State::Suspend && !CoroutineScheduler::get().contains(suspend_token); - } + bool resumable() const noexcept { return state == awaitable_impl_::State::Suspend && !CoroutineScheduler::get().contains(suspend_token); } void cancel() noexcept { state = awaitable_impl_::State::End; @@ -220,18 +215,16 @@ class wait_for_timer_t : awaitable_impl_::fork_id_watcher_t { awaitable_impl_::State state{awaitable_impl_::State::Init}; public: - explicit wait_for_timer_t(std::chrono::nanoseconds duration_) noexcept - : duration(duration_) {} + explicit wait_for_timer_t(std::chrono::nanoseconds duration_) noexcept : duration(duration_) {} - wait_for_timer_t(wait_for_timer_t &&other) noexcept - : duration(std::exchange(other.duration, std::chrono::nanoseconds{0})) - , timer_d(std::exchange(other.timer_d, k2::INVALID_PLATFORM_DESCRIPTOR)) - , suspend_token(std::exchange(other.suspend_token, std::make_pair(std::noop_coroutine(), WaitEvent::Rechedule{}))) - , state(std::exchange(other.state, awaitable_impl_::State::End)) {} + wait_for_timer_t(wait_for_timer_t&& other) noexcept + : duration(std::exchange(other.duration, std::chrono::nanoseconds{0})), timer_d(std::exchange(other.timer_d, k2::INVALID_PLATFORM_DESCRIPTOR)), + suspend_token(std::exchange(other.suspend_token, std::make_pair(std::noop_coroutine(), WaitEvent::Rechedule{}))), + state(std::exchange(other.state, awaitable_impl_::State::End)) {} - wait_for_timer_t(const wait_for_timer_t &) = delete; - wait_for_timer_t &operator=(const wait_for_timer_t &) = delete; - wait_for_timer_t &operator=(wait_for_timer_t &&) = delete; + wait_for_timer_t(const wait_for_timer_t&) = delete; + wait_for_timer_t& operator=(const wait_for_timer_t&) = delete; + wait_for_timer_t& operator=(wait_for_timer_t&&) = delete; ~wait_for_timer_t() { if (state == awaitable_impl_::State::Suspend) { @@ -262,9 +255,7 @@ class wait_for_timer_t : awaitable_impl_::fork_id_watcher_t { fork_id_watcher_t::await_resume(); } - bool resumable() const noexcept { - return state == awaitable_impl_::State::Suspend && !CoroutineScheduler::get().contains(suspend_token); - } + bool resumable() const noexcept { return state == awaitable_impl_::State::Suspend && !CoroutineScheduler::get().contains(suspend_token); } void cancel() noexcept { state = awaitable_impl_::State::End; @@ -292,20 +283,17 @@ class start_fork_t : awaitable_impl_::fork_id_watcher_t { public: explicit start_fork_t(task_t task_, execution exec_policy_) noexcept - : exec_policy(exec_policy_) - , fork_coro(task_.get_handle()) - , fork_id(ForkInstanceState::get().push_fork(std::move(task_))) {} - - start_fork_t(start_fork_t &&other) noexcept - : exec_policy(other.exec_policy) - , fork_coro(std::exchange(other.fork_coro, std::noop_coroutine())) - , fork_id(std::exchange(other.fork_id, INVALID_FORK_ID)) - , suspend_token(std::exchange(other.suspend_token, std::make_pair(std::noop_coroutine(), WaitEvent::Rechedule{}))) - , state(std::exchange(other.state, awaitable_impl_::State::End)) {} - - start_fork_t(const start_fork_t &) = delete; - start_fork_t &operator=(const start_fork_t &) = delete; - start_fork_t &operator=(start_fork_t &&) = delete; + : exec_policy(exec_policy_), fork_coro(task_.get_handle()), fork_id(ForkInstanceState::get().push_fork(std::move(task_))) {} + + start_fork_t(start_fork_t&& other) noexcept + : exec_policy(other.exec_policy), fork_coro(std::exchange(other.fork_coro, std::noop_coroutine())), + fork_id(std::exchange(other.fork_id, INVALID_FORK_ID)), + suspend_token(std::exchange(other.suspend_token, std::make_pair(std::noop_coroutine(), WaitEvent::Rechedule{}))), + state(std::exchange(other.state, awaitable_impl_::State::End)) {} + + start_fork_t(const start_fork_t&) = delete; + start_fork_t& operator=(const start_fork_t&) = delete; + start_fork_t& operator=(start_fork_t&&) = delete; ~start_fork_t() = default; constexpr bool await_ready() const noexcept { @@ -317,17 +305,17 @@ class start_fork_t : awaitable_impl_::fork_id_watcher_t { state = awaitable_impl_::State::Suspend; std::coroutine_handle<> continuation{}; switch (exec_policy) { - case execution::fork: { - suspend_token.first = current_coro; - continuation = fork_coro; - ForkInstanceState::get().running_fork_id = fork_id; - break; - } - case execution::self: { - suspend_token.first = fork_coro; - continuation = current_coro; - break; - } + case execution::fork: { + suspend_token.first = current_coro; + continuation = fork_coro; + ForkInstanceState::get().running_fork_id = fork_id; + break; + } + case execution::self: { + suspend_token.first = fork_coro; + continuation = current_coro; + break; + } } CoroutineScheduler::get().suspend(suspend_token); // reset fork_coro and suspend_token to guarantee that the same fork will be started only once @@ -345,7 +333,7 @@ class start_fork_t : awaitable_impl_::fork_id_watcher_t { // ================================================================================================ -template +template class wait_fork_t : awaitable_impl_::fork_id_watcher_t { int64_t fork_id; task_t fork_task; @@ -357,19 +345,15 @@ class wait_fork_t : awaitable_impl_::fork_id_watcher_t { public: explicit wait_fork_t(int64_t fork_id_) noexcept - : fork_id(fork_id_) - , fork_task(static_cast>(ForkInstanceState::get().pop_fork(fork_id))) - , fork_awaiter(std::addressof(fork_task)) {} + : fork_id(fork_id_), fork_task(static_cast>(ForkInstanceState::get().pop_fork(fork_id))), fork_awaiter(std::addressof(fork_task)) {} - wait_fork_t(wait_fork_t &&other) noexcept - : fork_id(std::exchange(other.fork_id, INVALID_FORK_ID)) - , fork_task(std::move(other.fork_task)) - , fork_awaiter(std::addressof(fork_task)) - , state(std::exchange(other.state, awaitable_impl_::State::End)) {} + wait_fork_t(wait_fork_t&& other) noexcept + : fork_id(std::exchange(other.fork_id, INVALID_FORK_ID)), fork_task(std::move(other.fork_task)), fork_awaiter(std::addressof(fork_task)), + state(std::exchange(other.state, awaitable_impl_::State::End)) {} - wait_fork_t(const wait_fork_t &) = delete; - wait_fork_t &operator=(const wait_fork_t &) = delete; - wait_fork_t &operator=(wait_fork_t &&) = delete; + wait_fork_t(const wait_fork_t&) = delete; + wait_fork_t& operator=(const wait_fork_t&) = delete; + wait_fork_t& operator=(wait_fork_t&&) = delete; ~wait_fork_t() { if (state == awaitable_impl_::State::Suspend) { @@ -410,7 +394,7 @@ class wait_fork_t : awaitable_impl_::fork_id_watcher_t { // ================================================================================================ -template +template class wait_with_timeout_t { T awaitable; wait_for_timer_t timer_awaitable; @@ -424,18 +408,15 @@ class wait_with_timeout_t { using await_resume_return_t = std::conditional_t, void, std::optional>; public: - wait_with_timeout_t(T &&awaitable_, std::chrono::nanoseconds timeout) noexcept - : awaitable(std::move(awaitable_)) - , timer_awaitable(timeout) {} - - wait_with_timeout_t(wait_with_timeout_t &&other) noexcept - : awaitable(std::move(other.awaitable)) - , timer_awaitable(std::move(other.timer_awaitable)) - , state(std::exchange(other.state, awaitable_impl_::State::End)) {} - - wait_with_timeout_t(const wait_with_timeout_t &) = delete; - wait_with_timeout_t &operator=(const wait_with_timeout_t &) = delete; - wait_with_timeout_t &operator=(wait_with_timeout_t &&) = delete; + wait_with_timeout_t(T&& awaitable_, std::chrono::nanoseconds timeout) noexcept : awaitable(std::move(awaitable_)), timer_awaitable(timeout) {} + + wait_with_timeout_t(wait_with_timeout_t&& other) noexcept + : awaitable(std::move(other.awaitable)), timer_awaitable(std::move(other.timer_awaitable)), + state(std::exchange(other.state, awaitable_impl_::State::End)) {} + + wait_with_timeout_t(const wait_with_timeout_t&) = delete; + wait_with_timeout_t& operator=(const wait_with_timeout_t&) = delete; + wait_with_timeout_t& operator=(wait_with_timeout_t&&) = delete; ~wait_with_timeout_t() = default; constexpr bool await_ready() noexcept { @@ -480,5 +461,5 @@ class wait_with_timeout_t { } }; -template -wait_with_timeout_t(T &&, std::chrono::nanoseconds) -> wait_with_timeout_t; +template +wait_with_timeout_t(T&&, std::chrono::nanoseconds) -> wait_with_timeout_t; diff --git a/runtime-light/coroutine/task.h b/runtime-light/coroutine/task.h index 64838f3445..a5dbbe11aa 100644 --- a/runtime-light/coroutine/task.h +++ b/runtime-light/coroutine/task.h @@ -22,20 +22,18 @@ struct task_base_t { task_base_t() = default; - explicit task_base_t(std::coroutine_handle<> handle) - : handle_address{handle.address()} {} + explicit task_base_t(std::coroutine_handle<> handle) : handle_address{handle.address()} {} - task_base_t(task_base_t &&task) noexcept - : handle_address{std::exchange(task.handle_address, nullptr)} {} + task_base_t(task_base_t&& task) noexcept : handle_address{std::exchange(task.handle_address, nullptr)} {} - task_base_t(const task_base_t &task) = delete; + task_base_t(const task_base_t& task) = delete; - task_base_t &operator=(task_base_t &&task) noexcept { + task_base_t& operator=(task_base_t&& task) noexcept { std::swap(handle_address, task.handle_address); return *this; } - task_base_t &operator=(const task_base_t &task) = delete; + task_base_t& operator=(const task_base_t& task) = delete; ~task_base_t() { if (handle_address) { @@ -49,7 +47,7 @@ struct task_base_t { } protected: - void *handle_address{nullptr}; + void* handle_address{nullptr}; }; /** @@ -57,9 +55,9 @@ struct task_base_t { * 1. C++20 coroutines — https://en.cppreference.com/w/cpp/language/coroutines * 2. C++ coroutines: understanding symmetric stransfer — https://lewissbaker.github.io/2020/05/11/understanding_symmetric_transfer */ -template +template struct task_t : public task_base_t { - template F> + template F> struct promise_non_void_t; struct promise_void_t; @@ -67,20 +65,14 @@ struct task_t : public task_base_t { using task_base_t::task_base_t; struct promise_base_t { - task_t get_return_object() noexcept { - return task_t{std::coroutine_handle::from_promise(*static_cast(this))}; - } + task_t get_return_object() noexcept { return task_t{std::coroutine_handle::from_promise(*static_cast(this))}; } - std::suspend_always initial_suspend() { - return {}; - } + std::suspend_always initial_suspend() { return {}; } struct final_suspend_t { final_suspend_t() = default; - bool await_ready() const noexcept { - return false; - } + bool await_ready() const noexcept { return false; } std::coroutine_handle<> await_suspend(std::coroutine_handle h) const noexcept { #ifdef CPPCORO_COMPILER_SUPPORTS_SYMMETRIC_TRANSFER @@ -88,7 +80,7 @@ struct task_t : public task_base_t { return std::coroutine_handle<>::from_address(h.promise().next); } #else - void *loaded_ptr = h.promise().next; + void* loaded_ptr = h.promise().next; if (loaded_ptr != nullptr) { if (loaded_ptr == &h.promise().next) { h.promise().next = nullptr; @@ -103,39 +95,34 @@ struct task_t : public task_base_t { void await_resume() const noexcept {} }; - final_suspend_t final_suspend() noexcept { - return final_suspend_t{}; - } + final_suspend_t final_suspend() noexcept { return final_suspend_t{}; } - void unhandled_exception() { - exception = std::current_exception(); - } + void unhandled_exception() { exception = std::current_exception(); } - void *next = nullptr; + void* next = nullptr; std::exception_ptr exception; - static task_t get_return_object_on_allocation_failure() { - php_critical_error("cannot allocate memory for task_t"); - } + static task_t get_return_object_on_allocation_failure() { php_critical_error("cannot allocate memory for task_t"); } - template - void *operator new(std::size_t n, [[maybe_unused]] Args &&...args) noexcept { + template + void* operator new(std::size_t n, [[maybe_unused]] Args&&... args) noexcept { // todo:k2 think about args in new // todo:k2 make coroutine allocator - void *buffer = k2::alloc(n); + void* buffer = k2::alloc(n); return buffer; } - void operator delete(void *ptr, size_t n) noexcept { + void operator delete(void* ptr, size_t n) noexcept { (void)n; k2::free(ptr); } }; - template F> + template F> struct promise_non_void_t : public promise_base_t { - template - requires std::constructible_from void return_value(E &&e) { + template + requires std::constructible_from + void return_value(E&& e) { ::new (bytes) F(std::forward(e)); } @@ -146,16 +133,14 @@ struct task_t : public task_base_t { void return_void() {} }; - void execute() { - get_handle().resume(); - } + void execute() { get_handle().resume(); } T get_result() noexcept { if (get_handle().promise().exception) { std::rethrow_exception(std::move(get_handle().promise().exception)); } if constexpr (!std::is_void{}) { - T *t = std::launder(reinterpret_cast(get_handle().promise().bytes)); + T* t = std::launder(reinterpret_cast(get_handle().promise().bytes)); const vk::final_action final_action([t] { t->~T(); }); return std::move(*t); } @@ -175,14 +160,11 @@ struct task_t : public task_base_t { } struct awaiter_t { - explicit awaiter_t(task_t *task) - : task{task} {} + explicit awaiter_t(task_t* task) : task{task} {} - constexpr bool await_ready() const noexcept { - return false; - } + constexpr bool await_ready() const noexcept { return false; } - template + template #ifdef CPPCORO_COMPILER_SUPPORTS_SYMMETRIC_TRANSFER std::coroutine_handle #else @@ -193,7 +175,7 @@ struct task_t : public task_base_t { task->get_handle().promise().next = h.address(); return task->get_handle(); #else - void *next_ptr = &task->get_handle().promise().next; + void* next_ptr = &task->get_handle().promise().next; task->get_handle().promise().next = next_ptr; task->get_handle().resume(); if (task->get_handle().promise().next == nullptr) { @@ -204,61 +186,52 @@ struct task_t : public task_base_t { #endif } - T await_resume() noexcept { - return task->get_result(); - } + T await_resume() noexcept { return task->get_result(); } - bool resumable() const noexcept { - return task->done(); - } + bool resumable() const noexcept { return task->done(); } - void cancel() const noexcept { - task->get_handle().promise().next = nullptr; - } + void cancel() const noexcept { task->get_handle().promise().next = nullptr; } - task_t *task; + task_t* task; }; - awaiter_t operator co_await() { - return awaiter_t{this}; - } + awaiter_t operator co_await() { return awaiter_t{this}; } - std::coroutine_handle get_handle() { - return std::coroutine_handle::from_address(handle_address); - } + std::coroutine_handle get_handle() { return std::coroutine_handle::from_address(handle_address); } // conversion functions // // erase type - explicit operator task_t() && noexcept { - return task_t{std::coroutine_handle<>::from_address(std::exchange(handle_address, nullptr))}; - } + explicit operator task_t() && noexcept { return task_t{std::coroutine_handle<>::from_address(std::exchange(handle_address, nullptr))}; } // restore erased type - template - requires(std::same_as) explicit operator task_t() && noexcept { + template + requires(std::same_as) + explicit operator task_t() && noexcept { return task_t{std::coroutine_handle<>::from_address(std::exchange(handle_address, nullptr))}; } }; // === Type traits ================================================================================ -template -requires std::invocable inline constexpr bool is_async_function_v = requires { - {static_cast>(std::declval>())}; +template +requires std::invocable +inline constexpr bool is_async_function_v = requires { + { static_cast>(std::declval>()) }; }; // ================================================================================================ -template -requires std::invocable class async_function_unwrapped_return_type { +template +requires std::invocable +class async_function_unwrapped_return_type { using return_type = std::invoke_result_t; - template + template struct task_inner { using type = U; }; - template + template struct task_inner> { using type = U; }; @@ -267,5 +240,6 @@ requires std::invocable class async_function_unwrapped_return_type { using type = task_inner::type; }; -template -requires std::invocable using async_function_unwrapped_return_type_t = async_function_unwrapped_return_type::type; +template +requires std::invocable +using async_function_unwrapped_return_type_t = async_function_unwrapped_return_type::type; diff --git a/runtime-light/k2-platform/k2-api.h b/runtime-light/k2-platform/k2-api.h index fd5c703799..10ba56a1f6 100644 --- a/runtime-light/k2-platform/k2-api.h +++ b/runtime-light/k2-platform/k2-api.h @@ -44,133 +44,73 @@ using ImageInfo = ImageInfo; using ControlFlags = ControlFlags; -inline const ImageInfo *describe() noexcept { - return k2_describe(); -} +inline const ImageInfo* describe() noexcept { return k2_describe(); } -inline const ControlFlags *control_flags() noexcept { - return k2_control_flags(); -} +inline const ControlFlags* control_flags() noexcept { return k2_control_flags(); } -inline const ImageState *image_state() noexcept { - return k2_image_state(); -} +inline const ImageState* image_state() noexcept { return k2_image_state(); } -inline const ComponentState *component_state() noexcept { - return k2_component_state(); -} +inline const ComponentState* component_state() noexcept { return k2_component_state(); } -inline InstanceState *instance_state() noexcept { - return k2_instance_state(); -} +inline InstanceState* instance_state() noexcept { return k2_instance_state(); } -inline void *alloc_align(size_t size, size_t align) noexcept { - return k2_alloc(size, align); -} +inline void* alloc_align(size_t size, size_t align) noexcept { return k2_alloc(size, align); } -inline void *alloc(size_t size) noexcept { - return k2::alloc_align(size, k2_impl_::DEFAULT_MEMORY_ALIGN); -} +inline void* alloc(size_t size) noexcept { return k2::alloc_align(size, k2_impl_::DEFAULT_MEMORY_ALIGN); } -inline void *realloc(void *ptr, size_t new_size) noexcept { - return k2_realloc(ptr, new_size); -} +inline void* realloc(void* ptr, size_t new_size) noexcept { return k2_realloc(ptr, new_size); } -inline void *realloc_checked(void *ptr, size_t old_size, size_t align, size_t new_size) noexcept { - return k2_realloc_checked(ptr, old_size, align, new_size); -} +inline void* realloc_checked(void* ptr, size_t old_size, size_t align, size_t new_size) noexcept { return k2_realloc_checked(ptr, old_size, align, new_size); } -inline void free(void *ptr) noexcept { - k2_free(ptr); -} +inline void free(void* ptr) noexcept { k2_free(ptr); } -inline void free_checked(void *ptr, size_t size, size_t align) noexcept { - k2_free_checked(ptr, size, align); -} +inline void free_checked(void* ptr, size_t size, size_t align) noexcept { k2_free_checked(ptr, size, align); } -[[noreturn]] inline void exit(int32_t exit_code) noexcept { - k2_exit(exit_code); -} +[[noreturn]] inline void exit(int32_t exit_code) noexcept { k2_exit(exit_code); } -inline uint32_t getpid() noexcept { - return k2_getpid(); -} +inline uint32_t getpid() noexcept { return k2_getpid(); } -inline int32_t uname(struct utsname *addr) noexcept { - return k2_uname(addr); -} +inline int32_t uname(struct utsname* addr) noexcept { return k2_uname(addr); } -inline int32_t open(uint64_t *stream_d, size_t name_len, const char *name) noexcept { - return k2_open(stream_d, name_len, name); -} +inline int32_t open(uint64_t* stream_d, size_t name_len, const char* name) noexcept { return k2_open(stream_d, name_len, name); } -inline void stream_status(uint64_t stream_d, StreamStatus *status) noexcept { - k2_stream_status(stream_d, status); -} +inline void stream_status(uint64_t stream_d, StreamStatus* status) noexcept { k2_stream_status(stream_d, status); } -inline size_t write(uint64_t stream_d, size_t data_len, const void *data) noexcept { - return k2_write(stream_d, data_len, data); -} +inline size_t write(uint64_t stream_d, size_t data_len, const void* data) noexcept { return k2_write(stream_d, data_len, data); } -inline size_t read(uint64_t stream_d, size_t buf_len, void *buf) noexcept { - return k2_read(stream_d, buf_len, buf); -} +inline size_t read(uint64_t stream_d, size_t buf_len, void* buf) noexcept { return k2_read(stream_d, buf_len, buf); } -inline void please_shutdown(uint64_t stream_d) noexcept { - k2_please_shutdown(stream_d); -} +inline void please_shutdown(uint64_t stream_d) noexcept { k2_please_shutdown(stream_d); } -inline void shutdown_write(uint64_t stream_d) noexcept { - k2_shutdown_write(stream_d); -} +inline void shutdown_write(uint64_t stream_d) noexcept { k2_shutdown_write(stream_d); } -inline void instant(TimePoint *time_point) noexcept { - k2_instant(time_point); -} +inline void instant(TimePoint* time_point) noexcept { k2_instant(time_point); } -inline int32_t new_timer(uint64_t *descriptor, uint64_t duration_ns) noexcept { - return k2_new_timer(descriptor, duration_ns); -} +inline int32_t new_timer(uint64_t* descriptor, uint64_t duration_ns) noexcept { return k2_new_timer(descriptor, duration_ns); } -inline int32_t timer_deadline(uint64_t d, TimePoint *deadline) noexcept { - return k2_timer_deadline(d, deadline); -} +inline int32_t timer_deadline(uint64_t d, TimePoint* deadline) noexcept { return k2_timer_deadline(d, deadline); } -inline void free_descriptor(uint64_t descriptor) noexcept { - k2_free_descriptor(descriptor); -} +inline void free_descriptor(uint64_t descriptor) noexcept { k2_free_descriptor(descriptor); } -inline uint8_t take_update(uint64_t *update_d) noexcept { - return k2_take_update(update_d); -} +inline uint8_t take_update(uint64_t* update_d) noexcept { return k2_take_update(update_d); } -inline void log(size_t level, size_t len, const char *str) noexcept { - k2_log(level, len, str); -} +inline void log(size_t level, size_t len, const char* str) noexcept { k2_log(level, len, str); } -inline size_t log_level_enabled() noexcept { - return k2_log_level_enabled(); -} +inline size_t log_level_enabled() noexcept { return k2_log_level_enabled(); } -inline void os_rnd(size_t len, void *bytes) noexcept { - k2_os_rnd(len, bytes); -} +inline void os_rnd(size_t len, void* bytes) noexcept { k2_os_rnd(len, bytes); } -inline void system_time(SystemTime *system_time) noexcept { - k2_system_time(system_time); -} +inline void system_time(SystemTime* system_time) noexcept { k2_system_time(system_time); } -inline uint32_t args_count() noexcept { - return k2_args_count(); -} +inline uint32_t args_count() noexcept { return k2_args_count(); } inline auto arg_fetch(uint32_t arg_num) noexcept { const auto key_len{k2_args_key_len(arg_num)}; const auto value_len{k2_args_value_len(arg_num)}; // +1 since we get non-null-terminated strings from platform and we want to null-terminate them on our side - auto *key_buffer{static_cast(k2::alloc(key_len + 1))}; - auto *value_buffer{static_cast(k2::alloc(value_len + 1))}; + auto* key_buffer{static_cast(k2::alloc(key_len + 1))}; + auto* value_buffer{static_cast(k2::alloc(value_len + 1))}; k2_args_fetch(arg_num, key_buffer, value_buffer); // null-terminate key_buffer[key_len] = '\0'; @@ -180,17 +120,15 @@ inline auto arg_fetch(uint32_t arg_num) noexcept { std::unique_ptr{value_buffer, k2::free}); } -inline uint32_t env_count() noexcept { - return k2_env_count(); -} +inline uint32_t env_count() noexcept { return k2_env_count(); } inline auto env_fetch(uint32_t arg_num) noexcept { const auto key_len{k2_env_key_len(arg_num)}; const auto value_len{k2_env_value_len(arg_num)}; // +1 since we get non-null-terminated strings from platform and we want to null-terminate them on our side - auto *key_buffer{static_cast(k2::alloc(key_len + 1))}; - auto *value_buffer{static_cast(k2::alloc(value_len + 1))}; + auto* key_buffer{static_cast(k2::alloc(key_len + 1))}; + auto* value_buffer{static_cast(k2::alloc(value_len + 1))}; k2_env_fetch(arg_num, key_buffer, value_buffer); // null-terminate key_buffer[key_len] = '\0'; @@ -200,12 +138,8 @@ inline auto env_fetch(uint32_t arg_num) noexcept { std::unique_ptr{value_buffer, k2::free}); } -inline int32_t udp_connect(uint64_t *socket_d, const char *host, size_t host_len) noexcept { - return k2_udp_connect(socket_d, host, host_len); -} +inline int32_t udp_connect(uint64_t* socket_d, const char* host, size_t host_len) noexcept { return k2_udp_connect(socket_d, host, host_len); } -inline int32_t tcp_connect(uint64_t *socket_d, const char *host, size_t host_len) noexcept { - return k2_tcp_connect(socket_d, host, host_len); -} +inline int32_t tcp_connect(uint64_t* socket_d, const char* host, size_t host_len) noexcept { return k2_tcp_connect(socket_d, host, host_len); } } // namespace k2 diff --git a/runtime-light/k2-platform/k2-header.h b/runtime-light/k2-platform/k2-header.h index e5567c5281..20726b56d1 100644 --- a/runtime-light/k2-platform/k2-header.h +++ b/runtime-light/k2-platform/k2-header.h @@ -84,7 +84,7 @@ enum PollStatus { struct ImageInfo { // TODO: null terminated string is OK? // TODO: namespaces? - const char *image_name; + const char* image_name; uint64_t build_timestamp; uint64_t header_h_version; @@ -102,14 +102,14 @@ struct ImageInfo { enum PollStatus k2_poll(); // Symbols provided by .so. -struct ImageState *k2_create_image(); +struct ImageState* k2_create_image(); void k2_init_image(); -struct ComponentState *k2_create_component(); +struct ComponentState* k2_create_component(); void k2_init_component(); -struct InstanceState *k2_create_instance(); +struct InstanceState* k2_create_instance(); void k2_init_instance(); -const struct ImageInfo *k2_describe(); +const struct ImageInfo* k2_describe(); struct ControlFlags { atomic_uint32_t please_yield; @@ -125,21 +125,21 @@ struct ControlFlags { * differences. Preferable way to communication with k2-node. * */ -struct ControlFlags *k2_control_flags(); -struct ImageState *k2_image_state(); -struct ComponentState *k2_component_state(); -struct InstanceState *k2_instance_state(); +struct ControlFlags* k2_control_flags(); +struct ImageState* k2_image_state(); +struct ComponentState* k2_component_state(); +struct InstanceState* k2_instance_state(); /** * If component track alignment and allocated memory size - * it is preferable to use the `*_checked` versions, which have additional checks enabled. * The rest of the functions are allowed to be used in any case. */ -void *k2_alloc(size_t size, size_t align); -void *k2_realloc(void *ptr, size_t new_size); -void *k2_realloc_checked(void *ptr, size_t old_size, size_t align, size_t new_size); -void k2_free(void *ptr); -void k2_free_checked(void *ptr, size_t size, size_t align); +void* k2_alloc(size_t size, size_t align); +void* k2_realloc(void* ptr, size_t new_size); +void* k2_realloc_checked(void* ptr, size_t old_size, size_t align, size_t new_size); +void k2_free(void* ptr); +void k2_free_checked(void* ptr, size_t size, size_t align); /** * Immediately abort component execution. @@ -161,7 +161,7 @@ uint32_t k2_getpid(); * Possible 'errno': * 'EFAULT' => buf is not valid */ -int32_t k2_uname(struct utsname *buf); +int32_t k2_uname(struct utsname* buf); /** * @return return `0` on success. libc-like `errno` otherwise @@ -174,7 +174,7 @@ int32_t k2_uname(struct utsname *buf); * `ENOMEM` => our component has no enough memory for stream * `EACCES` => permission denied */ -int32_t k2_open(uint64_t *stream_d, size_t name_len, const char *name); +int32_t k2_open(uint64_t* stream_d, size_t name_len, const char* name); /** * If the write or read status is `Blocked` - then the platform ensures that @@ -188,7 +188,7 @@ int32_t k2_open(uint64_t *stream_d, size_t name_len, const char *name); * `EBADF` => d is not valid(never was valid or used after free) * `EBADR` => d is valid descriptor, but not a stream (probably, timer) */ -void k2_stream_status(uint64_t stream_d, struct StreamStatus *status); +void k2_stream_status(uint64_t stream_d, struct StreamStatus* status); /** * Guaranteed to return `0` if the stream is `Closed`, `Blocked` or `stream_d` is invalid. @@ -201,7 +201,7 @@ void k2_stream_status(uint64_t stream_d, struct StreamStatus *status); * * @return number of written bytes. */ -size_t k2_write(uint64_t stream_d, size_t data_len, const void *data); +size_t k2_write(uint64_t stream_d, size_t data_len, const void* data); /** * Guaranteed to return `0` if the stream is `Closed`, `Blocked` or `stream_d` is invalid. @@ -214,7 +214,7 @@ size_t k2_write(uint64_t stream_d, size_t data_len, const void *data); * * @return number of read bytes. */ -size_t k2_read(uint64_t stream_d, size_t buf_len, void *buf); +size_t k2_read(uint64_t stream_d, size_t buf_len, void* buf); /** * Sets `StreamStatus.please_whutdown_write=true` for the component on the @@ -236,7 +236,7 @@ void k2_please_shutdown(uint64_t stream_d); void k2_shutdown_write(uint64_t stream_d); // Coordinated with timers. Monotonical, for timeouts, measurements, etc.. -void k2_instant(struct TimePoint *time_point); +void k2_instant(struct TimePoint* time_point); /** * One-shot timer. @@ -250,7 +250,7 @@ void k2_instant(struct TimePoint *time_point); * Looks like `ENOMEM` is only reasonable error. * I think component should prefer abortion in this case. */ -int32_t k2_new_timer(uint64_t *descriptor, uint64_t duration_ns); +int32_t k2_new_timer(uint64_t* descriptor, uint64_t duration_ns); /** * @return `0` on success. libc-like `errno` on error. @@ -261,7 +261,7 @@ int32_t k2_new_timer(uint64_t *descriptor, uint64_t duration_ns); * `EBADF` => `d` is not valid(never was valid or used after free) * `EBADR` => `d` is valid descriptor, but not a timer (probably stream) */ -int32_t k2_timer_deadline(uint64_t d, struct TimePoint *deadline); +int32_t k2_timer_deadline(uint64_t d, struct TimePoint* deadline); /** * "Free" associated descriptor. @@ -300,7 +300,7 @@ void k2_free_descriptor(uint64_t descriptor); * @return: `1` if update is successfully taken. `descriptor` will be assigned to updated descriptor. * @return: `1` if there is no updates to take. `descriptor` will be assigned to `0`. */ -uint8_t k2_take_update(uint64_t *update_d); +uint8_t k2_take_update(uint64_t* update_d); /** * Only utf-8 string supported. @@ -313,40 +313,40 @@ uint8_t k2_take_update(uint64_t *update_d); * Any other value will cause the log to be skipped * if `level` > `log_level_enabled()` log will be skipped */ -void k2_log(size_t level, size_t len, const char *str); +void k2_log(size_t level, size_t len, const char* str); // Use for optimization, see `k2_log` size_t k2_log_level_enabled(); // Note: prefer to use only as seed generator for pseudo-random -void k2_os_rnd(size_t len, void *bytes); +void k2_os_rnd(size_t len, void* bytes); // Time since epoch, non-monotonical -void k2_system_time(struct SystemTime *system_time); +void k2_system_time(struct SystemTime* system_time); /** * libc-like socket api. * @return: `0` on success, `errno != 0` otherwise */ -int32_t k2_socket(uint64_t *socket_d, int32_t domain, int32_t type, int32_t protocol); +int32_t k2_socket(uint64_t* socket_d, int32_t domain, int32_t type, int32_t protocol); /** * libc-like socket api. * @return: `0` on success, `errno != 0` otherwise */ -int32_t k2_connect(uint64_t socket_d, const struct sockaddr_storage *addr, size_t addrlen); +int32_t k2_connect(uint64_t socket_d, const struct sockaddr_storage* addr, size_t addrlen); /** * Perform sequentially `k2_lookup_host` -> `k2_socket` -> `k2_connect` * @return: `0` on success, `errno != 0` otherwise */ -int32_t k2_udp_connect(uint64_t *socket_d, const char *hostport, size_t hostport_len); +int32_t k2_udp_connect(uint64_t* socket_d, const char* hostport, size_t hostport_len); /** * Perform sequentially `k2_lookup_host` -> `k2_socket` -> `k2_connect` * @return: `0` on success, `errno != 0` otherwise */ -int32_t k2_tcp_connect(uint64_t *socket_d, const char *hostport, size_t hostport_len); +int32_t k2_tcp_connect(uint64_t* socket_d, const char* hostport, size_t hostport_len); struct SockAddr { uint16_t is_v6; @@ -378,7 +378,7 @@ struct SockAddr { * `result_buf_len` is set to the number of resolved addresses. `0 <= result_buf_len <= min(result_buf_len, 128)`. * the first `result_buf_len` items of `result_buf` will be filled with resolved addresses */ -int32_t k2_lookup_host(const char *hostport, size_t hostport_len, struct SockAddr *result_buf, size_t *result_buf_len); +int32_t k2_lookup_host(const char* hostport, size_t hostport_len, struct SockAddr* result_buf, size_t* result_buf_len); /** * Only available during `k2_create_component` call. Returns `0` in other context. @@ -405,7 +405,7 @@ uint32_t k2_args_value_len(uint32_t arg_num); * @param `key` buffer where key will be written, buffer len must staisfy `len >= k2_args_key_len(arg_num)` * @param `value` buffer where value will be written, buffer len must staisfy `len >= k2_args_value_len(arg_num)` */ -void k2_args_fetch(uint32_t arg_num, char *key, char *value); +void k2_args_fetch(uint32_t arg_num, char* key, char* value); /** * Even if env is available at any point, try to cache and parse it as soon as possible (during k2_create_component or even k2_create_image). @@ -432,7 +432,7 @@ uint32_t k2_env_value_len(uint32_t env_num); * @param `key` buffer where key will be written, buffer len must staisfy `len >= k2_env_key_len(env_num)` * @param `value` buffer where value will be written, buffer len must staisfy `len >= k2_env_value_len(env_num)` */ -void k2_env_fetch(uint32_t env_num, char *key, char *value); +void k2_env_fetch(uint32_t env_num, char* key, char* value); #ifdef __cplusplus } diff --git a/runtime-light/memory-resource-impl/monotonic-light-buffer-resource.cpp b/runtime-light/memory-resource-impl/monotonic-light-buffer-resource.cpp index dfb877fb2a..6d607e9c9c 100644 --- a/runtime-light/memory-resource-impl/monotonic-light-buffer-resource.cpp +++ b/runtime-light/memory-resource-impl/monotonic-light-buffer-resource.cpp @@ -6,7 +6,7 @@ namespace memory_resource { // todo:k2 How it should work in k2? -void monotonic_buffer_resource::critical_dump(void *, size_t) const noexcept {} +void monotonic_buffer_resource::critical_dump(void*, size_t) const noexcept {} void monotonic_buffer_resource::raise_oom(size_t) const noexcept {} } // namespace memory_resource \ No newline at end of file diff --git a/runtime-light/runtime-light.cpp b/runtime-light/runtime-light.cpp index 1c407c6cf3..0631a97857 100644 --- a/runtime-light/runtime-light.cpp +++ b/runtime-light/runtime-light.cpp @@ -9,10 +9,10 @@ #include "runtime-light/state/image-state.h" #include "runtime-light/state/instance-state.h" -ImageState *k2_create_image() { +ImageState* k2_create_image() { // Note that in k2_create_image most of K2 functionality is not yet available php_debug("create image state of \"%s\"", k2::describe()->image_name); - auto *image_state_ptr{static_cast(k2::alloc(sizeof(ImageState)))}; + auto* image_state_ptr{static_cast(k2::alloc(sizeof(ImageState)))}; if (image_state_ptr == nullptr) { php_warning("can't allocate enough memory for ImageState"); return nullptr; @@ -23,15 +23,15 @@ ImageState *k2_create_image() { void k2_init_image() { php_debug("start image state init"); - new (const_cast(k2::image_state())) ImageState{}; + new (const_cast(k2::image_state())) ImageState{}; init_php_scripts_once_in_master(); php_debug("end image state init"); } -ComponentState *k2_create_component() { +ComponentState* k2_create_component() { // Note that in k2_create_component most of K2 functionality is not yet available php_debug("create component state of \"%s\"", k2::describe()->image_name); - auto *component_state_ptr{static_cast(k2::alloc(sizeof(ComponentState)))}; + auto* component_state_ptr{static_cast(k2::alloc(sizeof(ComponentState)))}; if (component_state_ptr == nullptr) { php_warning("can't allocate enough memory for ImageState"); return nullptr; @@ -42,14 +42,14 @@ ComponentState *k2_create_component() { void k2_init_component() { php_debug("start component state init"); - new (const_cast(k2::component_state())) ComponentState{}; + new (const_cast(k2::component_state())) ComponentState{}; php_debug("end component state init"); } -InstanceState *k2_create_instance() { +InstanceState* k2_create_instance() { // Note that in k2_create_instance most of K2 functionality is not yet available php_debug("create instance state of \"%s\"", k2::describe()->image_name); - auto *instance_state_ptr{static_cast(k2::alloc(sizeof(InstanceState)))}; + auto* instance_state_ptr{static_cast(k2::alloc(sizeof(InstanceState)))}; if (instance_state_ptr == nullptr) { php_warning("cannot allocate enough memory for ComponentState"); return nullptr; @@ -67,7 +67,7 @@ void k2_init_instance() { k2::PollStatus k2_poll() { php_debug("k2_poll started..."); - auto &instance_state{InstanceState::get()}; + auto& instance_state{InstanceState::get()}; instance_state.process_platform_updates(); const auto poll_status{instance_state.poll_status}; php_debug("k2_poll finished with status: %d", poll_status); diff --git a/runtime-light/scheduler/scheduler.cpp b/runtime-light/scheduler/scheduler.cpp index 27f4e5f5d2..6d5fd561b9 100644 --- a/runtime-light/scheduler/scheduler.cpp +++ b/runtime-light/scheduler/scheduler.cpp @@ -16,9 +16,7 @@ // === SimpleCoroutineScheduler =================================================================== -SimpleCoroutineScheduler &SimpleCoroutineScheduler::get() noexcept { - return InstanceState::get().scheduler; -} +SimpleCoroutineScheduler& SimpleCoroutineScheduler::get() noexcept { return InstanceState::get().scheduler; } ScheduleStatus SimpleCoroutineScheduler::scheduleOnNoEvent() noexcept { if (yield_tokens.empty()) { @@ -56,79 +54,77 @@ ScheduleStatus SimpleCoroutineScheduler::scheduleOnStreamUpdate(uint64_t stream_ } } -ScheduleStatus SimpleCoroutineScheduler::scheduleOnYield() noexcept { - return ScheduleStatus::Skipped; -} +ScheduleStatus SimpleCoroutineScheduler::scheduleOnYield() noexcept { return ScheduleStatus::Skipped; } ScheduleStatus SimpleCoroutineScheduler::schedule(ScheduleEvent::EventT event) noexcept { return std::visit( - [this](auto &&event) noexcept { - using event_t = std::remove_cvref_t; - if constexpr (std::is_same_v) { - return scheduleOnNoEvent(); - } else if constexpr (std::is_same_v) { - return scheduleOnIncomingStream(); - } else if constexpr (std::is_same_v) { - return scheduleOnStreamUpdate(event.stream_d); - } else if constexpr (std::is_same_v) { - return scheduleOnStreamUpdate(event.timer_d); - } else if constexpr (std::is_same_v) { - return scheduleOnYield(); - } else { - static_assert(false, "non-exhaustive visitor"); - } - }, - event); + [this](auto&& event) noexcept { + using event_t = std::remove_cvref_t; + if constexpr (std::is_same_v) { + return scheduleOnNoEvent(); + } else if constexpr (std::is_same_v) { + return scheduleOnIncomingStream(); + } else if constexpr (std::is_same_v) { + return scheduleOnStreamUpdate(event.stream_d); + } else if constexpr (std::is_same_v) { + return scheduleOnStreamUpdate(event.timer_d); + } else if constexpr (std::is_same_v) { + return scheduleOnYield(); + } else { + static_assert(false, "non-exhaustive visitor"); + } + }, + event); } void SimpleCoroutineScheduler::suspend(SuspendToken token) noexcept { suspend_tokens.emplace(token); std::visit( - [this, token](auto &&event) noexcept { - using event_t = std::remove_cvref_t; - if constexpr (std::is_same_v) { - yield_tokens.push_back(token); - } else if constexpr (std::is_same_v) { - awaiting_for_stream_tokens.push_back(token); - } else if constexpr (std::is_same_v) { - if (event.stream_d == k2::INVALID_PLATFORM_DESCRIPTOR) { - return; + [this, token](auto&& event) noexcept { + using event_t = std::remove_cvref_t; + if constexpr (std::is_same_v) { + yield_tokens.push_back(token); + } else if constexpr (std::is_same_v) { + awaiting_for_stream_tokens.push_back(token); + } else if constexpr (std::is_same_v) { + if (event.stream_d == k2::INVALID_PLATFORM_DESCRIPTOR) { + return; + } + awaiting_for_update_tokens.emplace(event.stream_d, token); + } else if constexpr (std::is_same_v) { + if (event.timer_d == k2::INVALID_PLATFORM_DESCRIPTOR) { + return; + } + awaiting_for_update_tokens.emplace(event.timer_d, token); + } else { + static_assert(false, "non-exhaustive visitor"); } - awaiting_for_update_tokens.emplace(event.stream_d, token); - } else if constexpr (std::is_same_v) { - if (event.timer_d == k2::INVALID_PLATFORM_DESCRIPTOR) { - return; - } - awaiting_for_update_tokens.emplace(event.timer_d, token); - } else { - static_assert(false, "non-exhaustive visitor"); - } - }, - token.second); + }, + token.second); } void SimpleCoroutineScheduler::cancel(SuspendToken token) noexcept { suspend_tokens.erase(token); std::visit( - [this, token](auto &&event) noexcept { - using event_t = std::remove_cvref_t; - if constexpr (std::is_same_v) { - const auto it_token{std::find(yield_tokens.cbegin(), yield_tokens.cend(), token)}; - if (it_token != yield_tokens.cend()) { - yield_tokens.erase(it_token); - } - } else if constexpr (std::is_same_v) { - const auto it_token{std::find(awaiting_for_stream_tokens.cbegin(), awaiting_for_stream_tokens.cend(), token)}; - if (it_token != awaiting_for_stream_tokens.cend()) { - awaiting_for_stream_tokens.erase(it_token); + [this, token](auto&& event) noexcept { + using event_t = std::remove_cvref_t; + if constexpr (std::is_same_v) { + const auto it_token{std::find(yield_tokens.cbegin(), yield_tokens.cend(), token)}; + if (it_token != yield_tokens.cend()) { + yield_tokens.erase(it_token); + } + } else if constexpr (std::is_same_v) { + const auto it_token{std::find(awaiting_for_stream_tokens.cbegin(), awaiting_for_stream_tokens.cend(), token)}; + if (it_token != awaiting_for_stream_tokens.cend()) { + awaiting_for_stream_tokens.erase(it_token); + } + } else if constexpr (std::is_same_v) { + awaiting_for_update_tokens.erase(event.stream_d); + } else if constexpr (std::is_same_v) { + awaiting_for_update_tokens.erase(event.timer_d); + } else { + static_assert(false, "non-exhaustive visitor"); } - } else if constexpr (std::is_same_v) { - awaiting_for_update_tokens.erase(event.stream_d); - } else if constexpr (std::is_same_v) { - awaiting_for_update_tokens.erase(event.timer_d); - } else { - static_assert(false, "non-exhaustive visitor"); - } - }, - token.second); + }, + token.second); } diff --git a/runtime-light/scheduler/scheduler.h b/runtime-light/scheduler/scheduler.h index ada3330feb..847f9275ec 100644 --- a/runtime-light/scheduler/scheduler.h +++ b/runtime-light/scheduler/scheduler.h @@ -60,32 +60,24 @@ namespace WaitEvent { struct Rechedule { static constexpr size_t HASH_VALUE = 4001; - bool operator==([[maybe_unused]] const Rechedule &other) const noexcept { - return true; - } + bool operator==([[maybe_unused]] const Rechedule& other) const noexcept { return true; } }; struct IncomingStream { static constexpr size_t HASH_VALUE = 4003; - bool operator==([[maybe_unused]] const IncomingStream &other) const noexcept { - return true; - } + bool operator==([[maybe_unused]] const IncomingStream& other) const noexcept { return true; } }; struct UpdateOnStream { uint64_t stream_d{}; - bool operator==(const UpdateOnStream &other) const noexcept { - return stream_d == other.stream_d; - } + bool operator==(const UpdateOnStream& other) const noexcept { return stream_d == other.stream_d; } }; struct UpdateOnTimer { uint64_t timer_d{}; - bool operator==(const UpdateOnTimer &other) const noexcept { - return timer_d == other.timer_d; - } + bool operator==(const UpdateOnTimer& other) const noexcept { return timer_d == other.timer_d; } }; using EventT = std::variant; @@ -94,32 +86,24 @@ using EventT = std::variant +template <> struct std::hash { - size_t operator()([[maybe_unused]] const WaitEvent::Rechedule &v) const noexcept { - return WaitEvent::Rechedule::HASH_VALUE; - } + size_t operator()([[maybe_unused]] const WaitEvent::Rechedule& v) const noexcept { return WaitEvent::Rechedule::HASH_VALUE; } }; -template<> +template <> struct std::hash { - size_t operator()([[maybe_unused]] const WaitEvent::IncomingStream &v) const noexcept { - return WaitEvent::IncomingStream::HASH_VALUE; - } + size_t operator()([[maybe_unused]] const WaitEvent::IncomingStream& v) const noexcept { return WaitEvent::IncomingStream::HASH_VALUE; } }; -template<> +template <> struct std::hash { - size_t operator()(const WaitEvent::UpdateOnStream &v) const noexcept { - return v.stream_d; - } + size_t operator()(const WaitEvent::UpdateOnStream& v) const noexcept { return v.stream_d; } }; -template<> +template <> struct std::hash { - size_t operator()(const WaitEvent::UpdateOnTimer &v) const noexcept { - return v.timer_d; - } + size_t operator()(const WaitEvent::UpdateOnTimer& v) const noexcept { return v.timer_d; } }; /** @@ -127,9 +111,9 @@ struct std::hash { */ using SuspendToken = std::pair, WaitEvent::EventT>; -template<> +template <> struct std::hash { - size_t operator()(const SuspendToken &token) const noexcept { + size_t operator()(const SuspendToken& token) const noexcept { size_t suspend_token_hash{std::hash>{}(token.first)}; hash_combine(suspend_token_hash, token.second); return suspend_token_hash; @@ -148,29 +132,29 @@ struct std::hash { * 6. have `suspend` method that suspends specified coroutine; * 7. have `cancel` method that cancels specified SuspendToken. */ -template -concept CoroutineSchedulerConcept = std::constructible_from - && requires(scheduler_t && s, ScheduleEvent::EventT schedule_event, SuspendToken token) { - { scheduler_t::get() } noexcept -> std::same_as; - { s.done() } noexcept -> std::convertible_to; - { s.schedule(schedule_event) } noexcept -> std::same_as; - { s.contains(token) } noexcept -> std::convertible_to; - { s.suspend(token) } noexcept -> std::same_as; - { s.cancel(token) } noexcept -> std::same_as; -}; +template +concept CoroutineSchedulerConcept = std::constructible_from && + requires(scheduler_t&& s, ScheduleEvent::EventT schedule_event, SuspendToken token) { + { scheduler_t::get() } noexcept -> std::same_as; + { s.done() } noexcept -> std::convertible_to; + { s.schedule(schedule_event) } noexcept -> std::same_as; + { s.contains(token) } noexcept -> std::convertible_to; + { s.suspend(token) } noexcept -> std::same_as; + { s.cancel(token) } noexcept -> std::same_as; + }; // === SimpleCoroutineScheduler =================================================================== // This scheduler doesn't support waiting for the same event from multiple coroutines. // We need to finalize our decision whether we allow to do it from PHP code or not. class SimpleCoroutineScheduler { - template + template using unordered_map = memory_resource::stl::unordered_map; - template + template using unordered_set = memory_resource::stl::unordered_set; - template + template using deque = memory_resource::stl::deque; deque yield_tokens; @@ -184,23 +168,18 @@ class SimpleCoroutineScheduler { ScheduleStatus scheduleOnYield() noexcept; public: - explicit SimpleCoroutineScheduler(memory_resource::unsynchronized_pool_resource &memory_resource) noexcept - : yield_tokens(deque::allocator_type{memory_resource}) - , awaiting_for_stream_tokens(deque::allocator_type{memory_resource}) - , awaiting_for_update_tokens(unordered_map::allocator_type{memory_resource}) - , suspend_tokens(unordered_set::allocator_type{memory_resource}) {} + explicit SimpleCoroutineScheduler(memory_resource::unsynchronized_pool_resource& memory_resource) noexcept + : yield_tokens(deque::allocator_type{memory_resource}), awaiting_for_stream_tokens(deque::allocator_type{memory_resource}), + awaiting_for_update_tokens(unordered_map::allocator_type{memory_resource}), + suspend_tokens(unordered_set::allocator_type{memory_resource}) {} - static SimpleCoroutineScheduler &get() noexcept; + static SimpleCoroutineScheduler& get() noexcept; - bool done() const noexcept { - return suspend_tokens.empty(); - } + bool done() const noexcept { return suspend_tokens.empty(); } ScheduleStatus schedule(ScheduleEvent::EventT) noexcept; - bool contains(SuspendToken token) const noexcept { - return suspend_tokens.contains(token); - } + bool contains(SuspendToken token) const noexcept { return suspend_tokens.contains(token); } void suspend(SuspendToken) noexcept; void cancel(SuspendToken) noexcept; }; diff --git a/runtime-light/server/http/http-server-state.cpp b/runtime-light/server/http/http-server-state.cpp index 81266e6d40..12a821fc51 100644 --- a/runtime-light/server/http/http-server-state.cpp +++ b/runtime-light/server/http/http-server-state.cpp @@ -6,6 +6,4 @@ #include "runtime-light/state/instance-state.h" -HttpServerInstanceState &HttpServerInstanceState::get() noexcept { - return InstanceState::get().http_server_instance_state; -} +HttpServerInstanceState& HttpServerInstanceState::get() noexcept { return InstanceState::get().http_server_instance_state; } diff --git a/runtime-light/server/http/http-server-state.h b/runtime-light/server/http/http-server-state.h index 0c38e5214c..e96e901edb 100644 --- a/runtime-light/server/http/http-server-state.h +++ b/runtime-light/server/http/http-server-state.h @@ -56,26 +56,23 @@ struct HttpServerInstanceState final : private vk::not_copyable { HttpConnectionKind connection_kind{HttpConnectionKind::CLOSE}; private: - memory_resource::unsynchronized_pool_resource &memory_resource_; + memory_resource::unsynchronized_pool_resource& memory_resource_; headers_map_t headers_; public: - explicit HttpServerInstanceState(memory_resource::unsynchronized_pool_resource &memory_resource) noexcept - : memory_resource_(memory_resource) - , headers_(headers_map_t::allocator_type{memory_resource}) {} + explicit HttpServerInstanceState(memory_resource::unsynchronized_pool_resource& memory_resource) noexcept + : memory_resource_(memory_resource), headers_(headers_map_t::allocator_type{memory_resource}) {} - const headers_map_t &headers() const noexcept { - return headers_; - } + const headers_map_t& headers() const noexcept { return headers_; } void add_header(std::string_view name_view, std::string_view value_view, bool replace) noexcept { header_t name{name_view, header_t::allocator_type{memory_resource_}}; - std::ranges::for_each(name, [](auto &c) noexcept { c = std::tolower(c); }); + std::ranges::for_each(name, [](auto& c) noexcept { c = std::tolower(c); }); if (const auto it{headers_.find(name)}; replace && it != headers_.end()) [[unlikely]] { headers_.erase(name); } headers_.emplace(std::move(name), header_t{value_view, header_t::allocator_type{memory_resource_}}); } - static HttpServerInstanceState &get() noexcept; + static HttpServerInstanceState& get() noexcept; }; diff --git a/runtime-light/server/http/init-functions.cpp b/runtime-light/server/http/init-functions.cpp index c71235d05a..1aae716f27 100644 --- a/runtime-light/server/http/init-functions.cpp +++ b/runtime-light/server/http/init-functions.cpp @@ -59,7 +59,7 @@ constexpr std::string_view GET_METHOD = "GET"; constexpr std::string_view POST_METHOD = "POST"; constexpr std::string_view HEAD_METHOD = "HEAD"; -string get_server_protocol(tl::HttpVersion http_version, const std::optional &opt_scheme) noexcept { +string get_server_protocol(tl::HttpVersion http_version, const std::optional& opt_scheme) noexcept { std::string_view protocol_name{HTTP}; const auto protocol_version{http_version.string_view()}; if (opt_scheme.has_value()) { @@ -78,15 +78,15 @@ string get_server_protocol(tl::HttpVersion http_version, const std::optional(header.c_str())}; - auto *cookie_list_end{const_cast(header.c_str() + header.size())}; + auto* cookie_start{const_cast(header.c_str())}; + auto* cookie_list_end{const_cast(header.c_str() + header.size())}; do { - auto *cookie_end{std::find(cookie_start, cookie_list_end, ';')}; - char *cookie_domain_end{std::find(cookie_start, cookie_end, '=')}; + auto* cookie_end{std::find(cookie_start, cookie_list_end, ';')}; + char* cookie_domain_end{std::find(cookie_start, cookie_end, '=')}; if (cookie_domain_end != cookie_end) [[likely]] { - char *cookie_value_start{std::next(cookie_domain_end)}; + char* cookie_value_start{std::next(cookie_domain_end)}; const auto cookie_domain_size{static_cast(std::distance(cookie_start, cookie_domain_end))}; const auto cookie_value_size{static_cast(std::distance(cookie_value_start, cookie_end))}; string cookie_domain{cookie_start, cookie_domain_size}; @@ -105,14 +105,14 @@ void process_cookie_header(const string &header, PhpScriptBuiltInSuperGlobals &s // RFC link: https://tools.ietf.org/html/rfc2617#section-2 // Header example: // Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== -void process_authorization_header(const string &header, PhpScriptBuiltInSuperGlobals &superglobals) noexcept { +void process_authorization_header(const string& header, PhpScriptBuiltInSuperGlobals& superglobals) noexcept { array header_parts{explode(' ', header)}; if (header_parts.count() != 2) [[unlikely]] { return; } - const auto &auth_scheme{header_parts[0]}; - const auto &auth_credentials{header_parts[1]}; + const auto& auth_scheme{header_parts[0]}; + const auto& auth_credentials{header_parts[1]}; if (std::string_view{auth_scheme.c_str(), auth_scheme.size()} != AUTHORIZATION_BASIC) [[unlikely]] { return; } @@ -134,13 +134,13 @@ void process_authorization_header(const string &header, PhpScriptBuiltInSuperGlo } // returns content type -std::string_view process_headers(tl::K2InvokeHttp &invoke_http, PhpScriptBuiltInSuperGlobals &superglobals) noexcept { - auto &server{superglobals.v$_SERVER}; - auto &http_server_instance_st{HttpServerInstanceState::get()}; +std::string_view process_headers(tl::K2InvokeHttp& invoke_http, PhpScriptBuiltInSuperGlobals& superglobals) noexcept { + auto& server{superglobals.v$_SERVER}; + auto& http_server_instance_st{HttpServerInstanceState::get()}; std::string_view content_type{CONTENT_TYPE_APP_FORM_URLENCODED}; // platform provides headers that are already in lowercase - for (auto &[_, h_name, h_value] : invoke_http.headers) { + for (auto& [_, h_name, h_value] : invoke_http.headers) { const std::string_view h_name_view{h_name.c_str(), h_name.size()}; const std::string_view h_value_view{h_value.c_str(), h_value.size()}; @@ -195,10 +195,10 @@ std::string_view process_headers(tl::K2InvokeHttp &invoke_http, PhpScriptBuiltIn } // namespace -void init_http_server(tl::K2InvokeHttp &&invoke_http) noexcept { - auto &superglobals{InstanceState::get().php_script_mutable_globals_singleton.get_superglobals()}; - auto &server{superglobals.v$_SERVER}; - auto &http_server_instance_st{HttpServerInstanceState::get()}; +void init_http_server(tl::K2InvokeHttp&& invoke_http) noexcept { + auto& superglobals{InstanceState::get().php_script_mutable_globals_singleton.get_superglobals()}; + auto& server{superglobals.v$_SERVER}; + auto& http_server_instance_st{HttpServerInstanceState::get()}; { // determine HTTP method const std::string_view http_method{invoke_http.method.c_str(), invoke_http.method.size()}; @@ -294,7 +294,7 @@ void init_http_server(tl::K2InvokeHttp &&invoke_http) noexcept { // prepare some response headers // add content-type header - auto &static_SB{RuntimeContext::get().static_SB}; + auto& static_SB{RuntimeContext::get().static_SB}; static_SB.clean() << HttpHeader::CONTENT_TYPE.data() << ": " << CONTENT_TYPE_TEXT_WIN1251.data(); header({static_SB.c_str(), static_SB.size()}, true, HttpStatus::NO_STATUS); // add connection kind header @@ -302,8 +302,8 @@ void init_http_server(tl::K2InvokeHttp &&invoke_http) noexcept { static_SB.clean() << HttpHeader::CONNECTION.data() << ": " << connection_kind.data(); } -task_t finalize_http_server(const string_buffer &output) noexcept { - auto &http_server_instance_st{HttpServerInstanceState::get()}; +task_t finalize_http_server(const string_buffer& output) noexcept { + auto& http_server_instance_st{HttpServerInstanceState::get()}; string body{}; if (http_server_instance_st.http_method != HttpMethod::HEAD) { @@ -317,7 +317,7 @@ task_t finalize_http_server(const string_buffer &output) noexcept { if (encoded_body.has_value()) [[likely]] { body = std::move(*encoded_body); - auto &static_SB{RuntimeContext::get().static_SB}; + auto& static_SB{RuntimeContext::get().static_SB}; static_SB.clean() << HttpHeader::CONTENT_ENCODING.data() << ": " << (gzip_encoded ? ENCODING_GZIP.data() : ENCODING_DEFLATE.data()); header({static_SB.c_str(), static_SB.size()}, true, HttpStatus::NO_STATUS); } @@ -332,8 +332,8 @@ task_t finalize_http_server(const string_buffer &output) noexcept { // fill headers http_response.headers.data.reserve(http_server_instance_st.headers().size()); std::transform(http_server_instance_st.headers().cbegin(), http_server_instance_st.headers().cend(), std::back_inserter(http_response.headers.data), - [](const auto &header_entry) noexcept { - const auto &[name, value]{header_entry}; + [](const auto& header_entry) noexcept { + const auto& [name, value]{header_entry}; string header_name{name.data(), static_cast(name.size())}; string header_value{value.data(), static_cast(value.size())}; return tl::httpHeaderEntry{.is_sensitive = {}, .name = std::move(header_name), .value = std::move(header_value)}; @@ -342,7 +342,7 @@ task_t finalize_http_server(const string_buffer &output) noexcept { tl::TLBuffer tlb{}; tl::HttpResponse{.http_response = std::move(http_response)}.store(tlb); - auto &instance_st{InstanceState::get()}; + auto& instance_st{InstanceState::get()}; if ((co_await write_all_to_stream(instance_st.standard_stream(), tlb.data(), tlb.size())) != tlb.size()) [[unlikely]] { instance_st.poll_status = k2::PollStatus::PollFinishedError; php_warning("can't write component result to stream %" PRIu64, instance_st.standard_stream()); diff --git a/runtime-light/server/http/init-functions.h b/runtime-light/server/http/init-functions.h index 96945bde95..13fa92b272 100644 --- a/runtime-light/server/http/init-functions.h +++ b/runtime-light/server/http/init-functions.h @@ -8,6 +8,6 @@ #include "runtime-light/coroutine/task.h" #include "runtime-light/tl/tl-functions.h" -void init_http_server(tl::K2InvokeHttp &&invoke_http) noexcept; +void init_http_server(tl::K2InvokeHttp&& invoke_http) noexcept; -task_t finalize_http_server(const string_buffer &output) noexcept; +task_t finalize_http_server(const string_buffer& output) noexcept; diff --git a/runtime-light/server/init-functions.h b/runtime-light/server/init-functions.h index 5bf815939f..7d87f7b4be 100644 --- a/runtime-light/server/init-functions.h +++ b/runtime-light/server/init-functions.h @@ -17,29 +17,29 @@ using ServerQuery = std::variant; -inline void init_server(ServerQuery &&query) noexcept { +inline void init_server(ServerQuery&& query) noexcept { static constexpr std::string_view SERVER_SOFTWARE_VALUE = "K2/KPHP"; static constexpr std::string_view SERVER_SIGNATURE_VALUE = "K2/KPHP Server v0.0.0"; // common initialization { - auto &server{InstanceState::get().php_script_mutable_globals_singleton.get_superglobals().v$_SERVER}; + auto& server{InstanceState::get().php_script_mutable_globals_singleton.get_superglobals().v$_SERVER}; using namespace PhpServerSuperGlobalIndices; server.set_value(string{SERVER_SOFTWARE.data(), SERVER_SOFTWARE.size()}, string{SERVER_SOFTWARE_VALUE.data(), SERVER_SOFTWARE_VALUE.size()}); server.set_value(string{SERVER_SIGNATURE.data(), SERVER_SIGNATURE.size()}, string{SERVER_SIGNATURE_VALUE.data(), SERVER_SIGNATURE_VALUE.size()}); } // specific initialization std::visit( - [](auto &&query) noexcept { - using query_t = std::remove_cvref_t; + [](auto&& query) noexcept { + using query_t = std::remove_cvref_t; - if constexpr (std::same_as) { - init_http_server(std::forward(query)); - } else if constexpr (std::same_as) { - init_job_server(std::forward(query)); - } else { - static_assert(false, "non-exhaustive visitor!"); - } - }, - std::move(query)); + if constexpr (std::same_as) { + init_http_server(std::forward(query)); + } else if constexpr (std::same_as) { + init_job_server(std::forward(query)); + } else { + static_assert(false, "non-exhaustive visitor!"); + } + }, + std::move(query)); } diff --git a/runtime-light/server/job-worker/init-functions.h b/runtime-light/server/job-worker/init-functions.h index 3e923b3a81..6b4658ac6a 100644 --- a/runtime-light/server/job-worker/init-functions.h +++ b/runtime-light/server/job-worker/init-functions.h @@ -9,8 +9,8 @@ #include "runtime-light/state/instance-state.h" #include "runtime-light/tl/tl-functions.h" -inline void init_job_server(tl::K2InvokeJobWorker &&invoke_jw) noexcept { - auto &jw_server_ctx{JobWorkerServerInstanceState::get()}; +inline void init_job_server(tl::K2InvokeJobWorker&& invoke_jw) noexcept { + auto& jw_server_ctx{JobWorkerServerInstanceState::get()}; jw_server_ctx.kind = invoke_jw.ignore_answer ? JobWorkerServerInstanceState::Kind::NoReply : JobWorkerServerInstanceState::Kind::Regular; jw_server_ctx.state = JobWorkerServerInstanceState::State::Working; jw_server_ctx.job_id = invoke_jw.job_id; @@ -18,7 +18,7 @@ inline void init_job_server(tl::K2InvokeJobWorker &&invoke_jw) noexcept { { using namespace PhpServerSuperGlobalIndices; - auto &server{InstanceState::get().php_script_mutable_globals_singleton.get_superglobals().v$_SERVER}; + auto& server{InstanceState::get().php_script_mutable_globals_singleton.get_superglobals().v$_SERVER}; server.set_value(string{JOB_ID.data(), JOB_ID.size()}, invoke_jw.job_id); } } diff --git a/runtime-light/server/job-worker/job-worker-server-state.cpp b/runtime-light/server/job-worker/job-worker-server-state.cpp index c37d300d2b..9a2103f2dc 100644 --- a/runtime-light/server/job-worker/job-worker-server-state.cpp +++ b/runtime-light/server/job-worker/job-worker-server-state.cpp @@ -6,6 +6,4 @@ #include "runtime-light/state/instance-state.h" -JobWorkerServerInstanceState &JobWorkerServerInstanceState::get() noexcept { - return InstanceState::get().job_worker_server_instance_state; -} +JobWorkerServerInstanceState& JobWorkerServerInstanceState::get() noexcept { return InstanceState::get().job_worker_server_instance_state; } diff --git a/runtime-light/server/job-worker/job-worker-server-state.h b/runtime-light/server/job-worker/job-worker-server-state.h index f5fb822ab2..d5a8ae0e7a 100644 --- a/runtime-light/server/job-worker/job-worker-server-state.h +++ b/runtime-light/server/job-worker/job-worker-server-state.h @@ -19,5 +19,5 @@ struct JobWorkerServerInstanceState final : private vk::not_copyable { int64_t job_id{JOB_WORKER_INVALID_JOB_ID}; string body; - static JobWorkerServerInstanceState &get() noexcept; + static JobWorkerServerInstanceState& get() noexcept; }; diff --git a/runtime-light/state/component-state.h b/runtime-light/state/component-state.h index ab18612cc6..50e5375f56 100644 --- a/runtime-light/state/component-state.h +++ b/runtime-light/state/component-state.h @@ -23,22 +23,16 @@ struct ComponentState final : private vk::not_copyable { array env; ComponentState() noexcept - : allocator(INIT_COMPONENT_ALLOCATOR_SIZE, 0) - , argc(k2::args_count()) - , ini_opts(array_size{argc, false}) /* overapproximation */ - , envc(k2::env_count()) - , env(array_size{envc, false}) { + : allocator(INIT_COMPONENT_ALLOCATOR_SIZE, 0), argc(k2::args_count()), ini_opts(array_size{argc, false}) /* overapproximation */ + , + envc(k2::env_count()), env(array_size{envc, false}) { parse_env(); parse_args(); } - static const ComponentState &get() noexcept { - return *k2::component_state(); - } + static const ComponentState& get() noexcept { return *k2::component_state(); } - static ComponentState &get_mutable() noexcept { - return *const_cast(k2::component_state()); - } + static ComponentState& get_mutable() noexcept { return *const_cast(k2::component_state()); } private: static constexpr std::string_view INI_ARG_PREFIX = "ini "; diff --git a/runtime-light/state/image-state.h b/runtime-light/state/image-state.h index cedd045638..73dc4584c9 100644 --- a/runtime-light/state/image-state.h +++ b/runtime-light/state/image-state.h @@ -22,7 +22,7 @@ struct ImageState final : private vk::not_copyable { RuntimeAllocator allocator; - char *c_linear_mem{nullptr}; + char* c_linear_mem{nullptr}; uint32_t pid{}; string uname_info_s; string uname_info_n; @@ -35,9 +35,7 @@ struct ImageState final : private vk::not_copyable { StringImageState string_image_state; MathImageState math_image_state; - ImageState() noexcept - : allocator(INIT_IMAGE_ALLOCATOR_SIZE, 0) - , pid(k2::getpid()) { + ImageState() noexcept : allocator(INIT_IMAGE_ALLOCATOR_SIZE, 0), pid(k2::getpid()) { utsname uname_info{}; if (const auto err{k2::uname(std::addressof(uname_info))}; err != k2::errno_ok) [[unlikely]] { php_error("can't get uname, error '%d'", err); @@ -67,13 +65,9 @@ struct ImageState final : private vk::not_copyable { uname_info_a.set_reference_counter_to(ExtraRefCnt::for_global_const); } - static const ImageState &get() noexcept { - return *k2::image_state(); - } + static const ImageState& get() noexcept { return *k2::image_state(); } - static ImageState &get_mutable() noexcept { - return *const_cast(k2::image_state()); - } + static ImageState& get_mutable() noexcept { return *const_cast(k2::image_state()); } private: static constexpr auto INIT_IMAGE_ALLOCATOR_SIZE = static_cast(512U * 1024U); // 512KB diff --git a/runtime-light/state/init-functions.cpp b/runtime-light/state/init-functions.cpp index 152b52a555..ff1db05177 100644 --- a/runtime-light/state/init-functions.cpp +++ b/runtime-light/state/init-functions.cpp @@ -21,7 +21,7 @@ namespace { -void process_k2_invoke_http(tl::TLBuffer &tlb) noexcept { +void process_k2_invoke_http(tl::TLBuffer& tlb) noexcept { tl::K2InvokeHttp invoke_http{}; if (!invoke_http.fetch(tlb)) { php_error("erroneous http request"); @@ -29,7 +29,7 @@ void process_k2_invoke_http(tl::TLBuffer &tlb) noexcept { init_server(ServerQuery{std::move(invoke_http)}); } -void process_k2_invoke_job_worker(tl::TLBuffer &tlb) noexcept { +void process_k2_invoke_job_worker(tl::TLBuffer& tlb) noexcept { tl::K2InvokeJobWorker invoke_jw{}; if (!invoke_jw.fetch(tlb)) { php_error("erroneous job worker request"); @@ -42,7 +42,7 @@ void process_k2_invoke_job_worker(tl::TLBuffer &tlb) noexcept { task_t init_kphp_cli_component() noexcept { { // TODO superglobals init - auto &superglobals{InstanceState::get().php_script_mutable_globals_singleton.get_superglobals()}; + auto& superglobals{InstanceState::get().php_script_mutable_globals_singleton.get_superglobals()}; using namespace PhpServerSuperGlobalIndices; superglobals.v$argc = static_cast(0); superglobals.v$argv = array{}; @@ -54,8 +54,8 @@ task_t init_kphp_cli_component() noexcept { co_return co_await wait_for_incoming_stream_t{}; } -task_t finalize_kphp_cli_component(const string_buffer &output) noexcept { - auto &instance_st{InstanceState::get()}; +task_t finalize_kphp_cli_component(const string_buffer& output) noexcept { + auto& instance_st{InstanceState::get()}; if ((co_await write_all_to_stream(instance_st.standard_stream(), output.buffer(), output.size())) != output.size()) [[unlikely]] { instance_st.poll_status = k2::PollStatus::PollFinishedError; php_warning("can't write component result to stream %" PRIu64, instance_st.standard_stream()); @@ -71,27 +71,27 @@ task_t init_kphp_server_component() noexcept { k2::free(buffer); switch (const auto magic{*tlb.lookup_trivial()}) { // lookup magic - case tl::K2_INVOKE_HTTP_MAGIC: { - process_k2_invoke_http(tlb); - break; - } - case tl::K2_INVOKE_JOB_WORKER_MAGIC: { - process_k2_invoke_job_worker(tlb); - // release standard stream in case of a no reply job worker since we don't need that stream anymore - if (JobWorkerServerInstanceState::get().kind == JobWorkerServerInstanceState::Kind::NoReply) { - InstanceState::get().release_stream(stream_d); - stream_d = k2::INVALID_PLATFORM_DESCRIPTOR; - } - break; - } - default: { - php_error("unexpected magic: 0x%x", magic); + case tl::K2_INVOKE_HTTP_MAGIC: { + process_k2_invoke_http(tlb); + break; + } + case tl::K2_INVOKE_JOB_WORKER_MAGIC: { + process_k2_invoke_job_worker(tlb); + // release standard stream in case of a no reply job worker since we don't need that stream anymore + if (JobWorkerServerInstanceState::get().kind == JobWorkerServerInstanceState::Kind::NoReply) { + InstanceState::get().release_stream(stream_d); + stream_d = k2::INVALID_PLATFORM_DESCRIPTOR; } + break; + } + default: { + php_error("unexpected magic: 0x%x", magic); + } } co_return stream_d; } -task_t finalize_kphp_server_component(const string_buffer &output) noexcept { +task_t finalize_kphp_server_component(const string_buffer& output) noexcept { if (JobWorkerServerInstanceState::get().kind == JobWorkerServerInstanceState::Kind::Invalid) { co_await finalize_http_server(output); // http server case } diff --git a/runtime-light/state/init-functions.h b/runtime-light/state/init-functions.h index 879b749bcc..803d44e820 100644 --- a/runtime-light/state/init-functions.h +++ b/runtime-light/state/init-functions.h @@ -10,9 +10,9 @@ // Returns a stream descriptor that is supposed to be a stream to stdout task_t init_kphp_cli_component() noexcept; -task_t finalize_kphp_cli_component(const string_buffer &output) noexcept; +task_t finalize_kphp_cli_component(const string_buffer& output) noexcept; // Performs some initialization and returns a stream descriptor we need to write server response into task_t init_kphp_server_component() noexcept; -task_t finalize_kphp_server_component(const string_buffer &output) noexcept; +task_t finalize_kphp_server_component(const string_buffer& output) noexcept; diff --git a/runtime-light/state/instance-state.cpp b/runtime-light/state/instance-state.cpp index d79defaece..23e80dd7ec 100644 --- a/runtime-light/state/instance-state.cpp +++ b/runtime-light/state/instance-state.cpp @@ -24,8 +24,8 @@ namespace { int32_t merge_output_buffers() noexcept { - auto &instance_st{InstanceState::get()}; - Response &response{instance_st.response}; + auto& instance_st{InstanceState::get()}; + Response& response{instance_st.response}; php_assert(response.current_buffer >= 0); int32_t ob_first_not_empty{}; @@ -46,7 +46,7 @@ void InstanceState::init_script_execution() noexcept { scheduler.suspend(std::make_pair(main_task_.get_handle(), WaitEvent::Rechedule{})); } -template +template task_t InstanceState::run_instance_prologue() noexcept { static_assert(kind != ImageKind::Invalid); image_kind_ = kind; @@ -55,7 +55,7 @@ task_t InstanceState::run_instance_prologue() noexcept { { const auto time_mcs{f$_microtime_float()}; - auto &superglobals{php_script_mutable_globals_singleton.get_superglobals()}; + auto& superglobals{php_script_mutable_globals_singleton.get_superglobals()}; superglobals.v$_ENV = ComponentState::get().env; using namespace PhpServerSuperGlobalIndices; @@ -79,7 +79,7 @@ template task_t InstanceState::run_instance_prologue task_t InstanceState::run_instance_epilogue() noexcept { if (std::exchange(shutdown_state_, shutdown_state::in_progress) == shutdown_state::not_started) [[likely]] { - for (auto &sf : shutdown_functions) { + for (auto& sf : shutdown_functions) { co_await sf; } } @@ -90,22 +90,22 @@ task_t InstanceState::run_instance_epilogue() noexcept { } switch (image_kind_) { - case ImageKind::Oneshot: - case ImageKind::Multishot: - break; - case ImageKind::CLI: { - const auto &buffer{response.output_buffers[merge_output_buffers()]}; - co_await finalize_kphp_cli_component(buffer); - break; - } - case ImageKind::Server: { - const auto &buffer{response.output_buffers[merge_output_buffers()]}; - co_await finalize_kphp_server_component(buffer); - break; - } - default: { - php_error("unexpected ImageKind"); - } + case ImageKind::Oneshot: + case ImageKind::Multishot: + break; + case ImageKind::CLI: { + const auto& buffer{response.output_buffers[merge_output_buffers()]}; + co_await finalize_kphp_cli_component(buffer); + break; + } + case ImageKind::Server: { + const auto& buffer{response.output_buffers[merge_output_buffers()]}; + co_await finalize_kphp_server_component(buffer); + break; + } + default: { + php_error("unexpected ImageKind"); + } } release_all_streams(); shutdown_state_ = shutdown_state::finished; @@ -126,17 +126,17 @@ void InstanceState::process_platform_updates() noexcept { if (opened_streams_.contains(stream_d)) { // update on opened stream php_debug("took update on stream %" PRIu64, stream_d); switch (scheduler.schedule(ScheduleEvent::UpdateOnStream{.stream_d = stream_d})) { - case ScheduleStatus::Resumed: { // scheduler's resumed a coroutine waiting for update - break; - } - case ScheduleStatus::Skipped: { // no one is waiting for the event yet, so just save it - pending_updates_.insert(stream_d); - break; - } - case ScheduleStatus::Error: { // something bad's happened, stop execution - poll_status = k2::PollStatus::PollFinishedError; - return; - } + case ScheduleStatus::Resumed: { // scheduler's resumed a coroutine waiting for update + break; + } + case ScheduleStatus::Skipped: { // no one is waiting for the event yet, so just save it + pending_updates_.insert(stream_d); + break; + } + case ScheduleStatus::Error: { // something bad's happened, stop execution + poll_status = k2::PollStatus::PollFinishedError; + return; + } } } else { // update on incoming stream php_debug("got new incoming stream %" PRIu64, stream_d); @@ -149,17 +149,17 @@ void InstanceState::process_platform_updates() noexcept { } } else { // we'are out of updates so let the scheduler do whatever it wants switch (scheduler.schedule(ScheduleEvent::NoEvent{})) { - case ScheduleStatus::Resumed: { // scheduler's resumed some coroutine, so let's continue scheduling - break; - } - case ScheduleStatus::Skipped: { // scheduler's done nothing, so it's either scheduled all coroutines or is waiting for events - poll_status = scheduler.done() ? k2::PollStatus::PollFinishedOk : k2::PollStatus::PollBlocked; - return; - } - case ScheduleStatus::Error: { // something bad's happened, stop execution - poll_status = k2::PollStatus::PollFinishedError; - return; - } + case ScheduleStatus::Resumed: { // scheduler's resumed some coroutine, so let's continue scheduling + break; + } + case ScheduleStatus::Skipped: { // scheduler's done nothing, so it's either scheduled all coroutines or is waiting for events + poll_status = scheduler.done() ? k2::PollStatus::PollFinishedOk : k2::PollStatus::PollBlocked; + return; + } + case ScheduleStatus::Error: { // something bad's happened, stop execution + poll_status = k2::PollStatus::PollFinishedError; + return; + } } } } @@ -182,18 +182,18 @@ std::pair InstanceState::open_stream(std::string_view compone uint64_t stream_d{}; int32_t error_code{}; switch (stream_kind) { - case k2::StreamKind::Component: - error_code = k2::open(std::addressof(stream_d), component_name.size(), component_name.data()); - break; - case k2::StreamKind::TCP: - error_code = k2::tcp_connect(std::addressof(stream_d), component_name.data(), component_name.size()); - break; - case k2::StreamKind::UDP: - error_code = k2::udp_connect(std::addressof(stream_d), component_name.data(), component_name.size()); - break; - default: - error_code = k2::errno_einval; - break; + case k2::StreamKind::Component: + error_code = k2::open(std::addressof(stream_d), component_name.size(), component_name.data()); + break; + case k2::StreamKind::TCP: + error_code = k2::tcp_connect(std::addressof(stream_d), component_name.data(), component_name.size()); + break; + case k2::StreamKind::UDP: + error_code = k2::udp_connect(std::addressof(stream_d), component_name.data(), component_name.size()); + break; + default: + error_code = k2::errno_einval; + break; } if (error_code == k2::errno_ok) [[likely]] { diff --git a/runtime-light/state/instance-state.h b/runtime-light/state/instance-state.h index 271e276811..0f889baeea 100644 --- a/runtime-light/state/instance-state.h +++ b/runtime-light/state/instance-state.h @@ -25,8 +25,8 @@ #include "runtime-light/stdlib/file/file-system-state.h" #include "runtime-light/stdlib/fork/fork-state.h" #include "runtime-light/stdlib/job-worker/job-worker-client-state.h" -#include "runtime-light/stdlib/math/random-state.h" #include "runtime-light/stdlib/math/math-state.h" +#include "runtime-light/stdlib/math/random-state.h" #include "runtime-light/stdlib/output/output-buffer.h" #include "runtime-light/stdlib/rpc/rpc-state.h" #include "runtime-light/stdlib/serialization/serialization-state.h" @@ -48,59 +48,43 @@ static_assert(CoroutineSchedulerConcept); enum class ImageKind : uint8_t { Invalid, CLI, Server, Oneshot, Multishot }; struct InstanceState final : vk::not_copyable { - template + template using unordered_set = memory_resource::stl::unordered_set; - template + template using deque = memory_resource::stl::deque; - template + template using list = memory_resource::stl::list; InstanceState() noexcept - : allocator(INIT_INSTANCE_ALLOCATOR_SIZE, 0) - , scheduler(allocator.memory_resource) - , fork_instance_state(allocator.memory_resource) - , php_script_mutable_globals_singleton(allocator.memory_resource) - , rpc_instance_state(allocator.memory_resource) - , http_server_instance_state(allocator.memory_resource) - , regex_instance_state(allocator.memory_resource) - , shutdown_functions(decltype(shutdown_functions)::allocator_type{allocator.memory_resource}) - , incoming_streams_(decltype(incoming_streams_)::allocator_type{allocator.memory_resource}) - , opened_streams_(decltype(opened_streams_)::allocator_type{allocator.memory_resource}) - , pending_updates_(decltype(pending_updates_)::allocator_type{allocator.memory_resource}) {} + : allocator(INIT_INSTANCE_ALLOCATOR_SIZE, 0), scheduler(allocator.memory_resource), fork_instance_state(allocator.memory_resource), + php_script_mutable_globals_singleton(allocator.memory_resource), rpc_instance_state(allocator.memory_resource), + http_server_instance_state(allocator.memory_resource), regex_instance_state(allocator.memory_resource), + shutdown_functions(decltype(shutdown_functions)::allocator_type{allocator.memory_resource}), + incoming_streams_(decltype(incoming_streams_)::allocator_type{allocator.memory_resource}), + opened_streams_(decltype(opened_streams_)::allocator_type{allocator.memory_resource}), + pending_updates_(decltype(pending_updates_)::allocator_type{allocator.memory_resource}) {} ~InstanceState() = default; - static InstanceState &get() noexcept { - return *k2::instance_state(); - } + static InstanceState& get() noexcept { return *k2::instance_state(); } void init_script_execution() noexcept; - template + template task_t run_instance_prologue() noexcept; task_t run_instance_epilogue() noexcept; - ImageKind image_kind() const noexcept { - return image_kind_; - } + ImageKind image_kind() const noexcept { return image_kind_; } void process_platform_updates() noexcept; - bool stream_updated(uint64_t stream_d) const noexcept { - return pending_updates_.contains(stream_d); - } - const unordered_set &opened_streams() const noexcept { - return opened_streams_; - } - const deque &incoming_streams() const noexcept { - return incoming_streams_; - } - uint64_t standard_stream() const noexcept { - return standard_stream_; - } + bool stream_updated(uint64_t stream_d) const noexcept { return pending_updates_.contains(stream_d); } + const unordered_set& opened_streams() const noexcept { return opened_streams_; } + const deque& incoming_streams() const noexcept { return incoming_streams_; } + uint64_t standard_stream() const noexcept { return standard_stream_; } uint64_t take_incoming_stream() noexcept; std::pair open_stream(std::string_view, k2::StreamKind) noexcept; diff --git a/runtime-light/stdlib/array/array-functions.h b/runtime-light/stdlib/array/array-functions.h index 429e081bc0..3deea6f268 100644 --- a/runtime-light/stdlib/array/array-functions.h +++ b/runtime-light/stdlib/array/array-functions.h @@ -15,17 +15,17 @@ namespace array_functions_impl_ { -template +template concept convertible_to_php_bool = requires(T t) { { f$boolval(t) } -> std::convertible_to; }; -template -requires(std::invocable::const_iterator> - &&convertible_to_php_bool::const_iterator>>) - task_t> array_filter_impl(const array &a, Pred &&pred) noexcept { +template +requires(std::invocable::const_iterator> && + convertible_to_php_bool::const_iterator>>) +task_t> array_filter_impl(const array& a, Pred&& pred) noexcept { array result{a.size()}; - for (const auto &it : a) { + for (const auto& it : a) { bool condition{false}; if constexpr (is_async_function_v::const_iterator>) { condition = f$boolval(co_await std::invoke(std::forward(pred), it)); @@ -41,15 +41,15 @@ requires(std::invocable::const_iterator> } // namespace array_functions_impl_ -template -void f$shuffle(array &arr) noexcept { +template +void f$shuffle(array& arr) noexcept { const auto arr_size{arr.count()}; if (arr_size <= 1) [[unlikely]] { return; } array shuffled{array_size(arr_size, true)}; - for (const auto &it : arr) { + for (const auto& it : arr) { shuffled.push_back(it.get_value()); } for (int64_t i = 1; i < arr_size; i++) { @@ -59,32 +59,33 @@ void f$shuffle(array &arr) noexcept { arr = std::move(shuffled); } -template -task_t> f$array_filter(const array &a) noexcept { - co_return co_await array_functions_impl_::array_filter_impl(a, [](const auto &it) noexcept { return it.get_value(); }); +template +task_t> f$array_filter(const array& a) noexcept { + co_return co_await array_functions_impl_::array_filter_impl(a, [](const auto& it) noexcept { return it.get_value(); }); } -template -requires(std::invocable) task_t> f$array_filter(const array &a, Pred &&pred) noexcept { +template +requires(std::invocable) +task_t> f$array_filter(const array& a, Pred&& pred) noexcept { if constexpr (is_async_function_v) { - co_return co_await array_functions_impl_::array_filter_impl(a, [&pred](const auto &it) noexcept -> task_t { - co_return co_await std::invoke(std::forward(pred), it.get_value()); - }); + co_return co_await array_functions_impl_::array_filter_impl( + a, [&pred](const auto& it) noexcept -> task_t { co_return co_await std::invoke(std::forward(pred), it.get_value()); }); } else { - co_return co_await array_functions_impl_::array_filter_impl(a, [&pred](const auto &it) noexcept { return std::invoke(std::forward(pred), it.get_value()); }); + co_return co_await array_functions_impl_::array_filter_impl( + a, [&pred](const auto& it) noexcept { return std::invoke(std::forward(pred), it.get_value()); }); } } -template -typename array::key_type f$array_rand(const array &a) noexcept { +template +typename array::key_type f$array_rand(const array& a) noexcept { if (int64_t size{a.count()}) { return a.middle(f$mt_rand(0, size - 1)).get_key(); } return {}; } -template -mixed f$array_rand(const array &a, int64_t num) noexcept { +template +mixed f$array_rand(const array& a, int64_t num) noexcept { if (num == 1) { return f$array_rand(a); } @@ -97,7 +98,7 @@ mixed f$array_rand(const array &a, int64_t num) noexcept { } array::key_type> result(array_size(num, true)); - for (const auto &it : a) { + for (const auto& it : a) { if (f$mt_rand(0, --size) < num) { result.push_back(it.get_key()); --num; @@ -107,28 +108,28 @@ mixed f$array_rand(const array &a, int64_t num) noexcept { return result; } -template -array f$array_splice(array &a, int64_t offset, int64_t length, const array &) { +template +array f$array_splice(array& a, int64_t offset, int64_t length, const array&) { php_critical_error("call to unsupported function"); } -template -array f$array_splice(array &a, int64_t offset, int64_t length = std::numeric_limits::max(), const array &replacement = array()) { +template +array f$array_splice(array& a, int64_t offset, int64_t length = std::numeric_limits::max(), const array& replacement = array()) { php_critical_error("call to unsupported function"); } -template -ReturnT f$array_pad(const array &a, int64_t size, const DefaultValueT &default_value) { +template +ReturnT f$array_pad(const array& a, int64_t size, const DefaultValueT& default_value) { php_critical_error("call to unsupported function"); } -template -ReturnT f$array_pad(const array &a, int64_t size, const DefaultValueT &default_value) { +template +ReturnT f$array_pad(const array& a, int64_t size, const DefaultValueT& default_value) { php_critical_error("call to unsupported function"); } -template -array f$array_filter_by_key(const array &a, const T1 &callback) noexcept { +template +array f$array_filter_by_key(const array& a, const T1& callback) noexcept { php_critical_error("call to unsupported function"); } @@ -137,10 +138,10 @@ array f$array_filter_by_key(const array &a, const T1 &callback) noexcept { * we need to be careful with such functions. We may want to split such functions into sync and async * versions in case we face with performance problems. */ -template F, class R = async_function_unwrapped_return_type_t> +template F, class R = async_function_unwrapped_return_type_t> task_t> f$array_map(F f, array arr) noexcept { array result{arr.size()}; - for (const auto &it : arr) { + for (const auto& it : arr) { if constexpr (is_async_function_v) { result.set_value(it.get_key(), co_await std::invoke(f, it.get_value())); } else { @@ -150,163 +151,163 @@ task_t> f$array_map(F f, array arr) noexcept { co_return result; } -template -R f$array_reduce(const array &a, const CallbackT &callback, InitialT initial) { +template +R f$array_reduce(const array& a, const CallbackT& callback, InitialT initial) { php_critical_error("call to unsupported function"); } -template -T f$array_merge_spread(const T &a1) { +template +T f$array_merge_spread(const T& a1) { php_critical_error("call to unsupported function"); } -template -T f$array_merge_spread(const T &a1, const T &a2) { +template +T f$array_merge_spread(const T& a1, const T& a2) { php_critical_error("call to unsupported function"); } -template -T f$array_merge_spread(const T &a1, const T &a2, const T &a3, const T &a4 = T(), const T &a5 = T(), const T &a6 = T(), const T &a7 = T(), const T &a8 = T(), - const T &a9 = T(), const T &a10 = T(), const T &a11 = T(), const T &a12 = T()) { +template +T f$array_merge_spread(const T& a1, const T& a2, const T& a3, const T& a4 = T(), const T& a5 = T(), const T& a6 = T(), const T& a7 = T(), const T& a8 = T(), + const T& a9 = T(), const T& a10 = T(), const T& a11 = T(), const T& a12 = T()) { php_critical_error("call to unsupported function"); } -template -ReturnT f$array_merge_recursive(const Args &...args) { +template +ReturnT f$array_merge_recursive(const Args&... args) { php_critical_error("call to unsupported function"); } -template -array f$array_intersect_assoc(const array &a1, const array &a2) { +template +array f$array_intersect_assoc(const array& a1, const array& a2) { php_critical_error("call to unsupported function"); } -template -array f$array_intersect_assoc(const array &a1, const array &a2, const array &a3) { +template +array f$array_intersect_assoc(const array& a1, const array& a2, const array& a3) { php_critical_error("call to unsupported function"); } -template -array f$array_diff_key(const array &a1, const array &a2) { +template +array f$array_diff_key(const array& a1, const array& a2) { php_critical_error("call to unsupported function"); } -template -array f$array_diff_assoc(const array &a1, const array &a2) { +template +array f$array_diff_assoc(const array& a1, const array& a2) { php_critical_error("call to unsupported function"); } -template -array f$array_diff_assoc(const array &a1, const array &a2, const array &a3) { +template +array f$array_diff_assoc(const array& a1, const array& a2, const array& a3) { php_critical_error("call to unsupported function"); } -template -array f$array_count_values(const array &a) { +template +array f$array_count_values(const array& a) { php_critical_error("call to unsupported function"); } -template -array f$array_fill(int64_t start_index, int64_t num, const T &value) { +template +array f$array_fill(int64_t start_index, int64_t num, const T& value) { php_critical_error("call to unsupported function"); } -template -array f$array_fill_keys(const array &keys, const T &value) { +template +array f$array_fill_keys(const array& keys, const T& value) { php_critical_error("call to unsupported function"); } -template -array f$array_combine(const array &keys, const array &values) { +template +array f$array_combine(const array& keys, const array& values) { php_critical_error("call to unsupported function"); } -template -void f$usort(array &a, const T1 &compare) { +template +void f$usort(array& a, const T1& compare) { php_critical_error("call to unsupported function"); } -template -void f$uasort(array &a, const T1 &compare) { +template +void f$uasort(array& a, const T1& compare) { php_critical_error("call to unsupported function"); } -template -void f$uksort(array &a, const T1 &compare) { +template +void f$uksort(array& a, const T1& compare) { php_critical_error("call to unsupported function"); } -template -mixed f$getKeyByPos(const array &a, int64_t pos) { +template +mixed f$getKeyByPos(const array& a, int64_t pos) { php_critical_error("call to unsupported function"); } -template -T f$getValueByPos(const array &a, int64_t pos) { +template +T f$getValueByPos(const array& a, int64_t pos) { php_critical_error("call to unsupported function"); } -template -array f$create_vector(int64_t n, const T &default_value) { +template +array f$create_vector(int64_t n, const T& default_value) { php_critical_error("call to unsupported function"); } -template -mixed f$array_first_key(const array &a) { +template +mixed f$array_first_key(const array& a) { php_critical_error("call to unsupported function"); } -template -void f$array_swap_int_keys(array &a, int64_t idx1, int64_t idx2) noexcept { +template +void f$array_swap_int_keys(array& a, int64_t idx1, int64_t idx2) noexcept { php_critical_error("call to unsupported function"); } -template -Optional>> f$array_column(const array>> &a, const mixed &column_key) { +template +Optional>> f$array_column(const array>>& a, const mixed& column_key) { php_critical_error("call to unsupported function"); } -template -Optional>> f$array_column(const array>>> &a, const mixed &column_key) { +template +Optional>> f$array_column(const array>>>& a, const mixed& column_key) { php_critical_error("call to unsupported function"); } -template -Optional> f$array_column(const array> &a, const mixed &column_key, const mixed &index_key = {}) { +template +Optional> f$array_column(const array>& a, const mixed& column_key, const mixed& index_key = {}) { php_critical_error("call to unsupported function"); } -template -Optional> f$array_column(const array>> &a, const mixed &column_key, const mixed &index_key = {}) { +template +Optional> f$array_column(const array>>& a, const mixed& column_key, const mixed& index_key = {}) { php_critical_error("call to unsupported function"); } -inline Optional> f$array_column(const array &a, const mixed &column_key, const mixed &index_key = {}) { +inline Optional> f$array_column(const array& a, const mixed& column_key, const mixed& index_key = {}) { php_critical_error("call to unsupported function"); } -template -auto f$array_column(const Optional &a, const mixed &column_key, const mixed &index_key = {}) - -> decltype(f$array_column(std::declval(), column_key, index_key)) { +template +auto f$array_column(const Optional& a, const mixed& column_key, + const mixed& index_key = {}) -> decltype(f$array_column(std::declval(), column_key, index_key)) { php_critical_error("call to unsupported function"); } -template -mixed f$array_key_first(const array &a) { +template +mixed f$array_key_first(const array& a) { php_critical_error("call to unsupported function"); } -template -mixed f$array_key_last(const array &a) { +template +mixed f$array_key_last(const array& a) { php_critical_error("call to unsupported function"); } -template -std::tuple::key_type, T> f$array_find(const array &a, const T1 &callback) { +template +std::tuple::key_type, T> f$array_find(const array& a, const T1& callback) { php_critical_error("call to unsupported function"); } -template -T f$vk_dot_product(const array &a, const array &b) { +template +T f$vk_dot_product(const array& a, const array& b) { php_critical_error("call to unsupported function"); } diff --git a/runtime-light/stdlib/component/component-api.h b/runtime-light/stdlib/component/component-api.h index 4ab4c941b6..f85e00ba5a 100644 --- a/runtime-light/stdlib/component/component-api.h +++ b/runtime-light/stdlib/component/component-api.h @@ -19,25 +19,19 @@ struct C$ComponentQuery final : public refcountable_php_classes { uint64_t stream_d{k2::INVALID_PLATFORM_DESCRIPTOR}; - explicit constexpr C$ComponentQuery(uint64_t stream_d_) noexcept - : stream_d(stream_d_) {} - constexpr C$ComponentQuery(C$ComponentQuery &&other) noexcept - : stream_d(std::exchange(other.stream_d, k2::INVALID_PLATFORM_DESCRIPTOR)) {}; + explicit constexpr C$ComponentQuery(uint64_t stream_d_) noexcept : stream_d(stream_d_) {} + constexpr C$ComponentQuery(C$ComponentQuery&& other) noexcept : stream_d(std::exchange(other.stream_d, k2::INVALID_PLATFORM_DESCRIPTOR)) {}; - C$ComponentQuery(const C$ComponentQuery &) = delete; - C$ComponentQuery &operator=(const C$ComponentQuery &) = delete; - C$ComponentQuery &operator=(C$ComponentQuery &&other) = delete; + C$ComponentQuery(const C$ComponentQuery&) = delete; + C$ComponentQuery& operator=(const C$ComponentQuery&) = delete; + C$ComponentQuery& operator=(C$ComponentQuery&& other) = delete; - constexpr const char *get_class() const noexcept { - return "ComponentQuery"; - } + constexpr const char* get_class() const noexcept { return "ComponentQuery"; } - constexpr int32_t get_hash() const noexcept { - return static_cast(std::hash{}(get_class())); - } + constexpr int32_t get_hash() const noexcept { return static_cast(std::hash{}(get_class())); } ~C$ComponentQuery() { - auto &instance_st{InstanceState::get()}; + auto& instance_st{InstanceState::get()}; if (instance_st.opened_streams().contains(stream_d)) { instance_st.release_stream(stream_d); } diff --git a/runtime-light/stdlib/confdata/confdata-functions.cpp b/runtime-light/stdlib/confdata/confdata-functions.cpp index afc89464ad..4868c2c1cf 100644 --- a/runtime-light/stdlib/confdata/confdata-functions.cpp +++ b/runtime-light/stdlib/confdata/confdata-functions.cpp @@ -25,7 +25,7 @@ namespace { constexpr std::string_view CONFDATA_COMPONENT_NAME = "confdata"; // TODO: it may actually have an alias specified in linking config -mixed extract_confdata_value(tl::confdataValue &&confdata_value) noexcept { +mixed extract_confdata_value(tl::confdataValue&& confdata_value) noexcept { if (confdata_value.is_php_serialized && confdata_value.is_json_serialized) { // check that we don't have both flags set php_warning("confdata value has both php_serialized and json_serialized flags set"); return {}; @@ -43,7 +43,7 @@ mixed extract_confdata_value(tl::confdataValue &&confdata_value) noexcept { // TODO: the performance of this implementation can be enhanced. rework it when the platform has specific API for that bool f$is_confdata_loaded() noexcept { - auto &instance_st{InstanceState::get()}; + auto& instance_st{InstanceState::get()}; if (const auto [stream_d, errc]{instance_st.open_stream(CONFDATA_COMPONENT_NAME, k2::StreamKind::Component)}; errc == k2::errno_ok) { instance_st.release_stream(stream_d); return true; @@ -91,6 +91,6 @@ task_t> f$confdata_get_values_by_any_wildcard(string wildcard) noex array result{array_size{static_cast(dict_confdata_value.size()), false}}; std::for_each(dict_confdata_value.begin(), dict_confdata_value.end(), - [&result](auto &&dict_field) { result.set_value(std::move(dict_field.key), extract_confdata_value(std::move(dict_field.value))); }); + [&result](auto&& dict_field) { result.set_value(std::move(dict_field.key), extract_confdata_value(std::move(dict_field.value))); }); co_return std::move(result); } diff --git a/runtime-light/stdlib/confdata/confdata-functions.h b/runtime-light/stdlib/confdata/confdata-functions.h index c8cc97f938..2d2f5ac06a 100644 --- a/runtime-light/stdlib/confdata/confdata-functions.h +++ b/runtime-light/stdlib/confdata/confdata-functions.h @@ -16,5 +16,5 @@ task_t> f$confdata_get_values_by_any_wildcard(string wildcard) noex inline task_t> f$confdata_get_values_by_predefined_wildcard(string wildcard) noexcept { php_warning("K2 confdata does not support predefined wildcard optimization"); - co_return(co_await f$confdata_get_values_by_any_wildcard(std::move(wildcard))); + co_return (co_await f$confdata_get_values_by_any_wildcard(std::move(wildcard))); } diff --git a/runtime-light/stdlib/crypto/crypto-functions.cpp b/runtime-light/stdlib/crypto/crypto-functions.cpp index 7949e82ac0..70d96fbe90 100644 --- a/runtime-light/stdlib/crypto/crypto-functions.cpp +++ b/runtime-light/stdlib/crypto/crypto-functions.cpp @@ -15,7 +15,7 @@ namespace { -constexpr const char *CRYPTO_COMPONENT_NAME = "crypto"; +constexpr const char* CRYPTO_COMPONENT_NAME = "crypto"; } // namespace @@ -46,7 +46,7 @@ task_t> f$openssl_random_pseudo_bytes(int64_t length) noexcept co_return string(str_view.data(), str_view.size()); } -task_t>> f$openssl_x509_parse(const string &data, bool shortnames) noexcept { +task_t>> f$openssl_x509_parse(const string& data, bool shortnames) noexcept { tl::GetPemCertInfo request{.is_short = shortnames, .bytes = data}; tl::TLBuffer buffer; @@ -66,7 +66,7 @@ task_t>> f$openssl_x509_parse(const string &data, bool sho co_return response.data; } -task_t f$openssl_sign(const string &data, string &signature, const string &private_key, int64_t algo) noexcept { +task_t f$openssl_sign(const string& data, string& signature, const string& private_key, int64_t algo) noexcept { tl::DigestSign request{.data = data, .private_key = private_key, .algorithm = static_cast(algo)}; tl::TLBuffer buffer; @@ -89,7 +89,7 @@ task_t f$openssl_sign(const string &data, string &signature, const string co_return true; } -task_t f$openssl_verify(const string &data, const string &signature, const string &pub_key, int64_t algo) noexcept { +task_t f$openssl_verify(const string& data, const string& signature, const string& pub_key, int64_t algo) noexcept { tl::DigestVerify request{.data = data, .public_key = pub_key, .algorithm = static_cast(algo), .signature = signature}; tl::TLBuffer buffer; @@ -116,7 +116,7 @@ namespace { constexpr std::string_view AES_128_CBC = "aes-128-cbc"; constexpr std::string_view AES_256_CBC = "aes-256-cbc"; -std::optional parse_algorithm(const string &method) noexcept { +std::optional parse_algorithm(const string& method) noexcept { using namespace std::string_view_literals; std::string_view method_sv{method.c_str(), method.size()}; @@ -141,22 +141,22 @@ int64_t algorithm_iv_len([[maybe_unused]] tl::CipherAlgorithm algorithm) noexcep int64_t algorithm_key_len(tl::CipherAlgorithm algorithm) noexcept { switch (algorithm) { - case tl::CipherAlgorithm::AES128: { - return AES_128_KEY_LEN; - } - case tl::CipherAlgorithm::AES256: { - return AES_256_KEY_LEN; - } - default: { - php_warning("unexpected cipher algorithm"); - return 0; - } + case tl::CipherAlgorithm::AES128: { + return AES_128_KEY_LEN; + } + case tl::CipherAlgorithm::AES256: { + return AES_256_KEY_LEN; + } + default: { + php_warning("unexpected cipher algorithm"); + return 0; + } } } enum class cipher_opts : int64_t { OPENSSL_RAW_DATA = 1, OPENSSL_ZERO_PADDING = 2, OPENSSL_DONT_ZERO_PAD_KEY = 4 }; -Optional> algorithm_pad_key_iv(tl::CipherAlgorithm algorithm, const string &source_key, const string &source_iv, +Optional> algorithm_pad_key_iv(tl::CipherAlgorithm algorithm, const string& source_key, const string& source_iv, int64_t options) noexcept { const size_t iv_required_len = algorithm_iv_len(algorithm); const size_t key_required_len = algorithm_key_len(algorithm); @@ -193,11 +193,11 @@ Optional> algorithm_pad_key_iv(tl::CipherAlgorithm alg array f$openssl_get_cipher_methods([[maybe_unused]] bool aliases) noexcept { array return_value{ - {std::make_pair(0, string{AES_128_CBC.data(), AES_128_CBC.size()}), std::make_pair(1, string{AES_256_CBC.data(), AES_256_CBC.size()})}}; + {std::make_pair(0, string{AES_128_CBC.data(), AES_128_CBC.size()}), std::make_pair(1, string{AES_256_CBC.data(), AES_256_CBC.size()})}}; return return_value; } -Optional f$openssl_cipher_iv_length(const string &method) noexcept { +Optional f$openssl_cipher_iv_length(const string& method) noexcept { auto algorithm = parse_algorithm(method); if (!algorithm.has_value()) { php_warning("Unknown cipher algorithm"); @@ -206,8 +206,8 @@ Optional f$openssl_cipher_iv_length(const string &method) noexcept { return algorithm_iv_len(*algorithm); } -task_t> f$openssl_encrypt(const string &data, const string &method, const string &source_key, int64_t options, const string &source_iv, - string &tag, const string &aad, int64_t tag_length __attribute__((unused))) noexcept { +task_t> f$openssl_encrypt(const string& data, const string& method, const string& source_key, int64_t options, const string& source_iv, + string& tag, const string& aad, int64_t tag_length __attribute__((unused))) noexcept { auto algorithm = parse_algorithm(method); if (!algorithm.has_value()) { php_warning("Unknown cipher algorithm"); @@ -248,11 +248,11 @@ task_t> f$openssl_encrypt(const string &data, const string &met if (!response.fetch(buffer)) { co_return false; } - co_return(options & static_cast(cipher_opts::OPENSSL_RAW_DATA)) ? std::move(response.value) : f$base64_encode(response.value); + co_return (options & static_cast(cipher_opts::OPENSSL_RAW_DATA)) ? std::move(response.value) : f$base64_encode(response.value); } -task_t> f$openssl_decrypt(string data, const string &method, const string &source_key, int64_t options, const string &source_iv, string tag, - const string &aad) noexcept { +task_t> f$openssl_decrypt(string data, const string& method, const string& source_key, int64_t options, const string& source_iv, string tag, + const string& aad) noexcept { if (!(options & static_cast(cipher_opts::OPENSSL_RAW_DATA))) { Optional decoding_data = f$base64_decode(data, true); if (!decoding_data.has_value()) { diff --git a/runtime-light/stdlib/crypto/crypto-functions.h b/runtime-light/stdlib/crypto/crypto-functions.h index 964010bf96..9345c78ec7 100644 --- a/runtime-light/stdlib/crypto/crypto-functions.h +++ b/runtime-light/stdlib/crypto/crypto-functions.h @@ -13,12 +13,12 @@ #include "runtime-light/stdlib/string/string-state.h" #include "runtime-light/tl/tl-types.h" -inline string f$md5(const string &str, bool binary = false) noexcept { +inline string f$md5(const string& str, bool binary = false) noexcept { constexpr auto MD5_HASH_LEN = 16; string output{static_cast(MD5_HASH_LEN * (binary ? 1 : 2)), false}; - md5(reinterpret_cast(str.c_str()), static_cast(str.size()), reinterpret_cast(output.buffer())); + md5(reinterpret_cast(str.c_str()), static_cast(str.size()), reinterpret_cast(output.buffer())); if (!binary) { - const auto &lhex_digits{StringImageState::get().lhex_digits}; + const auto& lhex_digits{StringImageState::get().lhex_digits}; for (int64_t i = MD5_HASH_LEN - 1; i >= 0; --i) { output[2 * i + 1] = lhex_digits[output[i] & 0x0F]; output[2 * i] = lhex_digits[(output[i] >> 4) & 0x0F]; @@ -29,18 +29,18 @@ inline string f$md5(const string &str, bool binary = false) noexcept { task_t> f$openssl_random_pseudo_bytes(int64_t length) noexcept; -task_t>> f$openssl_x509_parse(const string &data, bool shortnames = true) noexcept; +task_t>> f$openssl_x509_parse(const string& data, bool shortnames = true) noexcept; -task_t f$openssl_sign(const string &data, string &signature, const string &private_key, int64_t algo = tl::DigestAlgorithm::SHA1) noexcept; +task_t f$openssl_sign(const string& data, string& signature, const string& private_key, int64_t algo = tl::DigestAlgorithm::SHA1) noexcept; -task_t f$openssl_verify(const string &data, const string &signature, const string &pub_key_id, int64_t algo = tl::DigestAlgorithm::SHA1) noexcept; +task_t f$openssl_verify(const string& data, const string& signature, const string& pub_key_id, int64_t algo = tl::DigestAlgorithm::SHA1) noexcept; array f$openssl_get_cipher_methods(bool aliases = false) noexcept; -Optional f$openssl_cipher_iv_length(const string &method) noexcept; +Optional f$openssl_cipher_iv_length(const string& method) noexcept; -task_t> f$openssl_encrypt(const string &data, const string &method, const string &key, int64_t options = 0, const string &iv = string{}, - string &tag = CryptoInstanceState::get().default_tag_dummy, const string &aad = string{}, +task_t> f$openssl_encrypt(const string& data, const string& method, const string& key, int64_t options = 0, const string& iv = string{}, + string& tag = CryptoInstanceState::get().default_tag_dummy, const string& aad = string{}, int64_t tag_length = 16) noexcept; -task_t> f$openssl_decrypt(string data, const string &method, const string &key, int64_t options = 0, const string &iv = string{}, - string tag = string{}, const string &aad = string{}) noexcept; +task_t> f$openssl_decrypt(string data, const string& method, const string& key, int64_t options = 0, const string& iv = string{}, + string tag = string{}, const string& aad = string{}) noexcept; diff --git a/runtime-light/stdlib/crypto/crypto-state.cpp b/runtime-light/stdlib/crypto/crypto-state.cpp index d4ba710427..4088a99c3c 100644 --- a/runtime-light/stdlib/crypto/crypto-state.cpp +++ b/runtime-light/stdlib/crypto/crypto-state.cpp @@ -6,6 +6,4 @@ #include "runtime-light/state/instance-state.h" -CryptoInstanceState &CryptoInstanceState::get() noexcept { - return InstanceState::get().crypto_instance_state; -} +CryptoInstanceState& CryptoInstanceState::get() noexcept { return InstanceState::get().crypto_instance_state; } diff --git a/runtime-light/stdlib/crypto/crypto-state.h b/runtime-light/stdlib/crypto/crypto-state.h index de33388b3e..4ea1c996b5 100644 --- a/runtime-light/stdlib/crypto/crypto-state.h +++ b/runtime-light/stdlib/crypto/crypto-state.h @@ -9,5 +9,5 @@ struct CryptoInstanceState final : private vk::not_copyable { string default_tag_dummy; - static CryptoInstanceState &get() noexcept; + static CryptoInstanceState& get() noexcept; }; diff --git a/runtime-light/stdlib/curl/curl-functions.h b/runtime-light/stdlib/curl/curl-functions.h index 40afac0721..889004a4e3 100644 --- a/runtime-light/stdlib/curl/curl-functions.h +++ b/runtime-light/stdlib/curl/curl-functions.h @@ -9,10 +9,8 @@ #include "runtime-common/core/runtime-core.h" #include "runtime-light/stdlib/curl/curl-state.h" -inline Optional> f$curl_multi_info_read(int64_t, int64_t & = CurlInstanceState::get().curl_multi_info_read_msgs_in_queue_stub) { +inline Optional> f$curl_multi_info_read(int64_t, int64_t& = CurlInstanceState::get().curl_multi_info_read_msgs_in_queue_stub) { php_critical_error("call to unsupported function : curl_multi_info_read"); } -inline bool f$curl_setopt_array(int64_t, const array &) noexcept { - php_critical_error("call to unsupported function : curl_multi_info_read"); -} +inline bool f$curl_setopt_array(int64_t, const array&) noexcept { php_critical_error("call to unsupported function : curl_multi_info_read"); } diff --git a/runtime-light/stdlib/curl/curl-state.cpp b/runtime-light/stdlib/curl/curl-state.cpp index 0c0ab08239..20ad7b64e7 100644 --- a/runtime-light/stdlib/curl/curl-state.cpp +++ b/runtime-light/stdlib/curl/curl-state.cpp @@ -6,6 +6,4 @@ #include "runtime-light/state/instance-state.h" -CurlInstanceState &CurlInstanceState::get() noexcept { - return InstanceState::get().curl_instance_state; -} +CurlInstanceState& CurlInstanceState::get() noexcept { return InstanceState::get().curl_instance_state; } diff --git a/runtime-light/stdlib/curl/curl-state.h b/runtime-light/stdlib/curl/curl-state.h index ffef55704c..68529b59b5 100644 --- a/runtime-light/stdlib/curl/curl-state.h +++ b/runtime-light/stdlib/curl/curl-state.h @@ -11,5 +11,5 @@ struct CurlInstanceState final : private vk::not_copyable { int64_t curl_multi_info_read_msgs_in_queue_stub{}; - static CurlInstanceState &get() noexcept; + static CurlInstanceState& get() noexcept; }; diff --git a/runtime-light/stdlib/exception/exception-functions.h b/runtime-light/stdlib/exception/exception-functions.h index e50c9acec8..3885e4822b 100644 --- a/runtime-light/stdlib/exception/exception-functions.h +++ b/runtime-light/stdlib/exception/exception-functions.h @@ -6,32 +6,38 @@ #include "runtime-common/core/runtime-core.h" -#define THROW_EXCEPTION(e) {php_critical_error("Exceptions unsupported");} +#define THROW_EXCEPTION(e) \ + { php_critical_error("Exceptions unsupported"); } #define CHECK_EXCEPTION(action) #ifdef __clang__ - #define TRY_CALL_RET_(x) x +#define TRY_CALL_RET_(x) x #else - #define TRY_CALL_RET_(x) std::move(x) +#define TRY_CALL_RET_(x) std::move(x) #endif -#define TRY_CALL_(CallT, call, action) ({ \ -CallT x_tmp___ = (call); \ -CHECK_EXCEPTION(action); \ -TRY_CALL_RET_(x_tmp___); \ -}) +#define TRY_CALL_(CallT, call, action) \ + ({ \ + CallT x_tmp___ = (call); \ + CHECK_EXCEPTION(action); \ + TRY_CALL_RET_(x_tmp___); \ + }) -#define TRY_CALL_VOID_(call, action) ({(call); CHECK_EXCEPTION(action); void();}) +#define TRY_CALL_VOID_(call, action) \ + ({ \ + (call); \ + CHECK_EXCEPTION(action); \ + void(); \ + }) #define TRY_CALL(CallT, ResT, call) TRY_CALL_(CallT, call, return (ResT())) #define TRY_CALL_VOID(ResT, call) TRY_CALL_VOID_(call, return (ResT())) -#define TRY_CALL_EXIT(CallT, message, call) TRY_CALL_(CallT, call, php_critical_error (message)) -#define TRY_CALL_VOID_EXIT(message, call) TRY_CALL_VOID_(call, php_critical_error (message)) +#define TRY_CALL_EXIT(CallT, message, call) TRY_CALL_(CallT, call, php_critical_error(message)) +#define TRY_CALL_VOID_EXIT(message, call) TRY_CALL_VOID_(call, php_critical_error(message)) - -template -T f$_exception_set_location(const T &e, const string &file, int64_t line) { +template +T f$_exception_set_location(const T& e, const string& file, int64_t line) { php_critical_error("call to unsupported function"); } diff --git a/runtime-light/stdlib/exit/exit-functions.cpp b/runtime-light/stdlib/exit/exit-functions.cpp index cc552f031e..f973a7c539 100644 --- a/runtime-light/stdlib/exit/exit-functions.cpp +++ b/runtime-light/stdlib/exit/exit-functions.cpp @@ -9,12 +9,12 @@ #include "runtime-light/k2-platform/k2-api.h" #include "runtime-light/state/instance-state.h" -task_t f$exit(const mixed &v) noexcept { // TODO: make it synchronous - auto &instance_st{InstanceState::get()}; +task_t f$exit(const mixed& v) noexcept { // TODO: make it synchronous + auto& instance_st{InstanceState::get()}; int64_t exit_code{}; if (v.is_string()) { - Response &response{instance_st.response}; + Response& response{instance_st.response}; response.output_buffers[response.current_buffer] << v; } else if (v.is_int()) { int64_t v_code{v.to_int()}; @@ -24,7 +24,7 @@ task_t f$exit(const mixed &v) noexcept { // TODO: make it synchronous exit_code = 1; } instance_st.poll_status = - instance_st.poll_status != k2::PollStatus::PollFinishedError && exit_code == 0 ? k2::PollStatus::PollFinishedOk : k2::PollStatus::PollFinishedError; + instance_st.poll_status != k2::PollStatus::PollFinishedError && exit_code == 0 ? k2::PollStatus::PollFinishedOk : k2::PollStatus::PollFinishedError; co_await instance_st.run_instance_epilogue(); k2::exit(static_cast(exit_code)); } diff --git a/runtime-light/stdlib/exit/exit-functions.h b/runtime-light/stdlib/exit/exit-functions.h index 9fc1345669..3e0c9298f3 100644 --- a/runtime-light/stdlib/exit/exit-functions.h +++ b/runtime-light/stdlib/exit/exit-functions.h @@ -7,8 +7,6 @@ #include "runtime-common/core/runtime-core.h" #include "runtime-light/coroutine/task.h" -task_t f$exit(const mixed &v = 0) noexcept; +task_t f$exit(const mixed& v = 0) noexcept; -inline task_t f$die(const mixed &v = 0) noexcept { - co_await f$exit(v); -} +inline task_t f$die(const mixed& v = 0) noexcept { co_await f$exit(v); } diff --git a/runtime-light/stdlib/file/file-system-functions.cpp b/runtime-light/stdlib/file/file-system-functions.cpp index 324290eec3..6e96882187 100644 --- a/runtime-light/stdlib/file/file-system-functions.cpp +++ b/runtime-light/stdlib/file/file-system-functions.cpp @@ -11,8 +11,8 @@ #include "runtime-light/k2-platform/k2-api.h" #include "runtime-light/stdlib/file/resource.h" -resource f$fopen(const string &filename, [[maybe_unused]] const string &mode, [[maybe_unused]] bool use_include_path, - [[maybe_unused]] const resource &context) noexcept { +resource f$fopen(const string& filename, [[maybe_unused]] const string& mode, [[maybe_unused]] bool use_include_path, + [[maybe_unused]] const resource& context) noexcept { underlying_resource_t rsrc{{filename.c_str(), filename.size()}}; if (rsrc.last_errc != k2::errno_ok) [[unlikely]] { return {}; @@ -21,8 +21,8 @@ resource f$fopen(const string &filename, [[maybe_unused]] const string &mode, [[ return f$to_mixed(make_instance(std::move(rsrc))); } -resource f$stream_socket_client(const string &address, mixed &error_code, [[maybe_unused]] mixed &error_message, [[maybe_unused]] double timeout, - [[maybe_unused]] int64_t flags, [[maybe_unused]] const resource &context) noexcept { +resource f$stream_socket_client(const string& address, mixed& error_code, [[maybe_unused]] mixed& error_message, [[maybe_unused]] double timeout, + [[maybe_unused]] int64_t flags, [[maybe_unused]] const resource& context) noexcept { /* * TODO: Here should be waiting with timeout, * but it can't be expressed simple ways by awaitables since we blocked inside k2 @@ -41,7 +41,7 @@ resource f$stream_socket_client(const string &address, mixed &error_code, [[mayb return f$to_mixed(make_instance(std::move(rsrc))); } -Optional f$file_get_contents(const string &stream) noexcept { +Optional f$file_get_contents(const string& stream) noexcept { underlying_resource_t rsrc{{stream.c_str(), stream.size()}}; if (rsrc.last_errc != k2::errno_ok) [[unlikely]] { return false; @@ -49,7 +49,7 @@ Optional f$file_get_contents(const string &stream) noexcept { return rsrc.get_contents(); } -task_t> f$fwrite(const resource &stream, const string &text) noexcept { +task_t> f$fwrite(const resource& stream, const string& text) noexcept { auto rsrc{from_mixed>(stream, {})}; if (rsrc.is_null()) [[unlikely]] { php_warning("wrong resource in fwrite %s", stream.to_string().c_str()); @@ -59,7 +59,7 @@ task_t> f$fwrite(const resource &stream, const string &text) n co_return co_await rsrc.get()->write({text.c_str(), text.size()}); } -bool f$fflush(const resource &stream) noexcept { +bool f$fflush(const resource& stream) noexcept { auto rsrc{from_mixed>(stream, {})}; if (rsrc.is_null()) [[unlikely]] { php_warning("wrong resource in fflush %s", stream.to_string().c_str()); @@ -70,7 +70,7 @@ bool f$fflush(const resource &stream) noexcept { return true; } -bool f$fclose(const resource &stream) noexcept { +bool f$fclose(const resource& stream) noexcept { auto rsrc{from_mixed>(stream, {})}; if (rsrc.is_null()) [[unlikely]] { php_warning("wrong resource in fclose: %s", stream.to_string().c_str()); diff --git a/runtime-light/stdlib/file/file-system-functions.h b/runtime-light/stdlib/file/file-system-functions.h index 2b8f88a6ed..6ed8890540 100644 --- a/runtime-light/stdlib/file/file-system-functions.h +++ b/runtime-light/stdlib/file/file-system-functions.h @@ -27,7 +27,7 @@ inline constexpr int64_t DEFAULT_SOCKET_TIMEOUT = 60; // // This implementation works the same way as PHP. That means we can face with some problems // during transition to K2 -inline string f$basename(const string &path, const string &suffix = {}) noexcept { +inline string f$basename(const string& path, const string& suffix = {}) noexcept { std::string_view path_view{path.c_str(), path.size()}; const std::string_view suffix_view{suffix.c_str(), suffix.size()}; // skip trailing separators @@ -44,16 +44,16 @@ inline string f$basename(const string &path, const string &suffix = {}) noexcept return {filename_view.data(), static_cast(filename_view.size())}; } -resource f$fopen(const string &filename, const string &mode, bool use_include_path = false, const resource &context = {}) noexcept; +resource f$fopen(const string& filename, const string& mode, bool use_include_path = false, const resource& context = {}) noexcept; -task_t> f$fwrite(const resource &stream, const string &text) noexcept; +task_t> f$fwrite(const resource& stream, const string& text) noexcept; -bool f$fflush(const resource &stream) noexcept; +bool f$fflush(const resource& stream) noexcept; -bool f$fclose(const resource &stream) noexcept; +bool f$fclose(const resource& stream) noexcept; -resource f$stream_socket_client(const string &address, mixed &error_code = FileSystemInstanceState::get().error_number_dummy, - mixed &error_message = FileSystemInstanceState::get().error_description_dummy, double timeout = DEFAULT_SOCKET_TIMEOUT, - int64_t flags = STREAM_CLIENT_CONNECT, const resource &context = {}) noexcept; +resource f$stream_socket_client(const string& address, mixed& error_code = FileSystemInstanceState::get().error_number_dummy, + mixed& error_message = FileSystemInstanceState::get().error_description_dummy, double timeout = DEFAULT_SOCKET_TIMEOUT, + int64_t flags = STREAM_CLIENT_CONNECT, const resource& context = {}) noexcept; -Optional f$file_get_contents(const string &stream) noexcept; +Optional f$file_get_contents(const string& stream) noexcept; diff --git a/runtime-light/stdlib/file/file-system-state.cpp b/runtime-light/stdlib/file/file-system-state.cpp index 6e77d6c532..d83750a404 100644 --- a/runtime-light/stdlib/file/file-system-state.cpp +++ b/runtime-light/stdlib/file/file-system-state.cpp @@ -6,6 +6,4 @@ #include "runtime-light/state/instance-state.h" -FileSystemInstanceState &FileSystemInstanceState::get() noexcept { - return InstanceState::get().file_system_instance_state; -} +FileSystemInstanceState& FileSystemInstanceState::get() noexcept { return InstanceState::get().file_system_instance_state; } diff --git a/runtime-light/stdlib/file/file-system-state.h b/runtime-light/stdlib/file/file-system-state.h index 9b4552eba2..37548a15c6 100644 --- a/runtime-light/stdlib/file/file-system-state.h +++ b/runtime-light/stdlib/file/file-system-state.h @@ -11,5 +11,5 @@ struct FileSystemInstanceState final : private vk::not_copyable { mixed error_number_dummy; mixed error_description_dummy; - static FileSystemInstanceState &get() noexcept; + static FileSystemInstanceState& get() noexcept; }; diff --git a/runtime-light/stdlib/file/resource.cpp b/runtime-light/stdlib/file/resource.cpp index ffc9af9057..f7ea86ed8e 100644 --- a/runtime-light/stdlib/file/resource.cpp +++ b/runtime-light/stdlib/file/resource.cpp @@ -11,43 +11,41 @@ #include "runtime-light/k2-platform/k2-api.h" #include "runtime-light/state/instance-state.h" -underlying_resource_t::underlying_resource_t(std::string_view scheme) noexcept - : kind(resource_impl_::uri_to_resource_kind(scheme)) { - auto &instance_st{InstanceState::get()}; +underlying_resource_t::underlying_resource_t(std::string_view scheme) noexcept : kind(resource_impl_::uri_to_resource_kind(scheme)) { + auto& instance_st{InstanceState::get()}; switch (kind) { - case resource_kind::STDIN: { - last_errc = instance_st.image_kind() == ImageKind::Server ? k2::errno_ok : k2::errno_einval; - break; - } - case resource_kind::STDERR: { - last_errc = k2::errno_einval; - break; - } - case resource_kind::STDOUT: { - if (instance_st.image_kind() == ImageKind::CLI) { - stream_d_ = instance_st.standard_stream(); - } else { - last_errc = k2::errno_einval; - } - break; - } - case resource_kind::UDP: { - const auto url{scheme.substr(resource_impl_::UDP_SCHEME_PREFIX.size(), scheme.size() - resource_impl_::UDP_SCHEME_PREFIX.size())}; - std::tie(stream_d_, last_errc) = instance_st.open_stream(url, k2::StreamKind::UDP); - kind = last_errc == k2::errno_ok ? resource_kind::UDP : resource_kind::UNKNOWN; - break; - } - case resource_kind::UNKNOWN: { + case resource_kind::STDIN: { + last_errc = instance_st.image_kind() == ImageKind::Server ? k2::errno_ok : k2::errno_einval; + break; + } + case resource_kind::STDERR: { + last_errc = k2::errno_einval; + break; + } + case resource_kind::STDOUT: { + if (instance_st.image_kind() == ImageKind::CLI) { + stream_d_ = instance_st.standard_stream(); + } else { last_errc = k2::errno_einval; - break; } + break; + } + case resource_kind::UDP: { + const auto url{scheme.substr(resource_impl_::UDP_SCHEME_PREFIX.size(), scheme.size() - resource_impl_::UDP_SCHEME_PREFIX.size())}; + std::tie(stream_d_, last_errc) = instance_st.open_stream(url, k2::StreamKind::UDP); + kind = last_errc == k2::errno_ok ? resource_kind::UDP : resource_kind::UNKNOWN; + break; + } + case resource_kind::UNKNOWN: { + last_errc = k2::errno_einval; + break; + } } } -underlying_resource_t::underlying_resource_t(underlying_resource_t &&other) noexcept - : stream_d_(std::exchange(other.stream_d_, k2::INVALID_PLATFORM_DESCRIPTOR)) - , kind(std::exchange(other.kind, resource_kind::UNKNOWN)) - , last_errc(std::exchange(other.last_errc, k2::errno_ok)) {} +underlying_resource_t::underlying_resource_t(underlying_resource_t&& other) noexcept + : stream_d_(std::exchange(other.stream_d_, k2::INVALID_PLATFORM_DESCRIPTOR)), kind(std::exchange(other.kind, resource_kind::UNKNOWN)), + last_errc(std::exchange(other.last_errc, k2::errno_ok)) {} underlying_resource_t::~underlying_resource_t() { if (stream_d_ == k2::INVALID_PLATFORM_DESCRIPTOR) { @@ -62,20 +60,20 @@ void underlying_resource_t::close() noexcept { } switch (kind) { - case resource_kind::STDIN: - case resource_kind::STDOUT: - case resource_kind::STDERR: { - // PHP supports multiple opening/closing operations on standard IO streams. - stream_d_ = k2::INVALID_PLATFORM_DESCRIPTOR; - break; - } - case resource_kind::UDP: { - InstanceState::get().release_stream(stream_d_); - stream_d_ = k2::INVALID_PLATFORM_DESCRIPTOR; - break; - } - case resource_kind::UNKNOWN: { - break; - } + case resource_kind::STDIN: + case resource_kind::STDOUT: + case resource_kind::STDERR: { + // PHP supports multiple opening/closing operations on standard IO streams. + stream_d_ = k2::INVALID_PLATFORM_DESCRIPTOR; + break; + } + case resource_kind::UDP: { + InstanceState::get().release_stream(stream_d_); + stream_d_ = k2::INVALID_PLATFORM_DESCRIPTOR; + break; + } + case resource_kind::UNKNOWN: { + break; + } } } diff --git a/runtime-light/stdlib/file/resource.h b/runtime-light/stdlib/file/resource.h index 12e8f783ce..7c83cab3c0 100644 --- a/runtime-light/stdlib/file/resource.h +++ b/runtime-light/stdlib/file/resource.h @@ -48,23 +48,19 @@ class underlying_resource_t : public refcountable_polymorphic_php_classes write(std::string_view text) const noexcept { - co_return co_await write_all_to_stream(stream_d_, text.data(), text.size()); - } + task_t write(std::string_view text) const noexcept { co_return co_await write_all_to_stream(stream_d_, text.data(), text.size()); } Optional get_contents() const noexcept { - auto &http_server_instance_st{HttpServerInstanceState::get()}; + auto& http_server_instance_st{HttpServerInstanceState::get()}; if (kind != resource_kind::STDIN || !http_server_instance_st.opt_raw_post_data.has_value()) { return false; } diff --git a/runtime-light/stdlib/fork/fork-functions.h b/runtime-light/stdlib/fork/fork-functions.h index 5f9bf84cf1..f3c17478c9 100644 --- a/runtime-light/stdlib/fork/fork-functions.h +++ b/runtime-light/stdlib/fork/fork-functions.h @@ -26,30 +26,29 @@ inline constexpr auto DEFAULT_TIMEOUT_NS = std::chrono::duration_cast -requires(is_optional::value || std::same_as || is_class_instance::value) task_t f$wait(int64_t fork_id, double timeout = -1.0) noexcept { - auto &fork_ctx{ForkInstanceState::get()}; +template +requires(is_optional::value || std::same_as || is_class_instance::value) +task_t f$wait(int64_t fork_id, double timeout = -1.0) noexcept { + auto& fork_ctx{ForkInstanceState::get()}; if (!fork_ctx.contains(fork_id)) { php_warning("can't find fork %" PRId64, fork_id); co_return T{}; } // normalize timeout const auto timeout_ns{timeout > 0 && timeout <= fork_api_impl_::MAX_TIMEOUT_S - ? std::chrono::duration_cast(std::chrono::duration{timeout}) - : fork_api_impl_::DEFAULT_TIMEOUT_NS}; + ? std::chrono::duration_cast(std::chrono::duration{timeout}) + : fork_api_impl_::DEFAULT_TIMEOUT_NS}; auto result_opt{co_await wait_with_timeout_t{wait_fork_t>{fork_id}, timeout_ns}}; co_return result_opt.has_value() ? T{std::move(result_opt.value())} : T{}; } -template -requires(is_optional::value || std::same_as || is_class_instance::value) task_t f$wait(Optional fork_id_opt, - double timeout = -1.0) noexcept { +template +requires(is_optional::value || std::same_as || is_class_instance::value) +task_t f$wait(Optional fork_id_opt, double timeout = -1.0) noexcept { co_return co_await f$wait(fork_id_opt.has_value() ? fork_id_opt.val() : INVALID_FORK_ID, timeout); } -inline task_t f$sched_yield() noexcept { - co_await wait_for_reschedule_t{}; -} +inline task_t f$sched_yield() noexcept { co_await wait_for_reschedule_t{}; } inline task_t f$sched_yield_sleep(double duration) noexcept { if (duration <= 0) { @@ -61,48 +60,30 @@ inline task_t f$sched_yield_sleep(double duration) noexcept { // === Non-blocking API ============================================================================ -inline int64_t f$get_running_fork_id() noexcept { - return ForkInstanceState::get().running_fork_id; -} +inline int64_t f$get_running_fork_id() noexcept { return ForkInstanceState::get().running_fork_id; } -inline int64_t f$wait_queue_create() { - php_critical_error("call to unsupported function"); -} +inline int64_t f$wait_queue_create() { php_critical_error("call to unsupported function"); } -inline int64_t f$wait_queue_create(const mixed &resumable_ids) { - php_critical_error("call to unsupported function"); -} +inline int64_t f$wait_queue_create(const mixed& resumable_ids) { php_critical_error("call to unsupported function"); } -inline int64_t f$wait_queue_push(int64_t queue_id, const mixed &resumable_ids) { - php_critical_error("call to unsupported function"); -} +inline int64_t f$wait_queue_push(int64_t queue_id, const mixed& resumable_ids) { php_critical_error("call to unsupported function"); } -inline bool f$wait_queue_empty(int64_t queue_id) { - php_critical_error("call to unsupported function"); -} +inline bool f$wait_queue_empty(int64_t queue_id) { php_critical_error("call to unsupported function"); } -inline Optional f$wait_queue_next(int64_t queue_id, double timeout = -1.0) { - php_critical_error("call to unsupported function"); -} +inline Optional f$wait_queue_next(int64_t queue_id, double timeout = -1.0) { php_critical_error("call to unsupported function"); } -inline bool f$wait_concurrently(int64_t fork_id) { - php_critical_error("call to unsupported function"); -} +inline bool f$wait_concurrently(int64_t fork_id) { php_critical_error("call to unsupported function"); } -inline bool f$wait_concurrently(Optional resumable_id) { - php_critical_error("call to unsupported function"); -} +inline bool f$wait_concurrently(Optional resumable_id) { php_critical_error("call to unsupported function"); } -inline bool f$wait_concurrently(const mixed &resumable_id) { - php_critical_error("call to unsupported function"); -} +inline bool f$wait_concurrently(const mixed& resumable_id) { php_critical_error("call to unsupported function"); } -template -T f$wait_multi(const array> &resumable_ids) { +template +T f$wait_multi(const array>& resumable_ids) { php_critical_error("call to unsupported function"); } -template -T f$wait_multi(const array &resumable_ids) { +template +T f$wait_multi(const array& resumable_ids) { php_critical_error("call to unsupported function"); } diff --git a/runtime-light/stdlib/fork/fork-state.cpp b/runtime-light/stdlib/fork/fork-state.cpp index c890edcff1..2de5cc67ce 100644 --- a/runtime-light/stdlib/fork/fork-state.cpp +++ b/runtime-light/stdlib/fork/fork-state.cpp @@ -6,6 +6,4 @@ #include "runtime-light/state/instance-state.h" -ForkInstanceState &ForkInstanceState::get() noexcept { - return InstanceState::get().fork_instance_state; -} +ForkInstanceState& ForkInstanceState::get() noexcept { return InstanceState::get().fork_instance_state; } diff --git a/runtime-light/stdlib/fork/fork-state.h b/runtime-light/stdlib/fork/fork-state.h index 10ebe5f28f..99bee04205 100644 --- a/runtime-light/stdlib/fork/fork-state.h +++ b/runtime-light/stdlib/fork/fork-state.h @@ -16,7 +16,7 @@ inline constexpr int64_t INVALID_FORK_ID = -1; class ForkInstanceState final : private vk::not_copyable { - template + template using unordered_map = memory_resource::stl::unordered_map; static constexpr auto FORK_ID_INIT = 0; @@ -24,9 +24,7 @@ class ForkInstanceState final : private vk::not_copyable { unordered_map> forks; int64_t next_fork_id{FORK_ID_INIT + 1}; - int64_t push_fork(task_t task) noexcept { - return forks.emplace(next_fork_id, std::move(task)), next_fork_id++; - } + int64_t push_fork(task_t task) noexcept { return forks.emplace(next_fork_id, std::move(task)), next_fork_id++; } task_t pop_fork(int64_t fork_id) noexcept { const auto it_fork{forks.find(fork_id)}; @@ -39,18 +37,16 @@ class ForkInstanceState final : private vk::not_copyable { } friend class start_fork_t; - template + template friend class wait_fork_t; public: int64_t running_fork_id{FORK_ID_INIT}; - explicit ForkInstanceState(memory_resource::unsynchronized_pool_resource &memory_resource) noexcept - : forks(unordered_map>::allocator_type{memory_resource}) {} + explicit ForkInstanceState(memory_resource::unsynchronized_pool_resource& memory_resource) noexcept + : forks(unordered_map>::allocator_type{memory_resource}) {} - static ForkInstanceState &get() noexcept; + static ForkInstanceState& get() noexcept; - bool contains(int64_t fork_id) const noexcept { - return forks.contains(fork_id); - } + bool contains(int64_t fork_id) const noexcept { return forks.contains(fork_id); } }; diff --git a/runtime-light/stdlib/instance-cache/instance-cache.h b/runtime-light/stdlib/instance-cache/instance-cache.h index 2b7a09139c..f7a8d009a7 100644 --- a/runtime-light/stdlib/instance-cache/instance-cache.h +++ b/runtime-light/stdlib/instance-cache/instance-cache.h @@ -6,12 +6,12 @@ #include "runtime-common/core/runtime-core.h" -template -bool f$instance_cache_store(const string & /*key*/, const ClassInstanceType & /*instance*/, int64_t /*ttl*/ = 0) { +template +bool f$instance_cache_store(const string& /*key*/, const ClassInstanceType& /*instance*/, int64_t /*ttl*/ = 0) { php_critical_error("call to unsupported function"); } -template -ClassInstanceType f$instance_cache_fetch(const string & /*class_name*/, const string & /*key*/, bool /*even_if_expired*/ = false) { +template +ClassInstanceType f$instance_cache_fetch(const string& /*class_name*/, const string& /*key*/, bool /*even_if_expired*/ = false) { php_critical_error("call to unsupported function"); } diff --git a/runtime-light/stdlib/job-worker/job-worker-api.cpp b/runtime-light/stdlib/job-worker/job-worker-api.cpp index daff83ebe1..e10492b2e3 100644 --- a/runtime-light/stdlib/job-worker/job-worker-api.cpp +++ b/runtime-light/stdlib/job-worker/job-worker-api.cpp @@ -28,7 +28,7 @@ namespace { -constexpr const char *JOB_WORKER_COMPONENT_NAME = "_self"; +constexpr const char* JOB_WORKER_COMPONENT_NAME = "_self"; constexpr double MIN_TIMEOUT_S = 0.05; constexpr double MAX_TIMEOUT_S = 86400.0; @@ -43,7 +43,7 @@ task_t kphp_job_worker_start_impl(string request, double timeout, bool co_return INVALID_FORK_ID; } - auto &jw_client_st{JobWorkerClientInstanceState::get()}; + auto& jw_client_st{JobWorkerClientInstanceState::get()}; // normalize timeout const auto timeout_ns{std::chrono::duration_cast(std::chrono::duration(std::clamp(timeout, MIN_TIMEOUT_S, MAX_TIMEOUT_S)))}; // prepare JW component request @@ -76,7 +76,7 @@ task_t kphp_job_worker_start_impl(string request, double timeout, bool co_return std::move(jw_response.body); }(std::move(comp_query), timeout_ns)}; // start waiter fork and return its ID - co_return(co_await start_fork_t{static_cast>(std::move(waiter_task)), start_fork_t::execution::self}); + co_return (co_await start_fork_t{static_cast>(std::move(waiter_task)), start_fork_t::execution::self}); } } // namespace @@ -95,7 +95,7 @@ task_t f$job_worker_send_noreply_request(string request, double timeout) n task_t>> f$job_worker_send_multi_request(array requests, double timeout) noexcept { array> fork_ids{requests.size()}; - for (const auto &it : requests) { + for (const auto& it : requests) { const auto fork_id{co_await kphp_job_worker_start_impl(it.get_value(), timeout, false)}; fork_ids.set_value(it.get_key(), fork_id != INVALID_FORK_ID ? fork_id : false); } @@ -110,7 +110,7 @@ task_t f$job_worker_fetch_request() noexcept { co_return string{}; } - auto &jw_server_st{JobWorkerServerInstanceState::get()}; + auto& jw_server_st{JobWorkerServerInstanceState::get()}; if (jw_server_st.job_id == JOB_WORKER_INVALID_JOB_ID || jw_server_st.body.empty()) { php_warning("couldn't fetch job worker request"); co_return string{}; @@ -119,8 +119,8 @@ task_t f$job_worker_fetch_request() noexcept { } task_t f$job_worker_store_response(string response) noexcept { - auto &instance_st{InstanceState::get()}; - auto &jw_server_st{JobWorkerServerInstanceState::get()}; + auto& instance_st{InstanceState::get()}; + auto& jw_server_st{JobWorkerServerInstanceState::get()}; if (!f$is_kphp_job_workers_enabled()) { // workers are enabled php_warning("couldn't store job worker response: job workers are disabled"); co_return static_cast(JobWorkerError::store_response_incorrect_call_error); diff --git a/runtime-light/stdlib/job-worker/job-worker-api.h b/runtime-light/stdlib/job-worker/job-worker-api.h index 5d51c23b44..e8b0b921ff 100644 --- a/runtime-light/stdlib/job-worker/job-worker-api.h +++ b/runtime-light/stdlib/job-worker/job-worker-api.h @@ -26,9 +26,7 @@ task_t f$job_worker_store_response(string response) noexcept; // === Misc ======================================================================================= -inline bool f$is_kphp_job_workers_enabled() noexcept { - return InstanceState::get().image_kind() == ImageKind::Server; -} +inline bool f$is_kphp_job_workers_enabled() noexcept { return InstanceState::get().image_kind() == ImageKind::Server; } inline int64_t f$get_job_workers_number() noexcept { return 50; // TODO diff --git a/runtime-light/stdlib/job-worker/job-worker-client-state.cpp b/runtime-light/stdlib/job-worker/job-worker-client-state.cpp index 68dc9dfe0c..bf84843ec2 100644 --- a/runtime-light/stdlib/job-worker/job-worker-client-state.cpp +++ b/runtime-light/stdlib/job-worker/job-worker-client-state.cpp @@ -6,6 +6,4 @@ #include "runtime-light/state/instance-state.h" -JobWorkerClientInstanceState &JobWorkerClientInstanceState::get() noexcept { - return InstanceState::get().job_worker_client_instance_state; -} +JobWorkerClientInstanceState& JobWorkerClientInstanceState::get() noexcept { return InstanceState::get().job_worker_client_instance_state; } diff --git a/runtime-light/stdlib/job-worker/job-worker-client-state.h b/runtime-light/stdlib/job-worker/job-worker-client-state.h index a4ba2cda16..acd3f657b6 100644 --- a/runtime-light/stdlib/job-worker/job-worker-client-state.h +++ b/runtime-light/stdlib/job-worker/job-worker-client-state.h @@ -12,5 +12,5 @@ struct JobWorkerClientInstanceState final : private vk::not_copyable { int64_t current_job_id{JOB_WORKER_VALID_JOB_ID_RANGE_START}; - static JobWorkerClientInstanceState &get() noexcept; + static JobWorkerClientInstanceState& get() noexcept; }; diff --git a/runtime-light/stdlib/job-worker/job-worker.h b/runtime-light/stdlib/job-worker/job-worker.h index 7dde383524..78689ec06d 100644 --- a/runtime-light/stdlib/job-worker/job-worker.h +++ b/runtime-light/stdlib/job-worker/job-worker.h @@ -20,12 +20,12 @@ namespace job_worker_impl_ { struct SendableBase : virtual abstract_refcountable_php_interface { - virtual void accept(ToArrayVisitor &) noexcept {} + virtual void accept(ToArrayVisitor&) noexcept {} - virtual const char *get_class() const noexcept = 0; + virtual const char* get_class() const noexcept = 0; virtual int32_t get_hash() const noexcept = 0; virtual size_t virtual_builtin_sizeof() const noexcept = 0; - virtual SendableBase *virtual_builtin_clone() const noexcept = 0; + virtual SendableBase* virtual_builtin_clone() const noexcept = 0; ~SendableBase() override = default; }; @@ -40,19 +40,19 @@ enum class JobWorkerError : int16_t { // === KphpJobWorkerSharedMemoryPiece ============================================================= struct C$KphpJobWorkerSharedMemoryPiece : public job_worker_impl_::SendableBase { - C$KphpJobWorkerSharedMemoryPiece *virtual_builtin_clone() const noexcept override = 0; + C$KphpJobWorkerSharedMemoryPiece* virtual_builtin_clone() const noexcept override = 0; }; // === KphpJobWorkerRequest ======================================================================= struct C$KphpJobWorkerRequest : public job_worker_impl_::SendableBase { - C$KphpJobWorkerRequest *virtual_builtin_clone() const noexcept override = 0; + C$KphpJobWorkerRequest* virtual_builtin_clone() const noexcept override = 0; }; // === KphpJobWorkerResponse ====================================================================== struct C$KphpJobWorkerResponse : public job_worker_impl_::SendableBase { - C$KphpJobWorkerResponse *virtual_builtin_clone() const noexcept override = 0; + C$KphpJobWorkerResponse* virtual_builtin_clone() const noexcept override = 0; }; // === KphpJobWorkerResponseError ================================================================= @@ -61,31 +61,19 @@ struct C$KphpJobWorkerResponseError : public refcountable_polymorphic_php_classe string error; int64_t error_code; - const char *get_class() const noexcept override { - return "KphpJobWorkerResponseError"; - } + const char* get_class() const noexcept override { return "KphpJobWorkerResponseError"; } - int32_t get_hash() const noexcept override { - return static_cast(std::hash{}(get_class())); - } + int32_t get_hash() const noexcept override { return static_cast(std::hash{}(get_class())); } - size_t virtual_builtin_sizeof() const noexcept override { - return sizeof(*this); - } + size_t virtual_builtin_sizeof() const noexcept override { return sizeof(*this); } - C$KphpJobWorkerResponseError *virtual_builtin_clone() const noexcept override { - return new C$KphpJobWorkerResponseError{*this}; - } + C$KphpJobWorkerResponseError* virtual_builtin_clone() const noexcept override { return new C$KphpJobWorkerResponseError{*this}; } }; inline class_instance f$KphpJobWorkerResponseError$$__construct(class_instance v$this) noexcept { return v$this; } -inline string f$KphpJobWorkerResponseError$$getError(class_instance v$this) noexcept { - return v$this.get()->error; -} +inline string f$KphpJobWorkerResponseError$$getError(class_instance v$this) noexcept { return v$this.get()->error; } -inline int64_t f$KphpJobWorkerResponseError$$getErrorCode(class_instance v$this) noexcept { - return v$this.get()->error_code; -} +inline int64_t f$KphpJobWorkerResponseError$$getErrorCode(class_instance v$this) noexcept { return v$this.get()->error_code; } diff --git a/runtime-light/stdlib/math/math-state.cpp b/runtime-light/stdlib/math/math-state.cpp index 5531393f20..fd11dbb333 100644 --- a/runtime-light/stdlib/math/math-state.cpp +++ b/runtime-light/stdlib/math/math-state.cpp @@ -7,10 +7,6 @@ #include "runtime-light/state/image-state.h" #include "runtime-light/state/instance-state.h" -MathInstanceState &MathInstanceState::get() noexcept { - return InstanceState::get().math_instance_state; -} +MathInstanceState& MathInstanceState::get() noexcept { return InstanceState::get().math_instance_state; } -const MathImageState &MathImageState::get() noexcept { - return ImageState::get().math_image_state; -} +const MathImageState& MathImageState::get() noexcept { return ImageState::get().math_image_state; } diff --git a/runtime-light/stdlib/math/random-functions.h b/runtime-light/stdlib/math/random-functions.h index f8f96dcc6e..e77d16143e 100644 --- a/runtime-light/stdlib/math/random-functions.h +++ b/runtime-light/stdlib/math/random-functions.h @@ -20,9 +20,7 @@ inline int64_t f$mt_rand(int64_t l, int64_t r) noexcept { return std::uniform_int_distribution{l, r}(RandomInstanceState::get().mt_gen); } -inline int64_t f$mt_rand() noexcept { - return f$mt_rand(0, f$mt_getrandmax()); -} +inline int64_t f$mt_rand() noexcept { return f$mt_rand(0, f$mt_getrandmax()); } inline void f$mt_srand(int64_t seed = std::numeric_limits::min()) noexcept { if (seed == std::numeric_limits::min()) { @@ -31,10 +29,6 @@ inline void f$mt_srand(int64_t seed = std::numeric_limits::min()) noexc RandomInstanceState::get().mt_gen.seed(static_cast(seed)); } -inline int64_t f$rand() noexcept { - return f$mt_rand(); -} +inline int64_t f$rand() noexcept { return f$mt_rand(); } -inline int64_t f$rand(int64_t l, int64_t r) noexcept { - return f$mt_rand(l, r); -} +inline int64_t f$rand(int64_t l, int64_t r) noexcept { return f$mt_rand(l, r); } diff --git a/runtime-light/stdlib/math/random-state.cpp b/runtime-light/stdlib/math/random-state.cpp index 1d8612d17e..dc813e4cb7 100644 --- a/runtime-light/stdlib/math/random-state.cpp +++ b/runtime-light/stdlib/math/random-state.cpp @@ -6,6 +6,4 @@ #include "runtime-light/state/instance-state.h" -RandomInstanceState &RandomInstanceState::get() noexcept { - return InstanceState::get().random_instance_state; -} +RandomInstanceState& RandomInstanceState::get() noexcept { return InstanceState::get().random_instance_state; } diff --git a/runtime-light/stdlib/math/random-state.h b/runtime-light/stdlib/math/random-state.h index 06def20376..2503b4efb4 100644 --- a/runtime-light/stdlib/math/random-state.h +++ b/runtime-light/stdlib/math/random-state.h @@ -20,5 +20,5 @@ struct RandomInstanceState final : private vk::not_copyable { mt_gen = std::mt19937_64{seed}; } - static RandomInstanceState &get() noexcept; + static RandomInstanceState& get() noexcept; }; diff --git a/runtime-light/stdlib/output/http-functions.h b/runtime-light/stdlib/output/http-functions.h index 8a746c0518..3cb3513ba9 100644 --- a/runtime-light/stdlib/output/http-functions.h +++ b/runtime-light/stdlib/output/http-functions.h @@ -8,8 +8,7 @@ #include "runtime-common/core/runtime-core.h" -template -string f$http_build_query(const array & /*a*/, const string & /*numeric_prefix*/ = {}, const string & /*arg_separator*/ = string(), - int64_t /*enc_type*/ = 1) { +template +string f$http_build_query(const array& /*a*/, const string& /*numeric_prefix*/ = {}, const string& /*arg_separator*/ = string(), int64_t /*enc_type*/ = 1) { php_critical_error("call to unsupported function"); } diff --git a/runtime-light/stdlib/output/output-buffer.cpp b/runtime-light/stdlib/output/output-buffer.cpp index 4493c10907..d4cd7a081c 100644 --- a/runtime-light/stdlib/output/output-buffer.cpp +++ b/runtime-light/stdlib/output/output-buffer.cpp @@ -11,8 +11,8 @@ static constexpr int32_t system_level_buffer = 0; -void f$ob_start(const string &callback) noexcept { - Response &httpResponse{InstanceState::get().response}; +void f$ob_start(const string& callback) noexcept { + Response& httpResponse{InstanceState::get().response}; if (httpResponse.current_buffer + 1 == Response::ob_max_buffers) { php_warning("Maximum nested level of output buffering reached. Can't do ob_start(%s)", callback.c_str()); return; @@ -25,24 +25,22 @@ void f$ob_start(const string &callback) noexcept { } Optional f$ob_get_length() noexcept { - Response &httpResponse{InstanceState::get().response}; + Response& httpResponse{InstanceState::get().response}; if (httpResponse.current_buffer == 0) { return false; } return httpResponse.output_buffers[httpResponse.current_buffer].size(); } -int64_t f$ob_get_level() noexcept { - return InstanceState::get().response.current_buffer; -} +int64_t f$ob_get_level() noexcept { return InstanceState::get().response.current_buffer; } void f$ob_clean() noexcept { - Response &httpResponse{InstanceState::get().response}; + Response& httpResponse{InstanceState::get().response}; httpResponse.output_buffers[httpResponse.current_buffer].clean(); } bool f$ob_end_clean() noexcept { - Response &httpResponse{InstanceState::get().response}; + Response& httpResponse{InstanceState::get().response}; if (httpResponse.current_buffer == system_level_buffer) { return false; } @@ -52,7 +50,7 @@ bool f$ob_end_clean() noexcept { } Optional f$ob_get_clean() noexcept { - Response &httpResponse{InstanceState::get().response}; + Response& httpResponse{InstanceState::get().response}; if (httpResponse.current_buffer == system_level_buffer) { return false; } @@ -60,12 +58,12 @@ Optional f$ob_get_clean() noexcept { } string f$ob_get_contents() noexcept { - Response &httpResponse{InstanceState::get().response}; + Response& httpResponse{InstanceState::get().response}; return httpResponse.output_buffers[httpResponse.current_buffer].str(); } void f$ob_flush() noexcept { - Response &httpResponse{InstanceState::get().response}; + Response& httpResponse{InstanceState::get().response}; if (httpResponse.current_buffer == 0) { php_warning("ob_flush with no buffer opented"); return; @@ -77,7 +75,7 @@ void f$ob_flush() noexcept { } bool f$ob_end_flush() noexcept { - Response &httpResponse{InstanceState::get().response}; + Response& httpResponse{InstanceState::get().response}; if (httpResponse.current_buffer == 0) { return false; } @@ -86,7 +84,7 @@ bool f$ob_end_flush() noexcept { } Optional f$ob_get_flush() noexcept { - Response &httpResponse{InstanceState::get().response}; + Response& httpResponse{InstanceState::get().response}; if (httpResponse.current_buffer == 0) { return false; } diff --git a/runtime-light/stdlib/output/output-buffer.h b/runtime-light/stdlib/output/output-buffer.h index 3a57fbdc30..a848acc7af 100644 --- a/runtime-light/stdlib/output/output-buffer.h +++ b/runtime-light/stdlib/output/output-buffer.h @@ -14,7 +14,7 @@ struct Response { int32_t current_buffer{}; }; -void f$ob_start(const string &callback = string()) noexcept; +void f$ob_start(const string& callback = string()) noexcept; Optional f$ob_get_length() noexcept; diff --git a/runtime-light/stdlib/output/print-functions.cpp b/runtime-light/stdlib/output/print-functions.cpp index e6401ddf5d..4b4731dc6b 100644 --- a/runtime-light/stdlib/output/print-functions.cpp +++ b/runtime-light/stdlib/output/print-functions.cpp @@ -13,188 +13,188 @@ namespace { -void do_print_r(const mixed &v, int32_t depth) noexcept { +void do_print_r(const mixed& v, int32_t depth) noexcept { if (depth == 10) { php_warning("Depth %d reached. Recursion?", depth); return; } - Response &httpResponse{InstanceState::get().response}; - string_buffer &coub{httpResponse.output_buffers[httpResponse.current_buffer]}; + Response& httpResponse{InstanceState::get().response}; + string_buffer& coub{httpResponse.output_buffers[httpResponse.current_buffer]}; switch (v.get_type()) { - case mixed::type::NUL: - break; - case mixed::type::BOOLEAN: - if (v.as_bool()) { - coub << '1'; - } - break; - case mixed::type::INTEGER: - coub << v.as_int(); - break; - case mixed::type::FLOAT: - coub << v.as_double(); - break; - case mixed::type::STRING: - coub << v.as_string(); - break; - case mixed::type::ARRAY: { - coub << "Array\n"; - - string shift(depth << 3, ' '); - coub << shift << "(\n"; - - for (array::const_iterator it = v.as_array().begin(); it != v.as_array().end(); ++it) { - coub << shift << " [" << it.get_key() << "] => "; - do_print_r(it.get_value(), depth + 1); - coub << '\n'; - } - - coub << shift << ")\n"; - break; + case mixed::type::NUL: + break; + case mixed::type::BOOLEAN: + if (v.as_bool()) { + coub << '1'; } - case mixed::type::OBJECT: { - php_warning("print_r used on object"); - coub << v.as_object()->get_class(); - break; + break; + case mixed::type::INTEGER: + coub << v.as_int(); + break; + case mixed::type::FLOAT: + coub << v.as_double(); + break; + case mixed::type::STRING: + coub << v.as_string(); + break; + case mixed::type::ARRAY: { + coub << "Array\n"; + + string shift(depth << 3, ' '); + coub << shift << "(\n"; + + for (array::const_iterator it = v.as_array().begin(); it != v.as_array().end(); ++it) { + coub << shift << " [" << it.get_key() << "] => "; + do_print_r(it.get_value(), depth + 1); + coub << '\n'; } - default: - php_critical_error("non-exhaustive switch"); + + coub << shift << ")\n"; + break; + } + case mixed::type::OBJECT: { + php_warning("print_r used on object"); + coub << v.as_object()->get_class(); + break; + } + default: + php_critical_error("non-exhaustive switch"); } } -void do_var_dump(const mixed &v, int32_t depth) noexcept { +void do_var_dump(const mixed& v, int32_t depth) noexcept { if (depth == 10) { php_warning("Depth %d reached. Recursion?", depth); return; } string shift(depth * 2, ' '); - Response &httpResponse{InstanceState::get().response}; - string_buffer &coub{httpResponse.output_buffers[httpResponse.current_buffer]}; + Response& httpResponse{InstanceState::get().response}; + string_buffer& coub{httpResponse.output_buffers[httpResponse.current_buffer]}; switch (v.get_type()) { - case mixed::type::NUL: - coub << shift << "NULL"; - break; - case mixed::type::BOOLEAN: - coub << shift << "bool(" << (v.as_bool() ? "true" : "false") << ')'; - break; - case mixed::type::INTEGER: - coub << shift << "int(" << v.as_int() << ')'; - break; - case mixed::type::FLOAT: - coub << shift << "float(" << v.as_double() << ')'; - break; - case mixed::type::STRING: - coub << shift << "string(" << static_cast(v.as_string().size()) << ") \"" << v.as_string() << '"'; - break; - case mixed::type::ARRAY: { - coub << shift << "array(" << v.as_array().count() << ") {\n"; - - for (array::const_iterator it = v.as_array().begin(); it != v.as_array().end(); ++it) { - coub << shift << " ["; - if (array::is_int_key(it.get_key())) { - coub << it.get_key(); - } else { - coub << '"' << it.get_key() << '"'; - } - coub << "]=>\n"; - do_var_dump(it.get_value(), depth + 1); + case mixed::type::NUL: + coub << shift << "NULL"; + break; + case mixed::type::BOOLEAN: + coub << shift << "bool(" << (v.as_bool() ? "true" : "false") << ')'; + break; + case mixed::type::INTEGER: + coub << shift << "int(" << v.as_int() << ')'; + break; + case mixed::type::FLOAT: + coub << shift << "float(" << v.as_double() << ')'; + break; + case mixed::type::STRING: + coub << shift << "string(" << static_cast(v.as_string().size()) << ") \"" << v.as_string() << '"'; + break; + case mixed::type::ARRAY: { + coub << shift << "array(" << v.as_array().count() << ") {\n"; + + for (array::const_iterator it = v.as_array().begin(); it != v.as_array().end(); ++it) { + coub << shift << " ["; + if (array::is_int_key(it.get_key())) { + coub << it.get_key(); + } else { + coub << '"' << it.get_key() << '"'; } - - coub << shift << "}"; - break; + coub << "]=>\n"; + do_var_dump(it.get_value(), depth + 1); } - case mixed::type::OBJECT: { - php_warning("var_dump used on object"); - auto s = string(v.as_object()->get_class(), static_cast(strlen(v.as_object()->get_class()))); - coub << shift << "string(" << static_cast(s.size()) << ") \"" << s << '"'; - break; - } - default: - php_critical_error("non-exhaustive switch"); + + coub << shift << "}"; + break; + } + case mixed::type::OBJECT: { + php_warning("var_dump used on object"); + auto s = string(v.as_object()->get_class(), static_cast(strlen(v.as_object()->get_class()))); + coub << shift << "string(" << static_cast(s.size()) << ") \"" << s << '"'; + break; + } + default: + php_critical_error("non-exhaustive switch"); } coub << '\n'; } -void var_export_escaped_string(const string &s) noexcept { - Response &httpResponse{InstanceState::get().response}; - string_buffer &coub{httpResponse.output_buffers[httpResponse.current_buffer]}; +void var_export_escaped_string(const string& s) noexcept { + Response& httpResponse{InstanceState::get().response}; + string_buffer& coub{httpResponse.output_buffers[httpResponse.current_buffer]}; for (string::size_type i = 0; i < s.size(); i++) { switch (s[i]) { - case '\'': - case '\\': - coub << "\\" << s[i]; - break; - case '\0': - coub << R"(' . "\0" . ')"; - break; - default: - coub << s[i]; + case '\'': + case '\\': + coub << "\\" << s[i]; + break; + case '\0': + coub << R"(' . "\0" . ')"; + break; + default: + coub << s[i]; } } } -void do_var_export(const mixed &v, int32_t depth, char endc = 0) noexcept { +void do_var_export(const mixed& v, int32_t depth, char endc = 0) noexcept { if (depth == 10) { php_warning("Depth %d reached. Recursion?", depth); return; } string shift(depth * 2, ' '); - Response &httpResponse{InstanceState::get().response}; - string_buffer &coub{httpResponse.output_buffers[httpResponse.current_buffer]}; + Response& httpResponse{InstanceState::get().response}; + string_buffer& coub{httpResponse.output_buffers[httpResponse.current_buffer]}; switch (v.get_type()) { - case mixed::type::NUL: - coub << shift << "NULL"; - break; - case mixed::type::BOOLEAN: - coub << shift << (v.as_bool() ? "true" : "false"); - break; - case mixed::type::INTEGER: - coub << shift << v.as_int(); - break; - case mixed::type::FLOAT: - coub << shift << v.as_double(); - break; - case mixed::type::STRING: - coub << shift << '\''; - var_export_escaped_string(v.as_string()); - coub << '\''; - break; - case mixed::type::ARRAY: { - const bool is_vector = v.as_array().is_vector(); - coub << shift << "array(\n"; - - for (array::const_iterator it = v.as_array().begin(); it != v.as_array().end(); ++it) { - if (!is_vector) { - coub << shift; - if (array::is_int_key(it.get_key())) { - coub << it.get_key(); - } else { - coub << '\'' << it.get_key() << '\''; - } - coub << " =>"; - if (it.get_value().is_array()) { - coub << "\n"; - do_var_export(it.get_value(), depth + 1, ','); - } else { - do_var_export(it.get_value(), 1, ','); - } + case mixed::type::NUL: + coub << shift << "NULL"; + break; + case mixed::type::BOOLEAN: + coub << shift << (v.as_bool() ? "true" : "false"); + break; + case mixed::type::INTEGER: + coub << shift << v.as_int(); + break; + case mixed::type::FLOAT: + coub << shift << v.as_double(); + break; + case mixed::type::STRING: + coub << shift << '\''; + var_export_escaped_string(v.as_string()); + coub << '\''; + break; + case mixed::type::ARRAY: { + const bool is_vector = v.as_array().is_vector(); + coub << shift << "array(\n"; + + for (array::const_iterator it = v.as_array().begin(); it != v.as_array().end(); ++it) { + if (!is_vector) { + coub << shift; + if (array::is_int_key(it.get_key())) { + coub << it.get_key(); } else { + coub << '\'' << it.get_key() << '\''; + } + coub << " =>"; + if (it.get_value().is_array()) { + coub << "\n"; do_var_export(it.get_value(), depth + 1, ','); + } else { + do_var_export(it.get_value(), 1, ','); } + } else { + do_var_export(it.get_value(), depth + 1, ','); } - - coub << shift << ")"; - break; } - case mixed::type::OBJECT: { - coub << shift << v.get_type_or_class_name(); - break; - } - default: - php_critical_error("non-exhaustive switch"); + + coub << shift << ")"; + break; + } + case mixed::type::OBJECT: { + coub << shift << v.get_type_or_class_name(); + break; + } + default: + php_critical_error("non-exhaustive switch"); } if (endc != 0) { coub << endc; @@ -204,7 +204,7 @@ void do_var_export(const mixed &v, int32_t depth, char endc = 0) noexcept { } // namespace -string f$var_export(const mixed &v, bool buffered) noexcept { +string f$var_export(const mixed& v, bool buffered) noexcept { if (buffered) { f$ob_start(); do_var_export(v, 0); @@ -214,7 +214,7 @@ string f$var_export(const mixed &v, bool buffered) noexcept { return {}; } -string f$print_r(const mixed &v, bool buffered) noexcept { +string f$print_r(const mixed& v, bool buffered) noexcept { if (buffered) { f$ob_start(); do_print_r(v, 0); @@ -225,6 +225,4 @@ string f$print_r(const mixed &v, bool buffered) noexcept { return {}; } -void f$var_dump(const mixed &v) noexcept { - do_var_dump(v, 0); -} +void f$var_dump(const mixed& v) noexcept { do_var_dump(v, 0); } diff --git a/runtime-light/stdlib/output/print-functions.h b/runtime-light/stdlib/output/print-functions.h index 6f5a525348..7a2116255b 100644 --- a/runtime-light/stdlib/output/print-functions.h +++ b/runtime-light/stdlib/output/print-functions.h @@ -11,72 +11,60 @@ // === print ====================================================================================== -inline void print(const char *s, size_t len) noexcept { - Response &response{InstanceState::get().response}; +inline void print(const char* s, size_t len) noexcept { + Response& response{InstanceState::get().response}; response.output_buffers[response.current_buffer].append(s, len); } -inline void print(const char *s) noexcept { - print(s, strlen(s)); -} +inline void print(const char* s) noexcept { print(s, strlen(s)); } -inline void print(const string_buffer &sb) noexcept { - print(sb.buffer(), sb.size()); -} +inline void print(const string_buffer& sb) noexcept { print(sb.buffer(), sb.size()); } -inline void print(const string &s) noexcept { - print(s.c_str(), s.size()); -} +inline void print(const string& s) noexcept { print(s.c_str(), s.size()); } -inline int64_t f$print(const string &s) noexcept { +inline int64_t f$print(const string& s) noexcept { print(s); return 1; } // === print_r ==================================================================================== -string f$print_r(const mixed &v, bool buffered = false) noexcept; +string f$print_r(const mixed& v, bool buffered = false) noexcept; -template -string f$print_r(const class_instance &v, bool buffered = false) noexcept { +template +string f$print_r(const class_instance& v, bool buffered = false) noexcept { php_warning("print_r used on object"); return f$print_r(string{v.get_class(), static_cast(strlen(v.get_class()))}, buffered); } // === var_export ================================================================================= -string f$var_export(const mixed &v, bool buffered = false) noexcept; +string f$var_export(const mixed& v, bool buffered = false) noexcept; -template -string f$var_export(const class_instance &v, bool buffered = false) noexcept { +template +string f$var_export(const class_instance& v, bool buffered = false) noexcept { php_warning("print_r used on object"); return f$var_export(string{v.get_class(), static_cast(strlen(v.get_class()))}, buffered); } // === var_dump =================================================================================== -void f$var_dump(const mixed &v) noexcept; +void f$var_dump(const mixed& v) noexcept; -template -void f$var_dump(const class_instance &v) noexcept { +template +void f$var_dump(const class_instance& v) noexcept { php_warning("print_r used on object"); return f$var_dump(string{v.get_class(), static_cast(strlen(v.get_class()))}); } // ================================================================================================ -inline void f$echo(const string &s) noexcept { - print(s); -} +inline void f$echo(const string& s) noexcept { print(s); } -inline Optional f$fprintf(const mixed &, const string &, const array &) { - php_critical_error("call to unsupported function"); -} +inline Optional f$fprintf(const mixed&, const string&, const array&) { php_critical_error("call to unsupported function"); } -inline Optional f$fputcsv(const mixed &, const array &, string = string(",", 1), string = string("\"", 1), string = string("\\", 1)) { +inline Optional f$fputcsv(const mixed&, const array&, string = string(",", 1), string = string("\"", 1), string = string("\\", 1)) { php_critical_error("call to unsupported function"); } -inline int64_t f$printf(const string &, const array &) { - php_critical_error("call to unsupported function"); -} +inline int64_t f$printf(const string&, const array&) { php_critical_error("call to unsupported function"); } diff --git a/runtime-light/stdlib/rpc/rpc-api.cpp b/runtime-light/stdlib/rpc/rpc-api.cpp index 1ec956f66d..7dc8db84f5 100644 --- a/runtime-light/stdlib/rpc/rpc-api.cpp +++ b/runtime-light/stdlib/rpc/rpc-api.cpp @@ -31,28 +31,28 @@ constexpr double DEFAULT_TIMEOUT_S = 0.3; constexpr auto MAX_TIMEOUT_NS = std::chrono::duration_cast(std::chrono::duration{MAX_TIMEOUT_S}); constexpr auto DEFAULT_TIMEOUT_NS = std::chrono::duration_cast(std::chrono::duration{DEFAULT_TIMEOUT_S}); -mixed mixed_array_get_value(const mixed &arr, const string &str_key, int64_t num_key) noexcept { +mixed mixed_array_get_value(const mixed& arr, const string& str_key, int64_t num_key) noexcept { if (!arr.is_array()) { return {}; } - if (const auto &elem{arr.get_value(num_key)}; !elem.is_null()) { + if (const auto& elem{arr.get_value(num_key)}; !elem.is_null()) { return elem; } - if (const auto &elem{arr.get_value(str_key)}; !elem.is_null()) { + if (const auto& elem{arr.get_value(str_key)}; !elem.is_null()) { return elem; } return {}; } -array make_fetch_error(string &&error_msg, int32_t error_code) { +array make_fetch_error(string&& error_msg, int32_t error_code) { array res; res.set_value(string{"__error", 7}, std::move(error_msg)); res.set_value(string{"__error_code", 12}, error_code); return res; } -array fetch_function_untyped(const class_instance &rpc_query) noexcept { +array fetch_function_untyped(const class_instance& rpc_query) noexcept { php_assert(!rpc_query.is_null()); CurrentTlQuery::get().set_current_tl_function(rpc_query); auto fetcher{rpc_query.get()->result_fetcher->extract_untyped_fetcher()}; @@ -64,7 +64,7 @@ array fetch_function_untyped(const class_instance &rpc_query) return res; } -class_instance fetch_function_typed(const class_instance &rpc_query, const RpcErrorFactory &error_factory) noexcept { +class_instance fetch_function_typed(const class_instance& rpc_query, const RpcErrorFactory& error_factory) noexcept { php_assert(!rpc_query.is_null()); CurrentTlQuery::get().set_current_tl_function(rpc_query); // check if the response is error @@ -77,9 +77,9 @@ class_instance fetch_function_typed(const class_instance store_function(const mixed &tl_object) noexcept { - auto &cur_query{CurrentTlQuery::get()}; - const auto &rpc_image_state{RpcImageState::get()}; +class_instance store_function(const mixed& tl_object) noexcept { + auto& cur_query{CurrentTlQuery::get()}; + const auto& rpc_image_state{RpcImageState::get()}; const auto fun_name{mixed_array_get_value(tl_object, string{"_"}, 0).to_string()}; // TODO: constexpr ctor for string{"_"} if (!rpc_image_state.tl_storers_ht.has_key(fun_name)) { @@ -91,14 +91,14 @@ class_instance store_function(const mixed &tl_object) noexcept { rpc_tl_query.get()->tl_function_name = fun_name; cur_query.set_current_tl_function(fun_name); - const auto &untyped_storer = rpc_image_state.tl_storers_ht.get_value(fun_name); + const auto& untyped_storer = rpc_image_state.tl_storers_ht.get_value(fun_name); rpc_tl_query.get()->result_fetcher = make_unique_on_script_memory(untyped_storer(tl_object)); cur_query.reset(); return rpc_tl_query; } task_t rpc_send_impl(string actor, double timeout, bool ignore_answer, bool collect_responses_extra_info) noexcept { - auto &rpc_ctx{RpcInstanceState::get()}; + auto& rpc_ctx{RpcInstanceState::get()}; // prepare RPC request string request_buf{}; size_t request_size{rpc_ctx.rpc_buffer.size()}; @@ -110,7 +110,7 @@ task_t rpc_send_impl(string actor, double timeout, bool ignore_ans request_size = request_size - cur_extra_header_size + new_extra_header_size; request_buf.reserve_at_least(request_size); - request_buf.append(reinterpret_cast(std::addressof(new_extra_header)), new_extra_header_size); + request_buf.append(reinterpret_cast(std::addressof(new_extra_header)), new_extra_header_size); request_buf.append(rpc_ctx.rpc_buffer.data() + cur_extra_header_size, rpc_ctx.rpc_buffer.size() - cur_extra_header_size); } else { request_buf.append(rpc_ctx.rpc_buffer.data(), request_size); @@ -138,7 +138,7 @@ task_t rpc_send_impl(string actor, double timeout, bool ignore_ans const auto response{(co_await wait_with_timeout_t{task_t::awaiter_t{std::addressof(fetch_task)}, timeout}).value_or(string{})}; // update response extra info if needed if (collect_responses_extra_info) { - auto &extra_info_map{RpcInstanceState::get().rpc_responses_extra_info}; + auto& extra_info_map{RpcInstanceState::get().rpc_responses_extra_info}; if (const auto it_extra_info{extra_info_map.find(query_id)}; it_extra_info != extra_info_map.end()) { const auto timestamp{std::chrono::duration{std::chrono::system_clock::now().time_since_epoch()}.count()}; it_extra_info->second.second = std::make_tuple(response.size(), timestamp - std::get<1>(it_extra_info->second.second)); @@ -160,7 +160,7 @@ task_t rpc_send_impl(string actor, double timeout, bool ignore_ans } task_t rpc_tl_query_one_impl(string actor, mixed tl_object, double timeout, bool collect_resp_extra_info, bool ignore_answer) noexcept { - auto &rpc_ctx{RpcInstanceState::get()}; + auto& rpc_ctx{RpcInstanceState::get()}; if (!tl_object.is_array()) { rpc_ctx.current_query.raise_storing_error("not an array passed to function rpc_tl_query"); @@ -180,9 +180,9 @@ task_t rpc_tl_query_one_impl(string actor, mixed tl_object, double co_return query_info; } -task_t typed_rpc_tl_query_one_impl(string actor, const RpcRequest &rpc_request, double timeout, bool collect_responses_extra_info, +task_t typed_rpc_tl_query_one_impl(string actor, const RpcRequest& rpc_request, double timeout, bool collect_responses_extra_info, bool ignore_answer) noexcept { - auto &rpc_ctx{RpcInstanceState::get()}; + auto& rpc_ctx{RpcInstanceState::get()}; if (rpc_request.empty()) { rpc_ctx.current_query.raise_storing_error("query function is null"); @@ -212,7 +212,7 @@ task_t> rpc_tl_query_result_one_impl(int64_t query_id) noexcept { co_return make_fetch_error(string{"wrong query_id"}, TL_ERROR_WRONG_QUERY_ID); } - auto &rpc_ctx{RpcInstanceState::get()}; + auto& rpc_ctx{RpcInstanceState::get()}; class_instance rpc_query{}; int64_t response_waiter_fork_id{INVALID_FORK_ID}; @@ -254,12 +254,12 @@ task_t> rpc_tl_query_result_one_impl(int64_t query_id) noexcept { co_return fetch_function_untyped(rpc_query); } -task_t> typed_rpc_tl_query_result_one_impl(int64_t query_id, const RpcErrorFactory &error_factory) noexcept { +task_t> typed_rpc_tl_query_result_one_impl(int64_t query_id, const RpcErrorFactory& error_factory) noexcept { if (query_id < RPC_VALID_QUERY_ID_RANGE_START) { co_return error_factory.make_error(string{"wrong query_id"}, TL_ERROR_WRONG_QUERY_ID); } - auto &rpc_ctx{RpcInstanceState::get()}; + auto& rpc_ctx{RpcInstanceState::get()}; class_instance rpc_query{}; int64_t response_waiter_fork_id{INVALID_FORK_ID}; @@ -328,28 +328,20 @@ bool f$store_double(double v) noexcept { return true; } -bool f$store_string(const string &v) noexcept { +bool f$store_string(const string& v) noexcept { RpcInstanceState::get().rpc_buffer.store_string(std::string_view{v.c_str(), v.size()}); return true; } // === Rpc Fetch ================================================================================== -int64_t f$fetch_int() noexcept { - return static_cast(RpcInstanceState::get().rpc_buffer.fetch_trivial().value_or(0)); -} +int64_t f$fetch_int() noexcept { return static_cast(RpcInstanceState::get().rpc_buffer.fetch_trivial().value_or(0)); } -int64_t f$fetch_long() noexcept { - return RpcInstanceState::get().rpc_buffer.fetch_trivial().value_or(0); -} +int64_t f$fetch_long() noexcept { return RpcInstanceState::get().rpc_buffer.fetch_trivial().value_or(0); } -double f$fetch_double() noexcept { - return RpcInstanceState::get().rpc_buffer.fetch_trivial().value_or(0.0); -} +double f$fetch_double() noexcept { return RpcInstanceState::get().rpc_buffer.fetch_trivial().value_or(0.0); } -double f$fetch_float() noexcept { - return static_cast(RpcInstanceState::get().rpc_buffer.fetch_trivial().value_or(0)); -} +double f$fetch_float() noexcept { return static_cast(RpcInstanceState::get().rpc_buffer.fetch_trivial().value_or(0)); } string f$fetch_string() noexcept { const std::string_view str{RpcInstanceState::get().rpc_buffer.fetch_string()}; @@ -368,7 +360,7 @@ task_t> f$rpc_send_requests(string actor, array tl_objects array query_ids{tl_objects.size()}; array req_extra_info_arr{tl_objects.size()}; - for (const auto &it : tl_objects) { + for (const auto& it : tl_objects) { const auto query_info{co_await rpc_impl_::rpc_tl_query_one_impl(actor, it.get_value(), timeout, collect_resp_extra_info, ignore_answer)}; query_ids.set_value(it.get_key(), query_info.id); req_extra_info_arr.set_value(it.get_key(), rpc_request_extra_info_t{query_info.request_size}); @@ -382,7 +374,7 @@ task_t> f$rpc_send_requests(string actor, array tl_objects task_t>> f$rpc_fetch_responses(array query_ids) noexcept { array> res{query_ids.size()}; - for (const auto &it : query_ids) { + for (const auto& it : query_ids) { res.set_value(it.get_key(), co_await rpc_impl_::rpc_tl_query_result_one_impl(it.get_value())); } co_return res; @@ -390,9 +382,7 @@ task_t>> f$rpc_fetch_responses(array query_ids) noex // === Rpc Misc ================================================================================== -void f$rpc_clean() noexcept { - RpcInstanceState::get().rpc_buffer.clean(); -} +void f$rpc_clean() noexcept { RpcInstanceState::get().rpc_buffer.clean(); } // === Misc ======================================================================================= @@ -404,13 +394,13 @@ bool is_int32_overflow(int64_t v) noexcept { return vk::none_of_equal(v, int64_t{v32}, int64_t{static_cast(v32)}); } -void store_raw_vector_double(const array &vector) noexcept { // TODO: didn't we forget vector's length? - const std::string_view vector_view{reinterpret_cast(vector.get_const_vector_pointer()), sizeof(double) * vector.count()}; +void store_raw_vector_double(const array& vector) noexcept { // TODO: didn't we forget vector's length? + const std::string_view vector_view{reinterpret_cast(vector.get_const_vector_pointer()), sizeof(double) * vector.count()}; RpcInstanceState::get().rpc_buffer.store_bytes(vector_view); } -void fetch_raw_vector_double(array &vector, int64_t num_elems) noexcept { - auto &rpc_buf{RpcInstanceState::get().rpc_buffer}; +void fetch_raw_vector_double(array& vector, int64_t num_elems) noexcept { + auto& rpc_buf{RpcInstanceState::get().rpc_buffer}; const auto len_bytes{sizeof(double) * num_elems}; if (rpc_buf.remaining() < len_bytes) { return; // TODO: error handling diff --git a/runtime-light/stdlib/rpc/rpc-api.h b/runtime-light/stdlib/rpc/rpc-api.h index 4fac53b8d7..37662327f3 100644 --- a/runtime-light/stdlib/rpc/rpc-api.h +++ b/runtime-light/stdlib/rpc/rpc-api.h @@ -26,10 +26,10 @@ struct RpcQueryInfo { double timestamp{0.0}; }; -task_t typed_rpc_tl_query_one_impl(string actor, const RpcRequest &rpc_request, double timeout, bool collect_responses_extra_info, +task_t typed_rpc_tl_query_one_impl(string actor, const RpcRequest& rpc_request, double timeout, bool collect_responses_extra_info, bool ignore_answer) noexcept; -task_t> typed_rpc_tl_query_result_one_impl(int64_t query_id, const RpcErrorFactory &error_factory) noexcept; +task_t> typed_rpc_tl_query_result_one_impl(int64_t query_id, const RpcErrorFactory& error_factory) noexcept; } // namespace rpc_impl_ @@ -43,7 +43,7 @@ bool f$store_float(double v) noexcept; bool f$store_double(double v) noexcept; -bool f$store_string(const string &v) noexcept; +bool f$store_string(const string& v) noexcept; // === Rpc Fetch ================================================================================== @@ -63,7 +63,7 @@ task_t> f$rpc_send_requests(string actor, array tl_objects class_instance requests_extra_info = {}, bool need_responses_extra_info = false) noexcept; -template rpc_function_t, std::same_as rpc_request_t = KphpRpcRequest> +template rpc_function_t, std::same_as rpc_request_t = KphpRpcRequest> task_t> f$rpc_send_typed_query_requests(string actor, array> query_functions, double timeout = -1.0, bool ignore_answer = false, class_instance requests_extra_info = {}, bool need_responses_extra_info = false) noexcept { @@ -75,9 +75,9 @@ task_t> f$rpc_send_typed_query_requests(string actor, array query_ids{query_functions.size()}; array req_extra_info_arr{query_functions.size()}; - for (const auto &it : query_functions) { + for (const auto& it : query_functions) { const auto query_info{ - co_await rpc_impl_::typed_rpc_tl_query_one_impl(actor, rpc_request_t{it.get_value()}, timeout, collect_resp_extra_info, ignore_answer)}; + co_await rpc_impl_::typed_rpc_tl_query_one_impl(actor, rpc_request_t{it.get_value()}, timeout, collect_resp_extra_info, ignore_answer)}; query_ids.set_value(it.get_key(), query_info.id); req_extra_info_arr.set_value(it.get_key(), rpc_request_extra_info_t{query_info.request_size}); } @@ -90,39 +90,39 @@ task_t> f$rpc_send_typed_query_requests(string actor, array>> f$rpc_fetch_responses(array query_ids) noexcept; -template query_id_t = int64_t, std::same_as error_factory_t = RpcResponseErrorFactory> -requires std::default_initializable task_t>> -f$rpc_fetch_typed_responses(array query_ids) noexcept { +template query_id_t = int64_t, std::same_as error_factory_t = RpcResponseErrorFactory> +requires std::default_initializable +task_t>> f$rpc_fetch_typed_responses(array query_ids) noexcept { array> res{query_ids.size()}; - for (const auto &it : query_ids) { + for (const auto& it : query_ids) { res.set_value(it.get_key(), co_await rpc_impl_::typed_rpc_tl_query_result_one_impl(it.get_value(), error_factory_t{})); } co_return res; } -template query_id_t = int64_t, std::same_as error_factory_t = RpcResponseErrorFactory> -requires std::default_initializable task_t>> -f$rpc_fetch_typed_responses_synchronously(array query_ids) noexcept { +template query_id_t = int64_t, std::same_as error_factory_t = RpcResponseErrorFactory> +requires std::default_initializable +task_t>> f$rpc_fetch_typed_responses_synchronously(array query_ids) noexcept { co_return co_await f$rpc_fetch_typed_responses(std::move(query_ids)); } -template query_id_t = int64_t, std::same_as error_factory_t = RpcResponseErrorFactory> -requires std::default_initializable task_t>> -f$typed_rpc_tl_query_result_synchronously(array query_ids) noexcept { +template query_id_t = int64_t, std::same_as error_factory_t = RpcResponseErrorFactory> +requires std::default_initializable +task_t>> f$typed_rpc_tl_query_result_synchronously(array query_ids) noexcept { co_return co_await f$rpc_fetch_typed_responses_synchronously(std::move(query_ids)); } -template -task_t>> f$rpc_tl_query_result(const array &) { +template +task_t>> f$rpc_tl_query_result(const array&) { php_critical_error("call to unsupported function"); } -template -array> f$rpc_tl_query_result_synchronously(const array &) { +template +array> f$rpc_tl_query_result_synchronously(const array&) { php_critical_error("call to unsupported function"); } -inline task_t> f$rpc_tl_query(const class_instance &, const array &, double = -1.0, bool = false, +inline task_t> f$rpc_tl_query(const class_instance&, const array&, double = -1.0, bool = false, class_instance = {}, bool = false) { php_critical_error("call to unsupported function"); } @@ -135,11 +135,11 @@ void f$rpc_clean() noexcept; bool is_int32_overflow(int64_t v) noexcept; -void store_raw_vector_double(const array &vector) noexcept; +void store_raw_vector_double(const array& vector) noexcept; -void fetch_raw_vector_double(array &vector, int64_t num_elems) noexcept; +void fetch_raw_vector_double(array& vector, int64_t num_elems) noexcept; -template +template bool f$rpc_parse(T) { php_critical_error("call to unsupported function"); } diff --git a/runtime-light/stdlib/rpc/rpc-extra-headers.cpp b/runtime-light/stdlib/rpc/rpc-extra-headers.cpp index 6c35e07a5a..e22a8b6bb9 100644 --- a/runtime-light/stdlib/rpc/rpc-extra-headers.cpp +++ b/runtime-light/stdlib/rpc/rpc-extra-headers.cpp @@ -17,8 +17,8 @@ constexpr uint32_t EMPTY_FLAGS = 0x0; } // namespace -std::pair, uint32_t> regularize_extra_headers(const char *rpc_payload, bool ignore_result) noexcept { - const auto magic{*reinterpret_cast(rpc_payload)}; +std::pair, uint32_t> regularize_extra_headers(const char* rpc_payload, bool ignore_result) noexcept { + const auto magic{*reinterpret_cast(rpc_payload)}; if (vk::none_of_equal(magic, TL_RPC_DEST_ACTOR, TL_RPC_DEST_FLAGS, TL_RPC_DEST_ACTOR_FLAGS)) { return {std::nullopt, 0}; } @@ -27,28 +27,28 @@ std::pair, uint32_t> regularize_extra_he uint32_t cur_extra_header_flags{EMPTY_FLAGS}; int64_t cur_extra_header_actor_id{EXPECTED_ACTOR_ID}; switch (magic) { - case TL_RPC_DEST_ACTOR_FLAGS: { - cur_extra_header_size = sizeof(RpcDestActorFlagsHeaders); - const auto cur_wrapper{*reinterpret_cast(rpc_payload)}; - cur_extra_header_flags = cur_wrapper.flags; - cur_extra_header_actor_id = cur_wrapper.actor_id; - break; - } - case TL_RPC_DEST_ACTOR: { - cur_extra_header_size = sizeof(RpcDestActorHeaders); - const auto cur_wrapper{*reinterpret_cast(rpc_payload)}; - cur_extra_header_actor_id = cur_wrapper.actor_id; - break; - } - case TL_RPC_DEST_FLAGS: { - cur_extra_header_size = sizeof(RpcDestFlagsHeaders); - const auto cur_wrapper{*reinterpret_cast(rpc_payload)}; - cur_extra_header_flags = cur_wrapper.flags; - break; - } - default: { - php_critical_error("unreachable path"); - } + case TL_RPC_DEST_ACTOR_FLAGS: { + cur_extra_header_size = sizeof(RpcDestActorFlagsHeaders); + const auto cur_wrapper{*reinterpret_cast(rpc_payload)}; + cur_extra_header_flags = cur_wrapper.flags; + cur_extra_header_actor_id = cur_wrapper.actor_id; + break; + } + case TL_RPC_DEST_ACTOR: { + cur_extra_header_size = sizeof(RpcDestActorHeaders); + const auto cur_wrapper{*reinterpret_cast(rpc_payload)}; + cur_extra_header_actor_id = cur_wrapper.actor_id; + break; + } + case TL_RPC_DEST_FLAGS: { + cur_extra_header_size = sizeof(RpcDestFlagsHeaders); + const auto cur_wrapper{*reinterpret_cast(rpc_payload)}; + cur_extra_header_flags = cur_wrapper.flags; + break; + } + default: { + php_critical_error("unreachable path"); + } } if (cur_extra_header_actor_id != EXPECTED_ACTOR_ID) { diff --git a/runtime-light/stdlib/rpc/rpc-extra-headers.h b/runtime-light/stdlib/rpc/rpc-extra-headers.h index dada642143..29cf5a2458 100644 --- a/runtime-light/stdlib/rpc/rpc-extra-headers.h +++ b/runtime-light/stdlib/rpc/rpc-extra-headers.h @@ -35,4 +35,4 @@ struct RpcDestFlagsHeaders { * 3) return \ pair. * Otherwise, return \. * */ -std::pair, uint32_t> regularize_extra_headers(const char *rpc_payload, bool ignore_result) noexcept; +std::pair, uint32_t> regularize_extra_headers(const char* rpc_payload, bool ignore_result) noexcept; diff --git a/runtime-light/stdlib/rpc/rpc-extra-info.cpp b/runtime-light/stdlib/rpc/rpc-extra-info.cpp index 6ea409f2b3..3dda798a66 100644 --- a/runtime-light/stdlib/rpc/rpc-extra-info.cpp +++ b/runtime-light/stdlib/rpc/rpc-extra-info.cpp @@ -8,9 +8,7 @@ #include "common/wrappers/string_view.h" #include "runtime-light/stdlib/rpc/rpc-state.h" -const char *C$KphpRpcRequestsExtraInfo::get_class() const noexcept { - return R"(KphpRpcRequestsExtraInfo)"; -} +const char* C$KphpRpcRequestsExtraInfo::get_class() const noexcept { return R"(KphpRpcRequestsExtraInfo)"; } int C$KphpRpcRequestsExtraInfo::get_hash() const noexcept { return static_cast(vk::std_hash(vk::string_view(C$KphpRpcRequestsExtraInfo::get_class()))); @@ -21,7 +19,7 @@ array f$KphpRpcRequestsExtraInfo$$get(class_instance f$extract_kphp_rpc_response_extra_info(int64_t query_id) noexcept { - auto &extra_info_map{RpcInstanceState::get().rpc_responses_extra_info}; + auto& extra_info_map{RpcInstanceState::get().rpc_responses_extra_info}; if (const auto it{extra_info_map.find(query_id)}; it != extra_info_map.end() && it->second.first == rpc_response_extra_info_status_t::READY) { const auto extra_info{it->second.second}; extra_info_map.erase(it); diff --git a/runtime-light/stdlib/rpc/rpc-extra-info.h b/runtime-light/stdlib/rpc/rpc-extra-info.h index 427f6fff23..080812f089 100644 --- a/runtime-light/stdlib/rpc/rpc-extra-info.h +++ b/runtime-light/stdlib/rpc/rpc-extra-info.h @@ -22,7 +22,7 @@ struct C$KphpRpcRequestsExtraInfo final : public refcountable_php_classes extra_info_arr; C$KphpRpcRequestsExtraInfo() = default; - const char *get_class() const noexcept; + const char* get_class() const noexcept; int get_hash() const noexcept; }; diff --git a/runtime-light/stdlib/rpc/rpc-state.cpp b/runtime-light/stdlib/rpc/rpc-state.cpp index 13ddfec80a..588bf369e4 100644 --- a/runtime-light/stdlib/rpc/rpc-state.cpp +++ b/runtime-light/stdlib/rpc/rpc-state.cpp @@ -7,14 +7,8 @@ #include "runtime-light/state/image-state.h" #include "runtime-light/state/instance-state.h" -RpcInstanceState &RpcInstanceState::get() noexcept { - return InstanceState::get().rpc_instance_state; -} +RpcInstanceState& RpcInstanceState::get() noexcept { return InstanceState::get().rpc_instance_state; } -const RpcImageState &RpcImageState::get() noexcept { - return ImageState::get().rpc_image_state; -} +const RpcImageState& RpcImageState::get() noexcept { return ImageState::get().rpc_image_state; } -RpcImageState &RpcImageState::get_mutable() noexcept { - return ImageState::get_mutable().rpc_image_state; -} +RpcImageState& RpcImageState::get_mutable() noexcept { return ImageState::get_mutable().rpc_image_state; } diff --git a/runtime-light/stdlib/rpc/rpc-state.h b/runtime-light/stdlib/rpc/rpc-state.h index 25c3cbd298..f838654b2c 100644 --- a/runtime-light/stdlib/rpc/rpc-state.h +++ b/runtime-light/stdlib/rpc/rpc-state.h @@ -16,7 +16,7 @@ #include "runtime-light/tl/tl-core.h" struct RpcInstanceState final : private vk::not_copyable { - template + template using unordered_map = memory_resource::stl::unordered_map; tl::TLBuffer rpc_buffer; @@ -26,14 +26,13 @@ struct RpcInstanceState final : private vk::not_copyable { unordered_map> response_fetcher_instances; unordered_map> rpc_responses_extra_info; - explicit RpcInstanceState(memory_resource::unsynchronized_pool_resource &memory_resource) noexcept - : current_query() - , response_waiter_forks(unordered_map::allocator_type{memory_resource}) - , response_fetcher_instances(unordered_map>::allocator_type{memory_resource}) - , rpc_responses_extra_info( - unordered_map>::allocator_type{memory_resource}) {} + explicit RpcInstanceState(memory_resource::unsynchronized_pool_resource& memory_resource) noexcept + : current_query(), response_waiter_forks(unordered_map::allocator_type{memory_resource}), + response_fetcher_instances(unordered_map>::allocator_type{memory_resource}), + rpc_responses_extra_info( + unordered_map>::allocator_type{memory_resource}) {} - static RpcInstanceState &get() noexcept; + static RpcInstanceState& get() noexcept; }; // ================================================================================================ @@ -42,6 +41,6 @@ struct RpcImageState final : private vk::not_copyable { array tl_storers_ht; tl_fetch_wrapper_ptr tl_fetch_wrapper{nullptr}; - static const RpcImageState &get() noexcept; - static RpcImageState &get_mutable() noexcept; + static const RpcImageState& get() noexcept; + static RpcImageState& get_mutable() noexcept; }; diff --git a/runtime-light/stdlib/rpc/rpc-tl-defs.h b/runtime-light/stdlib/rpc/rpc-tl-defs.h index b695f18f46..da7dc2fde0 100644 --- a/runtime-light/stdlib/rpc/rpc-tl-defs.h +++ b/runtime-light/stdlib/rpc/rpc-tl-defs.h @@ -12,29 +12,26 @@ #include "runtime-light/stdlib/rpc/rpc-tl-function.h" using tl_undefined_php_type = std::nullptr_t; -using tl_storer_ptr = std::unique_ptr (*)(const mixed &); +using tl_storer_ptr = std::unique_ptr (*)(const mixed&); using tl_fetch_wrapper_ptr = array (*)(std::unique_ptr); struct tl_exclamation_fetch_wrapper { std::unique_ptr fetcher; - explicit tl_exclamation_fetch_wrapper(std::unique_ptr fetcher) - : fetcher(std::move(fetcher)) {} + explicit tl_exclamation_fetch_wrapper(std::unique_ptr fetcher) : fetcher(std::move(fetcher)) {} tl_exclamation_fetch_wrapper() noexcept = default; - tl_exclamation_fetch_wrapper(const tl_exclamation_fetch_wrapper &) = delete; - tl_exclamation_fetch_wrapper(tl_exclamation_fetch_wrapper &&) noexcept = default; - tl_exclamation_fetch_wrapper &operator=(const tl_exclamation_fetch_wrapper &) = delete; - tl_exclamation_fetch_wrapper &operator=(tl_exclamation_fetch_wrapper &&) noexcept = delete; + tl_exclamation_fetch_wrapper(const tl_exclamation_fetch_wrapper&) = delete; + tl_exclamation_fetch_wrapper(tl_exclamation_fetch_wrapper&&) noexcept = default; + tl_exclamation_fetch_wrapper& operator=(const tl_exclamation_fetch_wrapper&) = delete; + tl_exclamation_fetch_wrapper& operator=(tl_exclamation_fetch_wrapper&&) noexcept = delete; ~tl_exclamation_fetch_wrapper() = default; - mixed fetch() const { - return fetcher->fetch(); - } + mixed fetch() const { return fetcher->fetch(); } using PhpType = class_instance; - void typed_fetch_to(PhpType &out) const { + void typed_fetch_to(PhpType& out) const { php_assert(fetcher); out = fetcher->typed_fetch(); } diff --git a/runtime-light/stdlib/rpc/rpc-tl-error.cpp b/runtime-light/stdlib/rpc/rpc-tl-error.cpp index b1299f76b6..4874d780c8 100644 --- a/runtime-light/stdlib/rpc/rpc-tl-error.cpp +++ b/runtime-light/stdlib/rpc/rpc-tl-error.cpp @@ -71,7 +71,7 @@ void TlRpcError::fetch_and_skip_header() const noexcept { } } -class_instance RpcErrorFactory::make_error(const char *error, int32_t error_code) const noexcept { +class_instance RpcErrorFactory::make_error(const char* error, int32_t error_code) const noexcept { return make_error(string{error}, error_code); } diff --git a/runtime-light/stdlib/rpc/rpc-tl-error.h b/runtime-light/stdlib/rpc/rpc-tl-error.h index a00aedc70f..62299c9132 100644 --- a/runtime-light/stdlib/rpc/rpc-tl-error.h +++ b/runtime-light/stdlib/rpc/rpc-tl-error.h @@ -21,9 +21,9 @@ struct TlRpcError { class RpcErrorFactory { public: - virtual class_instance make_error(const string &error, int32_t error_code) const noexcept = 0; + virtual class_instance make_error(const string& error, int32_t error_code) const noexcept = 0; - class_instance make_error(const char *error, int32_t error_code) const noexcept; + class_instance make_error(const char* error, int32_t error_code) const noexcept; class_instance make_error_from_exception_if_possible() const noexcept; class_instance fetch_error_if_possible() const noexcept; @@ -33,12 +33,12 @@ class RpcErrorFactory { namespace tl_rpc_error_impl_ { // use template, because _common\Types\rpcResponseError is unknown on runtime compilation -template +template struct RpcResponseErrorFactory : public RpcErrorFactory { RpcResponseErrorFactory() = default; private: - class_instance make_error(const string &error, int32_t error_code) const noexcept final { + class_instance make_error(const string& error, int32_t error_code) const noexcept final { auto err{make_instance()}; err.get()->$error = error; err.get()->$error_code = error_code; diff --git a/runtime-light/stdlib/rpc/rpc-tl-func-base.h b/runtime-light/stdlib/rpc/rpc-tl-func-base.h index 2e62a41c1d..2680a0c36a 100644 --- a/runtime-light/stdlib/rpc/rpc-tl-func-base.h +++ b/runtime-light/stdlib/rpc/rpc-tl-func-base.h @@ -19,7 +19,7 @@ struct tl_func_base : ScriptAllocatorManaged { return {}; } - virtual void rpc_server_typed_store([[maybe_unused]] const class_instance &res) { + virtual void rpc_server_typed_store([[maybe_unused]] const class_instance& res) { // all functions annotated with @kphp will override this method with the generated code php_critical_error("This function should never be called. Should be overridden in every @kphp TL function"); } diff --git a/runtime-light/stdlib/rpc/rpc-tl-function.h b/runtime-light/stdlib/rpc/rpc-tl-function.h index 272633c8a5..cbd5897727 100644 --- a/runtime-light/stdlib/rpc/rpc-tl-function.h +++ b/runtime-light/stdlib/rpc/rpc-tl-function.h @@ -24,25 +24,17 @@ class InstanceDeepDestroyVisitor; // this interface is implemented by all PHP classes that represent the TL functions (see tl-to-php) struct C$VK$TL$RpcFunction : abstract_refcountable_php_interface { - virtual const char *get_class() const { - return "VK\\TL\\RpcFunction"; - } - virtual int32_t get_hash() const { - return static_cast(vk::std_hash(vk::string_view(C$VK$TL$RpcFunction::get_class()))); - } - - virtual void accept(ToArrayVisitor &) noexcept {} - virtual void accept(CommonMemoryEstimateVisitor &) noexcept {} - virtual void accept(InstanceReferencesCountingVisitor &) noexcept {} - virtual void accept(InstanceDeepCopyVisitor &) noexcept {} - virtual void accept(InstanceDeepDestroyVisitor &) noexcept {} - - virtual size_t virtual_builtin_sizeof() const noexcept { - return 0; - } - virtual C$VK$TL$RpcFunction *virtual_builtin_clone() const noexcept { - return nullptr; - } + virtual const char* get_class() const { return "VK\\TL\\RpcFunction"; } + virtual int32_t get_hash() const { return static_cast(vk::std_hash(vk::string_view(C$VK$TL$RpcFunction::get_class()))); } + + virtual void accept(ToArrayVisitor&) noexcept {} + virtual void accept(CommonMemoryEstimateVisitor&) noexcept {} + virtual void accept(InstanceReferencesCountingVisitor&) noexcept {} + virtual void accept(InstanceDeepCopyVisitor&) noexcept {} + virtual void accept(InstanceDeepDestroyVisitor&) noexcept {} + + virtual size_t virtual_builtin_sizeof() const noexcept { return 0; } + virtual C$VK$TL$RpcFunction* virtual_builtin_clone() const noexcept { return nullptr; } ~C$VK$TL$RpcFunction() override = default; virtual std::unique_ptr store() const = 0; @@ -51,25 +43,17 @@ struct C$VK$TL$RpcFunction : abstract_refcountable_php_interface { // every TL function has a class for the result that implements RpcFunctionReturnResult; // which has ->value of the required type struct C$VK$TL$RpcFunctionReturnResult : abstract_refcountable_php_interface { - virtual const char *get_class() const { - return "VK\\TL\\RpcFunctionReturnResult"; - } - virtual int32_t get_hash() const { - return static_cast(vk::std_hash(vk::string_view(C$VK$TL$RpcFunctionReturnResult::get_class()))); - } - - virtual void accept(ToArrayVisitor &) noexcept {} - virtual void accept(CommonMemoryEstimateVisitor &) noexcept {} - virtual void accept(InstanceReferencesCountingVisitor &) noexcept {} - virtual void accept(InstanceDeepCopyVisitor &) noexcept {} - virtual void accept(InstanceDeepDestroyVisitor &) noexcept {} - - virtual size_t virtual_builtin_sizeof() const noexcept { - return 0; - } - virtual C$VK$TL$RpcFunctionReturnResult *virtual_builtin_clone() const noexcept { - return nullptr; - } + virtual const char* get_class() const { return "VK\\TL\\RpcFunctionReturnResult"; } + virtual int32_t get_hash() const { return static_cast(vk::std_hash(vk::string_view(C$VK$TL$RpcFunctionReturnResult::get_class()))); } + + virtual void accept(ToArrayVisitor&) noexcept {} + virtual void accept(CommonMemoryEstimateVisitor&) noexcept {} + virtual void accept(InstanceReferencesCountingVisitor&) noexcept {} + virtual void accept(InstanceDeepCopyVisitor&) noexcept {} + virtual void accept(InstanceDeepDestroyVisitor&) noexcept {} + + virtual size_t virtual_builtin_sizeof() const noexcept { return 0; } + virtual C$VK$TL$RpcFunctionReturnResult* virtual_builtin_clone() const noexcept { return nullptr; } ~C$VK$TL$RpcFunctionReturnResult() override = default; }; @@ -79,25 +63,17 @@ struct C$VK$TL$RpcFunctionReturnResult : abstract_refcountable_php_interface { struct C$VK$TL$RpcResponse : abstract_refcountable_php_interface { using X = class_instance; - virtual void accept(ToArrayVisitor &) noexcept {} - virtual void accept(CommonMemoryEstimateVisitor &) noexcept {} - virtual void accept(InstanceReferencesCountingVisitor &) noexcept {} - virtual void accept(InstanceDeepCopyVisitor &) noexcept {} - virtual void accept(InstanceDeepDestroyVisitor &) noexcept {} - - virtual const char *get_class() const { - return "VK\\TL\\RpcResponse"; - } - virtual int32_t get_hash() const { - return static_cast(vk::std_hash(vk::string_view(C$VK$TL$RpcResponse::get_class()))); - } - - virtual size_t virtual_builtin_sizeof() const noexcept { - return 0; - } - virtual C$VK$TL$RpcResponse *virtual_builtin_clone() const noexcept { - return nullptr; - } + virtual void accept(ToArrayVisitor&) noexcept {} + virtual void accept(CommonMemoryEstimateVisitor&) noexcept {} + virtual void accept(InstanceReferencesCountingVisitor&) noexcept {} + virtual void accept(InstanceDeepCopyVisitor&) noexcept {} + virtual void accept(InstanceDeepDestroyVisitor&) noexcept {} + + virtual const char* get_class() const { return "VK\\TL\\RpcResponse"; } + virtual int32_t get_hash() const { return static_cast(vk::std_hash(vk::string_view(C$VK$TL$RpcResponse::get_class()))); } + + virtual size_t virtual_builtin_sizeof() const noexcept { return 0; } + virtual C$VK$TL$RpcResponse* virtual_builtin_clone() const noexcept { return nullptr; } ~C$VK$TL$RpcResponse() override = default; }; diff --git a/runtime-light/stdlib/rpc/rpc-tl-kphp-request.h b/runtime-light/stdlib/rpc/rpc-tl-kphp-request.h index deaddb4027..ddcd8ac482 100644 --- a/runtime-light/stdlib/rpc/rpc-tl-kphp-request.h +++ b/runtime-light/stdlib/rpc/rpc-tl-kphp-request.h @@ -13,13 +13,12 @@ namespace tl_rpc_request_impl_ { // use template, because t_ReqResult_ is unknown on runtime compilation -template class t_ReqResult_> +template