diff --git a/DEPS b/DEPS index e30e409..94f802b 100644 --- a/DEPS +++ b/DEPS
@@ -261,11 +261,11 @@ 'reclient_version': 're_client_version:0.177.1.e58c0145-gomaip', # screen-ai CIPD packages - 'screen_ai_linux': 'version:127.21', - 'screen_ai_macos_amd64': 'version:127.21', - 'screen_ai_macos_arm64': 'version:127.21', - 'screen_ai_windows_amd64': 'version:127.21', - 'screen_ai_windows_386': 'version:127.21', + 'screen_ai_linux': 'version:127.24', + 'screen_ai_macos_amd64': 'version:127.24', + 'screen_ai_macos_arm64': 'version:127.24', + 'screen_ai_windows_amd64': 'version:127.24', + 'screen_ai_windows_386': 'version:127.24', # siso CIPD package version. 'siso_version': 'git_revision:ae99e5f46d1fbc718ad9c28bb82c16883d7de99b', @@ -291,19 +291,19 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling V8 # and whatever else without interference from each other. - 'src_internal_revision': 'b9a65e19474a3e02829e57463335f99df7b6939a', + 'src_internal_revision': '41278638c9719c44d0c524460a0ed2d6ba96be4c', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling Skia # and whatever else without interference from each other. - 'skia_revision': '22f5a70db6b391890418db99f8b00f7a9be48b5f', + 'skia_revision': '1e80d35a4d444ebea76749d1399ef8bd8ea7cabf', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling V8 # and whatever else without interference from each other. - 'v8_revision': 'f96f20ad4151649e8ecc9f12ac2ccfd9cb1cc226', + 'v8_revision': '570c6a0c527c3df6a3413051a06128c2699b235d', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling ANGLE # and whatever else without interference from each other. - 'angle_revision': 'a4d4a7735efc9c1e367867f73568e4fb0a8f1a66', + 'angle_revision': '1166eec4c0b125e9e945196acfc549983ef72b18', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling SwiftShader # and whatever else without interference from each other. @@ -387,7 +387,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling devtools-frontend # and whatever else without interference from each other. - 'devtools_frontend_revision': '22ebcbc1b76b65436c8dc57536f2c2a0aac7675d', + 'devtools_frontend_revision': '3353eedcf87f8f80af884cfd867006b89d0b961b', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling libprotobuf-mutator # and whatever else without interference from each other. @@ -411,7 +411,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. - 'dawn_revision': '516500a25109a6f42705c912e7bc72b8a0364c7d', + 'dawn_revision': '46d76d4aad3b9e3c84dbf0d9565f3b7bdabd3434', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. @@ -1145,7 +1145,7 @@ }, 'src/chrome/release_scripts': { - 'url': Var('chrome_git') + '/chrome/tools/release/scripts' + '@' + '7bc6ee818946760972db2112e46f97b5ea0fe1dd', + 'url': Var('chrome_git') + '/chrome/tools/release/scripts' + '@' + '4cee7d5d76a131b09b4f80dea737b1aecbe66dd4', 'condition': 'checkout_chrome_release_scripts', }, @@ -1473,7 +1473,7 @@ 'packages': [ { 'package': 'chromium/chrome/test/data/variations/cipd', - 'version': 'vsQNm5ormTjqzesXkNAXRdrSNOUJBdNlo-_hxM1bOyoC', + 'version': '35nPWbImP04Anxz4_HokzvKbtelNgH289jMXC1SDHZcC', }, ], 'dep_type': 'cipd', @@ -1484,7 +1484,7 @@ 'src/clank': { 'url': Var('chrome_git') + '/clank/internal/apps.git' + '@' + - '6b91d2bd0932898c7335092d8cb758efacbd61c8', + '3caed26bf65373a93272f352981764ff9e3b6209', 'condition': 'checkout_android and checkout_src_internal', }, @@ -1946,7 +1946,7 @@ # Tools used when building Chrome for Chrome OS. This affects both the Simple # Chrome workflow, as well as the chromeos-chrome ebuild. 'src/third_party/chromite': { - 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + '4bf6cc9908997fa11eb71f6969741ce49b676aca', + 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + '295110e661c6392bfc34ec77edd7c5910ea604d8', 'condition': 'checkout_chromeos', }, @@ -2524,7 +2524,7 @@ Var('pdfium_git') + '/pdfium.git' + '@' + Var('pdfium_revision'), 'src/third_party/perfetto': - Var('android_git') + '/platform/external/perfetto.git' + '@' + '7da1b1676f326e67cc3eb38774daf3154f876fd0', + Var('android_git') + '/platform/external/perfetto.git' + '@' + 'ea324cfbfd21cbbfbc1122e33575ab24b81cecbe', 'src/base/tracing/test/data': { 'bucket': 'perfetto', @@ -2892,7 +2892,7 @@ Var('chromium_git') + '/webpagereplay.git' + '@' + Var('webpagereplay_revision'), 'src/third_party/webrtc': - Var('webrtc_git') + '/src.git' + '@' + '03d202cd0fcc5dfaa030dac5178629db3f1ab931', + Var('webrtc_git') + '/src.git' + '@' + 'f14533349fc3ebcbf82ac8a371abef69ec4acdd8', # Wuffs' canonical repository is at github.com/google/wuffs, but we use # Skia's mirror of Wuffs, the same as in upstream Skia's DEPS file. @@ -4681,7 +4681,7 @@ 'src/ios_internal': { 'url': Var('chrome_git') + '/chrome/ios_internal.git' + '@' + - '41d60aadfdbde1077d2704420cd0c9ac52bbeec9', + 'f1cb064c6da4d2ef42d1f268c13d2ac07f5ae740', 'condition': 'checkout_ios and checkout_src_internal', },
diff --git a/android_webview/browser/network_service/aw_proxying_restricted_cookie_manager.cc b/android_webview/browser/network_service/aw_proxying_restricted_cookie_manager.cc index 55a9c798..25583e51 100644 --- a/android_webview/browser/network_service/aw_proxying_restricted_cookie_manager.cc +++ b/android_webview/browser/network_service/aw_proxying_restricted_cookie_manager.cc
@@ -143,6 +143,7 @@ const url::Origin& top_frame_origin, net::StorageAccessApiStatus storage_access_api_status, net::CookieInclusionStatus status, + bool is_ad_tagged, bool apply_devtools_overrides, SetCanonicalCookieCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); @@ -157,8 +158,8 @@ if (cookie.IsPartitioned() || cookieState == PrivacySetting::kStateAllowed) { underlying_restricted_cookie_manager_->SetCanonicalCookie( cookie, url, site_for_cookies, top_frame_origin, - storage_access_api_status, status, apply_devtools_overrides, - std::move(callback)); + storage_access_api_status, status, is_ad_tagged, + apply_devtools_overrides, std::move(callback)); } else { std::move(callback).Run(false); } @@ -195,6 +196,7 @@ const url::Origin& top_frame_origin, net::StorageAccessApiStatus storage_access_api_status, bool get_version_shared_memory, + bool is_ad_tagged, bool apply_devtools_overrides, const std::string& cookie, SetCookieFromStringCallback callback) { @@ -218,8 +220,8 @@ parsed_cookie.IsSecure())) { underlying_restricted_cookie_manager_->SetCookieFromString( url, site_for_cookies, top_frame_origin, storage_access_api_status, - get_version_shared_memory, apply_devtools_overrides, cookie, - std::move(callback)); + get_version_shared_memory, is_ad_tagged, apply_devtools_overrides, + cookie, std::move(callback)); } else { std::move(callback).Run(/*response=*/nullptr); }
diff --git a/android_webview/browser/network_service/aw_proxying_restricted_cookie_manager.h b/android_webview/browser/network_service/aw_proxying_restricted_cookie_manager.h index 7551434f..c2c5b04 100644 --- a/android_webview/browser/network_service/aw_proxying_restricted_cookie_manager.h +++ b/android_webview/browser/network_service/aw_proxying_restricted_cookie_manager.h
@@ -68,6 +68,7 @@ const url::Origin& top_frame_origin, net::StorageAccessApiStatus storage_access_api_status, net::CookieInclusionStatus status, + bool is_ad_tagged, bool apply_devtools_overrides, SetCanonicalCookieCallback callback) override; void AddChangeListener( @@ -84,6 +85,7 @@ const url::Origin& top_frame_origin, net::StorageAccessApiStatus storage_access_api_status, bool get_version_shared_memory, + bool is_ad_tagged, bool apply_devtools_overrides, const std::string& cookie, SetCookieFromStringCallback callback) override;
diff --git a/ash/accessibility/switch_access/DIR_METADATA b/ash/accessibility/switch_access/DIR_METADATA index 7e0cc2b..fca80477 100644 --- a/ash/accessibility/switch_access/DIR_METADATA +++ b/ash/accessibility/switch_access/DIR_METADATA
@@ -1 +1 @@ -mixins: "//chrome/browser/resources/chromeos/accessibility/switch_access/mv2/COMMON_METADATA" +mixins: "//chrome/browser/resources/chromeos/accessibility/switch_access/mv3/COMMON_METADATA"
diff --git a/ash/capture_mode/capture_mode_controller.cc b/ash/capture_mode/capture_mode_controller.cc index 96a8c168..4aa58ba 100644 --- a/ash/capture_mode/capture_mode_controller.cc +++ b/ash/capture_mode/capture_mode_controller.cc
@@ -685,6 +685,125 @@ image.Height() > lens::kMaxPixelsForImageSearch); } +// Attempts to parse the `response` as if it was a +// `FetchQueryFormulationMetadataResponse` encoded in JSON, and store the +// formatted text in `extracted_text`. Returns true if the response was +// successfully parsed (even if the text was empty), and false otherwise. See +// `google3/google/internal/lens/frontend/api/v1/service.proto` for more details +// about the expected response. +bool ParseQueryFormulationMetadataResponse( + const data_decoder::DataDecoder::ValueOrError& response, + std::string& extracted_text) { + if (!response.has_value() || !response->is_list() || + response->GetList().empty()) { + return false; + } + + const base::Value::List* metadata_response = + response->GetList()[0].GetIfList(); + if (!metadata_response || + metadata_response->size() < kQFMetadataResponseMinSize) { + return false; + } + + // Verify we have the right type of response message. + const std::string* message_id = + (*metadata_response)[kQFMetadataResponseFieldMessageIdIdx].GetIfString(); + if (!message_id || (*message_id) != kQFMetadataResponseMessageId) { + return false; + } + + // Deconstruct the metadata response in order to build our string for Copy + // Text. + const base::Value::List* detected_text = + (*metadata_response)[kQFMetadataResponseFieldDetectedText].GetIfList(); + if (!detected_text || detected_text->empty()) { + return false; + } + + // If we don't have a `text_layout` object, then there may not be any text to + // detect, so we should return true. + const base::Value::List* text_layout = + (*detected_text)[kDetectedTextFieldTextLayout].GetIfList(); + if (!text_layout) { + return true; + } + if (text_layout->empty()) { + return false; + } + + const base::Value::List* paragraph_list = + (*text_layout)[kTextLayoutFieldParagraphs].GetIfList(); + if (!paragraph_list || paragraph_list->empty()) { + return false; + } + + // Begin constructing the extracted text by looping through a sequence of + // paragraphs, lines, and words. + for (int i = 0; i < static_cast<int>(paragraph_list->size()); i++) { + const base::Value::List* paragraph = (*paragraph_list)[i].GetIfList(); + if (!paragraph || paragraph->size() < kParagraphMinSize) { + continue; + } + + const base::Value::List* line_list = + (*paragraph)[kParagraphFieldLines].GetIfList(); + if (!line_list || line_list->empty()) { + continue; + } + + // Add an extra newline between each paragraph (i.e., before each + // paragraph after the first). + if (i > 0) { + extracted_text += "\n"; + } + + for (int j = 0; j < static_cast<int>(line_list->size()); j++) { + const base::Value::List* line = (*line_list)[j].GetIfList(); + if (!line || line->empty()) { + continue; + } + + const base::Value::List* word_list = (*line)[kLineFieldWords].GetIfList(); + if (!word_list || word_list->empty()) { + continue; + } + + // Add a newline between each line (i.e., before each line after the + // first). + if (j > 0) { + extracted_text += "\n"; + } + + for (const base::Value& word_value : *word_list) { + const base::Value::List* word = word_value.GetIfList(); + if (!word || word->size() < kWordMinSize) { + continue; + } + + const std::string* plain_text = + (*word)[kWordFieldPlainText].GetIfString(); + if (!plain_text) { + continue; + } + + extracted_text += *plain_text; + + // Add the text separator if it exists. + const std::string* separator = + (*word)[kWordFieldTextSeparator].GetIfString(); + if (!separator) { + continue; + } + + extracted_text += *separator; + } + } + } + + return true; +} + } // namespace CaptureModeController::CaptureModeController( @@ -2177,7 +2296,15 @@ const gfx::Image& original_image, base::WeakPtr<BaseCaptureModeSession> image_search_token, const std::string& access_token) { - if (!image_search_token || access_token.empty()) { + // If the session is no longer valid, we can just return early. + if (!image_search_token) { + return; + } + + // If the access token is empty, let the user know that an error has occurred. + if (access_token.empty()) { + capture_mode_session_->ShowActionContainerError( + l10n_util::GetStringUTF16(IDS_ASH_SCANNER_ERROR_GENERIC)); return; } @@ -2310,9 +2437,11 @@ response_code = simple_url_loader->ResponseInfo()->headers->response_code(); } - // TODO: crbug.com/394648704 - Implement error handling when the response code - // is not a redirect. + // If the response code is not a success, return early and let the user know + // an error has occurred. if (!network::IsSuccessfulStatus(response_code)) { + capture_mode_session_->ShowActionContainerError( + l10n_util::GetStringUTF16(IDS_ASH_SCANNER_ERROR_GENERIC)); return; } @@ -2324,6 +2453,8 @@ // No other actions to take if we are not using the Lens Web API for Copy // Text. if (!features::IsSunfishLensWebCopyTextEnabled()) { + capture_mode_session_->ShowActionContainerError( + l10n_util::GetStringUTF16(IDS_ASH_SCANNER_ERROR_GENERIC)); return; } @@ -2350,7 +2481,16 @@ uploads_in_progress_.remove_if(base::MatchesUniquePtr(url_loader.get())); }; - if (!image_search_token || !response_body) { + // If the session is no longer valid, we can just return early. + if (!image_search_token) { + return; + } + + // If there is no response body, return early and let the user know an error + // has occurred. + if (!response_body) { + capture_mode_session_->ShowActionContainerError( + l10n_util::GetStringUTF16(IDS_ASH_SCANNER_ERROR_GENERIC)); return; } @@ -2367,109 +2507,17 @@ void CaptureModeController::OnJsonParsed( data_decoder::DataDecoder::ValueOrError result) { - if (!result.has_value() || !result->is_list() || result->GetList().empty()) { - return; - } - - const base::Value::List* metadata_response = result->GetList()[0].GetIfList(); - if (!metadata_response || - metadata_response->size() < kQFMetadataResponseMinSize) { - return; - } - - // Verify we have the right type of response message. - const std::string* message_id = - (*metadata_response)[kQFMetadataResponseFieldMessageIdIdx].GetIfString(); - if (!message_id || (*message_id) != kQFMetadataResponseMessageId) { - return; - } - - // Deconstruct the metadata response in order to build our string for Copy - // Text. See `FetchQueryFormulationMetadataResponse` in - // `google3/google/internal/lens/frontend/api/v1/service.proto` for details. - - const base::Value::List* detected_text = - (*metadata_response)[kQFMetadataResponseFieldDetectedText].GetIfList(); - if (!detected_text || detected_text->empty()) { - return; - } - - const base::Value::List* text_layout = - (*detected_text)[kDetectedTextFieldTextLayout].GetIfList(); - if (!text_layout || text_layout->empty()) { - return; - } - - const base::Value::List* paragraph_list = - (*text_layout)[kTextLayoutFieldParagraphs].GetIfList(); - if (!paragraph_list || paragraph_list->empty()) { - return; - } - - // Begin constructing the extracted text by looping through a sequence of - // paragraphs, lines, and words. std::string extracted_text; - for (int i = 0; i < static_cast<int>(paragraph_list->size()); i++) { - const base::Value::List* paragraph = (*paragraph_list)[i].GetIfList(); - if (!paragraph || paragraph->size() < kParagraphMinSize) { - continue; - } - - const base::Value::List* line_list = - (*paragraph)[kParagraphFieldLines].GetIfList(); - if (!line_list || line_list->empty()) { - continue; - } - - // Add an extra newline between each paragraph (i.e., before each - // paragraph after the first). - if (i > 0) { - extracted_text += "\n"; - } - - for (int j = 0; j < static_cast<int>(line_list->size()); j++) { - const base::Value::List* line = (*line_list)[j].GetIfList(); - if (!line || line->empty()) { - continue; - } - - const base::Value::List* word_list = (*line)[kLineFieldWords].GetIfList(); - if (!word_list || word_list->empty()) { - continue; - } - - // Add a newline between each line (i.e., before each line after the - // first). - if (j > 0) { - extracted_text += "\n"; - } - - for (const base::Value& word_value : *word_list) { - const base::Value::List* word = word_value.GetIfList(); - if (!word || word->size() < kWordMinSize) { - continue; - } - - const std::string* plain_text = - (*word)[kWordFieldPlainText].GetIfString(); - if (!plain_text) { - continue; - } - - extracted_text += *plain_text; - - // Add the text separator if it exists. - const std::string* separator = - (*word)[kWordFieldTextSeparator].GetIfString(); - if (!separator) { - continue; - } - - extracted_text += *separator; - } - } + // Attempty to parse the JSON further to get the extracted text. If + // unsuccessful, return early and let the user know an error has occurred. + if (!ParseQueryFormulationMetadataResponse(result, extracted_text)) { + capture_mode_session_->ShowActionContainerError( + l10n_util::GetStringUTF16(IDS_ASH_SCANNER_ERROR_GENERIC)); + return; } + // If the extracted text is empty, we can simply return without showing the + // Copy Text button. if (extracted_text.empty()) { return; }
diff --git a/ash/system/accessibility/switch_access/DIR_METADATA b/ash/system/accessibility/switch_access/DIR_METADATA index 7e0cc2b..fca80477 100644 --- a/ash/system/accessibility/switch_access/DIR_METADATA +++ b/ash/system/accessibility/switch_access/DIR_METADATA
@@ -1 +1 @@ -mixins: "//chrome/browser/resources/chromeos/accessibility/switch_access/mv2/COMMON_METADATA" +mixins: "//chrome/browser/resources/chromeos/accessibility/switch_access/mv3/COMMON_METADATA"
diff --git a/base/check_is_test.cc b/base/check_is_test.cc index f7ad65c..ce54877 100644 --- a/base/check_is_test.cc +++ b/base/check_is_test.cc
@@ -4,8 +4,7 @@ #include "base/check_is_test.h" -#include "base/check.h" -#include "base/logging.h" +#include "base/base_export.h" namespace { bool g_this_is_a_test = false; @@ -22,16 +21,6 @@ // `AllowCheckIsTestForTesting`, but is only allowed to be included in test // code. We therefore have to also mark the symbol as exported here. BASE_EXPORT void AllowCheckIsTestForTesting() { - // This CHECK ensures that `AllowCheckIsTestForTesting` is called - // just once. Since it is called in `base::TestSuite`, this should effectively - // prevent calls to `AllowCheckIsTestForTesting` in production code - // (assuming that code has unit test coverage). - // - // This is just in case someone ignores the fact that this function in the - // `base::test` namespace and ends on "ForTesting". - CHECK(!g_this_is_a_test) - << "AllowCheckIsTestForTesting must not be called more than once"; - g_this_is_a_test = true; } } // namespace base::test
diff --git a/base/sampling_heap_profiler/poisson_allocation_sampler.cc b/base/sampling_heap_profiler/poisson_allocation_sampler.cc index 2637da2e..7cb9296 100644 --- a/base/sampling_heap_profiler/poisson_allocation_sampler.cc +++ b/base/sampling_heap_profiler/poisson_allocation_sampler.cc
@@ -234,6 +234,12 @@ return g_sampling_interval.load(std::memory_order_relaxed); } +void PoissonAllocationSampler::SetTargetHashSetLoadFactor( + std::optional<float> load_factor) { + AutoLock lock(mutex_); + address_cache_target_load_factor_ = load_factor.value_or(1.0); +} + PoissonAllocationSamplerStats PoissonAllocationSampler::GetAndResetStats() { ScopedMuteThreadSamples no_reentrancy_scope; AutoLock lock(mutex_); @@ -393,7 +399,7 @@ // All the readers continue to use the old one until the atomic switch // process takes place. LockFreeAddressHashSet& current_set = sampled_addresses_set(); - if (current_set.load_factor() < 1) { + if (current_set.load_factor() < address_cache_target_load_factor_) { return; } auto new_set = std::make_unique<LockFreeAddressHashSet>(
diff --git a/base/sampling_heap_profiler/poisson_allocation_sampler.h b/base/sampling_heap_profiler/poisson_allocation_sampler.h index 92a17a5..a5b4e4d 100644 --- a/base/sampling_heap_profiler/poisson_allocation_sampler.h +++ b/base/sampling_heap_profiler/poisson_allocation_sampler.h
@@ -6,6 +6,7 @@ #define BASE_SAMPLING_HEAP_PROFILER_POISSON_ALLOCATION_SAMPLER_H_ #include <atomic> +#include <optional> #include <vector> #include "base/allocator/dispatcher/notification_data.h" @@ -154,6 +155,10 @@ // Returns the current mean sampling interval, in bytes. size_t SamplingInterval() const; + // Sets the max load factor before rebalancing the LockFreeAddressHashSet, or + // resets it to the default if `load_factor` is nulloptr. + void SetTargetHashSetLoadFactor(std::optional<float> load_factor); + // Returns statistics about the allocation sampler, and resets the running // counts so that each call to this returns only stats about the period // between calls. @@ -225,7 +230,7 @@ const char* context); void DoRecordFree(void* address); - void BalanceAddressesHashSet(); + void BalanceAddressesHashSet() EXCLUSIVE_LOCKS_REQUIRED(mutex_); Lock mutex_; @@ -256,12 +261,19 @@ std::atomic<size_t> address_cache_hits_; std::atomic<size_t> address_cache_misses_; size_t address_cache_max_size_ GUARDED_BY(mutex_) = 0; + // The max load factor that's observed in sampled_addresses_set(). float address_cache_max_load_factor_ GUARDED_BY(mutex_) = 0; + // The load factor that will trigger rebalancing in sampled_addresses_set(). + // By definition `address_cache_max_load_factor_` will never exceed this. + float address_cache_target_load_factor_ GUARDED_BY(mutex_) = 1.0; + friend class NoDestructor<PoissonAllocationSampler>; friend class PoissonAllocationSamplerStateTest; friend class SamplingHeapProfilerTest; FRIEND_TEST_ALL_PREFIXES(PoissonAllocationSamplerTest, MuteHooksWithoutInit); + FRIEND_TEST_ALL_PREFIXES(PoissonAllocationSamplerLoadFactorTest, + BalanceSampledAddressesSet); FRIEND_TEST_ALL_PREFIXES(SamplingHeapProfilerTest, HookedAllocatorMuted); };
diff --git a/base/sampling_heap_profiler/poisson_allocation_sampler_unittest.cc b/base/sampling_heap_profiler/poisson_allocation_sampler_unittest.cc index 578219d..15a4ca4 100644 --- a/base/sampling_heap_profiler/poisson_allocation_sampler_unittest.cc +++ b/base/sampling_heap_profiler/poisson_allocation_sampler_unittest.cc
@@ -10,27 +10,37 @@ #include <atomic> #include <bitset> #include <memory> +#include <optional> #include <utility> #include <vector> +#include "base/allocator/dispatcher/notification_data.h" +#include "base/allocator/dispatcher/subsystem.h" #include "base/barrier_closure.h" #include "base/containers/extend.h" #include "base/functional/bind.h" #include "base/functional/callback.h" #include "base/memory/scoped_refptr.h" #include "base/run_loop.h" +#include "base/sampling_heap_profiler/lock_free_address_hash_set.h" +#include "base/synchronization/lock.h" #include "base/task/bind_post_task.h" #include "base/task/single_thread_task_runner.h" #include "base/task/single_thread_task_runner_thread_mode.h" #include "base/task/thread_pool.h" #include "base/test/task_environment.h" +#include "build/build_config.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/abseil-cpp/absl/cleanup/cleanup.h" namespace base { namespace { +using allocator::dispatcher::AllocationNotificationData; +using allocator::dispatcher::AllocationSubsystem; +using allocator::dispatcher::FreeNotificationData; using ::testing::AssertionFailure; using ::testing::AssertionResult; using ::testing::AssertionSuccess; @@ -40,7 +50,7 @@ void SampleAdded(void* address, size_t size, size_t total, - base::allocator::dispatcher::AllocationSubsystem type, + AllocationSubsystem type, const char* context) final {} void SampleRemoved(void* address) final {} }; @@ -383,4 +393,125 @@ } } +class PoissonAllocationSamplerLoadFactorTest + : public ::testing::TestWithParam<float> {}; + +INSTANTIATE_TEST_SUITE_P(All, + PoissonAllocationSamplerLoadFactorTest, + ::testing::Values(0, 0.5, 1.5)); + +// TODO(crbug.com/383374205): This test flakily crashes on iOS without leaving +// any logs. +#if BUILDFLAG(IS_IOS) +#define MAYBE_BalanceSampledAddressesSet DISABLED_BalanceSampledAddressesSet +#else +#define MAYBE_BalanceSampledAddressesSet BalanceSampledAddressesSet +#endif + +TEST_P(PoissonAllocationSamplerLoadFactorTest, + MAYBE_BalanceSampledAddressesSet) { + PoissonAllocationSampler::ScopedMuteHookedSamplesForTesting mute_hooks; + PoissonAllocationSampler::ScopedSuppressRandomnessForTesting + suppress_randomness; + + auto* sampler = PoissonAllocationSampler::Get(); + + // Validate the starting state of the hash set. + size_t starting_buckets; + float last_load_factor; + { + base::AutoLock lock(sampler->mutex_); + starting_buckets = sampler->sampled_addresses_set().buckets_count(); + EXPECT_EQ(sampler->sampled_addresses_set().size(), 0); + last_load_factor = sampler->sampled_addresses_set().load_factor(); + EXPECT_EQ(last_load_factor, 0.0); + } + + size_t target_load_factor = GetParam(); + if (target_load_factor == 0) { + // Use the default load factor. + target_load_factor = 1.0; + } else { + sampler->SetTargetHashSetLoadFactor(target_load_factor); + } + + // Adding an observer starts the profiler. + DummySamplesObserver observer; + sampler->AddSamplesObserver(&observer); + + absl::Cleanup reset_singleton_state = [&] { + sampler->RemoveSamplesObserver(&observer); + sampler->SetTargetHashSetLoadFactor(std::nullopt); + }; + + // Helper to dump the hash set state to the test output. + auto dump_hash_set_state = [sampler] { + base::AutoLock lock(sampler->mutex_); + return ::testing::Message() + << "hash set size " << sampler->sampled_addresses_set().size() + << ", bucket count " + << sampler->sampled_addresses_set().buckets_count() + << ", load factor " + << sampler->sampled_addresses_set().load_factor(); + }; + + // Allocations that keep the load factor below target should not rebalance. + const size_t target_allocations = starting_buckets * target_load_factor; + SCOPED_TRACE(::testing::Message() + << "target_allocations " << target_allocations); + for (uintptr_t i = 1; i < target_allocations; ++i) { + SCOPED_TRACE(::testing::Message() << "allocation " << i); + sampler->OnAllocation(AllocationNotificationData( + reinterpret_cast<void*>(i), sampler->SamplingInterval(), "dummy", + AllocationSubsystem::kManualForTesting)); + + SCOPED_TRACE(dump_hash_set_state()); + base::AutoLock lock(sampler->mutex_); + EXPECT_EQ(sampler->sampled_addresses_set().size(), i); + EXPECT_EQ(sampler->sampled_addresses_set().buckets_count(), + starting_buckets); + + float load_factor = sampler->sampled_addresses_set().load_factor(); + EXPECT_GT(load_factor, last_load_factor); + EXPECT_LT(load_factor, target_load_factor); + last_load_factor = load_factor; + } + + // Next allocation should rebalance: number of buckets goes up, load factor + // goes down. + sampler->OnAllocation(AllocationNotificationData( + reinterpret_cast<void*>(target_allocations), sampler->SamplingInterval(), + "dummy", AllocationSubsystem::kManualForTesting)); + + size_t rebalanced_buckets; + { + SCOPED_TRACE(dump_hash_set_state()); + base::AutoLock lock(sampler->mutex_); + EXPECT_EQ(sampler->sampled_addresses_set().size(), target_allocations); + rebalanced_buckets = sampler->sampled_addresses_set().buckets_count(); + EXPECT_GT(rebalanced_buckets, starting_buckets); + + float load_factor = sampler->sampled_addresses_set().load_factor(); + EXPECT_LT(load_factor, last_load_factor); + last_load_factor = load_factor; + } + + // Deallocating should not rebalance. + for (uintptr_t i = target_allocations; i > 0; --i) { + SCOPED_TRACE(::testing::Message() << "deallocation " << i); + sampler->OnFree(FreeNotificationData( + reinterpret_cast<void*>(i), AllocationSubsystem::kManualForTesting)); + + SCOPED_TRACE(dump_hash_set_state()); + base::AutoLock lock(sampler->mutex_); + EXPECT_EQ(sampler->sampled_addresses_set().size(), i - 1); + EXPECT_EQ(sampler->sampled_addresses_set().buckets_count(), + rebalanced_buckets); + + float load_factor = sampler->sampled_addresses_set().load_factor(); + EXPECT_LT(load_factor, last_load_factor); + last_load_factor = load_factor; + } +} + } // namespace base
diff --git a/base/task/single_thread_task_executor_unittest.cc b/base/task/single_thread_task_executor_unittest.cc index 2062a388..2cc39a9 100644 --- a/base/task/single_thread_task_executor_unittest.cc +++ b/base/task/single_thread_task_executor_unittest.cc
@@ -423,7 +423,7 @@ TestIOHandler::TestIOHandler(const wchar_t* name, HANDLE signal) : MessagePumpForIO::IOHandler(FROM_HERE), signal_(signal) { - memset(buffer_, 0, sizeof(buffer_)); + UNSAFE_TODO(memset(buffer_, 0, sizeof(buffer_))); file_.Set(CreateFile(name, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL));
diff --git a/base/test/android/javatests/src/org/chromium/base/test/transit/BatchedPublicTransitRule.java b/base/test/android/javatests/src/org/chromium/base/test/transit/BatchedPublicTransitRule.java index bcef826a..ad62a525 100644 --- a/base/test/android/javatests/src/org/chromium/base/test/transit/BatchedPublicTransitRule.java +++ b/base/test/android/javatests/src/org/chromium/base/test/transit/BatchedPublicTransitRule.java
@@ -42,8 +42,10 @@ try { testName = desc.getMethodName(); TrafficControl.onTestStarted(testName); - TransitAsserts.assertCurrentStationType( - mHomeStationType, "beginning of test", true); + if (mExpectResetByTest) { + TransitAsserts.assertCurrentStationType( + mHomeStationType, "beginning of test", true); + } base.evaluate(); if (mExpectResetByTest) { TransitAsserts.assertCurrentStationType(
diff --git a/base/test/android/javatests/src/org/chromium/base/test/transit/README.md b/base/test/android/javatests/src/org/chromium/base/test/transit/README.md index 0311972..8d29de7 100644 --- a/base/test/android/javatests/src/org/chromium/base/test/transit/README.md +++ b/base/test/android/javatests/src/org/chromium/base/test/transit/README.md
@@ -141,6 +141,10 @@ #### How to Batch restarting the Activity between tests +This restarts the Android Activities while keeping the browser process alive. +Static fields, singletons and globals are not reset unless ResettersForTesting +was used. + 1. Add `@Batch(Batch.PER_CLASS)` to the test class. 2. Use the `@Rule` returned by `ChromeTransitTestRules.freshChromeTabbedActivityRule()`. @@ -151,22 +155,39 @@ is not necessary. However, this does not run as fast as "reusing the Activity" below, especially in Release. -#### How to Batch reusing the Activity between tests +#### How to Batch reusing the Activity between tests but resetting tab state + +This keeps the Activity, but closes all tabs between tests and returns to a +blank page. + +Using `AutoResetCtaTransitTestRule`: 1. Add `@Batch(Batch.PER_CLASS)` to the test class. -2. Use a "reused" `@Rule` such as +2. Use `ChromeTransitTestRules.autoResetCtaActivityRule()`. +3. Get the first station in each test case from the test rule: + `mCtaTestRule.startOnBlankPage()`. + +Tests don't need to return to the home station. Only some reset paths are +supported - this is best effort since this reset transition is not part of a +regular user flow. + +#### How to Batch reusing the Activity between tests staying on the same state + +This both keeps the Activiy and doesn't reset any app state between tests (apart +from ResettersForTesting) - a test is started immediately after the previous +finished. + +Using `ReusedCtaTransitTestRule`: + +1. Add `@Batch(Batch.PER_CLASS)` to the test class. +2. Use a "Reused" factory method such as `ChromeTransitTestRules.blankPageStartReusedActivityRule()`. 3. Get the first station in each test case from the test rule: - `mCtaTestRule#start()`. -4. Each test should return to the home station. If a test does not end in the - home station, it will fail (if it already hasn't) with a descriptive message. - The following tests will also fail right at the start. + `mCtaTestRule.start()`. -In Chrome, in many situations, [`BlankCTATabInitialStatePublicTransitRule`] is -more practical to use to automatically reset Tab state. It also acts as entry -point. - -[`BlankCTATabInitialStatePublicTransitRule`]: https://source.chromium.org/search?q=symbol:BlankCTATabInitialStatePublicTransitRule&ss=chromium +Each test should return to the home station. If a test does not end in the +home station, it will fail (if it already hasn't) with a descriptive message. +The following tests will also fail right at the start. ### ViewPrinter
diff --git a/base/test/android/javatests/src/org/chromium/base/test/transit/getting_started.md b/base/test/android/javatests/src/org/chromium/base/test/transit/getting_started.md index 2f3302f..20da68f 100644 --- a/base/test/android/javatests/src/org/chromium/base/test/transit/getting_started.md +++ b/base/test/android/javatests/src/org/chromium/base/test/transit/getting_started.md
@@ -254,30 +254,27 @@ } ``` -### Option 2: Reset State with BlankCTATabInitialStatePublicTransitRule +### Option 2: Reset State with AutoResetCtaTransitTestRule Manually resetting in each test doesn't scale very well in many cases. There are some shortcuts for undoing state set during a test, and for tabs specifically, -we are going to use `BlankCTATabInitialStatePublicTransitRule`, which resets +we are going to use `AutoResetCtaTransitTestRule`, which resets Chrome to a single blank page at the start of each test: ```java public class MyPTTest { - @Rule -- public BatchedPublicTransitRule<PageStation> mBatchedRule = -- new BatchedPublicTransitRule<>(PageStation.class, /* expectResetByTest= */ true); -- -- ChromeTabbedActivityPublicTransitEntryPoints mEntryPoints = -- new ChromeTabbedActivityPublicTransitEntryPoints(sActivityTestRule); +- public ReusedCtaTransitTestRule<WebPageStation> mCtaTestRule = +- ChromeTransitTestRules.blankPageStartReusedActivityRule(); + @Rule -+ public BlankCTATabInitialStatePublicTransitRule mInitialStateRule = -+ new BlankCTATabInitialStatePublicTransitRule(sActivityTestRule); ++ public AutoResetCtaTransitTestRule mCtaTestRule = ++ new ChromeTransitTestRules.autoResetCtaActivityRule(); public void testTwoTabs_II() { - PageStation page = mCtaTestRule.start(); -+ PageStation page = mInitialStateRule.startOnBlankPage(); ++ PageStation page = mCtaTestRule.startOnBlankPage(); [...] } } @@ -291,7 +288,7 @@ ```java public class MyPTTest { public void testFiveTabs_V() { - PageStation page = mInitialStateRule.startOnBlankPage(); + PageStation page = mCtaTestRule.startOnBlankPage(); page = Journeys.prepareTabs(page, 5, 0, "about:blank"); ImageButton tabSwitcherButton = page.getTabSwitcherButton(); @@ -373,7 +370,7 @@ ```java public class MyPTTest { public void testOneTab_I() { - PageStation page = mInitialStateRule.startOnBlankPage(); + PageStation page = mCtaTestRule.startOnBlankPage(); TabSwitcherButtonFacility tabSwitcherButton = page.focusOnTabSwitcherButton(); assertEquals("I", tabSwitcherButton.getTextRendered()); @@ -441,7 +438,7 @@ ```java public class MyPTTest { public void testOneTab_I() { - PageStation page = mInitialStateRule.startOnBlankPage(); + PageStation page = mCtaTestRule.startOnBlankPage(); TabSwitcherButtonFacility tabSwitcherButton = page.focusOnTabSwitcherButton("I"); + TransitAsserts.assertFinalDestination(page); }
diff --git a/base/test/launcher/test_results_tracker.cc b/base/test/launcher/test_results_tracker.cc index 5352815..fe34e14c 100644 --- a/base/test/launcher/test_results_tracker.cc +++ b/base/test/launcher/test_results_tracker.cc
@@ -222,6 +222,9 @@ // Partially copy the primary TestResult. TestResult test_result; test_result.elapsed_time = primary_test_result.elapsed_time; + test_result.links = primary_test_result.links; + test_result.properties = primary_test_result.properties; + test_result.tags = primary_test_result.tags; test_result.thread_id = primary_test_result.thread_id; test_result.timestamp = primary_test_result.timestamp; if (sub_test_result.failure_message) {
diff --git a/base/win/event_trace_consumer_unittest.cc b/base/win/event_trace_consumer_unittest.cc index 96d4734..55e98ff 100644 --- a/base/win/event_trace_consumer_unittest.cc +++ b/base/win/event_trace_consumer_unittest.cc
@@ -13,6 +13,7 @@ #include <iterator> #include <list> +#include "base/compiler_specific.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" @@ -62,7 +63,7 @@ if (event->MofData != nullptr && event->MofLength != 0) { back.MofData = new char[event->MofLength]; - memcpy(back.MofData, event->MofData, event->MofLength); + UNSAFE_TODO(memcpy(back.MofData, event->MofData, event->MofLength)); } }
diff --git a/base/win/i18n_unittest.cc b/base/win/i18n_unittest.cc index 86e792c..b05497b5 100644 --- a/base/win/i18n_unittest.cc +++ b/base/win/i18n_unittest.cc
@@ -9,6 +9,7 @@ #include <stddef.h> #include <string.h> +#include "base/compiler_specific.h" #include "base/strings/string_util.h" #include "base/win/windows_version.h" #include "testing/gtest/include/gtest/gtest.h" @@ -25,7 +26,7 @@ for (const auto& language : languages) { EXPECT_FALSE(language.empty()); // Ensure there's no extra trailing 0 characters. - EXPECT_EQ(language.size(), wcslen(language.c_str())); + EXPECT_EQ(language.size(), UNSAFE_TODO(wcslen(language.c_str()))); } } @@ -36,7 +37,7 @@ EXPECT_FALSE(languages.empty()); for (const auto& language : languages) { EXPECT_FALSE(language.empty()); - EXPECT_EQ(language.size(), wcslen(language.c_str())); + EXPECT_EQ(language.size(), UNSAFE_TODO(wcslen(language.c_str()))); } }
diff --git a/base/win/winrt_storage_util_unittest.cc b/base/win/winrt_storage_util_unittest.cc index 5c54819..ee279cc 100644 --- a/base/win/winrt_storage_util_unittest.cc +++ b/base/win/winrt_storage_util_unittest.cc
@@ -9,6 +9,7 @@ #include <vector> +#include "base/compiler_specific.h" #include "base/strings/string_util.h" #include "base/win/core_winrt_util.h" #include "base/win/scoped_com_initializer.h" @@ -32,7 +33,7 @@ GetPointerToBufferData(buffer.Get(), &p_buffer_data, &length)); ASSERT_EQ(data.size(), length); - EXPECT_EQ(0, memcmp(p_buffer_data, data.data(), data.size())); + EXPECT_EQ(0, UNSAFE_TODO(memcmp(p_buffer_data, data.data(), data.size()))); } } // namespace win
diff --git a/cc/mojo_embedder/viz_layer_context.cc b/cc/mojo_embedder/viz_layer_context.cc index 625bc58..48807ed 100644 --- a/cc/mojo_embedder/viz_layer_context.cc +++ b/cc/mojo_embedder/viz_layer_context.cc
@@ -52,6 +52,8 @@ old_node->element_id == new_node.element_id && old_node->local == new_node.local && old_node->origin == new_node.origin && + old_node->post_translation == new_node.post_translation && + old_node->to_parent == new_node.to_parent && old_node->sticky_position_constraint_id == new_node.sticky_position_constraint_id && old_node->anchor_position_scroll_data_id == @@ -84,6 +86,8 @@ wire->element_id = new_node.element_id; wire->local = new_node.local; wire->origin = new_node.origin; + wire->post_translation = new_node.post_translation; + wire->to_parent = new_node.to_parent; if (new_node.sticky_position_constraint_id >= 0) { wire->sticky_position_constraint_id = base::checked_cast<uint32_t>(new_node.sticky_position_constraint_id);
diff --git a/cc/raster/bitmap_raster_buffer_provider.cc b/cc/raster/bitmap_raster_buffer_provider.cc index 25491f8..407fe1c 100644 --- a/cc/raster/bitmap_raster_buffer_provider.cc +++ b/cc/raster/bitmap_raster_buffer_provider.cc
@@ -28,14 +28,10 @@ class BitmapRasterBufferImpl : public RasterBuffer { public: - BitmapRasterBufferImpl(const gfx::Size& size, - const gfx::ColorSpace& color_space, - ResourcePool::Backing* backing, + BitmapRasterBufferImpl(ResourcePool::Backing* backing, uint64_t resource_content_id, uint64_t previous_content_id) - : resource_size_(size), - color_space_(color_space), - resource_has_previous_content_( + : resource_has_previous_content_( resource_content_id && resource_content_id == previous_content_id), backing_(backing) {} BitmapRasterBufferImpl(const BitmapRasterBufferImpl&) = delete; @@ -62,8 +58,9 @@ auto mapping = backing_->shared_image()->Map(); void* memory = mapping->GetMemoryForPlane(0).data(); RasterBufferProvider::PlaybackToMemory( - memory, format, resource_size_, stride, raster_source, raster_full_rect, - playback_rect, transform, color_space_, playback_settings); + memory, format, backing_->shared_image()->size(), stride, raster_source, + raster_full_rect, playback_rect, transform, + backing_->shared_image()->color_space(), playback_settings); } bool SupportsBackgroundThreadPriority() const override { return true; } @@ -106,9 +103,8 @@ } ResourcePool::Backing* backing = resource.backing(); - return std::make_unique<BitmapRasterBufferImpl>( - resource.size(), resource.color_space(), backing, resource_content_id, - previous_content_id); + return std::make_unique<BitmapRasterBufferImpl>(backing, resource_content_id, + previous_content_id); } void BitmapRasterBufferProvider::Flush() {}
diff --git a/cc/test/pixel_test.cc b/cc/test/pixel_test.cc index 7a9608d..0d76248 100644 --- a/cc/test/pixel_test.cc +++ b/cc/test/pixel_test.cc
@@ -242,6 +242,15 @@ return result; } +bool PixelTest::RunPixelTest(viz::AggregatedRenderPassList* pass_list, + viz::AggregatedRenderPassList* ref_pass_list, + const PixelComparator& comparator) { + RenderReadbackTargetAndAreaToResultBitmap( + ref_pass_list, ref_pass_list->back().get(), nullptr); + std::unique_ptr<SkBitmap> output = std::move(result_bitmap_); + return RunPixelTest(pass_list, *output, comparator); +} + void PixelTest::ReadbackResult(base::OnceClosure quit_run_loop, std::unique_ptr<viz::CopyOutputResult> result) { ASSERT_FALSE(result->IsEmpty());
diff --git a/cc/test/pixel_test.h b/cc/test/pixel_test.h index ce70bf8d..75466ba 100644 --- a/cc/test/pixel_test.h +++ b/cc/test/pixel_test.h
@@ -73,6 +73,10 @@ SkBitmap ref_bitmap, const PixelComparator& comparator); + bool RunPixelTest(viz::AggregatedRenderPassList* pass_list, + viz::AggregatedRenderPassList* ref_pass_list, + const PixelComparator& comparator); + bool RunPixelTestWithCopyOutputRequest( viz::AggregatedRenderPassList* pass_list, viz::AggregatedRenderPass* target,
diff --git a/cc/test/pixel_test_utils.cc b/cc/test/pixel_test_utils.cc index 5da703d..cc1628e 100644 --- a/cc/test/pixel_test_utils.cc +++ b/cc/test/pixel_test_utils.cc
@@ -87,7 +87,6 @@ LOG(ERROR) << "Cannot read reference image: " << ref_img_path.value(); return false; } - LOG(ERROR) << "Using reference image path " << ref_img_path; return MatchesBitmap(gen_bmp, ref_bmp, comparator); }
diff --git a/chrome/android/BUILD.gn b/chrome/android/BUILD.gn index 874bb79c..bc8f131 100644 --- a/chrome/android/BUILD.gn +++ b/chrome/android/BUILD.gn
@@ -1086,6 +1086,7 @@ "//chrome/browser/readaloud/android:junit", "//chrome/browser/recent_tabs:junit", "//chrome/browser/recent_tabs/internal:junit", + "//chrome/browser/safe_browsing/android:junit", "//chrome/browser/safety_check/android:junit", "//chrome/browser/safety_hub/android:junit", "//chrome/browser/search_engines/android:junit",
diff --git a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabGridDialogCoordinator.java b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabGridDialogCoordinator.java index 4827fb2b..7483e2c 100644 --- a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabGridDialogCoordinator.java +++ b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabGridDialogCoordinator.java
@@ -15,6 +15,7 @@ import android.widget.FrameLayout; import android.widget.PopupWindow; +import androidx.annotation.ColorInt; import androidx.annotation.DrawableRes; import androidx.annotation.LayoutRes; import androidx.annotation.NonNull; @@ -49,6 +50,7 @@ import org.chromium.chrome.tab_ui.R; import org.chromium.components.browser_ui.bottomsheet.BottomSheetController; import org.chromium.components.browser_ui.desktop_windowing.DesktopWindowStateManager; +import org.chromium.components.browser_ui.styles.SemanticColorUtils; import org.chromium.components.browser_ui.widget.scrim.ScrimManager; import org.chromium.components.collaboration.CollaborationService; import org.chromium.components.collaboration.ServiceStatus; @@ -170,8 +172,13 @@ DataSharingService dataSharingService = DataSharingServiceFactory.getForProfile(originalProfile); + @ColorInt + int backgroundColor = SemanticColorUtils.getDialogBgColor(mDialogView.getContext()); SharedImageTilesConfig config = - new SharedImageTilesConfig.Builder(activity).build(); + new SharedImageTilesConfig.Builder(activity) + .setBorderColor(backgroundColor) + .setBackgroundColor(backgroundColor) + .build(); mSharedImageTilesCoordinator = new SharedImageTilesCoordinator( activity, config, dataSharingService, collaborationService);
diff --git a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabSwitcherPanePublicTransitTest.java b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabSwitcherPanePublicTransitTest.java index 7a9106052..c3aa4658 100644 --- a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabSwitcherPanePublicTransitTest.java +++ b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabSwitcherPanePublicTransitTest.java
@@ -18,7 +18,6 @@ import androidx.recyclerview.widget.RecyclerView; import androidx.test.filters.MediumTest; -import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; @@ -29,8 +28,8 @@ import org.chromium.chrome.browser.ChromeTabbedActivity; import org.chromium.chrome.browser.flags.ChromeSwitches; import org.chromium.chrome.test.ChromeJUnit4ClassRunner; -import org.chromium.chrome.test.ChromeTabbedActivityTestRule; -import org.chromium.chrome.test.transit.BlankCTATabInitialStatePublicTransitRule; +import org.chromium.chrome.test.transit.AutoResetCtaTransitTestRule; +import org.chromium.chrome.test.transit.ChromeTransitTestRules; import org.chromium.chrome.test.transit.hub.IncognitoTabSwitcherStation; import org.chromium.chrome.test.transit.hub.RegularTabSwitcherStation; import org.chromium.chrome.test.transit.hub.TabSwitcherListEditorFacility; @@ -49,19 +48,15 @@ @Batch(Batch.PER_CLASS) @ImportantFormFactors(DeviceFormFactor.TABLET) public class TabSwitcherPanePublicTransitTest { - @ClassRule - public static ChromeTabbedActivityTestRule sActivityTestRule = - new ChromeTabbedActivityTestRule(); - @Rule - public BlankCTATabInitialStatePublicTransitRule mInitialStateRule = - new BlankCTATabInitialStatePublicTransitRule(sActivityTestRule); + public AutoResetCtaTransitTestRule mCtaTestRule = + ChromeTransitTestRules.autoResetCtaActivityRule(); @Test @MediumTest public void testSwitchTabModel_ScrollToSelectedTab() { - WebPageStation firstPage = mInitialStateRule.startOnBlankPage(); - ChromeTabbedActivity cta = sActivityTestRule.getActivity(); + WebPageStation firstPage = mCtaTestRule.startOnBlankPage(); + ChromeTabbedActivity cta = mCtaTestRule.getActivity(); PageStation page = firstPage; for (int i = 1; i < 10; i++) { @@ -92,7 +87,7 @@ @Test @MediumTest public void testTabListEditor_EnterAndExit() { - WebPageStation firstPage = mInitialStateRule.startOnBlankPage(); + WebPageStation firstPage = mCtaTestRule.startOnBlankPage(); RegularTabSwitcherStation regularTabSwitcher = firstPage.openRegularTabSwitcher(); TabSwitcherListEditorFacility listEditor = @@ -107,8 +102,8 @@ @Test @MediumTest public void testEmptyStateView() { - WebPageStation firstPage = mInitialStateRule.startOnBlankPage(); - ChromeTabbedActivity cta = sActivityTestRule.getActivity(); + WebPageStation firstPage = mCtaTestRule.startOnBlankPage(); + ChromeTabbedActivity cta = mCtaTestRule.getActivity(); IncognitoNewTabPageStation incognitoNtp = firstPage.openNewIncognitoTabFast(); assertTrue(cta.getCurrentTabModel().isIncognito());
diff --git a/chrome/android/features/tab_ui/javatests/src/org/chromium/chrome/browser/tasks/tab_management/TabGroupDialogPTTest.java b/chrome/android/features/tab_ui/javatests/src/org/chromium/chrome/browser/tasks/tab_management/TabGroupDialogPTTest.java index 79185460..fe87d06 100644 --- a/chrome/android/features/tab_ui/javatests/src/org/chromium/chrome/browser/tasks/tab_management/TabGroupDialogPTTest.java +++ b/chrome/android/features/tab_ui/javatests/src/org/chromium/chrome/browser/tasks/tab_management/TabGroupDialogPTTest.java
@@ -8,7 +8,6 @@ import androidx.test.filters.MediumTest; -import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; @@ -19,8 +18,8 @@ import org.chromium.chrome.browser.flags.ChromeFeatureList; import org.chromium.chrome.browser.flags.ChromeSwitches; import org.chromium.chrome.test.ChromeJUnit4ClassRunner; -import org.chromium.chrome.test.ChromeTabbedActivityTestRule; -import org.chromium.chrome.test.transit.BlankCTATabInitialStatePublicTransitRule; +import org.chromium.chrome.test.transit.AutoResetCtaTransitTestRule; +import org.chromium.chrome.test.transit.ChromeTransitTestRules; import org.chromium.chrome.test.transit.Journeys; import org.chromium.chrome.test.transit.hub.IncognitoTabSwitcherStation; import org.chromium.chrome.test.transit.hub.RegularTabSwitcherStation; @@ -39,18 +38,14 @@ // or enable Google Sans (Text) in //chrome/ tests on Android T+. @Features.DisableFeatures(ChromeFeatureList.ANDROID_ELEGANT_TEXT_HEIGHT) public class TabGroupDialogPTTest { - @ClassRule - public static ChromeTabbedActivityTestRule sActivityTestRule = - new ChromeTabbedActivityTestRule(); - @Rule - public BlankCTATabInitialStatePublicTransitRule mInitialStateRule = - new BlankCTATabInitialStatePublicTransitRule(sActivityTestRule); + public AutoResetCtaTransitTestRule mCtaTestRule = + ChromeTransitTestRules.autoResetCtaActivityRule(); @Test @MediumTest public void testNewTabCreation() { - WebPageStation firstPage = mInitialStateRule.startOnBlankPage(); + WebPageStation firstPage = mCtaTestRule.startOnBlankPage(); WebPageStation pageStation = Journeys.prepareTabsWithThumbnails( firstPage, 3, 0, "about:blank", WebPageStation::newBuilder); @@ -68,7 +63,7 @@ @Test @MediumTest public void testIncognitoNewTabCreation() { - WebPageStation firstPage = mInitialStateRule.startOnBlankPage(); + WebPageStation firstPage = mCtaTestRule.startOnBlankPage(); WebPageStation pageStation = Journeys.prepareTabsWithThumbnails( firstPage, 1, 3, "about:blank", WebPageStation::newBuilder); @@ -86,7 +81,7 @@ @Test @MediumTest public void testTabGroupNameChange() { - WebPageStation firstPage = mInitialStateRule.startOnBlankPage(); + WebPageStation firstPage = mCtaTestRule.startOnBlankPage(); WebPageStation pageStation = Journeys.prepareTabsWithThumbnails( firstPage, 3, 0, "about:blank", WebPageStation::newBuilder);
diff --git a/chrome/android/features/tab_ui/javatests/src/org/chromium/chrome/browser/tasks/tab_management/TabSwitcherLayoutPTTest.java b/chrome/android/features/tab_ui/javatests/src/org/chromium/chrome/browser/tasks/tab_management/TabSwitcherLayoutPTTest.java index 80e7e61..5c4223d 100644 --- a/chrome/android/features/tab_ui/javatests/src/org/chromium/chrome/browser/tasks/tab_management/TabSwitcherLayoutPTTest.java +++ b/chrome/android/features/tab_ui/javatests/src/org/chromium/chrome/browser/tasks/tab_management/TabSwitcherLayoutPTTest.java
@@ -27,8 +27,6 @@ import androidx.test.filters.MediumTest; import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; @@ -49,9 +47,9 @@ import org.chromium.chrome.browser.flags.ChromeFeatureList; import org.chromium.chrome.browser.flags.ChromeSwitches; import org.chromium.chrome.test.ChromeJUnit4ClassRunner; -import org.chromium.chrome.test.ChromeTabbedActivityTestRule; import org.chromium.chrome.test.R; -import org.chromium.chrome.test.transit.BlankCTATabInitialStatePublicTransitRule; +import org.chromium.chrome.test.transit.AutoResetCtaTransitTestRule; +import org.chromium.chrome.test.transit.ChromeTransitTestRules; import org.chromium.chrome.test.transit.Journeys; import org.chromium.chrome.test.transit.hub.IncognitoTabSwitcherStation; import org.chromium.chrome.test.transit.hub.NewTabGroupDialogFacility; @@ -67,7 +65,6 @@ import org.chromium.chrome.test.util.ChromeRenderTestRule; import org.chromium.components.embedder_support.util.UrlConstants; import org.chromium.components.tab_groups.TabGroupColorId; -import org.chromium.net.test.EmbeddedTestServer; import java.io.IOException; import java.lang.ref.WeakReference; @@ -87,13 +84,9 @@ private static final String TEST_URL = "/chrome/test/data/android/google.html"; - @ClassRule - public static ChromeTabbedActivityTestRule sActivityTestRule = - new ChromeTabbedActivityTestRule(); - @Rule - public BlankCTATabInitialStatePublicTransitRule mInitialStateRule = - new BlankCTATabInitialStatePublicTransitRule(sActivityTestRule); + public AutoResetCtaTransitTestRule mCtaTestRule = + ChromeTransitTestRules.autoResetCtaActivityRule(); @Rule public ChromeRenderTestRule mRenderTestRule = @@ -102,25 +95,15 @@ .setBugComponent(ChromeRenderTestRule.Component.UI_BROWSER_MOBILE_HUB) .build(); - private static EmbeddedTestServer sTestServer; - private WebPageStation mStartPage; private WeakReference<Bitmap> mBitmap; @Before public void setUp() throws ExecutionException { // After setUp, Chrome is launched and has one NTP. - mStartPage = mInitialStateRule.startOnBlankPage(); + mStartPage = mCtaTestRule.startOnBlankPage(); - sActivityTestRule - .getActivity() - .getTabContentManager() - .setCaptureMinRequestTimeForTesting(0); - } - - @BeforeClass - public static void setUpClass() throws ExecutionException { - sTestServer = sActivityTestRule.getTestServer(); + mCtaTestRule.getActivity().getTabContentManager().setCaptureMinRequestTimeForTesting(0); } /** Enters the regular Tab Switcher, making sure all tabs have a thumbnail. */ @@ -148,7 +131,7 @@ "Flaky in arm64 (crbug.com/378137969 and crbug.com/378502216), affects flake rate of" + " other tests") public void testRenderGrid_10WebTabs() throws IOException { - ChromeTabbedActivity cta = sActivityTestRule.getActivity(); + ChromeTabbedActivity cta = mCtaTestRule.getActivity(); WebPageStation pageStation = Journeys.prepareTabsWithThumbnails( mStartPage, 10, 0, "about:blank", WebPageStation::newBuilder); @@ -172,7 +155,7 @@ "Flaky in arm64 (crbug.com/378137969 and crbug.com/378502216), affects flake rate of" + " other tests") public void testRenderGrid_10WebTabs_InitialScroll() throws IOException { - ChromeTabbedActivity cta = sActivityTestRule.getActivity(); + ChromeTabbedActivity cta = mCtaTestRule.getActivity(); WebPageStation pageStation = Journeys.prepareTabsWithThumbnails( mStartPage, 10, 0, "about:blank", WebPageStation::newBuilder); @@ -193,10 +176,14 @@ @DisabledTest(message = "Test is flaky due to thumbnails not being reliably captured") @RequiresRestart("Disable batching while re-enabling other tests") public void testRenderGrid_3WebTabs() throws IOException { - ChromeTabbedActivity cta = sActivityTestRule.getActivity(); + ChromeTabbedActivity cta = mCtaTestRule.getActivity(); WebPageStation pageStation = Journeys.prepareTabsWithThumbnails( - mStartPage, 3, 0, sTestServer.getURL(TEST_URL), WebPageStation::newBuilder); + mStartPage, + 3, + 0, + mCtaTestRule.getTestServer().getURL(TEST_URL), + WebPageStation::newBuilder); // Make sure all thumbnails are there before switching tabs. RegularTabSwitcherStation tabSwitcherStation = enterRegularHTSWithThumbnailChecking(pageStation); @@ -215,7 +202,7 @@ @MediumTest @Feature({"RenderTest"}) public void testRenderGrid_3NativeTabs() throws IOException { - ChromeTabbedActivity cta = sActivityTestRule.getActivity(); + ChromeTabbedActivity cta = mCtaTestRule.getActivity(); RegularNewTabPageStation pageStation = Journeys.prepareTabsWithThumbnails( mStartPage, @@ -242,7 +229,7 @@ @MediumTest @Feature({"RenderTest"}) public void testRenderGrid_Incognito() throws IOException { - ChromeTabbedActivity cta = sActivityTestRule.getActivity(); + ChromeTabbedActivity cta = mCtaTestRule.getActivity(); // Prepare some incognito tabs and enter tab switcher. WebPageStation pageStation = Journeys.createTabsWithThumbnails( @@ -269,9 +256,9 @@ @MediumTest @Feature({"RenderTest"}) public void testRenderGrid_1TabGroup_ColorIcon() throws IOException { - ChromeTabbedActivity cta = sActivityTestRule.getActivity(); + ChromeTabbedActivity cta = mCtaTestRule.getActivity(); - WebPageStation firstPage = mInitialStateRule.startOnBlankPage(); + WebPageStation firstPage = mCtaTestRule.startOnBlankPage(); int firstTabId = firstPage.getLoadedTab().getId(); RegularNewTabPageStation secondPage = firstPage.openNewTabFast(); int secondTabId = secondPage.getLoadedTab().getId(); @@ -300,7 +287,7 @@ @MediumTest @EnableAnimations public void testTabToGridAndBack_NoReset() { - WebPageStation firstPage = mInitialStateRule.startOnBlankPage(); + WebPageStation firstPage = mCtaTestRule.startOnBlankPage(); WebPageStation page = roundtripToHTSWithThumbnailChecks( firstPage, @@ -314,8 +301,8 @@ @MediumTest @EnableAnimations public void testTabToGridAndBack_SoftCleanup() { - WebPageStation firstPage = mInitialStateRule.startOnBlankPage(); - ChromeTabbedActivity cta = sActivityTestRule.getActivity(); + WebPageStation firstPage = mCtaTestRule.startOnBlankPage(); + ChromeTabbedActivity cta = mCtaTestRule.getActivity(); Runnable resetHTSStateOnUiThread = () -> { var tabSwitcherPane = @@ -341,9 +328,9 @@ @EnableAnimations @RequiresRestart("Flaky on desktop (crbug.com/381679686), affects flake rate of other tests") public void testTabToGridAndBack_SoftCleanup_Ntp() { - WebPageStation firstPage = mInitialStateRule.startOnBlankPage(); + WebPageStation firstPage = mCtaTestRule.startOnBlankPage(); RegularNewTabPageStation ntp = firstPage.openNewTabFast(); - ChromeTabbedActivity cta = sActivityTestRule.getActivity(); + ChromeTabbedActivity cta = mCtaTestRule.getActivity(); Runnable resetHTSStateOnUiThread = () -> { var tabSwitcherPane = @@ -368,8 +355,8 @@ @MediumTest @EnableAnimations public void testTabToGridAndBack_HardCleanup() { - WebPageStation firstPage = mInitialStateRule.startOnBlankPage(); - ChromeTabbedActivity cta = sActivityTestRule.getActivity(); + WebPageStation firstPage = mCtaTestRule.startOnBlankPage(); + ChromeTabbedActivity cta = mCtaTestRule.getActivity(); Runnable resetHTSStateOnUiThread = () -> { var tabSwitcherPane = @@ -395,8 +382,8 @@ @MediumTest @EnableAnimations public void testTabToGridAndBack_NoCoordinator() { - WebPageStation firstPage = mInitialStateRule.startOnBlankPage(); - ChromeTabbedActivity cta = sActivityTestRule.getActivity(); + WebPageStation firstPage = mCtaTestRule.startOnBlankPage(); + ChromeTabbedActivity cta = mCtaTestRule.getActivity(); Runnable resetHTSStateOnUiThread = () -> { var tabSwitcherPane = @@ -422,7 +409,7 @@ @Test @MediumTest public void testTabGroupColorInTabSwitcher() { - WebPageStation firstPage = mInitialStateRule.startOnBlankPage(); + WebPageStation firstPage = mCtaTestRule.startOnBlankPage(); // Expect that the the dialog is dismissed via backpress. HistogramWatcher watcher = @@ -455,7 +442,7 @@ @Test @MediumTest public void testTabGroupCreation_acceptInputValues() { - WebPageStation firstPage = mInitialStateRule.startOnBlankPage(); + WebPageStation firstPage = mCtaTestRule.startOnBlankPage(); // Expect that the the dialog is accepted. var histograms = @@ -494,7 +481,7 @@ @Test @MediumTest public void testTabGroupCreation_acceptNullTitle() { - WebPageStation firstPage = mInitialStateRule.startOnBlankPage(); + WebPageStation firstPage = mCtaTestRule.startOnBlankPage(); // Open 2 tabs int firstTabId = firstPage.getLoadedTab().getId(); @@ -523,7 +510,7 @@ @Test @MediumTest public void testTabGroupCreation_dismissEmptyTitle() { - WebPageStation firstPage = mInitialStateRule.startOnBlankPage(); + WebPageStation firstPage = mCtaTestRule.startOnBlankPage(); // Open 2 tabs int firstTabId = firstPage.getLoadedTab().getId(); @@ -554,7 +541,7 @@ @Test @MediumTest public void testTabGroupCreation_rejectInvalidTitle() { - WebPageStation firstPage = mInitialStateRule.startOnBlankPage(); + WebPageStation firstPage = mCtaTestRule.startOnBlankPage(); // Open 2 tabs int firstTabId = firstPage.getLoadedTab().getId(); @@ -589,7 +576,7 @@ @Test @MediumTest public void testTabGroupCreation_dismissSavesState() { - WebPageStation firstPage = mInitialStateRule.startOnBlankPage(); + WebPageStation firstPage = mCtaTestRule.startOnBlankPage(); // Open 2 tabs int firstTabId = firstPage.getLoadedTab().getId(); @@ -618,7 +605,7 @@ @Test @MediumTest public void testTabGroupOverflowMenuInTabSwitcher_closeGroup() { - WebPageStation firstPage = mInitialStateRule.startOnBlankPage(); + WebPageStation firstPage = mCtaTestRule.startOnBlankPage(); // Open 2 tabs int firstTabId = firstPage.getLoadedTab().getId(); @@ -665,10 +652,7 @@ ThreadUtils.runOnUiThreadBlocking( () -> { ImageView view = - (ImageView) - sActivityTestRule - .getActivity() - .findViewById(R.id.tab_thumbnail); + (ImageView) mCtaTestRule.getActivity().findViewById(R.id.tab_thumbnail); mBitmap = new WeakReference<>(((BitmapDrawable) view.getDrawable()).getBitmap()); assertNotNull(mBitmap.get()); @@ -705,7 +689,7 @@ assertEquals( ColorStateList.valueOf( ColorPickerUtils.getTabGroupColorPickerItemColor( - sActivityTestRule.getActivity(), color, false)), + mCtaTestRule.getActivity(), color, false)), drawable.getColor()); }); }
diff --git a/chrome/android/features/tab_ui/javatests/src/org/chromium/chrome/browser/tasks/tab_management/TabSwitcherListEditorPTTest.java b/chrome/android/features/tab_ui/javatests/src/org/chromium/chrome/browser/tasks/tab_management/TabSwitcherListEditorPTTest.java index 6a164cf..0b50f81 100644 --- a/chrome/android/features/tab_ui/javatests/src/org/chromium/chrome/browser/tasks/tab_management/TabSwitcherListEditorPTTest.java +++ b/chrome/android/features/tab_ui/javatests/src/org/chromium/chrome/browser/tasks/tab_management/TabSwitcherListEditorPTTest.java
@@ -9,7 +9,6 @@ import androidx.test.filters.MediumTest; -import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; @@ -25,8 +24,8 @@ import org.chromium.chrome.browser.tabmodel.TabList; import org.chromium.chrome.browser.tabmodel.TabModel; import org.chromium.chrome.test.ChromeJUnit4ClassRunner; -import org.chromium.chrome.test.ChromeTabbedActivityTestRule; -import org.chromium.chrome.test.transit.BlankCTATabInitialStatePublicTransitRule; +import org.chromium.chrome.test.transit.AutoResetCtaTransitTestRule; +import org.chromium.chrome.test.transit.ChromeTransitTestRules; import org.chromium.chrome.test.transit.Journeys; import org.chromium.chrome.test.transit.hub.NewTabGroupDialogFacility; import org.chromium.chrome.test.transit.hub.RegularTabSwitcherStation; @@ -51,18 +50,14 @@ // or enable Google Sans (Text) in //chrome/ tests on Android T+. @Features.DisableFeatures(ChromeFeatureList.ANDROID_ELEGANT_TEXT_HEIGHT) public class TabSwitcherListEditorPTTest { - @ClassRule - public static ChromeTabbedActivityTestRule sActivityTestRule = - new ChromeTabbedActivityTestRule(); - @Rule - public BlankCTATabInitialStatePublicTransitRule mInitialStateRule = - new BlankCTATabInitialStatePublicTransitRule(sActivityTestRule); + public AutoResetCtaTransitTestRule mCtaTestRule = + ChromeTransitTestRules.autoResetCtaActivityRule(); @Test @MediumTest public void testLeaveEditorViaBackPress() { - WebPageStation firstPage = mInitialStateRule.startOnBlankPage(); + WebPageStation firstPage = mCtaTestRule.startOnBlankPage(); RegularTabSwitcherStation tabSwitcher = firstPage.openRegularTabSwitcher(); TabSwitcherListEditorFacility editor = tabSwitcher.openAppMenu().clickSelectTabs(); editor.pressBackToExit(); @@ -75,7 +70,7 @@ @Test @MediumTest public void testCreateTabGroupOf1() { - WebPageStation firstPage = mInitialStateRule.startOnBlankPage(); + WebPageStation firstPage = mCtaTestRule.startOnBlankPage(); int firstTabId = firstPage.getLoadedTab().getId(); RegularTabSwitcherStation tabSwitcher = firstPage.openRegularTabSwitcher(); TabSwitcherListEditorFacility editor = tabSwitcher.openAppMenu().clickSelectTabs(); @@ -95,7 +90,7 @@ @Test @MediumTest public void testClose2Tabs() { - WebPageStation firstPage = mInitialStateRule.startOnBlankPage(); + WebPageStation firstPage = mCtaTestRule.startOnBlankPage(); int firstTabId = firstPage.getLoadedTab().getId(); RegularNewTabPageStation secondPage = firstPage.openNewTabFast(); int secondTabId = secondPage.getLoadedTab().getId(); @@ -119,7 +114,7 @@ @Test @MediumTest public void testCreateTabGroupOf2() { - WebPageStation firstPage = mInitialStateRule.startOnBlankPage(); + WebPageStation firstPage = mCtaTestRule.startOnBlankPage(); int firstTabId = firstPage.getLoadedTab().getId(); RegularNewTabPageStation secondPage = firstPage.openNewTabFast(); int secondTabId = secondPage.getLoadedTab().getId(); @@ -144,15 +139,10 @@ @MediumTest @RequiresRestart("crbug.com/378502216") public void testCreateTabGroupOf10() { - WebPageStation firstPage = mInitialStateRule.startOnBlankPage(); + WebPageStation firstPage = mCtaTestRule.startOnBlankPage(); WebPageStation pageStation = - Journeys.prepareTabsWithThumbnails( - firstPage, - 10, - 0, - "about:blank", - WebPageStation::newBuilder - ); + Journeys.prepareTabsWithThumbnails( + firstPage, 10, 0, "about:blank", WebPageStation::newBuilder); RegularTabSwitcherStation tabSwitcher = pageStation.openRegularTabSwitcher(); Journeys.mergeAllTabsToNewGroup(tabSwitcher); @@ -165,20 +155,23 @@ @MediumTest @RequiresRestart("crbug.com/378502216") public void testCreate10TabsAndCreateTabGroupOf4() { - WebPageStation firstPage = mInitialStateRule.startOnBlankPage(); + WebPageStation firstPage = mCtaTestRule.startOnBlankPage(); WebPageStation pageStation = - Journeys.prepareTabsWithThumbnails( - firstPage, - 10, - 0, - "about:blank", - WebPageStation::newBuilder - ); + Journeys.prepareTabsWithThumbnails( + firstPage, 10, 0, "about:blank", WebPageStation::newBuilder); RegularTabSwitcherStation tabSwitcher = pageStation.openRegularTabSwitcher(); - TabList tabList = tabSwitcher.getTabModelSelectorSupplier().get() - .getCurrentModel().getComprehensiveModel(); - List<Tab> tabs = List.of(tabList.getTabAt(0), - tabList.getTabAt(3), tabList.getTabAt(5), tabList.getTabAt(9)); + TabList tabList = + tabSwitcher + .getTabModelSelectorSupplier() + .get() + .getCurrentModel() + .getComprehensiveModel(); + List<Tab> tabs = + List.of( + tabList.getTabAt(0), + tabList.getTabAt(3), + tabList.getTabAt(5), + tabList.getTabAt(9)); Journeys.mergeTabsToNewGroup(tabSwitcher, tabs); // Go back to PageStation for InitialStateRule to reset @@ -190,7 +183,7 @@ @MediumTest @RequiresRestart("crbug.com/378502216") public void testCreate2TabGroups() { - WebPageStation pageStation = mInitialStateRule.startOnBlankPage(); + WebPageStation pageStation = mCtaTestRule.startOnBlankPage(); pageStation = Journeys.prepareTabsWithThumbnails( pageStation, 10, 0, "about:blank", WebPageStation::newBuilder); @@ -221,7 +214,7 @@ @Test @MediumTest public void testUndoCreateTabGroup() { - WebPageStation firstPage = mInitialStateRule.startOnBlankPage(); + WebPageStation firstPage = mCtaTestRule.startOnBlankPage(); TabModel tabModel = firstPage.getActivity().getCurrentTabModel();
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/app/appmenu/AppMenuPropertiesDelegateImpl.java b/chrome/android/java/src/org/chromium/chrome/browser/app/appmenu/AppMenuPropertiesDelegateImpl.java index 958d1c8..0ac6e10 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/app/appmenu/AppMenuPropertiesDelegateImpl.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/app/appmenu/AppMenuPropertiesDelegateImpl.java
@@ -33,6 +33,7 @@ import org.chromium.base.CallbackController; import org.chromium.base.ResettersForTesting; import org.chromium.base.metrics.RecordHistogram; +import org.chromium.base.metrics.RecordUserAction; import org.chromium.base.supplier.ObservableSupplier; import org.chromium.base.supplier.OneshotSupplier; import org.chromium.base.supplier.Supplier; @@ -1443,6 +1444,20 @@ && !currentTab.isIncognito()) { BrowserUiUtils.recordModuleClickHistogram(ModuleTypeOnStartAndNtp.MENU_BUTTON); } + switch (getMenuGroup()) { + case MenuGroup.PAGE_MENU: + RecordUserAction.record("MobileMenuShow.PageMenu"); + break; + case MenuGroup.OVERVIEW_MODE_MENU: + RecordUserAction.record("MobileMenuShow.OverviewModeMenu"); + break; + case MenuGroup.TABLET_EMPTY_MODE_MENU: + RecordUserAction.record("MobileMenuShow.TabletEmptyModeMenu"); + break; + case MenuGroup.INVALID: // fallthrough + default: + // Intentional noop. + } } public @StringRes int getAddToGroupMenuItemString() {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/strip/StripLayoutHelper.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/strip/StripLayoutHelper.java index 849e665..c0e60a26 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/strip/StripLayoutHelper.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/strip/StripLayoutHelper.java
@@ -4200,19 +4200,20 @@ // 2. Anchor the popupMenu to the view associated with the tab View tabView = TabModelUtils.getCurrentTab(mModel).getView(); mCloseButtonMenu.setAnchorView(tabView); - // 3. Set the vertical offset to align the tab menu with bottom of the tab strip + // 3. Set the vertical offset to align the close button menu with bottom of the tab strip int tabHeight = mManagerHost.getHeight(); int verticalOffset = -(tabHeight - (int) mContext.getResources().getDimension(R.dimen.tab_strip_height)); mCloseButtonMenu.setVerticalOffset(verticalOffset); - // 4. Set the horizontal offset to align the tab menu with the right side of the tab + // 4. Set the horizontal offset to align the close button menu with the right side of the + // tab int horizontalOffset = Math.round( (anchorTab.getDrawX() + anchorTab.getWidth()) * mContext.getResources().getDisplayMetrics().density) - mCloseButtonMenu.getWidth(); - // Cap the horizontal offset so that the tab menu doesn't get drawn off screen. + // Cap the horizontal offset so that the close button menu doesn't get drawn off screen. horizontalOffset = Math.max(horizontalOffset, 0); mCloseButtonMenu.setHorizontalOffset(horizontalOffset); @@ -4303,7 +4304,7 @@ } /** - * @return true if the tab menu is showing + * @return true if the close button menu is showing */ public boolean isCloseButtonMenuShowingForTesting() { return mCloseButtonMenu.isShowing();
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/dom_distiller/ReaderModeManager.java b/chrome/android/java/src/org/chromium/chrome/browser/dom_distiller/ReaderModeManager.java index c4bb396..7883cb7 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/dom_distiller/ReaderModeManager.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/dom_distiller/ReaderModeManager.java
@@ -9,6 +9,7 @@ import android.content.res.Resources; import android.net.Uri; import android.os.SystemClock; +import android.util.Pair; import androidx.annotation.IntDef; import androidx.annotation.NonNull; @@ -68,9 +69,9 @@ import java.util.LinkedHashSet; /** - * Manages UI effects for reader mode including hiding and showing the - * reader mode and reader mode preferences toolbar icon and hiding the - * browser controls when a reader mode page has finished loading. + * Manages UI effects for reader mode including hiding and showing the reader mode and reader mode + * preferences toolbar icon and hiding the browser controls when a reader mode page has finished + * loading. */ public class ReaderModeManager extends EmptyTabObserver implements UserData { /** Possible states that the distiller can be in on a web page. */ @@ -116,8 +117,8 @@ /** The url of the last page visited if the last page was reader mode page. Otherwise null. */ private GURL mReaderModePageUrl; - /** Whether the fact that the current web page was distillable or not has been recorded. */ - private boolean mIsUmaRecorded; + /** Whether the current web page was distillable or not has been determined. */ + private boolean mIsCurrentPageDistillationStatusDetermined; /** The WebContentsObserver responsible for updates to the distillation status of the tab. */ private WebContentsObserver mWebContentsObserver; @@ -427,7 +428,7 @@ DomDistillerUrlUtils.getOriginalUrlFromDistillerUrl( mReaderModePageUrl))) { mDistillationStatus = DistillationStatus.NOT_POSSIBLE; - mIsUmaRecorded = false; + mIsCurrentPageDistillationStatusDetermined = false; } mReaderModePageUrl = null; @@ -473,7 +474,7 @@ // This prompt should only be shown on incognito or custom tabs, in other cases we'll show a // toolbar button (contextual page action) instead. - if (!mTab.isCustomTab() && !mTab.isIncognito()) return; + if (!shouldUseReaderModeMessages(mTab)) return; // Test if the user is requesting the desktop site. Ignore this if distiller is set to // ALWAYS_TRUE. @@ -672,36 +673,79 @@ (tab, isDistillable, isLast, isMobileOptimized) -> { // Make sure the page didn't navigate while waiting for a response. if (!tab.getUrl().equals(mDistillerUrl)) return; + // Make sure the page distillation status hasn't already been determined. + if (mIsCurrentPageDistillationStatusDetermined) return; + // Make sure that reader mode messages infra should be used. + if (!shouldUseReaderModeMessages(tab)) return; - // So here we want to record (1) is the page distillable - boolean shouldExcludeMobileFriendly = - DomDistillerTabUtils.shouldExcludeMobileFriendly(tabToObserve); - boolean excludeCurrentMobilePage = - isMobileOptimized && shouldExcludeMobileFriendly; - if (isDistillable && !excludeCurrentMobilePage) { - mDistillationStatus = DistillationStatus.POSSIBLE; + Pair<Boolean, Integer> result = + ReaderModeManager.computeDistillationStatus( + tab, isDistillable, isMobileOptimized, isLast); + mIsCurrentPageDistillationStatusDetermined = result.first; + mDistillationStatus = result.second; + if (mIsCurrentPageDistillationStatusDetermined) { tryShowingPrompt(); - } else { - mDistillationStatus = DistillationStatus.NOT_POSSIBLE; - } - if (!mIsUmaRecorded - && (mDistillationStatus == DistillationStatus.POSSIBLE || isLast)) { - mIsUmaRecorded = true; - RecordHistogram.recordBooleanHistogram( - ACCESSIBILITY_SETTING_HISTOGRAM, - DomDistillerTabUtils.isReaderModeAccessibilitySettingEnabled( - tabToObserve.getProfile())); - RecordHistogram.recordBooleanHistogram( - DISTILLABLE_MOBILE_PAGE_EXCLUDED_HISTOGRAM, - isDistillable && excludeCurrentMobilePage); - RecordHistogram.recordBooleanHistogram( - PAGE_DISTILLABLE_RESULT_HISTOGRAM, - mDistillationStatus == DistillationStatus.POSSIBLE); } }; TabDistillabilityProvider.get(tabToObserve).addObserver(mDistillabilityObserver); } + // Returns whether reader mode should trigger through messages. This happens for CCTs and + // incognito tabs. + private boolean shouldUseReaderModeMessages(Tab tab) { + return tab != null && (tab.isCustomTab() || tab.isIncognito()); + } + + /** + * Gets the distillation status for the given arguments, and records metrics if distillability + * has been fully determined. + * + * @param tab The {@link Tab} to determine distillability for. + * @param isDistillable Whether the tab is considered distillable. + * @param isMobileOptimized Whether the tab is considered optimized for mobile. + * @param isLast Whether this is the last signal we'll get for the tab. + * @returns A pair which contains: pair.first - Whether distillability has been fully + * determined. pair.second - The current distillation status. + */ + public static Pair<Boolean, Integer> computeDistillationStatus( + Tab tab, boolean isDistillable, boolean isMobileOptimized, boolean isLast) { + // Compute if mobile friendly pages should be excluded for use in distillation status as + // well as metrics recording. + boolean shouldExcludeMobileFriendly = DomDistillerTabUtils.shouldExcludeMobileFriendly(tab); + boolean excludeCurrentMobilePage = isMobileOptimized && shouldExcludeMobileFriendly; + // Test if the user is requesting the desktop site. Ignore this if distiller is set to + // ALWAYS_TRUE. + // TODO(crbug.com/405186704): Add histogram when RDS results in a RM exclusion. + boolean excludeRequestDesktopSite = + tab.getWebContents() != null + && tab.getWebContents().getNavigationController().getUseDesktopUserAgent() + && !DomDistillerTabUtils.isHeuristicAlwaysTrue(); + + // Determine and store distillation status. + @DistillationStatus int distillationStatus; + if (isDistillable && !excludeCurrentMobilePage && !excludeRequestDesktopSite) { + distillationStatus = DistillationStatus.POSSIBLE; + } else { + distillationStatus = DistillationStatus.NOT_POSSIBLE; + } + + // If we get a positive distillation status, or a signal that this is the last distillation + // signal we'll receive, record metrics and inform the user. + if (distillationStatus == DistillationStatus.POSSIBLE || isLast) { + RecordHistogram.recordBooleanHistogram( + ACCESSIBILITY_SETTING_HISTOGRAM, + DomDistillerTabUtils.isReaderModeAccessibilitySettingEnabled(tab.getProfile())); + RecordHistogram.recordBooleanHistogram( + DISTILLABLE_MOBILE_PAGE_EXCLUDED_HISTOGRAM, + isDistillable && excludeCurrentMobilePage); + RecordHistogram.recordBooleanHistogram( + PAGE_DISTILLABLE_RESULT_HISTOGRAM, + distillationStatus == DistillationStatus.POSSIBLE); + return new Pair<>(true, distillationStatus); + } + return new Pair<>(false, distillationStatus); + } + private int urlToHash(GURL url) { return url.getHost().hashCode(); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/hub/HubLayoutPublicTransitTest.java b/chrome/android/java/src/org/chromium/chrome/browser/hub/HubLayoutPublicTransitTest.java index 1fdf696b..34cb3b4 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/hub/HubLayoutPublicTransitTest.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/hub/HubLayoutPublicTransitTest.java
@@ -13,7 +13,6 @@ import androidx.test.filters.LargeTest; -import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; @@ -26,8 +25,8 @@ import org.chromium.chrome.browser.flags.ChromeFeatureList; import org.chromium.chrome.browser.flags.ChromeSwitches; import org.chromium.chrome.test.ChromeJUnit4ClassRunner; -import org.chromium.chrome.test.ChromeTabbedActivityTestRule; -import org.chromium.chrome.test.transit.BlankCTATabInitialStatePublicTransitRule; +import org.chromium.chrome.test.transit.AutoResetCtaTransitTestRule; +import org.chromium.chrome.test.transit.ChromeTransitTestRules; import org.chromium.chrome.test.transit.hub.IncognitoTabSwitcherStation; import org.chromium.chrome.test.transit.hub.RegularTabSwitcherStation; import org.chromium.chrome.test.transit.hub.TabSwitcherAppMenuFacility; @@ -41,18 +40,14 @@ @CommandLineFlags.Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE}) @Batch(Batch.PER_CLASS) public class HubLayoutPublicTransitTest { - @ClassRule - public static ChromeTabbedActivityTestRule sActivityTestRule = - new ChromeTabbedActivityTestRule(); - @Rule - public BlankCTATabInitialStatePublicTransitRule mInitialStateRule = - new BlankCTATabInitialStatePublicTransitRule(sActivityTestRule); + public AutoResetCtaTransitTestRule mCtaTestRule = + ChromeTransitTestRules.autoResetCtaActivityRule(); @Test @LargeTest public void testEnterAndExitHub() { - WebPageStation firstPage = mInitialStateRule.startOnBlankPage(); + WebPageStation firstPage = mCtaTestRule.startOnBlankPage(); RegularTabSwitcherStation tabSwitcher = firstPage.openRegularTabSwitcher(); firstPage = tabSwitcher.leaveHubToPreviousTabViaBack(WebPageStation.newBuilder()); @@ -63,7 +58,7 @@ @Test @LargeTest public void testEnterHubAndLeaveViaAppMenuNewTab() { - WebPageStation firstPage = mInitialStateRule.startOnBlankPage(); + WebPageStation firstPage = mCtaTestRule.startOnBlankPage(); RegularTabSwitcherStation tabSwitcher = firstPage.openRegularTabSwitcher(); TabSwitcherAppMenuFacility appMenu = tabSwitcher.openAppMenu(); @@ -75,7 +70,7 @@ @Test @LargeTest public void testEnterHubAndLeaveViaAppMenuNewIncognitoTab() { - WebPageStation firstPage = mInitialStateRule.startOnBlankPage(); + WebPageStation firstPage = mCtaTestRule.startOnBlankPage(); RegularTabSwitcherStation tabSwitcher = firstPage.openRegularTabSwitcher(); TabSwitcherAppMenuFacility appMenu = tabSwitcher.openAppMenu(); @@ -87,7 +82,7 @@ @Test @LargeTest public void testChangeTabSwitcherPanes() { - WebPageStation firstPage = mInitialStateRule.startOnBlankPage(); + WebPageStation firstPage = mCtaTestRule.startOnBlankPage(); IncognitoNewTabPageStation incognitoNewTabPage = firstPage.openNewIncognitoTabFast(); IncognitoTabSwitcherStation incognitoTabSwitcher = @@ -112,7 +107,7 @@ public void testExitHubOnStartSurfaceAsNtp() { ChromeFeatureList.sStartSurfaceReturnTimeTabletSecs.setForTesting(0); - WebPageStation blankPage = mInitialStateRule.startOnBlankPage(); + WebPageStation blankPage = mCtaTestRule.startOnBlankPage(); RegularNewTabPageStation newTabPage = blankPage.openNewTabFast(); RegularTabSwitcherStation tabSwitcher = newTabPage.openRegularTabSwitcher(); blankPage = tabSwitcher.selectTabAtIndex(0, WebPageStation.newBuilder()); @@ -132,10 +127,10 @@ currentStation.travelToSync( destination, () -> { - ChromeTabbedActivity cta = sActivityTestRule.getActivity(); + ChromeTabbedActivity cta = mCtaTestRule.getActivity(); ChromeApplicationTestUtils.fireHomeScreenIntent(cta); try { - sActivityTestRule.resumeMainActivityFromLauncher(); + mCtaTestRule.getActivityTestRule().resumeMainActivityFromLauncher(); } catch (Exception e) { throw new RuntimeException(e); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/segmentation_platform/ReaderModeActionProvider.java b/chrome/android/java/src/org/chromium/chrome/browser/segmentation_platform/ReaderModeActionProvider.java index a7e564e6..4d58b55 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/segmentation_platform/ReaderModeActionProvider.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/segmentation_platform/ReaderModeActionProvider.java
@@ -6,9 +6,10 @@ import android.os.Handler; import android.os.Looper; +import android.util.Pair; -import org.chromium.chrome.browser.dom_distiller.DomDistillerTabUtils; import org.chromium.chrome.browser.dom_distiller.ReaderModeManager; +import org.chromium.chrome.browser.dom_distiller.ReaderModeManager.DistillationStatus; import org.chromium.chrome.browser.dom_distiller.TabDistillabilityProvider; import org.chromium.chrome.browser.dom_distiller.TabDistillabilityProvider.DistillabilityObserver; import org.chromium.chrome.browser.tab.Tab; @@ -20,12 +21,16 @@ public void getAction(Tab tab, SignalAccumulator signalAccumulator) { final TabDistillabilityProvider tabDistillabilityProvider = TabDistillabilityProvider.get(tab); + // TODO(crbug.com/405420546): Consider emitting a signal from TabDistillabilityProvider when + // an observer is added if distillability is already determined. if (tabDistillabilityProvider.isDistillabilityDetermined()) { - notifyActionAvailable( - tabDistillabilityProvider.isDistillable(), - tabDistillabilityProvider.isMobileOptimized(), - tab, - signalAccumulator); + Pair<Boolean, Integer> result = + ReaderModeManager.computeDistillationStatus( + tab, + tabDistillabilityProvider.isDistillable(), + tabDistillabilityProvider.isMobileOptimized(), + /* isLast= */ true); + notifyActionAvailable(result.second == DistillationStatus.POSSIBLE, signalAccumulator); return; } @@ -38,9 +43,18 @@ boolean isDistillable, boolean isLast, boolean isMobileOptimized) { - notifyActionAvailable( - isDistillable, isMobileOptimized, tab, signalAccumulator); - tabDistillabilityProvider.removeObserver(this); + Pair<Boolean, Integer> result = + ReaderModeManager.computeDistillationStatus( + tab, + tabDistillabilityProvider.isDistillable(), + tabDistillabilityProvider.isMobileOptimized(), + /* isLast= */ true); + if (result.first) { + notifyActionAvailable( + result.second == DistillationStatus.POSSIBLE, + signalAccumulator); + tabDistillabilityProvider.removeObserver(this); + } } }; tabDistillabilityProvider.addObserver(distillabilityObserver); @@ -66,30 +80,9 @@ /* delayMillis= */ 500); } - private void notifyActionAvailable( - boolean isDistillable, - boolean isMobileOptimized, - Tab tab, - SignalAccumulator signalAccumulator) { + private void notifyActionAvailable(boolean isDistillable, SignalAccumulator signalAccumulator) { // TODO(shaktisahu): Can we merge these into a single method call? - signalAccumulator.setHasReaderMode(isDistillable && !isFilteredOut(tab, isMobileOptimized)); + signalAccumulator.setHasReaderMode(isDistillable); signalAccumulator.notifySignalAvailable(); } - - private boolean isFilteredOut(Tab tab, boolean isMobileOptimized) { - // Test if the user is requesting the desktop site. Ignore this if distiller is set to - // ALWAYS_TRUE. - boolean usingRequestDesktopSite = - tab.getWebContents() != null - && tab.getWebContents().getNavigationController().getUseDesktopUserAgent() - && !DomDistillerTabUtils.isHeuristicAlwaysTrue(); - - if (usingRequestDesktopSite) return true; - - if (isMobileOptimized && DomDistillerTabUtils.shouldExcludeMobileFriendly(tab)) { - return true; - } - - return false; - } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/segmentation_platform/ReaderModeActionProviderTest.java b/chrome/android/java/src/org/chromium/chrome/browser/segmentation_platform/ReaderModeActionProviderTest.java index 2a3f025..c4ecb12 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/segmentation_platform/ReaderModeActionProviderTest.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/segmentation_platform/ReaderModeActionProviderTest.java
@@ -28,8 +28,13 @@ import org.chromium.chrome.browser.dom_distiller.DomDistillerTabUtils; import org.chromium.chrome.browser.dom_distiller.ReaderModeManager; import org.chromium.chrome.browser.dom_distiller.TabDistillabilityProvider; +import org.chromium.chrome.browser.preferences.Pref; +import org.chromium.chrome.browser.profiles.Profile; import org.chromium.chrome.browser.segmentation_platform.ContextualPageActionController.ActionProvider; import org.chromium.chrome.browser.tab.Tab; +import org.chromium.components.prefs.PrefService; +import org.chromium.components.user_prefs.UserPrefs; +import org.chromium.components.user_prefs.UserPrefsJni; import org.chromium.content_public.browser.NavigationController; import org.chromium.content_public.browser.WebContents; @@ -46,6 +51,9 @@ @Mock private Tab mMockTab; @Mock private ReaderModeManager mMockReaderModeManager; @Mock private SignalAccumulator mMockSignalAccumulator; + @Mock private Profile mProfile; + @Mock private UserPrefs.Natives mUserPrefsJniMock; + @Mock private PrefService mPrefService; @Before public void setUp() { @@ -58,6 +66,11 @@ private void initializeReaderModeBackend() { UserDataHost userDataHost = new UserDataHost(); when(mMockTab.getUserDataHost()).thenReturn(userDataHost); + when(mMockTab.getProfile()).thenReturn(mProfile); + UserPrefsJni.setInstanceForTesting(mUserPrefsJniMock); + when(mUserPrefsJniMock.get(mProfile)).thenReturn(mPrefService); + when(mPrefService.getBoolean(Pref.READER_FOR_ACCESSIBILITY)).thenReturn(false); + TabDistillabilityProvider.createForTab(mMockTab); DomDistillerTabUtils.setExcludeMobileFriendlyForTesting(true); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/suggestions/tile/SuggestionsTileView.java b/chrome/android/java/src/org/chromium/chrome/browser/suggestions/tile/SuggestionsTileView.java index 5c55086..375f7fcb 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/suggestions/tile/SuggestionsTileView.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/suggestions/tile/SuggestionsTileView.java
@@ -30,6 +30,7 @@ /** * Initializes the view using the data held by {@code tile}. This should be called immediately * after inflation. + * * @param tile The tile that holds the data to populate this view. * @param titleLines The number of text lines to use for the tile title. */ @@ -80,5 +81,9 @@ resources.getDimensionPixelSize(R.dimen.tile_view_icon_margin_top_modern); } mIconView.setLayoutParams(params); + + if (mData.source == TileSource.CUSTOM_LINKS) { + setStyleForCustomTile(); + } } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tabbed_mode/TabbedRootUiCoordinator.java b/chrome/android/java/src/org/chromium/chrome/browser/tabbed_mode/TabbedRootUiCoordinator.java index 458acc25..fc6f710 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/tabbed_mode/TabbedRootUiCoordinator.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/tabbed_mode/TabbedRootUiCoordinator.java
@@ -116,6 +116,7 @@ import org.chromium.chrome.browser.profiles.Profile; import org.chromium.chrome.browser.read_later.ReadLaterIphController; import org.chromium.chrome.browser.readaloud.ReadAloudIphController; +import org.chromium.chrome.browser.safe_browsing.AdvancedProtectionCoordinator; import org.chromium.chrome.browser.search_engines.choice_screen.ChoiceDialogCoordinator; import org.chromium.chrome.browser.share.ShareDelegate; import org.chromium.chrome.browser.share.link_to_text.LinkToTextIphController; @@ -249,6 +250,7 @@ private @Nullable LoadingFullscreenCoordinator mLoadingFullscreenCoordinator; private @Nullable BookmarkOpener mBookmarkOpener; private @NonNull ObservableSupplier<BookmarkManagerOpener> mBookmarkManagerOpenerSupplier; + private @NonNull AdvancedProtectionCoordinator mAdvancedProtectionCoordinator; // Activity tab observer that updates the current tab used by various UI components. private class RootUiTabObserver extends ActivityTabTabObserver { @@ -507,6 +509,8 @@ savedInstanceState, mEdgeToEdgeManager.getEdgeToEdgeStateProvider()); mBookmarkManagerOpenerSupplier = bookmarkManagerOpenerSupplier; + + mAdvancedProtectionCoordinator = new AdvancedProtectionCoordinator(mWindowAndroid); } @Override @@ -625,6 +629,8 @@ mLoadingFullscreenCoordinator = null; } + mAdvancedProtectionCoordinator.destroy(); + super.onDestroy(); } @@ -1536,6 +1542,10 @@ return true; } + if (mAdvancedProtectionCoordinator.showMessageOnStartupIfNeeded()) { + return true; + } + return triggerPromo(profile, intentWithEffect); }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/PopupPTTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/PopupPTTest.java index ed1fa90..02317ba 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/PopupPTTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/PopupPTTest.java
@@ -14,7 +14,6 @@ import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; -import org.junit.ClassRule; import org.junit.FixMethodOrder; import org.junit.Rule; import org.junit.Test; @@ -25,8 +24,8 @@ import org.chromium.base.test.util.CommandLineFlags; import org.chromium.chrome.browser.flags.ChromeSwitches; import org.chromium.chrome.test.ChromeJUnit4ClassRunner; -import org.chromium.chrome.test.ChromeTabbedActivityTestRule; -import org.chromium.chrome.test.transit.BlankCTATabInitialStatePublicTransitRule; +import org.chromium.chrome.test.transit.AutoResetCtaTransitTestRule; +import org.chromium.chrome.test.transit.ChromeTransitTestRules; import org.chromium.chrome.test.transit.page.PopupBlockedMessageFacility; import org.chromium.chrome.test.transit.page.WebPageStation; import org.chromium.chrome.test.transit.testhtmls.PopupOnClickPageStation; @@ -39,13 +38,9 @@ @Batch(Batch.PER_CLASS) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class PopupPTTest { - @ClassRule - public static ChromeTabbedActivityTestRule sActivityTestRule = - new ChromeTabbedActivityTestRule(); - @Rule - public BlankCTATabInitialStatePublicTransitRule mInitialStateRule = - new BlankCTATabInitialStatePublicTransitRule(sActivityTestRule); + public AutoResetCtaTransitTestRule mCtaTestRule = + ChromeTransitTestRules.autoResetCtaActivityRule(); private static final String METADATA_FOR_ABUSIVE_ENFORCEMENT = "{\"matches\":[{\"threat_type\":\"13\",\"sf_absv\":\"\"}]}"; @@ -65,7 +60,7 @@ @Before public void setUp() { - mEntryPage = mInitialStateRule.startOnBlankPage(); + mEntryPage = mCtaTestRule.startOnBlankPage(); } @After @@ -77,20 +72,23 @@ @MediumTest public void test010PopupOnLoadBlocked() { var pair = - PopupOnLoadPageStation.loadInCurrentTabExpectBlocked(sActivityTestRule, mEntryPage); + PopupOnLoadPageStation.loadInCurrentTabExpectBlocked( + mCtaTestRule.getActivityTestRule(), mEntryPage); PopupOnLoadPageStation page = pair.first; PopupBlockedMessageFacility popupBlockedMessage = pair.second; - assertEquals(1, sActivityTestRule.tabsCount(/* incognito= */ false)); + assertEquals(1, mCtaTestRule.tabsCount(/* incognito= */ false)); popupBlockedMessage.dismiss(); // Test that dismissing does not allow the popups and they get blocked again - pair = PopupOnLoadPageStation.loadInCurrentTabExpectBlocked(sActivityTestRule, page); + pair = + PopupOnLoadPageStation.loadInCurrentTabExpectBlocked( + mCtaTestRule.getActivityTestRule(), page); page = pair.first; popupBlockedMessage = pair.second; - assertEquals(1, sActivityTestRule.tabsCount(/* incognito= */ false)); + assertEquals(1, mCtaTestRule.tabsCount(/* incognito= */ false)); assertFinalDestination(page, popupBlockedMessage); } @@ -98,10 +96,11 @@ @MediumTest public void test020SafeGestureTabNotBlocked() { PopupOnClickPageStation page = - PopupOnClickPageStation.loadInCurrentTab(sActivityTestRule, mEntryPage); + PopupOnClickPageStation.loadInCurrentTab( + mCtaTestRule.getActivityTestRule(), mEntryPage); page = page.clickLinkToOpenPopup(); - assertEquals(2, sActivityTestRule.tabsCount(/* incognito= */ false)); + assertEquals(2, mCtaTestRule.tabsCount(/* incognito= */ false)); assertFinalDestination(page); } @@ -111,21 +110,22 @@ @MediumTest public void test900PopupWindowsAppearWhenAllowed() { PopupBlockedMessageFacility popupBlockedMessage = - PopupOnLoadPageStation.loadInCurrentTabExpectBlocked(sActivityTestRule, mEntryPage) + PopupOnLoadPageStation.loadInCurrentTabExpectBlocked( + mCtaTestRule.getActivityTestRule(), mEntryPage) .second; - assertEquals(1, sActivityTestRule.tabsCount(/* incognito= */ false)); + assertEquals(1, mCtaTestRule.tabsCount(/* incognito= */ false)); // Click the "Always allow" button. WebPageStation poppedUpPage = popupBlockedMessage.clickAlwaysAllow(); - assertEquals(3, sActivityTestRule.tabsCount(/* incognito= */ false)); + assertEquals(3, mCtaTestRule.tabsCount(/* incognito= */ false)); // Test that revisiting the original page makes pop-up windows show immediately. // The second pop-up opens navigate/page_two.html. WebPageStation pageTwo = PopupOnLoadPageStation.loadInCurrentTabExpectPopups( - sActivityTestRule, poppedUpPage); + mCtaTestRule.getActivityTestRule(), poppedUpPage); - assertEquals(5, sActivityTestRule.tabsCount(/* incognito= */ false)); + assertEquals(5, mCtaTestRule.tabsCount(/* incognito= */ false)); assertFinalDestination(pageTwo); } @@ -133,15 +133,16 @@ @MediumTest public void test030AbusiveGesturePopupBlocked() { MockSafeBrowsingApiHandler.addMockResponse( - sActivityTestRule.getTestServer().getURL(PopupOnClickPageStation.PATH), + mCtaTestRule.getTestServer().getURL(PopupOnClickPageStation.PATH), MockSafeBrowsingApiHandler.ABUSIVE_EXPERIENCE_VIOLATION_CODE); PopupOnClickPageStation page = - PopupOnClickPageStation.loadInCurrentTab(sActivityTestRule, mEntryPage); + PopupOnClickPageStation.loadInCurrentTab( + mCtaTestRule.getActivityTestRule(), mEntryPage); PopupBlockedMessageFacility popupBlockedMessage = page.clickLinkAndExpectPopupBlockedMessage(); - assertEquals(1, sActivityTestRule.tabsCount(/* incognito= */ false)); + assertEquals(1, mCtaTestRule.tabsCount(/* incognito= */ false)); assertFinalDestination(page, popupBlockedMessage); } }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/app/appmenu/TabbedAppMenuPTTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/app/appmenu/TabbedAppMenuPTTest.java index 61d0c4c..a346849c 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/app/appmenu/TabbedAppMenuPTTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/app/appmenu/TabbedAppMenuPTTest.java
@@ -10,7 +10,6 @@ import androidx.test.filters.LargeTest; -import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; @@ -25,8 +24,8 @@ import org.chromium.chrome.browser.layouts.LayoutType; import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.test.ChromeJUnit4ClassRunner; -import org.chromium.chrome.test.ChromeTabbedActivityTestRule; -import org.chromium.chrome.test.transit.BlankCTATabInitialStatePublicTransitRule; +import org.chromium.chrome.test.transit.AutoResetCtaTransitTestRule; +import org.chromium.chrome.test.transit.ChromeTransitTestRules; import org.chromium.chrome.test.transit.hub.RegularTabSwitcherStation; import org.chromium.chrome.test.transit.ntp.IncognitoNewTabPageAppMenuFacility; import org.chromium.chrome.test.transit.ntp.IncognitoNewTabPageStation; @@ -46,13 +45,9 @@ @CommandLineFlags.Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE}) @Batch(Batch.PER_CLASS) public class TabbedAppMenuPTTest { - @ClassRule - public static ChromeTabbedActivityTestRule sActivityTestRule = - new ChromeTabbedActivityTestRule(); - @Rule - public BlankCTATabInitialStatePublicTransitRule mInitialStateRule = - new BlankCTATabInitialStatePublicTransitRule(sActivityTestRule); + public AutoResetCtaTransitTestRule mCtaTestRule = + ChromeTransitTestRules.autoResetCtaActivityRule(); @Rule public final ChromeRenderTestRule mRenderTestRule = @@ -67,10 +62,10 @@ @LargeTest public void testOpenNewTab() { RegularNewTabPageStation newTabPage = - mInitialStateRule.startOnBlankPage().openRegularTabAppMenu().openNewTab(); + mCtaTestRule.startOnBlankPage().openRegularTabAppMenu().openNewTab(); - assertEquals(2, sActivityTestRule.tabsCount(/* incognito= */ false)); - assertEquals(0, sActivityTestRule.tabsCount(/* incognito= */ true)); + assertEquals(2, mCtaTestRule.tabsCount(/* incognito= */ false)); + assertEquals(0, mCtaTestRule.tabsCount(/* incognito= */ true)); assertFinalDestination(newTabPage); } @@ -79,10 +74,10 @@ @LargeTest public void testOpenNewIncognitoTab() { IncognitoNewTabPageStation newIncognitoTabPage = - mInitialStateRule.startOnBlankPage().openRegularTabAppMenu().openNewIncognitoTab(); + mCtaTestRule.startOnBlankPage().openRegularTabAppMenu().openNewIncognitoTab(); - assertEquals(1, sActivityTestRule.tabsCount(/* incognito= */ false)); - assertEquals(1, sActivityTestRule.tabsCount(/* incognito= */ true)); + assertEquals(1, mCtaTestRule.tabsCount(/* incognito= */ false)); + assertEquals(1, mCtaTestRule.tabsCount(/* incognito= */ true)); assertFinalDestination(newIncognitoTabPage); } @@ -90,7 +85,7 @@ @Test @LargeTest public void testOpenSettings() { - WebPageStation pageStation = mInitialStateRule.startOnBlankPage(); + WebPageStation pageStation = mCtaTestRule.startOnBlankPage(); Tab tab = pageStation.getLoadedTab(); SettingsStation settings = pageStation.openRegularTabAppMenu().openSettings(); @@ -113,7 +108,7 @@ @LargeTest @Feature({"RenderTest"}) public void testNewTabPageRegularAppMenuItems() throws IOException { - WebPageStation blankPage = mInitialStateRule.startOnBlankPage(); + WebPageStation blankPage = mCtaTestRule.startOnBlankPage(); RegularNewTabPageStation newTabPage = blankPage.openRegularTabAppMenu().openNewTab(); RegularNewTabPageAppMenuFacility menu = newTabPage.openAppMenu(); @@ -134,7 +129,7 @@ @Feature({"RenderTest"}) public void testNewTabPageIncognitoAppMenuItems() throws IOException { IncognitoNewTabPageStation incognitoNewTabPage = - mInitialStateRule.startOnBlankPage().openRegularTabAppMenu().openNewIncognitoTab(); + mCtaTestRule.startOnBlankPage().openRegularTabAppMenu().openNewIncognitoTab(); IncognitoNewTabPageAppMenuFacility menu = incognitoNewTabPage.openAppMenu(); mRenderTestRule.render(menu.getView(), "incognito_ntp_app_menu"); @@ -153,7 +148,7 @@ @LargeTest @Feature({"RenderTest"}) public void testWebPageRegularAppMenuItems() throws IOException { - WebPageStation blankPage = mInitialStateRule.startOnBlankPage(); + WebPageStation blankPage = mCtaTestRule.startOnBlankPage(); RegularWebPageAppMenuFacility menu = blankPage.openRegularTabAppMenu(); mRenderTestRule.render(menu.getView(), "regular_webpage_app_menu"); @@ -173,11 +168,11 @@ @Feature({"RenderTest"}) public void testWebPageIncognitoAppMenuItems() throws IOException { IncognitoNewTabPageStation incognitoNtp = - mInitialStateRule.startOnBlankPage().openRegularTabAppMenu().openNewIncognitoTab(); + mCtaTestRule.startOnBlankPage().openRegularTabAppMenu().openNewIncognitoTab(); WebPageStation pageOne = incognitoNtp.loadPageProgrammatically( - sActivityTestRule.getTestServer().getURL(NavigatePageStations.PATH_ONE), + mCtaTestRule.getTestServer().getURL(NavigatePageStations.PATH_ONE), NavigatePageStations.newNavigateOnePageBuilder()); IncognitoWebPageAppMenuFacility menu = pageOne.openIncognitoTabAppMenu(); @@ -193,8 +188,8 @@ @Test @LargeTest public void testHideMenuOnToggleOverview() { - WebPageStation page = mInitialStateRule.startOnBlankPage(); - ChromeTabbedActivity activity = sActivityTestRule.getActivity(); + WebPageStation page = mCtaTestRule.startOnBlankPage(); + ChromeTabbedActivity activity = mCtaTestRule.getActivity(); LayoutManagerChrome layoutManager = activity.getLayoutManager(); page.openRegularTabAppMenu();
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/app/edge_to_edge/EdgeToEdgePTTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/app/edge_to_edge/EdgeToEdgePTTest.java index 9366268..815d30b 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/app/edge_to_edge/EdgeToEdgePTTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/app/edge_to_edge/EdgeToEdgePTTest.java
@@ -13,7 +13,6 @@ import androidx.test.filters.MediumTest; import androidx.test.filters.SmallTest; -import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; @@ -30,8 +29,8 @@ import org.chromium.chrome.browser.flags.ChromeFeatureList; import org.chromium.chrome.browser.flags.ChromeSwitches; import org.chromium.chrome.test.ChromeJUnit4ClassRunner; -import org.chromium.chrome.test.ChromeTabbedActivityTestRule; -import org.chromium.chrome.test.transit.BlankCTATabInitialStatePublicTransitRule; +import org.chromium.chrome.test.transit.AutoResetCtaTransitTestRule; +import org.chromium.chrome.test.transit.ChromeTransitTestRules; import org.chromium.chrome.test.transit.edge_to_edge.EdgeToEdgeBottomChinFacility; import org.chromium.chrome.test.transit.edge_to_edge.ViewportFitCoverPageStation; import org.chromium.chrome.test.transit.page.WebPageStation; @@ -58,20 +57,16 @@ @MinAndroidSdkLevel(VERSION_CODES.S_V2) @Restriction({DeviceFormFactor.PHONE, DeviceRestriction.RESTRICTION_TYPE_NON_AUTO}) public class EdgeToEdgePTTest { - @ClassRule - public static ChromeTabbedActivityTestRule sActivityTestRule = - new ChromeTabbedActivityTestRule(); - @Rule - public BlankCTATabInitialStatePublicTransitRule mInitialStateRule = - new BlankCTATabInitialStatePublicTransitRule(sActivityTestRule); + public AutoResetCtaTransitTestRule mCtaTestRule = + ChromeTransitTestRules.autoResetCtaActivityRule(); @Test @SmallTest public void loadViewportFitCover() { - WebPageStation blankPage = mInitialStateRule.startOnBlankPage(); + WebPageStation blankPage = mCtaTestRule.startOnBlankPage(); ViewportFitCoverPageStation e2ePage = - loadViewportFitCoverPage(sActivityTestRule, blankPage); + loadViewportFitCoverPage(mCtaTestRule.getActivityTestRule(), blankPage); TransitAsserts.assertFinalDestination(e2ePage); } @@ -80,9 +75,9 @@ @MediumTest public void openNewTabInGroupAtPageBottom() { ThreadUtils.runOnUiThread(() -> FirstRunStatus.setFirstRunFlowComplete(true)); - WebPageStation blankPage = mInitialStateRule.startOnBlankPage(); + WebPageStation blankPage = mCtaTestRule.startOnBlankPage(); var topBottomLinkPageAndTop = - TopBottomLinksPageStation.loadPage(sActivityTestRule, blankPage); + TopBottomLinksPageStation.loadPage(mCtaTestRule.getActivityTestRule(), blankPage); TopBottomLinksPageStation topBottomLinkPage = topBottomLinkPageAndTop.first; TopBottomLinksPageStation.TopFacility topFacility = topBottomLinkPageAndTop.second; @@ -98,7 +93,7 @@ @EnableFeatures({ChromeFeatureList.DRAW_KEY_NATIVE_EDGE_TO_EDGE}) public void fromNtpToRegularPage() { // Start the page on NTP, chin is not visible. - var newTabPage = mInitialStateRule.startOnNtp(); + var newTabPage = mCtaTestRule.startOnNtp(); var chinOnNtp = newTabPage.enterFacilitySync( new EdgeToEdgeBottomChinFacility<>(true), /* trigger= */ null); @@ -108,7 +103,8 @@ chinOnNtp.getBottomChin().getLayerVisibility()); // Navigate the page to another web page, ensure the page has the chin visible. - var pair = TopBottomLinksPageStation.loadPage(sActivityTestRule, newTabPage); + var pair = + TopBottomLinksPageStation.loadPage(mCtaTestRule.getActivityTestRule(), newTabPage); TopBottomLinksPageStation regularPage = pair.first; var chinOnWebPage = regularPage.enterFacilitySync( @@ -126,7 +122,7 @@ @EnableFeatures({ChromeFeatureList.DRAW_KEY_NATIVE_EDGE_TO_EDGE}) public void fromNtpToTabSwitcher() { // Start the page on NTP, chin is not visible. - var newTabPage = mInitialStateRule.startOnNtp(); + var newTabPage = mCtaTestRule.startOnNtp(); var chinOnNtp = newTabPage.enterFacilitySync( new EdgeToEdgeBottomChinFacility<>(true), /* trigger= */ null); @@ -157,7 +153,7 @@ }) public void fromNtpToOptInPage() { // Start the page on NTP, chin is not visible. - var newTabPage = mInitialStateRule.startOnNtp(); + var newTabPage = mCtaTestRule.startOnNtp(); var chinOnNtp = newTabPage.enterFacilitySync( new EdgeToEdgeBottomChinFacility<>(true), /* trigger= */ null); @@ -168,7 +164,8 @@ // Navigate the page to another web page, ensure the page has the chin visible. var optInPage = - ViewportFitCoverPageStation.loadViewportFitCoverPage(sActivityTestRule, newTabPage); + ViewportFitCoverPageStation.loadViewportFitCoverPage( + mCtaTestRule.getActivityTestRule(), newTabPage); var chinOnOptInPage = optInPage.enterFacilitySync( new EdgeToEdgeBottomChinFacility<>(true), /* trigger= */ null); @@ -185,7 +182,7 @@ @EnableFeatures({ChromeFeatureList.EDGE_TO_EDGE_WEB_OPT_IN}) public void fromBlankPageToOptInPage() { // Start the page on NTP, chin is not visible. - var blankPage = mInitialStateRule.startOnBlankPage(); + var blankPage = mCtaTestRule.startOnBlankPage(); var chinOnBlankPage = blankPage.enterFacilitySync( new EdgeToEdgeBottomChinFacility<>(false), /* trigger= */ null); @@ -196,7 +193,8 @@ // Navigate the page to another web page, ensure the page has the chin visible. var optInPage = - ViewportFitCoverPageStation.loadViewportFitCoverPage(sActivityTestRule, blankPage); + ViewportFitCoverPageStation.loadViewportFitCoverPage( + mCtaTestRule.getActivityTestRule(), blankPage); var chinOnOptInPage = optInPage.enterFacilitySync( new EdgeToEdgeBottomChinFacility<>(true), /* trigger= */ null);
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/bookmarks/BookmarkPaneTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/bookmarks/BookmarkPaneTest.java index ca1ce01..860a733a 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/bookmarks/BookmarkPaneTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/bookmarks/BookmarkPaneTest.java
@@ -27,7 +27,6 @@ import org.junit.After; import org.junit.Before; -import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; @@ -43,8 +42,9 @@ import org.chromium.chrome.browser.flags.ChromeSwitches; import org.chromium.chrome.browser.profiles.Profile; import org.chromium.chrome.test.ChromeJUnit4ClassRunner; -import org.chromium.chrome.test.ChromeTabbedActivityTestRule; -import org.chromium.chrome.test.transit.BlankCTATabInitialStatePublicTransitRule; +import org.chromium.chrome.test.transit.AutoResetCtaTransitTestRule; +import org.chromium.chrome.test.transit.ChromeTransitTestRules; +import org.chromium.chrome.test.transit.page.WebPageStation; import org.chromium.chrome.test.util.BookmarkTestUtil; import org.chromium.chrome.test.util.MenuUtils; import org.chromium.ui.test.util.DeviceRestriction; @@ -55,23 +55,20 @@ @Batch(Batch.PER_CLASS) @EnableFeatures(ChromeFeatureList.BOOKMARK_PANE_ANDROID) public class BookmarkPaneTest { - - @ClassRule - public static ChromeTabbedActivityTestRule sActivityTestRule = - new ChromeTabbedActivityTestRule(); - @Rule - public BlankCTATabInitialStatePublicTransitRule mInitialStateRule = - new BlankCTATabInitialStatePublicTransitRule(sActivityTestRule); + public AutoResetCtaTransitTestRule mCtaTestRule = + ChromeTransitTestRules.autoResetCtaActivityRule(); + + private WebPageStation mStartingPage; @Before public void setUp() { - mInitialStateRule.startOnBlankPage(); + mStartingPage = mCtaTestRule.startOnBlankPage(); } @After public void tearDown() { - ChromeTabbedActivity cta = sActivityTestRule.getActivity(); + ChromeTabbedActivity cta = mCtaTestRule.getActivity(); runOnUiThreadBlocking( () -> clearBookmarks(cta.getProfileProviderSupplier().get().getOriginalProfile())); } @@ -80,16 +77,14 @@ @MediumTest @Restriction({DeviceRestriction.RESTRICTION_TYPE_NON_AUTO}) public void testBookmarkIsDisplayed() { - ChromeTabbedActivity cta = sActivityTestRule.getActivity(); + ChromeTabbedActivity cta = mCtaTestRule.getActivity(); String urlOne = - sActivityTestRule - .getTestServer() - .getURL("/chrome/test/data/android/navigate/one.html"); - sActivityTestRule.loadUrl(urlOne); + mCtaTestRule.getTestServer().getURL("/chrome/test/data/android/navigate/one.html"); + mStartingPage.loadWebPageProgrammatically(urlOne); BookmarkTestUtil.waitForBookmarkModelLoaded(); MenuUtils.invokeCustomMenuActionSync( InstrumentationRegistry.getInstrumentation(), - sActivityTestRule.getActivity(), + mCtaTestRule.getActivity(), R.id.bookmark_this_page_id); enterTabSwitcher(cta); @@ -103,16 +98,14 @@ @MediumTest @Restriction({DeviceRestriction.RESTRICTION_TYPE_NON_AUTO}) public void testBookmarkSearchMatch() { - ChromeTabbedActivity cta = sActivityTestRule.getActivity(); + ChromeTabbedActivity cta = mCtaTestRule.getActivity(); String urlOne = - sActivityTestRule - .getTestServer() - .getURL("/chrome/test/data/android/navigate/one.html"); - sActivityTestRule.loadUrl(urlOne); + mCtaTestRule.getTestServer().getURL("/chrome/test/data/android/navigate/one.html"); + mStartingPage.loadWebPageProgrammatically(urlOne); BookmarkTestUtil.waitForBookmarkModelLoaded(); MenuUtils.invokeCustomMenuActionSync( InstrumentationRegistry.getInstrumentation(), - sActivityTestRule.getActivity(), + mCtaTestRule.getActivity(), R.id.bookmark_this_page_id); enterTabSwitcher(cta); @@ -130,23 +123,19 @@ @MediumTest @Restriction({DeviceRestriction.RESTRICTION_TYPE_NON_AUTO}) public void testBookmarkClickOpens() { - ChromeTabbedActivity cta = sActivityTestRule.getActivity(); + ChromeTabbedActivity cta = mCtaTestRule.getActivity(); String urlOne = - sActivityTestRule - .getTestServer() - .getURL("/chrome/test/data/android/navigate/one.html"); - sActivityTestRule.loadUrl(urlOne); + mCtaTestRule.getTestServer().getURL("/chrome/test/data/android/navigate/one.html"); + WebPageStation pageOne = mStartingPage.loadWebPageProgrammatically(urlOne); BookmarkTestUtil.waitForBookmarkModelLoaded(); MenuUtils.invokeCustomMenuActionSync( InstrumentationRegistry.getInstrumentation(), - sActivityTestRule.getActivity(), + mCtaTestRule.getActivity(), R.id.bookmark_this_page_id); String urlTwo = - sActivityTestRule - .getTestServer() - .getURL("/chrome/test/data/android/navigate/two.html"); - sActivityTestRule.loadUrl(urlTwo); + mCtaTestRule.getTestServer().getURL("/chrome/test/data/android/navigate/two.html"); + pageOne.loadWebPageProgrammatically(urlTwo); enterTabSwitcher(cta); enterBookmarkPane();
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/bookmarks/bar/BookmarkBarTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/bookmarks/bar/BookmarkBarTest.java index af1f627d..75ee45a 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/bookmarks/bar/BookmarkBarTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/bookmarks/bar/BookmarkBarTest.java
@@ -39,7 +39,6 @@ import org.hamcrest.Matcher; import org.junit.After; import org.junit.Before; -import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; @@ -57,8 +56,8 @@ import org.chromium.chrome.browser.flags.ChromeSwitches; import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.test.ChromeJUnit4ClassRunner; -import org.chromium.chrome.test.ChromeTabbedActivityTestRule; -import org.chromium.chrome.test.transit.BlankCTATabInitialStatePublicTransitRule; +import org.chromium.chrome.test.transit.AutoResetCtaTransitTestRule; +import org.chromium.chrome.test.transit.ChromeTransitTestRules; import org.chromium.chrome.test.util.BookmarkTestUtil; import org.chromium.components.bookmarks.BookmarkId; import org.chromium.content_public.browser.test.util.TouchCommon; @@ -80,14 +79,9 @@ @Restriction({DeviceFormFactor.TABLET, DeviceRestriction.RESTRICTION_TYPE_NON_AUTO}) @RunWith(ChromeJUnit4ClassRunner.class) public class BookmarkBarTest { - - @ClassRule - public static final ChromeTabbedActivityTestRule sActivityTestRule = - new ChromeTabbedActivityTestRule(); - @Rule - public final BlankCTATabInitialStatePublicTransitRule mInitialStateRule = - new BlankCTATabInitialStatePublicTransitRule(sActivityTestRule); + public AutoResetCtaTransitTestRule mCtaTestRule = + ChromeTransitTestRules.autoResetCtaActivityRule(); private BookmarkModel mModel; private BookmarkId mDesktopFolderId; @@ -95,11 +89,11 @@ @Before public void setUp() { - mInitialStateRule.startOnBlankPage(); + mCtaTestRule.startOnBlankPage(); BookmarkTestUtil.waitForBookmarkModelLoaded(); ThreadUtils.runOnUiThreadBlocking( () -> { - mModel = sActivityTestRule.getActivity().getBookmarkModelForTesting(); + mModel = mCtaTestRule.getActivity().getBookmarkModelForTesting(); mModel.removeAllUserBookmarks(); mDesktopFolderId = mModel.getDesktopFolderId(); }); @@ -116,12 +110,17 @@ private @Nullable BookmarkId addBookmark(int index, @NonNull String title, @NonNull GURL url) throws ExecutionException { return BookmarkTestUtil.addBookmark( - sActivityTestRule, mModel, index, title, url, /* parent= */ mDesktopFolderId); + mCtaTestRule.getActivityTestRule(), + mModel, + index, + title, + url, + /* parent= */ mDesktopFolderId); } private @Nullable BookmarkId addFolder(@NonNull String title) throws ExecutionException { return BookmarkTestUtil.addFolder( - sActivityTestRule, mModel, title, /* parent= */ mDesktopFolderId); + mCtaTestRule.getActivityTestRule(), mModel, title, /* parent= */ mDesktopFolderId); } private @NonNull Matcher<View> bookmarkBarItemWithText(@NonNull String text) { @@ -187,16 +186,16 @@ } private @Nullable Tab getCurrentTab() { - return sActivityTestRule.getActivity().getActivityTab(); + return mCtaTestRule.getActivity().getActivityTab(); } private @Nullable Tab getLastTab() { - final var tabModel = sActivityTestRule.getActivity().getCurrentTabModel(); + final var tabModel = mCtaTestRule.getActivity().getCurrentTabModel(); return tabModel.getTabAt(tabModel.getCount() - 1); } private @NonNull GURL getTestServerUrl(@NonNull String relativeUrl) { - return new GURL(sActivityTestRule.getTestServer().getURL(relativeUrl)); + return new GURL(mCtaTestRule.getTestServer().getURL(relativeUrl)); } private <T> @NonNull Optional<T> optionalOfThrowable(@NonNull Callable<T> callable) {
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/contextmenu/ContextMenuTabPTTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/contextmenu/ContextMenuTabPTTest.java index e155e6b5..c7902ea6 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/contextmenu/ContextMenuTabPTTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/contextmenu/ContextMenuTabPTTest.java
@@ -9,7 +9,6 @@ import androidx.test.filters.MediumTest; import org.junit.BeforeClass; -import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; @@ -21,8 +20,8 @@ import org.chromium.chrome.browser.firstrun.FirstRunStatus; import org.chromium.chrome.browser.flags.ChromeSwitches; import org.chromium.chrome.test.ChromeJUnit4ClassRunner; -import org.chromium.chrome.test.ChromeTabbedActivityTestRule; -import org.chromium.chrome.test.transit.BlankCTATabInitialStatePublicTransitRule; +import org.chromium.chrome.test.transit.AutoResetCtaTransitTestRule; +import org.chromium.chrome.test.transit.ChromeTransitTestRules; import org.chromium.chrome.test.transit.page.PageStation; import org.chromium.chrome.test.transit.page.WebPageStation; import org.chromium.chrome.test.transit.tabmodel.TabGroupUiFacility; @@ -43,19 +42,14 @@ // the espresso matching in the public transit framework. See https://crbug.com/363047177. @Restriction(DeviceFormFactor.PHONE) public class ContextMenuTabPTTest { - - @ClassRule - public static ChromeTabbedActivityTestRule sActivityTestRule = - new ChromeTabbedActivityTestRule(); - @BeforeClass public static void setupBeforeClass() { ThreadUtils.runOnUiThreadBlocking(() -> FirstRunStatus.setFirstRunFlowComplete(true)); } @Rule - public BlankCTATabInitialStatePublicTransitRule mInitialStateRule = - new BlankCTATabInitialStatePublicTransitRule(sActivityTestRule); + public AutoResetCtaTransitTestRule mCtaTestRule = + ChromeTransitTestRules.autoResetCtaActivityRule(); /** * Assert open tab in new tab group. This test is greatly in common with @@ -64,10 +58,10 @@ @Test @MediumTest public void openNewTabFromContextMenu() { - PageStation blankPage = mInitialStateRule.startOnBlankPage(); + PageStation blankPage = mCtaTestRule.startOnBlankPage(); var topBottomLinkPageAndTop = - TopBottomLinksPageStation.loadPage(sActivityTestRule, blankPage); + TopBottomLinksPageStation.loadPage(mCtaTestRule.getActivityTestRule(), blankPage); TopBottomLinksPageStation contextMenuPage = topBottomLinkPageAndTop.first; TopBottomLinksPageStation.TopFacility topFacility = topBottomLinkPageAndTop.second; @@ -79,10 +73,10 @@ @Test @MediumTest public void openNewTabInGroupFromContextMenu() { - PageStation blankPage = mInitialStateRule.startOnBlankPage(); + PageStation blankPage = mCtaTestRule.startOnBlankPage(); var topBottomLinkPageAndTop = - TopBottomLinksPageStation.loadPage(sActivityTestRule, blankPage); + TopBottomLinksPageStation.loadPage(mCtaTestRule.getActivityTestRule(), blankPage); TopBottomLinksPageStation contextMenuPage = topBottomLinkPageAndTop.first; TopBottomLinksPageStation.TopFacility topFacility = topBottomLinkPageAndTop.second;
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/history/HistoryPaneTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/history/HistoryPaneTest.java index 738ca574..b15c8346 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/history/HistoryPaneTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/history/HistoryPaneTest.java
@@ -16,17 +16,14 @@ import static org.hamcrest.CoreMatchers.allOf; import static org.hamcrest.CoreMatchers.containsString; -import static org.junit.Assert.assertEquals; import static org.chromium.base.ThreadUtils.runOnUiThreadBlocking; -import static org.chromium.chrome.browser.tasks.tab_management.TabUiTestHelper.enterTabSwitcher; import static org.chromium.chrome.test.transit.hub.HubBaseStation.HUB_PANE_SWITCHER; import static org.chromium.ui.test.util.ViewUtils.onViewWaiting; import androidx.test.filters.MediumTest; import org.junit.Before; -import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; @@ -44,8 +41,9 @@ import org.chromium.chrome.browser.flags.ChromeSwitches; import org.chromium.chrome.browser.profiles.Profile; import org.chromium.chrome.test.ChromeJUnit4ClassRunner; -import org.chromium.chrome.test.ChromeTabbedActivityTestRule; -import org.chromium.chrome.test.transit.BlankCTATabInitialStatePublicTransitRule; +import org.chromium.chrome.test.transit.AutoResetCtaTransitTestRule; +import org.chromium.chrome.test.transit.ChromeTransitTestRules; +import org.chromium.chrome.test.transit.page.WebPageStation; /** Public transit tests for the Hub's history pane. */ @RunWith(ChromeJUnit4ClassRunner.class) @@ -53,19 +51,16 @@ @Batch(Batch.PER_CLASS) @EnableFeatures(ChromeFeatureList.HISTORY_PANE_ANDROID) public class HistoryPaneTest { - - @ClassRule - public static ChromeTabbedActivityTestRule sActivityTestRule = - new ChromeTabbedActivityTestRule(); - @Rule - public BlankCTATabInitialStatePublicTransitRule mInitialStateRule = - new BlankCTATabInitialStatePublicTransitRule(sActivityTestRule); + public AutoResetCtaTransitTestRule mCtaTestRule = + ChromeTransitTestRules.autoResetCtaActivityRule(); + + private WebPageStation mStartingPage; @Before public void setUp() { - mInitialStateRule.startOnBlankPage(); - ChromeTabbedActivity cta = sActivityTestRule.getActivity(); + mStartingPage = mCtaTestRule.startOnBlankPage(); + ChromeTabbedActivity cta = mCtaTestRule.getActivity(); runOnUiThreadBlocking( () -> clearHistory(cta.getProfileProviderSupplier().get().getOriginalProfile())); } @@ -73,8 +68,7 @@ @Test @MediumTest public void testEmptyView() { - ChromeTabbedActivity cta = sActivityTestRule.getActivity(); - enterTabSwitcher(cta); + mStartingPage.openRegularTabSwitcher(); enterHistoryPane(); onViewWaiting(withText("You’ll find your history here")).check(matches(isDisplayed())); @@ -88,19 +82,14 @@ @Test @MediumTest public void testOpenedHistoryItem_HistoryItemsAreDisplayed() { - ChromeTabbedActivity cta = sActivityTestRule.getActivity(); String urlOne = - sActivityTestRule - .getTestServer() - .getURL("/chrome/test/data/android/navigate/one.html"); + mCtaTestRule.getTestServer().getURL("/chrome/test/data/android/navigate/one.html"); String urlTwo = - sActivityTestRule - .getTestServer() - .getURL("/chrome/test/data/android/navigate/two.html"); - sActivityTestRule.loadUrl(urlOne); - sActivityTestRule.loadUrl(urlTwo); - - enterTabSwitcher(cta); + mCtaTestRule.getTestServer().getURL("/chrome/test/data/android/navigate/two.html"); + mStartingPage + .loadWebPageProgrammatically(urlOne) + .loadWebPageProgrammatically(urlTwo) + .openRegularTabSwitcher(); enterHistoryPane(); onViewWaiting(withText("One")).check(matches(isDisplayed())); @@ -110,19 +99,14 @@ @Test @MediumTest public void testOpenedHistoryItem_SearchMatch() { - ChromeTabbedActivity cta = sActivityTestRule.getActivity(); String urlOne = - sActivityTestRule - .getTestServer() - .getURL("/chrome/test/data/android/navigate/one.html"); + mCtaTestRule.getTestServer().getURL("/chrome/test/data/android/navigate/one.html"); String urlTwo = - sActivityTestRule - .getTestServer() - .getURL("/chrome/test/data/android/navigate/two.html"); - sActivityTestRule.loadUrl(urlOne); - sActivityTestRule.loadUrl(urlTwo); - - enterTabSwitcher(cta); + mCtaTestRule.getTestServer().getURL("/chrome/test/data/android/navigate/two.html"); + mStartingPage + .loadWebPageProgrammatically(urlOne) + .loadWebPageProgrammatically(urlTwo) + .openRegularTabSwitcher(); enterHistoryPane(); onViewWaiting(withText("One")).check(matches(isDisplayed())); @@ -139,27 +123,27 @@ @Test @MediumTest public void testOpenedHistoryItem_SingleClickOpensInSameTab() { - ChromeTabbedActivity cta = sActivityTestRule.getActivity(); String urlOne = - sActivityTestRule - .getTestServer() - .getURL("/chrome/test/data/android/navigate/one.html"); + mCtaTestRule.getTestServer().getURL("/chrome/test/data/android/navigate/one.html"); String urlTwo = - sActivityTestRule - .getTestServer() - .getURL("/chrome/test/data/android/navigate/two.html"); - sActivityTestRule.loadUrl(urlOne); - sActivityTestRule.loadUrl(urlTwo); - // Load two urls, and make sure that urlTwo is currently loaded. - assertEquals(urlTwo, cta.getTabModelSelector().getCurrentTab().getUrl().getSpec()); - - enterTabSwitcher(cta); + mCtaTestRule.getTestServer().getURL("/chrome/test/data/android/navigate/two.html"); + mStartingPage + .loadWebPageProgrammatically(urlOne) + .loadWebPageProgrammatically(urlTwo) + .openRegularTabSwitcher(); enterHistoryPane(); onViewWaiting(withText("One")).perform(click()); // When the history view is clicked, it should replace the current tab's URL. CriteriaHelper.pollUiThread( - () -> urlOne.equals(cta.getTabModelSelector().getCurrentTab().getUrl().getSpec())); + () -> + urlOne.equals( + mCtaTestRule + .getActivity() + .getTabModelSelector() + .getCurrentTab() + .getUrl() + .getSpec())); } private void enterHistoryPane() {
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/jsdialog/JavascriptTabModalDialogTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/jsdialog/JavascriptTabModalDialogTest.java index 8841a40..8c750a5 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/jsdialog/JavascriptTabModalDialogTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/jsdialog/JavascriptTabModalDialogTest.java
@@ -13,6 +13,7 @@ import static androidx.test.espresso.matcher.ViewMatchers.withId; import static androidx.test.espresso.matcher.ViewMatchers.withText; +import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; @@ -144,7 +145,7 @@ Assert.assertNotNull("No dialog showing.", jsDialog); onView(withText(R.string.ok)).check(matches(isDisplayed())); - onView(withText(R.string.cancel)).check(matches(isDisplayed())); + onView(allOf(withText(R.string.cancel), isDisplayed())); onView(withText(R.string.ok)).perform(click()); Assert.assertTrue( @@ -159,7 +160,7 @@ jsDialog = getCurrentDialog(); Assert.assertNotNull("No dialog showing.", jsDialog); - onView(withText(R.string.cancel)).perform(click()); + onView(allOf(withText(R.string.cancel), isDisplayed())).perform(click()); Assert.assertTrue( "JavaScript execution should continue after closing dialog.", scriptEvent.waitUntilHasValue());
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/page_info/PageInfoViewTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/page_info/PageInfoViewTest.java index 175b1e5..d8a9ff09 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/page_info/PageInfoViewTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/page_info/PageInfoViewTest.java
@@ -80,6 +80,7 @@ import org.chromium.base.test.util.Features.DisableFeatures; import org.chromium.base.test.util.Features.EnableFeatures; import org.chromium.base.test.util.Restriction; +import org.chromium.base.test.util.UserActionTester; import org.chromium.chrome.browser.FederatedIdentityTestUtils; import org.chromium.chrome.browser.app.ChromeActivity; import org.chromium.chrome.browser.browser_controls.BrowserControlsStateProvider.ControlsPosition; @@ -869,6 +870,7 @@ public void shouldNavigateToSiteSettingsWhenRwsManagedAndButtonClicked() throws IOException { mFakePrivacySandboxBridge.setIsRwsManaged(true); SettingsNavigationFactory.setInstanceForTesting(mSettingsNavigation); + UserActionTester userActionTester = new UserActionTester(); String hostName = "example.com"; String url = mTestServerRule.getServer().getURLWithHostName(hostName, "/"); Website currentSite = new Website(WebsiteAddress.create(url), null); @@ -885,6 +887,10 @@ extras.putSerializable(EXTRA_SITE, currentSite); Mockito.verify(mSettingsNavigation) .startSettings(any(), eq(SingleWebsiteSettings.class), refEq(extras)); + assertEquals( + 1, + userActionTester.getActionCount("PageInfo.CookiesSubpage.RwsSiteSettingsOpened")); + userActionTester.tearDown(); } /** Tests the cookies page of the PageInfo UI with the Cookie Controls UI enabled. */
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/site_settings/AllSiteSettingsTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/site_settings/AllSiteSettingsTest.java index 0c07fbf2..b4461c0d 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/site_settings/AllSiteSettingsTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/site_settings/AllSiteSettingsTest.java
@@ -5,7 +5,6 @@ package org.chromium.chrome.browser.site_settings; import static androidx.test.espresso.Espresso.onView; -import static androidx.test.espresso.assertion.ViewAssertions.doesNotExist; import static androidx.test.espresso.assertion.ViewAssertions.matches; import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed; import static androidx.test.espresso.matcher.ViewMatchers.withText; @@ -35,7 +34,6 @@ import org.chromium.chrome.browser.flags.ChromeFeatureList; import org.chromium.chrome.browser.flags.ChromeSwitches; import org.chromium.chrome.browser.permissions.PermissionTestRule; -import org.chromium.chrome.browser.privacy_sandbox.PrivacySandboxBridgeJni; import org.chromium.chrome.browser.profiles.ProfileManager; import org.chromium.chrome.browser.settings.SettingsActivity; import org.chromium.chrome.test.ChromeJUnit4ClassRunner; @@ -49,7 +47,6 @@ import org.chromium.ui.test.util.RenderTestRule; import org.chromium.ui.test.util.RenderTestRule.Component; -import java.util.Set; import java.util.concurrent.TimeoutException; @RunWith(ChromeJUnit4ClassRunner.class) @@ -162,90 +159,4 @@ settingsActivity.finish(); } - - @Test - @SmallTest - @Feature({"Preferences"}) - public void testAllSitesWithRelatedFilter() throws Exception { - ThreadUtils.runOnUiThreadBlocking( - () -> { - WebsitePreferenceBridge.setContentSettingCustomScope( - getBrowserContextHandle(), - ContentSettingsType.COOKIES, - A_GITHUB_IO, - "*", - ContentSettingValues.ALLOW); - WebsitePreferenceBridge.setContentSettingCustomScope( - getBrowserContextHandle(), - ContentSettingsType.COOKIES, - B_GITHUB_IO, - "*", - ContentSettingValues.ALLOW); - }); - String relatedFilter = String.format("related:%s", C_GITHUB_IO); - - SettingsActivity settingsActivity = - SiteSettingsTestUtils.startAllSitesSettingsForRws( - SiteSettingsCategory.Type.ALL_SITES, C_GITHUB_IO); - onViewWaiting(withText(containsString("Delete browsing"))).check(matches(isDisplayed())); - onView(withText(relatedFilter)).check(matches(isDisplayed())); - onView(withText(A_GITHUB_IO)).check(doesNotExist()); - onView(withText(B_GITHUB_IO)).check(doesNotExist()); - - settingsActivity.finish(); - } - - @Test - @SmallTest - @Feature({"Preferences", "RenderTest"}) - public void testOneRwsGroupWithRelatedFilter() throws Exception { - FakeRwsPrivacySandboxBridge fakeRwsPrivacySandboxBridge = - new FakeRwsPrivacySandboxBridge(C_GITHUB_IO, Set.of(A_GITHUB_IO, B_GITHUB_IO)); - PrivacySandboxBridgeJni.setInstanceForTesting(fakeRwsPrivacySandboxBridge); - - ThreadUtils.runOnUiThreadBlocking( - () -> { - WebsitePreferenceBridge.setContentSettingCustomScope( - getBrowserContextHandle(), - ContentSettingsType.COOKIES, - A_GITHUB_IO, - "*", - ContentSettingValues.ALLOW); - WebsitePreferenceBridge.setContentSettingCustomScope( - getBrowserContextHandle(), - ContentSettingsType.COOKIES, - B_GITHUB_IO, - "*", - ContentSettingValues.ALLOW); - WebsitePreferenceBridge.setContentSettingCustomScope( - getBrowserContextHandle(), - ContentSettingsType.COOKIES, - D_GITHUB_IO, - "*", - ContentSettingValues.ALLOW); - }); - String relatedFilter = String.format("related:%s", C_GITHUB_IO); - - SettingsActivity settingsActivity = - SiteSettingsTestUtils.startAllSitesSettingsForRws( - SiteSettingsCategory.Type.ALL_SITES, C_GITHUB_IO); - onViewWaiting(withText(containsString("Delete browsing"))).check(matches(isDisplayed())); - - onView(withText(relatedFilter)).check(matches(isDisplayed())); - onView(withText(A_GITHUB_IO)).check(matches(isDisplayed())); - onView(withText(B_GITHUB_IO)).check(matches(isDisplayed())); - onView(withText(D_GITHUB_IO)).check(doesNotExist()); - - View view = - ThreadUtils.runOnUiThreadBlocking( - () -> { - PreferenceFragmentCompat preferenceFragment = - (PreferenceFragmentCompat) settingsActivity.getMainFragment(); - return preferenceFragment.getView(); - }); - ChromeRenderTestRule.sanitize(view); - mRenderTestRule.render(view, "site_settings_all_sites_rws_group_with_filter"); - - settingsActivity.finish(); - } }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/site_settings/SiteSettingsTestUtils.java b/chrome/android/javatests/src/org/chromium/chrome/browser/site_settings/SiteSettingsTestUtils.java index 19b42b0..51a24f13 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/site_settings/SiteSettingsTestUtils.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/site_settings/SiteSettingsTestUtils.java
@@ -91,15 +91,6 @@ return startSiteSettings(AllSiteSettings.class, fragmentArgs); } - public static SettingsActivity startAllSitesSettingsForRws( - @SiteSettingsCategory.Type int type, String rwsPage) { - Bundle fragmentArgs = new Bundle(); - fragmentArgs.putString( - AllSiteSettings.EXTRA_CATEGORY, SiteSettingsCategory.preferenceKey(type)); - fragmentArgs.putString(AllSiteSettings.EXTRA_SEARCH, rwsPage); - return startSiteSettings(AllSiteSettings.class, fragmentArgs); - } - private static SettingsActivity startSiteSettings( Class<? extends Fragment> fragmentClass, Bundle fragmentArgs) { SettingsNavigation settingsNavigation =
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/dom_distiller/ReaderModeManagerTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/dom_distiller/ReaderModeManagerTest.java index 07f8e726..4b31f99 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/dom_distiller/ReaderModeManagerTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/dom_distiller/ReaderModeManagerTest.java
@@ -156,6 +156,7 @@ @Test @Feature("ReaderMode") public void testUi_notTriggered_muted() { + when(mTab.isCustomTab()).thenReturn(true); mManager.muteSiteForTesting(mTab.getUrl()); mDistillabilityObserver.onIsPageDistillableResult(mTab, true, true, false); assertEquals( @@ -168,6 +169,7 @@ @Test @Feature("ReaderMode") public void testUi_notTriggered_mutedByDomain() { + when(mTab.isCustomTab()).thenReturn(true); mManager.muteSiteForTesting(JUnitTestGURLs.GOOGLE_URL_DOG); mDistillabilityObserver.onIsPageDistillableResult(mTab, true, true, false); assertEquals( @@ -183,10 +185,11 @@ @Test @Feature("ReaderMode") public void testUi_notTriggered_contextualPageActionUiEnabled() { + when(mTab.isIncognito()).thenReturn(false); mDistillabilityObserver.onIsPageDistillableResult(mTab, true, true, false); assertEquals( - "Distillation should be possible.", - DistillationStatus.POSSIBLE, + "Distillation isn't possible because it will be handled by the CPA.", + DistillationStatus.NOT_POSSIBLE, mManager.getDistillationStatus()); verify( mMessageDispatcher, @@ -286,6 +289,7 @@ @Test @Feature("ReaderMode") public void testDistillationMetricsOnDistillabilityResult() { + when(mTab.isCustomTab()).thenReturn(true); HistogramWatcher watcher = HistogramWatcher.newBuilder() .expectBooleanRecord( @@ -305,7 +309,27 @@ @Test @Feature("ReaderMode") + public void testDistillationMetricsOnDistillabilityResult_noMetricsRecordedForRegularTabs() { + when(mTab.isCustomTab()).thenReturn(false); + HistogramWatcher watcher = + HistogramWatcher.newBuilder() + .expectNoRecords(ReaderModeManager.ACCESSIBILITY_SETTING_HISTOGRAM) + .expectNoRecords( + ReaderModeManager.DISTILLABLE_MOBILE_PAGE_EXCLUDED_HISTOGRAM) + .expectNoRecords(ReaderModeManager.PAGE_DISTILLABLE_RESULT_HISTOGRAM) + .build(); + mDistillabilityObserver.onIsPageDistillableResult( + mTab, + /* isDistillable= */ true, + /* isLast= */ true, + /* isMobileOptimized= */ false); + watcher.assertExpected(); + } + + @Test + @Feature("ReaderMode") public void testDistillationMetricsOnDistillabilityResult_mobilePageExcluded() { + when(mTab.isCustomTab()).thenReturn(true); HistogramWatcher watcher = HistogramWatcher.newBuilder() .expectBooleanRecord( @@ -323,6 +347,7 @@ @Test @Feature("ReaderMode") public void testDistillationMetricsOnDistillabilityResult_mobilePageNotExcluded() { + when(mTab.isCustomTab()).thenReturn(true); when(mPrefService.getBoolean(Pref.READER_FOR_ACCESSIBILITY)).thenReturn(true); HistogramWatcher watcher = HistogramWatcher.newBuilder()
diff --git a/chrome/app/generated_resources.grd b/chrome/app/generated_resources.grd index ef908237b..95b48db 100644 --- a/chrome/app/generated_resources.grd +++ b/chrome/app/generated_resources.grd
@@ -12420,24 +12420,6 @@ </message> <!-- /Page Action --> - <!-- Toast --> - <message name="IDS_DATA_SHARING_TOAST_TAB_REMOVED" desc="A description of the member removing a tab for the toast."> - <ph name="MEMBER_FIRST_NAME">$1<ex>Ali</ex></ph> removed tab “<ph name="WEBSITE_TITLE">$2<ex>chromium.org</ex></ph>” - </message> - <message name="IDS_DATA_SHARING_TOAST_TAB_REMOVED_ACTION" desc="The action that can be taken from the toast when a member removes a tab."> - Reopen - </message> - <message name="IDS_DATA_SHARING_TOAST_NEW_MEMBER" desc="A description of a new member being added to a shared group for the toast."> - <ph name="MEMBER_FIRST_NAME">$1<ex>Ali</ex></ph> joined "<ph name="GROUP_NAME">$2<ex>Vacation</ex></ph>" tab group - </message> - <message name="IDS_DATA_SHARING_TOAST_NEW_MEMBER_ACTION" desc="The action that can be taken from the toast when a member is added to a shared group."> - Manage - </message> - <message name="IDS_DATA_SHARING_TOAST_BLOCK_LEAVE" desc="A description of a member being blocked/leaving from a shared group for the toast."> - The "<ph name="GROUP_NAME">$1<ex>Vacation</ex></ph>" tab group is no longer available - </message> - <!-- /Toast --> - <!-- User Education --> <message name="IDS_DATA_SHARING_USER_ED_FIRST_TAB_CHANGE" desc="A description of how shared tabs work in a shared group for user education."> Changes made are seen by everyone in the group
diff --git a/chrome/app/resources/generated_resources_hy.xtb b/chrome/app/resources/generated_resources_hy.xtb index 8887f84..16af700 100644 --- a/chrome/app/resources/generated_resources_hy.xtb +++ b/chrome/app/resources/generated_resources_hy.xtb
@@ -2800,6 +2800,7 @@ <translation id="2921081876747860777">Ձեր տեղային տվյալները պաշտպանելու համար ստեղծեք գաղտնաբառ:</translation> <translation id="2923006468155067296">Ձեր <ph name="DEVICE_TYPE" /> սարքն այժմ կկողպվի։ Համաձայն <ph name="DOMAIN" /> տիրույթի կանոնների՝ խելացի քարտը պետք է տեղադրված լինի։</translation> +<translation id="2923122530864139191">{NUM_TASKS,plural, =1{<ph name="TASK_ROW" />}one{<ph name="TASK_ROW" />։ <ph name="OTHER_TASK_NUM" /> այլ առաջադրանքներ նույն աշխատանքային խմբում՝ <ph name="OTHER_TASKS" />}other{<ph name="TASK_ROW" />։ <ph name="OTHER_TASK_NUM" /> այլ առաջադրանքներ նույն աշխատանքային խմբում՝ <ph name="OTHER_TASKS" />}}</translation> <translation id="2923234477033317484">Հեռացնել հաշիվը</translation> <translation id="2923644930701689793">Բացեք ձեր հեռախոսի ֆոտոժապավենը</translation> <translation id="292371311537977079">Chrome-ի կարգավորումներ</translation>
diff --git a/chrome/app/resources/generated_resources_pt-BR.xtb b/chrome/app/resources/generated_resources_pt-BR.xtb index fbe9ed56..9a42dd2 100644 --- a/chrome/app/resources/generated_resources_pt-BR.xtb +++ b/chrome/app/resources/generated_resources_pt-BR.xtb
@@ -2811,6 +2811,7 @@ <translation id="2921081876747860777">Crie uma senha para proteger seus dados locais.</translation> <translation id="2923006468155067296">Seu <ph name="DEVICE_TYPE" /> será bloqueado agora. <ph name="DOMAIN" /> requer que você mantenha o cartão inteligente inserido.</translation> +<translation id="2923122530864139191">{NUM_TASKS,plural, =1{<ph name="TASK_ROW" />}one{<ph name="TASK_ROW" />. Mais <ph name="OTHER_TASK_NUM" /> tarefa no mesmo grupo: <ph name="OTHER_TASKS" />}other{<ph name="TASK_ROW" />. Mais <ph name="OTHER_TASK_NUM" /> tarefas no mesmo grupo: <ph name="OTHER_TASKS" />}}</translation> <translation id="2923234477033317484">Remover esta conta</translation> <translation id="2923644930701689793">Acessar o rolo da câmera do smartphone</translation> <translation id="292371311537977079">Configurações do Chrome</translation>
diff --git a/chrome/app/resources/generated_resources_sq.xtb b/chrome/app/resources/generated_resources_sq.xtb index c0c76b4..89e12832 100644 --- a/chrome/app/resources/generated_resources_sq.xtb +++ b/chrome/app/resources/generated_resources_sq.xtb
@@ -2796,6 +2796,7 @@ <translation id="2921081876747860777">Krijo një fjalëkalimin për të mbrojtur të dhënat e tua lokale.</translation> <translation id="2923006468155067296">Pajisja jote <ph name="DEVICE_TYPE" /> do të kyçet tani. <ph name="DOMAIN" /> kërkon që ti ta mbash kartën tënde smart të futur.</translation> +<translation id="2923122530864139191">{NUM_TASKS,plural, =1{<ph name="TASK_ROW" />}other{<ph name="TASK_ROW" />. <ph name="OTHER_TASK_NUM" /> detyra të tjera në të njëjtin grup detyrash: <ph name="OTHER_TASKS" />}}</translation> <translation id="2923234477033317484">Hiqe këtë llogari</translation> <translation id="2923644930701689793">Qasu te filmi i kamerës i telefonit tënd</translation> <translation id="292371311537977079">Cilësimet e Chrome</translation>
diff --git a/chrome/browser/about_flags.cc b/chrome/browser/about_flags.cc index 5c5c070..7e841be 100644 --- a/chrome/browser/about_flags.cc +++ b/chrome/browser/about_flags.cc
@@ -8036,6 +8036,12 @@ kOsCrOS, FEATURE_VALUE_TYPE(features::kAccessibilityManifestV3EnhancedNetworkTts)}, + {"enable-accessibility-manifest-v3-switch-access", + flag_descriptions::kAccessibilityManifestV3SwitchAccessName, + flag_descriptions::kAccessibilityManifestV3SwitchAccessDescription, + kOsCrOS, + FEATURE_VALUE_TYPE(features::kAccessibilityManifestV3SwitchAccess)}, + {"enable-accessibility-mousekeys", flag_descriptions::kAccessibilityMouseKeysName, flag_descriptions::kAccessibilityMouseKeysDescription, kOsCrOS,
diff --git a/chrome/browser/accessibility/BUILD.gn b/chrome/browser/accessibility/BUILD.gn index 7166d32..32ba48e 100644 --- a/chrome/browser/accessibility/BUILD.gn +++ b/chrome/browser/accessibility/BUILD.gn
@@ -31,8 +31,6 @@ source_set("utils") { sources = [ - "accessibility_state_utils.cc", - "accessibility_state_utils.h", "pdf_ocr_metrics.cc", "pdf_ocr_metrics.h", ]
diff --git a/chrome/browser/accessibility/accessibility_labels_service.cc b/chrome/browser/accessibility/accessibility_labels_service.cc index 7a667ba..d2869e6 100644 --- a/chrome/browser/accessibility/accessibility_labels_service.cc +++ b/chrome/browser/accessibility/accessibility_labels_service.cc
@@ -9,7 +9,6 @@ #include "base/no_destructor.h" #include "base/strings/string_split.h" #include "build/build_config.h" -#include "chrome/browser/accessibility/accessibility_state_utils.h" #include "chrome/browser/language/url_language_histogram_factory.h" #include "chrome/browser/manta/manta_service_factory.h" #include "chrome/browser/profiles/profile.h" @@ -31,6 +30,7 @@ #include "services/image_annotation/image_annotation_service.h" #include "ui/accessibility/ax_action_data.h" #include "ui/accessibility/ax_enums.mojom.h" +#include "ui/accessibility/platform/ax_platform.h" #if !BUILDFLAG(IS_ANDROID) #include "chrome/browser/ui/tab_contents/tab_contents_iterator.h" @@ -196,7 +196,7 @@ void AccessibilityLabelsService::EnableLabelsServiceOnce( content::WebContents* web_contents) { - if (!accessibility_state_utils::IsScreenReaderEnabled()) { + if (!ui::AXPlatform::GetInstance().IsScreenReaderActive()) { return; }
diff --git a/chrome/browser/accessibility/accessibility_state_utils.cc b/chrome/browser/accessibility/accessibility_state_utils.cc deleted file mode 100644 index 976f0f5..0000000 --- a/chrome/browser/accessibility/accessibility_state_utils.cc +++ /dev/null
@@ -1,40 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/accessibility/accessibility_state_utils.h" - -#include "build/build_config.h" - -#if BUILDFLAG(IS_CHROMEOS) -#include "chrome/browser/ash/accessibility/accessibility_manager.h" -#endif // BUILDFLAG(IS_CHROMEOS) - -#include "content/public/browser/browser_accessibility_state.h" -#include "ui/accessibility/platform/ax_platform.h" - -namespace accessibility_state_utils { - -#if BUILDFLAG(IS_CHROMEOS) -using ::ash::AccessibilityManager; -#endif // BUILDFLAG(IS_CHROMEOS) - -bool IsScreenReaderEnabled() { - return ui::AXPlatform::GetInstance().IsScreenReaderActive(); -} - -void OverrideIsScreenReaderEnabledForTesting(bool enabled) { - content::BrowserAccessibilityState::GetInstance()->SetScreenReaderAppActive( - enabled); -} - -bool IsSelectToSpeakEnabled() { -#if BUILDFLAG(IS_CHROMEOS) - return AccessibilityManager::Get() && - AccessibilityManager::Get()->IsSelectToSpeakEnabled(); -#else - return false; -#endif // BUILDFLAG(IS_CHROMEOS) -} - -} // namespace accessibility_state_utils
diff --git a/chrome/browser/accessibility/accessibility_state_utils.h b/chrome/browser/accessibility/accessibility_state_utils.h deleted file mode 100644 index f09e9fd..0000000 --- a/chrome/browser/accessibility/accessibility_state_utils.h +++ /dev/null
@@ -1,25 +0,0 @@ -// Copyright 2019 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_ACCESSIBILITY_ACCESSIBILITY_STATE_UTILS_H_ -#define CHROME_BROWSER_ACCESSIBILITY_ACCESSIBILITY_STATE_UTILS_H_ - -namespace accessibility_state_utils { - -// On ChromeOS returns true if the screen reader is enabled. -// On other platforms returns true if screen reader mode is enabled, which can -// be true if any functionality that needs screen reader compatibility is -// enabled. -bool IsScreenReaderEnabled(); - -// Overrides |IsScreenReaderEnabled| for testing. -void OverrideIsScreenReaderEnabledForTesting(bool enabled); - -// Returns true if Select-to-Speak is enabled on ChromeOS; returns false on -// other platforms. -bool IsSelectToSpeakEnabled(); - -} // namespace accessibility_state_utils - -#endif // CHROME_BROWSER_ACCESSIBILITY_ACCESSIBILITY_STATE_UTILS_H_
diff --git a/chrome/browser/accessibility/ax_main_node_annotator_controller.cc b/chrome/browser/accessibility/ax_main_node_annotator_controller.cc index 4f73062c8..5ff0837e 100644 --- a/chrome/browser/accessibility/ax_main_node_annotator_controller.cc +++ b/chrome/browser/accessibility/ax_main_node_annotator_controller.cc
@@ -4,7 +4,6 @@ #include "chrome/browser/accessibility/ax_main_node_annotator_controller.h" -#include "chrome/browser/accessibility/accessibility_state_utils.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/screen_ai/screen_ai_service_router.h" #include "chrome/browser/screen_ai/screen_ai_service_router_factory.h" @@ -15,13 +14,10 @@ #include "components/prefs/pref_service.h" #include "content/public/browser/browser_accessibility_state.h" #include "content/public/browser/scoped_accessibility_mode.h" +#include "ui/accessibility/platform/ax_platform.h" #include "ui/base/l10n/l10n_util.h" #include "ui/views/accessibility/view_accessibility.h" -#if BUILDFLAG(IS_CHROMEOS) -#include "chrome/browser/ash/accessibility/accessibility_manager.h" -#endif - namespace { // Invoke screen reader alert to notify the user of the state. @@ -58,20 +54,9 @@ weak_ptr_factory_.GetWeakPtr())); // Register for changes to screenreader/spoken feedback. -#if BUILDFLAG(IS_CHROMEOS) - if (auto* const accessibility_manager = ash::AccessibilityManager::Get(); - accessibility_manager) { - // Unretained is safe because `this` owns the subscription. - accessibility_status_subscription_ = - accessibility_manager->RegisterCallback(base::BindRepeating( - &AXMainNodeAnnotatorController::OnAccessibilityStatusEvent, - base::Unretained(this))); - } -#else // BUILDFLAG(IS_CHROMEOS) ax_mode_observation_.Observe(&ui::AXPlatform::GetInstance()); -#endif // BUILDFLAG(IS_CHROMEOS) - activated_ = accessibility_state_utils::IsScreenReaderEnabled(); + activated_ = ui::AXPlatform::GetInstance().IsScreenReaderActive(); OnActivationChanged(); } @@ -89,17 +74,6 @@ OnActivationChanged(); } -#if BUILDFLAG(IS_CHROMEOS) -void AXMainNodeAnnotatorController::OnAccessibilityStatusEvent( - const ash::AccessibilityStatusEventDetails& details) { - if (details.notification_type == - ash::AccessibilityNotificationType::kToggleSpokenFeedback) { - activated_ = accessibility_state_utils::IsScreenReaderEnabled(); - OnActivationChanged(); - } -} -#endif // BUIDLFLAG(IS_CHROMEOS) - void AXMainNodeAnnotatorController::OnActivationChanged() { const bool is_activated = activated_ && profile_->GetPrefs()->GetBoolean( @@ -189,12 +163,10 @@ OnActivationChanged(); } -#if !BUILDFLAG(IS_CHROMEOS) void AXMainNodeAnnotatorController::OnAssistiveTechChanged( ui::AssistiveTech assistive_tech) { activated_ = ui::IsScreenReader(assistive_tech); OnActivationChanged(); } -#endif // !BUILDFLAG(IS_CHROMEOS) } // namespace screen_ai
diff --git a/chrome/browser/accessibility/ax_main_node_annotator_controller.h b/chrome/browser/accessibility/ax_main_node_annotator_controller.h index b9662df4..57e5f50 100644 --- a/chrome/browser/accessibility/ax_main_node_annotator_controller.h +++ b/chrome/browser/accessibility/ax_main_node_annotator_controller.h
@@ -13,21 +13,11 @@ #include "components/keyed_service/core/keyed_service.h" #include "components/prefs/pref_change_registrar.h" -#if BUILDFLAG(IS_CHROMEOS) -#include "base/callback_list.h" -#else #include "ui/accessibility/platform/ax_mode_observer.h" #include "ui/accessibility/platform/ax_platform.h" -#endif class Profile; -#if BUILDFLAG(IS_CHROMEOS) -namespace ash { -struct AccessibilityStatusEventDetails; -} -#endif - namespace content { class ScopedAccessibilityMode; } // namespace content @@ -40,12 +30,8 @@ // changes in the per-profile preference and updates the accessibility mode of // WebContents when it changes, provided its feature flag is enabled. class AXMainNodeAnnotatorController : public KeyedService, - public ScreenAIInstallState::Observer -#if !BUILDFLAG(IS_CHROMEOS) - , - public ui::AXModeObserver -#endif -{ + public ScreenAIInstallState::Observer, + public ui::AXModeObserver { public: explicit AXMainNodeAnnotatorController(Profile* profile); AXMainNodeAnnotatorController(const AXMainNodeAnnotatorController&) = delete; @@ -61,10 +47,8 @@ void Activate(); -#if !BUILDFLAG(IS_CHROMEOS) // ui::AXModeObserver: void OnAssistiveTechChanged(ui::AssistiveTech assistive_tech) override; -#endif void set_service_ready_for_testing() { service_ready_ = true; } void complete_service_intialization_for_testing() { @@ -74,11 +58,6 @@ private: friend class AXMainNodeAnnotatorControllerFactory; -#if BUILDFLAG(IS_CHROMEOS) - void OnAccessibilityStatusEvent( - const ash::AccessibilityStatusEventDetails& details); -#endif - // Receives the result of main node extraction service initialization. void MainNodeExtractionServiceInitializationCallback(bool successful); @@ -93,14 +72,9 @@ // before the profile gets destroyed. raw_ptr<Profile> profile_; -#if BUILDFLAG(IS_CHROMEOS) - // Observes spoken feedback. - base::CallbackListSubscription accessibility_status_subscription_; -#else // Observes the presence of a screen reader. base::ScopedObservation<ui::AXPlatform, ui::AXModeObserver> ax_mode_observation_{this}; -#endif // Observes changes in Screen AI component download and readiness state. base::ScopedObservation<ScreenAIInstallState, ScreenAIInstallState::Observer>
diff --git a/chrome/browser/accessibility/ax_main_node_annotator_controller_browsertest.cc b/chrome/browser/accessibility/ax_main_node_annotator_controller_browsertest.cc index c113296..c050a3fb 100644 --- a/chrome/browser/accessibility/ax_main_node_annotator_controller_browsertest.cc +++ b/chrome/browser/accessibility/ax_main_node_annotator_controller_browsertest.cc
@@ -7,7 +7,6 @@ #include "base/test/scoped_feature_list.h" #include "base/test/test_future.h" #include "build/build_config.h" -#include "chrome/browser/accessibility/accessibility_state_utils.h" #include "chrome/browser/accessibility/ax_main_node_annotator_controller_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/screen_ai/screen_ai_install_state.h" @@ -28,6 +27,7 @@ #include "services/screen_ai/public/cpp/utilities.h" #include "ui/accessibility/accessibility_features.h" #include "ui/accessibility/ax_features.mojom-features.h" +#include "ui/accessibility/platform/ax_platform.h" #if BUILDFLAG(IS_CHROMEOS) #include "chrome/browser/ash/accessibility/accessibility_manager.h" @@ -243,7 +243,8 @@ EnabledByPreference) { // If the test is run with --force-renderer-accessibility, then initializing // the class causes the service to kick off. We need to force it to complete. - if (accessibility_state_utils::IsScreenReaderEnabled()) { + bool screen_reader = ui::AXPlatform::GetInstance().IsScreenReaderActive(); + if (screen_reader) { CompleteServiceInitialization(); } else { Connect(); @@ -258,7 +259,7 @@ // If the test is run without --force-renderer-accessibility, then no screen // reader should have been detected yet, and the feature should be off. - if (!accessibility_state_utils::IsScreenReaderEnabled()) { + if (!screen_reader) { EXPECT_FALSE(web_contents->GetAccessibilityMode().has_mode( ui::AXMode::kAnnotateMainNode)); EnableScreenReader(true);
diff --git a/chrome/browser/accessibility/media_app/ax_media_app_untrusted_service.cc b/chrome/browser/accessibility/media_app/ax_media_app_untrusted_service.cc index 5536ab32..94db948 100644 --- a/chrome/browser/accessibility/media_app/ax_media_app_untrusted_service.cc +++ b/chrome/browser/accessibility/media_app/ax_media_app_untrusted_service.cc
@@ -22,7 +22,7 @@ #include "base/numerics/checked_math.h" #include "base/strings/stringprintf.h" #include "base/types/to_address.h" -#include "chrome/browser/accessibility/accessibility_state_utils.h" +#include "chrome/browser/ash/accessibility/accessibility_manager.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/screen_ai/public/optical_character_recognizer.h" #include "chrome/browser/ui/browser.h" @@ -89,15 +89,11 @@ : browser_context_(context), native_window_(native_window), media_app_page_(std::move(page)) { -#if BUILDFLAG(IS_CHROMEOS) - if (auto* accessibility_manager = ash::AccessibilityManager::Get()) { - // Unretained is safe because `this` owns the subscription. - accessibility_status_subscription_ = - accessibility_manager->RegisterCallback(base::BindRepeating( - &AXMediaAppUntrustedService::OnAshAccessibilityModeChanged, - base::Unretained(this))); - } -#endif + // Unretained is safe because `this` owns the subscription. + accessibility_status_subscription_ = + ash::AccessibilityManager::Get()->RegisterCallback(base::BindRepeating( + &AXMediaAppUntrustedService::OnAshAccessibilityModeChanged, + base::Unretained(this))); if (IsAccessibilityEnabled()) { ToggleAccessibilityState(); } @@ -154,11 +150,12 @@ } bool AXMediaAppUntrustedService::IsAccessibilityEnabled() const { - return accessibility_state_utils::IsScreenReaderEnabled() || - accessibility_state_utils::IsSelectToSpeakEnabled(); + // This class is only supported for ChromeOS, and only needs to be aware of + // ChromeOS assistive technologies. + return ash::AccessibilityManager::Get()->IsSpokenFeedbackEnabled() || + ash::AccessibilityManager::Get()->IsSelectToSpeakEnabled(); } -#if BUILDFLAG(IS_CHROMEOS) void AXMediaAppUntrustedService::OnAshAccessibilityModeChanged( const ash::AccessibilityStatusEventDetails& details) { if (details.notification_type == @@ -173,7 +170,6 @@ media_app_->AccessibilityEnabledChanged(IsAccessibilityEnabled()); } } -#endif // BUILDFLAG(IS_CHROMEOS) void AXMediaAppUntrustedService::PerformAction( const ui::AXActionData& action_data) {
diff --git a/chrome/browser/accessibility/media_app/ax_media_app_untrusted_service.h b/chrome/browser/accessibility/media_app/ax_media_app_untrusted_service.h index 31fcdf4..e416236 100644 --- a/chrome/browser/accessibility/media_app/ax_media_app_untrusted_service.h +++ b/chrome/browser/accessibility/media_app/ax_media_app_untrusted_service.h
@@ -112,10 +112,8 @@ void OnOCRServiceInitialized(bool is_successful); -#if BUILDFLAG(IS_CHROMEOS) void OnAshAccessibilityModeChanged( const ash::AccessibilityStatusEventDetails& details); -#endif // ui::AXActionHandlerBase: void PerformAction(const ui::AXActionData& action_data) override; @@ -192,10 +190,8 @@ ui::AXNode& starting_node) const; std::unique_ptr<gfx::Transform> MakeTransformFromOffsetAndScale() const; -#if BUILDFLAG(IS_CHROMEOS) // Observes whether spoken feedback is enabled in Ash. base::CallbackListSubscription accessibility_status_subscription_; -#endif // BUILDFLAG(IS_CHROMEOS) // This `BrowserContext` will always outlive the WebUI, so this is safe. raw_ref<content::BrowserContext> browser_context_; gfx::NativeWindow native_window_;
diff --git a/chrome/browser/accessibility/media_app/ax_media_app_untrusted_service_browsertest.cc b/chrome/browser/accessibility/media_app/ax_media_app_untrusted_service_browsertest.cc index 384be0c..b6a1dcc 100644 --- a/chrome/browser/accessibility/media_app/ax_media_app_untrusted_service_browsertest.cc +++ b/chrome/browser/accessibility/media_app/ax_media_app_untrusted_service_browsertest.cc
@@ -14,7 +14,6 @@ #include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" #include "base/test/metrics/histogram_tester.h" -#include "chrome/browser/accessibility/accessibility_state_utils.h" #include "chrome/browser/accessibility/media_app/ax_media_app.h" #include "chrome/browser/accessibility/media_app/ax_media_app_service_factory.h" #include "chrome/browser/accessibility/media_app/test/fake_ax_media_app.h" @@ -148,6 +147,9 @@ FakeAXMediaApp fake_media_app_; std::unique_ptr<TestAXMediaAppUntrustedService> service_; + + private: + std::optional<content::ScopedAccessibilityModeOverride> mode_override_; }; std::vector<PageMetadataPtr> @@ -179,37 +181,23 @@ } void AXMediaAppUntrustedServiceTest::EnableScreenReaderForTesting() { - accessibility_state_utils::OverrideIsScreenReaderEnabledForTesting(true); -#if BUILDFLAG(IS_CHROMEOS) AccessibilityManager::Get()->EnableSpokenFeedback(true); -#else - content::ScopedAccessibilityModeOverride scoped_mode(ui::kAXModeComplete); -#endif // BUILDFLAG(IS_CHROMEOS) + mode_override_.emplace(ui::kAXModeComplete); } void AXMediaAppUntrustedServiceTest::DisableScreenReaderForTesting() { - accessibility_state_utils::OverrideIsScreenReaderEnabledForTesting(false); -#if BUILDFLAG(IS_CHROMEOS) AccessibilityManager::Get()->EnableSpokenFeedback(false); -#else - content::ScopedAccessibilityModeOverride scoped_mode(ui::kNone); -#endif // BUILDFLAG(IS_CHROMEOS) + mode_override_.reset(); } void AXMediaAppUntrustedServiceTest::EnableSelectToSpeakForTesting() { -#if BUILDFLAG(IS_CHROMEOS) AccessibilityManager::Get()->SetSelectToSpeakEnabled(true); -#else - content::ScopedAccessibilityModeOverride scoped_mode(ui::kAXModeComplete); -#endif // BUILDFLAG(IS_CHROMEOS) + mode_override_.emplace(ui::kAXModeComplete); } void AXMediaAppUntrustedServiceTest::DisableSelectToSpeakForTesting() { -#if BUILDFLAG(IS_CHROMEOS) AccessibilityManager::Get()->SetSelectToSpeakEnabled(false); -#else - content::ScopedAccessibilityModeOverride scoped_mode(ui::kAXModeComplete); -#endif // BUILDFLAG(IS_CHROMEOS) + mode_override_.reset(); } void AXMediaAppUntrustedServiceTest::WaitForOcringPages(
diff --git a/chrome/browser/accessibility/pdf_ocr_controller.cc b/chrome/browser/accessibility/pdf_ocr_controller.cc index 93a6125..54a9846 100644 --- a/chrome/browser/accessibility/pdf_ocr_controller.cc +++ b/chrome/browser/accessibility/pdf_ocr_controller.cc
@@ -12,7 +12,6 @@ #include "base/metrics/metrics_hashes.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" -#include "chrome/browser/accessibility/accessibility_state_utils.h" #include "chrome/browser/pdf/pdf_viewer_stream_manager.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/screen_ai/screen_ai_install_state.h" @@ -31,6 +30,7 @@ #include "content/public/browser/web_contents.h" #include "pdf/pdf_features.h" #include "ui/accessibility/accessibility_features.h" +#include "ui/accessibility/platform/ax_platform.h" #if BUILDFLAG(IS_CHROMEOS) #include "chrome/browser/ash/accessibility/accessibility_manager.h" @@ -107,14 +107,14 @@ // enabled. bool IsAccessibilityEnabled(Profile* profile) { // Active if a screen reader is present. - if (accessibility_state_utils::IsScreenReaderEnabled()) { + if (ui::AXPlatform::GetInstance().IsScreenReaderActive()) { return true; } #if BUILDFLAG(IS_CHROMEOS) // Conditionally active if select-to-speak is enabled. if (features::IsAccessibilityPdfOcrForSelectToSpeakEnabled() && - accessibility_state_utils::IsSelectToSpeakEnabled()) { + ash::AccessibilityManager::Get()->IsSelectToSpeakEnabled()) { return true; } #endif // BUILDFLAG(IS_CHROMEOS)
diff --git a/chrome/browser/accessibility/pdf_ocr_metrics.cc b/chrome/browser/accessibility/pdf_ocr_metrics.cc index 4fc60f51..306d45f3 100644 --- a/chrome/browser/accessibility/pdf_ocr_metrics.cc +++ b/chrome/browser/accessibility/pdf_ocr_metrics.cc
@@ -5,7 +5,11 @@ #include "chrome/browser/accessibility/pdf_ocr_metrics.h" #include "base/metrics/histogram_macros.h" -#include "chrome/browser/accessibility/accessibility_state_utils.h" +#include "ui/accessibility/platform/ax_platform.h" + +#if BUILDFLAG(IS_CHROMEOS) +#include "chrome/browser/ash/accessibility/accessibility_manager.h" +#endif // BUILDFLAG(IS_CHROMEOS) namespace accessibility { @@ -16,14 +20,17 @@ bool is_pdf_ocr_on = true; #endif - if (accessibility_state_utils::IsScreenReaderEnabled()) { + if (ui::AXPlatform::GetInstance().IsScreenReaderActive()) { UMA_HISTOGRAM_BOOLEAN("Accessibility.PDF.OpenedWithScreenReader.PdfOcr", is_pdf_ocr_on); } - if (accessibility_state_utils::IsSelectToSpeakEnabled()) { + +#if BUILDFLAG(IS_CHROMEOS) + if (ash::AccessibilityManager::Get()->IsSelectToSpeakEnabled()) { UMA_HISTOGRAM_BOOLEAN("Accessibility.PDF.OpenedWithSelectToSpeak.PdfOcr", is_pdf_ocr_on); } +#endif } } // namespace accessibility
diff --git a/chrome/browser/accessibility/tree_fixing/ax_tree_fixing_services_router.cc b/chrome/browser/accessibility/tree_fixing/ax_tree_fixing_services_router.cc index 561b34aa..9c96b95 100644 --- a/chrome/browser/accessibility/tree_fixing/ax_tree_fixing_services_router.cc +++ b/chrome/browser/accessibility/tree_fixing/ax_tree_fixing_services_router.cc
@@ -6,7 +6,6 @@ #include "base/check.h" #include "base/functional/bind.h" -#include "chrome/browser/accessibility/accessibility_state_utils.h" #include "chrome/browser/accessibility/tree_fixing/internal/ax_tree_fixing_screen_ai_service.h" #include "chrome/browser/profiles/profile.h" #include "content/public/browser/render_view_host.h" @@ -122,9 +121,7 @@ continue; } if (web_contents->GetAccessibilityMode().has_mode( - ui::AXMode::kExtendedProperties) || - accessibility_state_utils::IsScreenReaderEnabled() || - accessibility_state_utils::IsSelectToSpeakEnabled()) { + ui::AXMode::kExtendedProperties)) { web_contents_observers_.AddObserver( new WebContentsObserver(*web_contents)); } else {
diff --git a/chrome/browser/ash/accessibility/accessibility_manager.cc b/chrome/browser/ash/accessibility/accessibility_manager.cc index f1b1328..95bf547 100644 --- a/chrome/browser/ash/accessibility/accessibility_manager.cc +++ b/chrome/browser/ash/accessibility/accessibility_manager.cc
@@ -582,12 +582,16 @@ base::BindRepeating(&AccessibilityManager::PostUnloadSelectToSpeak, weak_ptr_factory_.GetWeakPtr()))); + const bool enable_switch_access_v3_manifest = + ::features::IsAccessibilityManifestV3EnabledForSwitchAccess(); const base::FilePath::CharType* switch_access_manifest_filename = - enable_v3_manifest ? extension_misc::kSwitchAccessManifestV3Filename - : extension_misc::kSwitchAccessManifestFilename; + enable_v3_manifest || enable_switch_access_v3_manifest + ? extension_misc::kSwitchAccessManifestV3Filename + : extension_misc::kSwitchAccessManifestFilename; const base::FilePath::CharType* switch_access_guest_manifest_filename = - enable_v3_manifest ? extension_misc::kSwitchAccessGuestManifestV3Filename - : extension_misc::kSwitchAccessGuestManifestFilename; + enable_v3_manifest || enable_switch_access_v3_manifest + ? extension_misc::kSwitchAccessGuestManifestV3Filename + : extension_misc::kSwitchAccessGuestManifestFilename; switch_access_loader_ = base::WrapUnique(new AccessibilityExtensionLoader( extension_misc::kSwitchAccessExtensionId,
diff --git a/chrome/browser/ash/bruschetta/bruschetta_network_context.cc b/chrome/browser/ash/bruschetta/bruschetta_network_context.cc index aad33174..ce571b8 100644 --- a/chrome/browser/ash/bruschetta/bruschetta_network_context.cc +++ b/chrome/browser/ash/bruschetta/bruschetta_network_context.cc
@@ -238,6 +238,11 @@ std::move(callback).Run(false); } +void BruschettaNetworkContext::OnLocalNetworkAccessPermissionRequired( + OnLocalNetworkAccessPermissionRequiredCallback callback) { + std::move(callback).Run(false); +} + void BruschettaNetworkContext::OnClearSiteData( const GURL& url, const std::string& header_value,
diff --git a/chrome/browser/ash/bruschetta/bruschetta_network_context.h b/chrome/browser/ash/bruschetta/bruschetta_network_context.h index e910148d..99e4091 100644 --- a/chrome/browser/ash/bruschetta/bruschetta_network_context.h +++ b/chrome/browser/ash/bruschetta/bruschetta_network_context.h
@@ -74,6 +74,8 @@ const std::optional<std::string>& private_network_device_id, const std::optional<std::string>& private_network_device_name, OnPrivateNetworkAccessPermissionRequiredCallback callback) override; + void OnLocalNetworkAccessPermissionRequired( + OnLocalNetworkAccessPermissionRequiredCallback callback) override; void OnClearSiteData( const GURL& url, const std::string& header_value,
diff --git a/chrome/browser/ash/crostini/crostini_manager.cc b/chrome/browser/ash/crostini/crostini_manager.cc index 8f7ef99..1d3db7a 100644 --- a/chrome/browser/ash/crostini/crostini_manager.cc +++ b/chrome/browser/ash/crostini/crostini_manager.cc
@@ -1490,9 +1490,16 @@ } else if (result == BaguetteInstaller::InstallResult::Cancelled) { LOG(ERROR) << "Installing Baguette failed: cancelled"; res = CrostiniResult::INSTALL_BAGUETTE_CANCELLED; + } else if (result == BaguetteInstaller::InstallResult::ChecksumError) { + LOG(ERROR) << "Installing Baguette failed: checksum did not match."; + res = CrostiniResult::INSTALL_BAGUETTE_CANCELLED; + } else if (result == BaguetteInstaller::InstallResult::DownloadError) { + LOG(ERROR) << "Installing Baguette failed: download failed."; + res = CrostiniResult::INSTALL_BAGUETTE_CANCELLED; } else { - NOTREACHED() - << "Got unexpected value of BaguetteInstaller::InstallResult"; + LOG(ERROR) + << "Installing Baguette failed: encountered an unknown error."; + res = CrostiniResult::UNKNOWN_ERROR; } std::move(callback).Run(std::move(fd), res); },
diff --git a/chrome/browser/autocomplete/chrome_autocomplete_provider_client.cc b/chrome/browser/autocomplete/chrome_autocomplete_provider_client.cc index 15ea75d..469f538 100644 --- a/chrome/browser/autocomplete/chrome_autocomplete_provider_client.cc +++ b/chrome/browser/autocomplete/chrome_autocomplete_provider_client.cc
@@ -587,8 +587,8 @@ browser->GetActiveTabInterface() ->GetTabFeatures() ->lens_overlay_controller() - ->ShowUI(lens::LensOverlayInvocationSource::kOmnibox, - /*should_start_focused=*/false); + ->StartContextualizationWithoutOverlay( + lens::LensOverlayInvocationSource::kOmnibox); } #endif // !BUILDFLAG(IS_ANDROID) }
diff --git a/chrome/browser/browser_switcher/alternative_browser_driver_win.cc b/chrome/browser/browser_switcher/alternative_browser_driver_win.cc index 80ee29f0..4223eaa4 100644 --- a/chrome/browser/browser_switcher/alternative_browser_driver_win.cc +++ b/chrome/browser/browser_switcher/alternative_browser_driver_win.cc
@@ -13,6 +13,7 @@ #include <string_view> +#include "base/compiler_specific.h" #include "base/containers/heap_array.h" #include "base/files/file_path.h" #include "base/logging.h" @@ -156,7 +157,7 @@ size_t url_index = arg->find(kUrlVarName); if (url_index == std::wstring::npos) return false; - arg->replace(url_index, wcslen(kUrlVarName), url_spec); + arg->replace(url_index, UNSAFE_TODO(wcslen(kUrlVarName)), url_spec); return true; }
diff --git a/chrome/browser/chrome_process_singleton.cc b/chrome/browser/chrome_process_singleton.cc index 166dd73..66f30fc8 100644 --- a/chrome/browser/chrome_process_singleton.cc +++ b/chrome/browser/chrome_process_singleton.cc
@@ -11,6 +11,7 @@ #if BUILDFLAG(IS_WIN) #include <windows.h> +#include "base/compiler_specific.h" #include "base/metrics/histogram_functions.h" #include "chrome/common/chrome_features.h" #include "components/app_launch_prefetch/app_launch_prefetch.h" @@ -83,7 +84,7 @@ // It is expected that this will overall improve the behavior of ALPF on // Windows, which should decrease startup time for ordinary browser processes. if (is_singleton_instance_ && - (wcsstr(::GetCommandLineW(), L"/prefetch:") == nullptr) && + (UNSAFE_TODO(wcsstr(::GetCommandLineW(), L"/prefetch:")) == nullptr) && base::FeatureList::IsEnabled(features::kOverridePrefetchOnSingleton)) { OVERRIDE_PREFETCH_PARAMETER prefetch_parameter = {}; prefetch_parameter.Value = app_launch_prefetch::GetPrefetchBucket(
diff --git a/chrome/browser/collaboration/android/java/src/org/chromium/chrome/browser/collaboration/CollaborationControllerDelegateImpl.java b/chrome/browser/collaboration/android/java/src/org/chromium/chrome/browser/collaboration/CollaborationControllerDelegateImpl.java index a80915c4..615281e1 100644 --- a/chrome/browser/collaboration/android/java/src/org/chromium/chrome/browser/collaboration/CollaborationControllerDelegateImpl.java +++ b/chrome/browser/collaboration/android/java/src/org/chromium/chrome/browser/collaboration/CollaborationControllerDelegateImpl.java
@@ -99,7 +99,6 @@ if (mFlowType == FlowType.JOIN) { loadingFullscreenCoordinator.startLoading( - mActivity.getString(R.string.collaboration_loading_text), () -> { destroy(); });
diff --git a/chrome/browser/collaboration/android/java/src/org/chromium/chrome/browser/collaboration/CollaborationControllerDelegateImplUnitTest.java b/chrome/browser/collaboration/android/java/src/org/chromium/chrome/browser/collaboration/CollaborationControllerDelegateImplUnitTest.java index 771d0e2f..9c3cb60 100644 --- a/chrome/browser/collaboration/android/java/src/org/chromium/chrome/browser/collaboration/CollaborationControllerDelegateImplUnitTest.java +++ b/chrome/browser/collaboration/android/java/src/org/chromium/chrome/browser/collaboration/CollaborationControllerDelegateImplUnitTest.java
@@ -137,7 +137,7 @@ mStartAccountRefreshCallback); if (type == FlowType.JOIN) { - verify(mLoadingFullscreenCoordinator).startLoading(any(), any()); + verify(mLoadingFullscreenCoordinator).startLoading(any()); } } @@ -152,7 +152,7 @@ mLoadingFullscreenCoordinator, mSwitchToTabSwitcherCallback, mStartAccountRefreshCallback); - verify(mLoadingFullscreenCoordinator).startLoading(any(), any()); + verify(mLoadingFullscreenCoordinator).startLoading(any()); long resultCallback = 1; long exitCallback = 2;
diff --git a/chrome/browser/collaboration/messaging/DEPS b/chrome/browser/collaboration/messaging/DEPS index 508ca58..32aa9f58 100644 --- a/chrome/browser/collaboration/messaging/DEPS +++ b/chrome/browser/collaboration/messaging/DEPS
@@ -3,6 +3,7 @@ "+components/collaboration/internal/messaging/configuration.h", "+components/collaboration/internal/messaging/data_sharing_change_notifier_impl.h", "+components/collaboration/internal/messaging/empty_messaging_backend_service.h", + "+components/collaboration/internal/messaging/instant_message_processor_impl.h", "+components/collaboration/internal/messaging/messaging_backend_service_impl.h", "+components/collaboration/internal/messaging/storage/empty_messaging_backend_database.h", "+components/collaboration/internal/messaging/storage/messaging_backend_database_impl.h",
diff --git a/chrome/browser/collaboration/messaging/messaging_backend_service_factory.cc b/chrome/browser/collaboration/messaging/messaging_backend_service_factory.cc index 5b6f4a76..542f65e5 100644 --- a/chrome/browser/collaboration/messaging/messaging_backend_service_factory.cc +++ b/chrome/browser/collaboration/messaging/messaging_backend_service_factory.cc
@@ -18,6 +18,7 @@ #include "components/collaboration/internal/messaging/configuration.h" #include "components/collaboration/internal/messaging/data_sharing_change_notifier_impl.h" #include "components/collaboration/internal/messaging/empty_messaging_backend_service.h" +#include "components/collaboration/internal/messaging/instant_message_processor_impl.h" #include "components/collaboration/internal/messaging/messaging_backend_service_impl.h" #include "components/collaboration/internal/messaging/storage/empty_messaging_backend_database.h" #include "components/collaboration/internal/messaging/storage/messaging_backend_database_impl.h" @@ -96,6 +97,8 @@ auto messaging_backend_store = std::make_unique<MessagingBackendStoreImpl>( std::move(messaging_backend_database)); + auto instant_message_processor = + std::make_unique<InstantMessageProcessorImpl>(); // This configuration object allows us to control platform specific behavior. MessagingBackendConfiguration configuration; @@ -107,8 +110,8 @@ auto service = std::make_unique<MessagingBackendServiceImpl>( configuration, std::move(tab_group_change_notifier), std::move(data_sharing_change_notifier), - std::move(messaging_backend_store), tab_group_sync_service, - data_sharing_service, identity_manager); + std::move(messaging_backend_store), std::move(instant_message_processor), + tab_group_sync_service, data_sharing_service, identity_manager); return std::move(service); }
diff --git a/chrome/browser/data_sharing/android/java/src/org/chromium/chrome/browser/data_sharing/InstantMessageDelegateImplUnitTest.java b/chrome/browser/data_sharing/android/java/src/org/chromium/chrome/browser/data_sharing/InstantMessageDelegateImplUnitTest.java index a19e0335..e717c246 100644 --- a/chrome/browser/data_sharing/android/java/src/org/chromium/chrome/browser/data_sharing/InstantMessageDelegateImplUnitTest.java +++ b/chrome/browser/data_sharing/android/java/src/org/chromium/chrome/browser/data_sharing/InstantMessageDelegateImplUnitTest.java
@@ -171,7 +171,7 @@ attribution.tabGroupMetadata.syncTabGroupId = SYNC_GROUP_ID1; attribution.triggeringUser = GROUP_MEMBER1; InstantMessage instantMessage = new InstantMessage(); - instantMessage.attribution = attribution; + instantMessage.attributions.add(attribution); instantMessage.collaborationEvent = collaborationEvent; instantMessage.level = InstantNotificationLevel.BROWSER; return instantMessage; @@ -225,7 +225,7 @@ @Test public void testTabRemoved_NullUrl() { InstantMessage message = newInstantMessage(CollaborationEvent.TAB_REMOVED); - message.attribution.tabMetadata.lastKnownUrl = null; + message.attributions.get(0).tabMetadata.lastKnownUrl = null; mDelegate.displayInstantaneousMessage(message, mSuccessCallback); verify(mManagedMessageDispatcher) @@ -296,7 +296,7 @@ @Test public void testCollaborationMemberAdded() { InstantMessage message = newInstantMessage(CollaborationEvent.COLLABORATION_MEMBER_ADDED); - message.attribution.collaborationId = COLLABORATION_ID1; + message.attributions.get(0).collaborationId = COLLABORATION_ID1; mDelegate.displayInstantaneousMessage(message, mSuccessCallback); verify(mManagedMessageDispatcher) @@ -320,7 +320,7 @@ @Test public void testCollaborationMemberAdded_NullCollaborationId() { InstantMessage message = newInstantMessage(CollaborationEvent.COLLABORATION_MEMBER_ADDED); - message.attribution.collaborationId = null; + message.attributions.get(0).collaborationId = null; mDelegate.displayInstantaneousMessage(message, mSuccessCallback); verify(mManagedMessageDispatcher) @@ -336,7 +336,7 @@ public void testCollaborationMemberAdded_FallbackTitle() { when(mTabGroupModelFilter.getTabCountForGroup(any())).thenReturn(TAB_COUNT_IN_GROUP); InstantMessage message = newInstantMessage(CollaborationEvent.COLLABORATION_MEMBER_ADDED); - message.attribution.tabGroupMetadata.lastKnownTitle = ""; + message.attributions.get(0).tabGroupMetadata.lastKnownTitle = ""; mDelegate.displayInstantaneousMessage(message, mSuccessCallback); verify(mManagedMessageDispatcher) @@ -377,7 +377,7 @@ when(mTabGroupModelFilter.getTabCountForGroup(any())).thenReturn(1); InstantMessage message = newInstantMessage(CollaborationEvent.TAB_GROUP_REMOVED); - message.attribution.tabGroupMetadata.lastKnownTitle = null; + message.attributions.get(0).tabGroupMetadata.lastKnownTitle = null; mDelegate.displayInstantaneousMessage(message, mSuccessCallback); verify(mManagedMessageDispatcher) @@ -397,7 +397,7 @@ when(mTabGroupModelFilter.getRootIdFromTabGroupId(any())).thenReturn(TAB_ID); when(mTabGroupModelFilter.getTabCountForGroup(TAB_GROUP_ID)).thenReturn(TAB_COUNT_IN_GROUP); InstantMessage message = newInstantMessage(CollaborationEvent.TAB_GROUP_REMOVED); - message.attribution.tabGroupMetadata.lastKnownTitle = ""; + message.attributions.get(0).tabGroupMetadata.lastKnownTitle = ""; mDelegate.displayInstantaneousMessage(message, mSuccessCallback); verify(mManagedMessageDispatcher) @@ -416,7 +416,8 @@ public void testSystemNotification() { InstantMessage message = newInstantMessage(CollaborationEvent.COLLABORATION_MEMBER_ADDED); message.level = InstantNotificationLevel.SYSTEM; - message.attribution.id = UUID.fromString("00000000-0000-0000-0000-000000000009").toString(); + message.attributions.get(0).id = + UUID.fromString("00000000-0000-0000-0000-000000000009").toString(); mDelegate.displayInstantaneousMessage(message, mSuccessCallback);
diff --git a/chrome/browser/flag-metadata.json b/chrome/browser/flag-metadata.json index 401df64f..fecadf8 100644 --- a/chrome/browser/flag-metadata.json +++ b/chrome/browser/flag-metadata.json
@@ -2385,6 +2385,11 @@ "expiry_milestone": 145 }, { + "name": "enable-accessibility-manifest-v3-switch-access", + "owners": [ "spectranaut@igalia.com", "akihiroota@chromium.org", "//ui/accessibility/OWNERS" ], + "expiry_milestone": 145 + }, + { "name": "enable-accessibility-mousekeys", "owners": [ "zork@chromium.org", "//ash/accessibility/OWNERS" ], "expiry_milestone": 142
diff --git a/chrome/browser/flag_descriptions.cc b/chrome/browser/flag_descriptions.cc index 570eabd0..342df5db 100644 --- a/chrome/browser/flag_descriptions.cc +++ b/chrome/browser/flag_descriptions.cc
@@ -6584,6 +6584,12 @@ "Experimental migration of Enhanced Network TTS from extension manifest " "v2 to v3."; +const char kAccessibilityManifestV3SwitchAccessName[] = + "Changes accessibility extension Switch Access manifest v2 to v3."; +const char kAccessibilityManifestV3SwitchAccessDescription[] = + "Experimental migration of Switch Access from extension manifest " + "v2 to v3."; + const char kExperimentalAccessibilitySwitchAccessTextName[] = "Enable enhanced Switch Access text input."; const char kExperimentalAccessibilitySwitchAccessTextDescription[] =
diff --git a/chrome/browser/flag_descriptions.h b/chrome/browser/flag_descriptions.h index 4e2c22ab..1e2b7ab 100644 --- a/chrome/browser/flag_descriptions.h +++ b/chrome/browser/flag_descriptions.h
@@ -3872,6 +3872,9 @@ extern const char kAccessibilityManifestV3EnhancedNetworkTtsName[]; extern const char kAccessibilityManifestV3EnhancedNetworkTtsDescription[]; +extern const char kAccessibilityManifestV3SwitchAccessName[]; +extern const char kAccessibilityManifestV3SwitchAccessDescription[]; + extern const char kExperimentalAccessibilitySwitchAccessTextName[]; extern const char kExperimentalAccessibilitySwitchAccessTextDescription[];
diff --git a/chrome/browser/glic/host/glic_page_handler.cc b/chrome/browser/glic/host/glic_page_handler.cc index 072dcfeb..7cef4c8d 100644 --- a/chrome/browser/glic/host/glic_page_handler.cc +++ b/chrome/browser/glic/host/glic_page_handler.cc
@@ -388,10 +388,9 @@ glic_service_->GetContextFromFocusedTab(*options, std::move(callback)); } - void ActInFocusedTab( - const std::vector<uint8_t>& action_proto, - glic::mojom::GetTabContextOptionsPtr options, - ActInFocusedTabCallback callback) override { + void ActInFocusedTab(const std::vector<uint8_t>& action_proto, + glic::mojom::GetTabContextOptionsPtr options, + ActInFocusedTabCallback callback) override { glic_service_->ActInFocusedTab(action_proto, *options, std::move(callback)); } @@ -432,6 +431,13 @@ bool enabled, SetMicrophonePermissionStateCallback callback) override { pref_service_->SetBoolean(prefs::kGlicMicrophoneEnabled, enabled); + if (enabled) { + base::RecordAction( + base::UserMetricsAction("GlicMicrophonePermissionEnabled")); + } else { + base::RecordAction( + base::UserMetricsAction("GlicMicrophonePermissionDisabled")); + } std::move(callback).Run(); } @@ -439,6 +445,13 @@ bool enabled, SetLocationPermissionStateCallback callback) override { pref_service_->SetBoolean(prefs::kGlicGeolocationEnabled, enabled); + if (enabled) { + base::RecordAction( + base::UserMetricsAction("GlicLocationPermissionEnabled")); + } else { + base::RecordAction( + base::UserMetricsAction("GlicLocationPermissionDisabled")); + } std::move(callback).Run(); }
diff --git a/chrome/browser/glic/resources/browser_resources.grd b/chrome/browser/glic/resources/browser_resources.grd index 017c1bc..39baa24 100644 --- a/chrome/browser/glic/resources/browser_resources.grd +++ b/chrome/browser/glic/resources/browser_resources.grd
@@ -133,7 +133,7 @@ Something went wrong </message> <message name="IDS_GLIC_ERROR_NOTICE" translateable="false" desc="This is the text of the glic error notice."> - Glic isn't available right now. Try again later + Glic isn't available right now. Try again later. </message> <message name="IDS_GLIC_ERROR_NOTICE_ACTION_BUTTON" translateable="false" desc="This is the button label text for the glic error notice."> Try again
diff --git a/chrome/browser/hub/internal/android/java/src/org/chromium/chrome/browser/hub/HubPaneHostView.java b/chrome/browser/hub/internal/android/java/src/org/chromium/chrome/browser/hub/HubPaneHostView.java index eec850e..460c892 100644 --- a/chrome/browser/hub/internal/android/java/src/org/chromium/chrome/browser/hub/HubPaneHostView.java +++ b/chrome/browser/hub/internal/android/java/src/org/chromium/chrome/browser/hub/HubPaneHostView.java
@@ -12,6 +12,7 @@ import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.content.Context; +import android.content.res.ColorStateList; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; @@ -19,6 +20,7 @@ import android.widget.FrameLayout; import android.widget.ImageView; +import androidx.annotation.ColorInt; import androidx.annotation.Nullable; import org.chromium.base.Callback; @@ -94,6 +96,11 @@ PANE_COLOR_BLEND_ANIMATION_DURATION_MS, colorScheme -> HubColors.getBackgroundColor(context, colorScheme), mPaneFrame::setBackgroundColor)); + mixer.registerBlend( + new SingleHubViewColorBlend( + PANE_COLOR_BLEND_ANIMATION_DURATION_MS, + colorScheme -> HubColors.getHairlineColor(context, colorScheme), + this::setHairlineColor)); } void setHairlineVisibility(boolean visible) { @@ -113,4 +120,8 @@ mPaneFrame.addView(rootView); } } + + void setHairlineColor(@ColorInt int hairlineColor) { + mHairline.setImageTintList(ColorStateList.valueOf(hairlineColor)); + } }
diff --git a/chrome/browser/hub/internal/android/java/src/org/chromium/chrome/browser/hub/HubPaneHostViewUnitTest.java b/chrome/browser/hub/internal/android/java/src/org/chromium/chrome/browser/hub/HubPaneHostViewUnitTest.java index 503ad20..60359fd1 100644 --- a/chrome/browser/hub/internal/android/java/src/org/chromium/chrome/browser/hub/HubPaneHostViewUnitTest.java +++ b/chrome/browser/hub/internal/android/java/src/org/chromium/chrome/browser/hub/HubPaneHostViewUnitTest.java
@@ -7,6 +7,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.chromium.chrome.browser.hub.HubColorMixer.COLOR_MIXER; @@ -147,7 +148,7 @@ @Test public void testHubColorScheme() { - verify(mColorMixer).registerBlend(any()); + verify(mColorMixer, times(2)).registerBlend(any()); } /** Order of children does not matter. */
diff --git a/chrome/browser/metrics/variations/variations_http_headers_browsertest.cc b/chrome/browser/metrics/variations/variations_http_headers_browsertest.cc index c930da4..fa35f27e 100644 --- a/chrome/browser/metrics/variations/variations_http_headers_browsertest.cc +++ b/chrome/browser/metrics/variations/variations_http_headers_browsertest.cc
@@ -88,17 +88,10 @@ }; class VariationsHttpHeadersBrowserTest - : public InProcessBrowserTest, - public testing::WithParamInterface<bool> { + : public InProcessBrowserTest { public: VariationsHttpHeadersBrowserTest() - : https_server_(net::test_server::EmbeddedTestServer::TYPE_HTTPS) { - if (IsPlzDedicatedWorkerEnabled()) { - feature_list_.InitAndEnableFeature(blink::features::kPlzDedicatedWorker); - } else { - feature_list_.InitAndDisableFeature(blink::features::kPlzDedicatedWorker); - } - } + : https_server_(net::test_server::EmbeddedTestServer::TYPE_HTTPS) {} VariationsHttpHeadersBrowserTest(const VariationsHttpHeadersBrowserTest&) = delete; @@ -107,8 +100,6 @@ ~VariationsHttpHeadersBrowserTest() override = default; - static bool IsPlzDedicatedWorkerEnabled() { return GetParam(); } - void CreatedBrowserMainParts(content::BrowserMainParts* parts) override { InProcessBrowserTest::CreatedBrowserMainParts(parts); static_cast<ChromeBrowserMainParts*>(parts)->AddParts( @@ -382,9 +373,6 @@ // For waiting for requests. std::map<GURL, base::OnceClosure> done_callbacks_; - - // To enable/disable the PlzDedicatedWorker feature during the test. - base::test::ScopedFeatureList feature_list_; }; std::unique_ptr<net::test_server::HttpResponse> @@ -544,7 +532,7 @@ // Verify in an integration test that the variations header (X-Client-Data) is // attached to network requests to Google but stripped on redirects. -IN_PROC_BROWSER_TEST_P(VariationsHttpHeadersBrowserTest, +IN_PROC_BROWSER_TEST_F(VariationsHttpHeadersBrowserTest, TestStrippingHeadersFromResourceRequest) { ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), GetGoogleRedirectUrl1())); @@ -556,7 +544,7 @@ // Verify in an integration that that the variations header (X-Client-Data) is // correctly attached and stripped from network requests. -IN_PROC_BROWSER_TEST_P(VariationsHttpHeadersBrowserTest, +IN_PROC_BROWSER_TEST_F(VariationsHttpHeadersBrowserTest, TestStrippingHeadersFromSubresourceRequest) { GURL url = server()->GetURL("/simple_page.html"); ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); @@ -568,7 +556,7 @@ EXPECT_FALSE(HasReceivedHeader(GetExampleUrl(), "X-Client-Data")); } -IN_PROC_BROWSER_TEST_P(VariationsHttpHeadersBrowserTest, Incognito) { +IN_PROC_BROWSER_TEST_F(VariationsHttpHeadersBrowserTest, Incognito) { Browser* incognito = CreateIncognitoBrowser(); ASSERT_TRUE(ui_test_utils::NavigateToURL(incognito, GetGoogleUrl())); @@ -579,7 +567,7 @@ EXPECT_FALSE(HasReceivedHeader(GetGoogleSubresourceUrl(), "X-Client-Data")); } -IN_PROC_BROWSER_TEST_P(VariationsHttpHeadersBrowserTest, UserSignedIn) { +IN_PROC_BROWSER_TEST_F(VariationsHttpHeadersBrowserTest, UserSignedIn) { // Ensure GetClientDataHeader() returns different values when signed in vs // not signed in. variations::VariationID signed_in_id = 8; @@ -629,7 +617,7 @@ EXPECT_TRUE(base::Contains(ids_any_context, signed_in_id)); } -IN_PROC_BROWSER_TEST_P(VariationsHttpHeadersBrowserTest, UserNotSignedIn) { +IN_PROC_BROWSER_TEST_F(VariationsHttpHeadersBrowserTest, UserNotSignedIn) { // Ensure GetClientDataHeader() returns different values when signed in vs // not signed in. variations::VariationID signed_in_id = 8; @@ -676,7 +664,7 @@ EXPECT_FALSE(base::Contains(ids_any_context, signed_in_id)); } -IN_PROC_BROWSER_TEST_P(VariationsHttpHeadersBrowserTest, +IN_PROC_BROWSER_TEST_F(VariationsHttpHeadersBrowserTest, PRE_CheckLowEntropySourceValue) { // We use the PRE_ prefix mechanism to ensure that this test always runs // before CheckLowEntropyValue(). None of the subclasses in the @@ -687,7 +675,7 @@ local_state->SetInteger(metrics::prefs::kMetricsLowEntropySource, 5); } -IN_PROC_BROWSER_TEST_P(VariationsHttpHeadersBrowserTest, +IN_PROC_BROWSER_TEST_F(VariationsHttpHeadersBrowserTest, CheckLowEntropySourceValue) { auto entropy_providers = g_browser_process->GetMetricsServicesManager() ->CreateEntropyProvidersForTesting(); @@ -717,12 +705,12 @@ // The PRE_ prefix ensures this runs before // LimitedEntropyRandomization_ExperimentLogging. -IN_PROC_BROWSER_TEST_P(VariationsHttpHeadersBrowserTest, +IN_PROC_BROWSER_TEST_F(VariationsHttpHeadersBrowserTest, PRE_LimitedEntropyRandomization_ExperimentLogging) { SetUpLimitedEntropyRandomizationSource(); } -IN_PROC_BROWSER_TEST_P(VariationsHttpHeadersBrowserTest, +IN_PROC_BROWSER_TEST_F(VariationsHttpHeadersBrowserTest, LimitedEntropyRandomization_ExperimentLogging) { // CreateEntropyProvidersForTesting() ensures a limited entropy provider is // created. @@ -754,13 +742,13 @@ // The PRE_ prefix ensures this runs before // LimitedEntropyRandomization_ExperimentLoggingWithoutGoogleWebExperimentationId. -IN_PROC_BROWSER_TEST_P( +IN_PROC_BROWSER_TEST_F( VariationsHttpHeadersBrowserTest, PRE_LimitedEntropyRandomization_ExperimentLoggingWithoutGoogleWebExperimentationId) { SetUpLimitedEntropyRandomizationSource(); } -IN_PROC_BROWSER_TEST_P( +IN_PROC_BROWSER_TEST_F( VariationsHttpHeadersBrowserTest, LimitedEntropyRandomization_ExperimentLoggingWithoutGoogleWebExperimentationId) { // CreateEntropyProvidersForTesting() ensures a limited entropy provider is @@ -840,17 +828,17 @@ expected_header_value); } -IN_PROC_BROWSER_TEST_P(VariationsHttpHeadersBrowserTest, +IN_PROC_BROWSER_TEST_F(VariationsHttpHeadersBrowserTest, TestGoogleWebVisibilityInFirstPartyContexts) { GoogleWebVisibilityTopFrameTest(/*top_frame_is_first_party=*/true); } -IN_PROC_BROWSER_TEST_P(VariationsHttpHeadersBrowserTest, +IN_PROC_BROWSER_TEST_F(VariationsHttpHeadersBrowserTest, TestGoogleWebVisibilityInThirdPartyContexts) { GoogleWebVisibilityTopFrameTest(/*top_frame_is_first_party=*/false); } -IN_PROC_BROWSER_TEST_P( +IN_PROC_BROWSER_TEST_F( VariationsHttpHeadersBrowserTest, TestStrippingHeadersFromRequestUsingSimpleURLLoaderWithProfileNetworkContext) { GURL url = GetGoogleRedirectUrl1(); @@ -883,7 +871,7 @@ EXPECT_FALSE(HasReceivedHeader(GetExampleUrl(), "X-Client-Data")); } -IN_PROC_BROWSER_TEST_P( +IN_PROC_BROWSER_TEST_F( VariationsHttpHeadersBrowserTest, TestStrippingHeadersFromRequestUsingSimpleURLLoaderWithGlobalSystemNetworkContext) { GURL url = GetGoogleRedirectUrl1(); @@ -918,7 +906,7 @@ // Verify in an integration test that the variations header (X-Client-Data) is // attached to service worker navigation preload requests. Regression test // for https://crbug.com/873061. -IN_PROC_BROWSER_TEST_P(VariationsHttpHeadersBrowserTest, +IN_PROC_BROWSER_TEST_F(VariationsHttpHeadersBrowserTest, ServiceWorkerNavigationPreload) { // Register a service worker that uses navigation preload. RegisterServiceWorker("/service_worker/navigation_preload_worker.js"); @@ -934,14 +922,14 @@ // Verify in an integration test that the variations header (X-Client-Data) is // attached to requests after the service worker falls back to network. -IN_PROC_BROWSER_TEST_P(VariationsHttpHeadersBrowserTest, +IN_PROC_BROWSER_TEST_F(VariationsHttpHeadersBrowserTest, ServiceWorkerNetworkFallback) { ServiceWorkerTest("/service_worker/network_fallback_worker.js"); } // Verify in an integration test that the variations header (X-Client-Data) is // not exposed in the service worker fetch event. -IN_PROC_BROWSER_TEST_P(VariationsHttpHeadersBrowserTest, +IN_PROC_BROWSER_TEST_F(VariationsHttpHeadersBrowserTest, ServiceWorkerDoesNotSeeHeader) { ServiceWorkerTest("/service_worker/fail_on_variations_header_worker.js"); } @@ -949,14 +937,14 @@ // Verify in an integration test that the variations header (X-Client-Data) is // attached to requests after the service worker does // respondWith(fetch(request)). -IN_PROC_BROWSER_TEST_P(VariationsHttpHeadersBrowserTest, +IN_PROC_BROWSER_TEST_F(VariationsHttpHeadersBrowserTest, ServiceWorkerRespondWithFetch) { ServiceWorkerTest("/service_worker/respond_with_fetch_worker.js"); } // Verify in an integration test that the variations header (X-Client-Data) is // attached to requests for service worker scripts when installing and updating. -IN_PROC_BROWSER_TEST_P(VariationsHttpHeadersBrowserTest, ServiceWorkerScript) { +IN_PROC_BROWSER_TEST_F(VariationsHttpHeadersBrowserTest, ServiceWorkerScript) { // Register a service worker that imports scripts. GURL absolute_import = GetExampleUrlWithPath("/service_worker/empty.js"); const std::string worker_path = @@ -994,23 +982,19 @@ // Verify in an integration test that the variations header (X-Client-Data) is // attached to requests for shared worker scripts. -IN_PROC_BROWSER_TEST_P(VariationsHttpHeadersBrowserTest, SharedWorkerScript) { +IN_PROC_BROWSER_TEST_F(VariationsHttpHeadersBrowserTest, SharedWorkerScript) { WorkerScriptTest("/workers/create_shared_worker.html", "/workers/import_scripts_shared_worker.js"); } // Verify in an integration test that the variations header (X-Client-Data) is // attached to requests for dedicated worker scripts. -IN_PROC_BROWSER_TEST_P(VariationsHttpHeadersBrowserTest, +IN_PROC_BROWSER_TEST_F(VariationsHttpHeadersBrowserTest, DedicatedWorkerScript) { WorkerScriptTest("/workers/create_dedicated_worker.html", "/workers/import_scripts_dedicated_worker.js"); } -INSTANTIATE_TEST_SUITE_P(All, - VariationsHttpHeadersBrowserTest, - testing::Bool()); - namespace { // A test fixture for testing prefetches from the Loading Predictor. @@ -1076,7 +1060,7 @@ // Verify in an integration test that that the variations header (X-Client-Data) // is correctly attached to prefetch requests from the Loading Predictor. -IN_PROC_BROWSER_TEST_P(VariationsHttpHeadersBrowserTestWithOptimizationGuide, +IN_PROC_BROWSER_TEST_F(VariationsHttpHeadersBrowserTestWithOptimizationGuide, Prefetch) { GURL url = server()->GetURL("test.com", "/simple_page.html"); GURL google_url = GetGoogleSubresourceUrl(); @@ -1096,7 +1080,3 @@ EXPECT_TRUE(HasReceivedHeader(google_url, "X-Client-Data")); EXPECT_FALSE(HasReceivedHeader(non_google_url, "X-Client-Data")); } - -INSTANTIATE_TEST_SUITE_P(All, - VariationsHttpHeadersBrowserTestWithOptimizationGuide, - testing::Bool());
diff --git a/chrome/browser/nearby_sharing/certificates/nearby_share_decrypted_public_certificate.h b/chrome/browser/nearby_sharing/certificates/nearby_share_decrypted_public_certificate.h index 8777afd..47238e4 100644 --- a/chrome/browser/nearby_sharing/certificates/nearby_share_decrypted_public_certificate.h +++ b/chrome/browser/nearby_sharing/certificates/nearby_share_decrypted_public_certificate.h
@@ -14,7 +14,6 @@ #include "base/time/time.h" #include "chrome/browser/nearby_sharing/certificates/constants.h" #include "chrome/browser/nearby_sharing/certificates/nearby_share_encrypted_metadata_key.h" -#include "crypto/symmetric_key.h" #include "third_party/nearby/sharing/proto/encrypted_metadata.pb.h" #include "third_party/nearby/sharing/proto/rpc_resources.pb.h"
diff --git a/chrome/browser/nearby_sharing/certificates/nearby_share_private_certificate.cc b/chrome/browser/nearby_sharing/certificates/nearby_share_private_certificate.cc index e6b5b2c..90e0a02 100644 --- a/chrome/browser/nearby_sharing/certificates/nearby_share_private_certificate.cc +++ b/chrome/browser/nearby_sharing/certificates/nearby_share_private_certificate.cc
@@ -30,7 +30,6 @@ #include "crypto/ec_signature_creator.h" #include "crypto/hmac.h" #include "crypto/sha2.h" -#include "crypto/symmetric_key.h" namespace {
diff --git a/chrome/browser/on_device_translation/translation_manager_impl.cc b/chrome/browser/on_device_translation/translation_manager_impl.cc index bb0a2d2e..416b603 100644 --- a/chrome/browser/on_device_translation/translation_manager_impl.cc +++ b/chrome/browser/on_device_translation/translation_manager_impl.cc
@@ -37,7 +37,6 @@ using blink::mojom::CanCreateTranslatorResult; using blink::mojom::CreateTranslatorError; using blink::mojom::CreateTranslatorResult; -using blink::mojom::TranslationAvailability; using blink::mojom::TranslationManagerCreateTranslatorClient; using blink::mojom::TranslatorLanguageCode; using blink::mojom::TranslatorLanguageCodePtr; @@ -260,33 +259,6 @@ weak_ptr_factory_.GetWeakPtr(), std::move(create_translator))); } -void TranslationManagerImpl::GetTranslatorAvailabilityInfo( - GetTranslatorAvailabilityInfoCallback callback) { - auto info = blink::mojom::TranslatorAvailabilityInfo::New(); - - if (!IsTranslatorAllowed(browser_context())) { - info->availability = TranslationAvailability::kNo; - std::move(callback).Run(std::move(info)); - return; - } - - const std::vector<std::string_view> accept_languages = - GetAcceptLanguages(browser_context()); - const std::set<LanguagePackKey> installed_packs = - ComponentManager::GetInstalledLanguagePacks(); - info->language_categories = CreateLanguageCategories( - accept_languages, installed_packs, - /*is_en_preferred*/ IsInAcceptLanguage(accept_languages, "en")); - info->language_availability_matrix = CreateAvailabilityMatrix( - /*accept_languages_check_enabled*/ kTranslationAPIAcceptLanguagesCheck - .Get(), - GetInstallablePackageCount(installed_packs.size())); - info->availability = ComponentManager::GetTranslateKitLibraryPath().empty() - ? TranslationAvailability::kAfterDownload - : TranslationAvailability::kReadily; - std::move(callback).Run(std::move(info)); -} - OnDeviceTranslationServiceController& TranslationManagerImpl::GetServiceController() { if (!service_controller_) {
diff --git a/chrome/browser/on_device_translation/translation_manager_impl.h b/chrome/browser/on_device_translation/translation_manager_impl.h index 5dcbd33e..0b208d0 100644 --- a/chrome/browser/on_device_translation/translation_manager_impl.h +++ b/chrome/browser/on_device_translation/translation_manager_impl.h
@@ -83,8 +83,6 @@ mojo::PendingRemote< blink::mojom::TranslationManagerCreateTranslatorClient> client, blink::mojom::TranslatorCreateOptionsPtr options) override; - void GetTranslatorAvailabilityInfo( - GetTranslatorAvailabilityInfoCallback callback) override; void TranslationAvailable(blink::mojom::TranslatorLanguageCodePtr source_lang, blink::mojom::TranslatorLanguageCodePtr target_lang,
diff --git a/chrome/browser/on_device_translation/translation_manager_util.cc b/chrome/browser/on_device_translation/translation_manager_util.cc index 497d824..dbd8552 100644 --- a/chrome/browser/on_device_translation/translation_manager_util.cc +++ b/chrome/browser/on_device_translation/translation_manager_util.cc
@@ -18,137 +18,7 @@ namespace on_device_translation { -using blink::mojom::TranslationAvailability; -using blink::mojom::TranslatorLanguageCode; -using blink::mojom::TranslatorLanguageCodePtr; - -// The number of language categories in the availability matrix. -constexpr size_t kLanguageCategoriesSize = 8u; - -TranslationAvailability CalculateTranslationAvailability( - const LanguageCategory& source, - const LanguageCategory& target, - bool accept_languages_check_enabled, - size_t installable_package_count) { - if (accept_languages_check_enabled) { - // If both the source and the destination language are not in the user's - // accept language, the translation is not available. - if (!(source.preferred || target.preferred)) { - return TranslationAvailability::kNo; - } - // If the languages which is not in the user's accept language is not a - // popular language, the translation is not available. - if ((!source.preferred && !source.popular) || - (!target.preferred && !target.popular)) { - return TranslationAvailability::kNo; - } - } - - // If both the source and the destination language are installed, the - // translation is available. - if (source.installed && target.installed) { - return TranslationAvailability::kReadily; - } - // If both the source and the destination language are not installed, that - // means the user has to download the two language packs. - if (!source.installed && !target.installed) { - // If the user can download two language packs, the translation is available - // after download, otherwise it is not available. - return installable_package_count >= 2 - ? TranslationAvailability::kAfterDownload - : TranslationAvailability::kNo; - } - - // If one of the source or the destination language is installed, that means - // the user only needs to download one language pack. - // So if the user can download one language pack, the translation is available - // after download, otherwise it is not available. - return installable_package_count >= 1 - ? TranslationAvailability::kAfterDownload - : TranslationAvailability::kNo; -} - -std::vector<std::vector<TranslationAvailability>> CreateAvailabilityMatrix( - bool accept_languages_check_enabled, - size_t installable_package_count) { - const std::vector<LanguageCategory> categories = CreateLanguageCategoryList(); - std::vector<std::vector<TranslationAvailability>> matrix; - matrix.reserve(kLanguageCategoriesSize); - for (const auto& source : categories) { - std::vector<TranslationAvailability> availability_row; - availability_row.reserve(kLanguageCategoriesSize); - for (auto target : categories) { - availability_row.emplace_back(CalculateTranslationAvailability( - source, target, accept_languages_check_enabled, - installable_package_count)); - } - matrix.emplace_back(std::move(availability_row)); - } - return matrix; -} - -std::vector<std::vector<TranslatorLanguageCodePtr>> CreateLanguageCategories( - const std::vector<std::string_view>& accept_languages, - const std::set<LanguagePackKey>& installed_packs, - bool is_en_preferred) { - std::vector<std::vector<TranslatorLanguageCodePtr>> language_categories( - kLanguageCategoriesSize); - language_categories[GetLanguageCategoryIndex(/*installed=*/true, - is_en_preferred, - /*popular=*/true)] - .emplace_back(TranslatorLanguageCode::New("en")); - - for (const auto& it : kLanguagePackComponentConfigMap) { - const LanguagePackKey key = it.first; - const SupportedLanguage supported_language = - NonEnglishSupportedLanguageFromLanguagePackKey(key); - const std::string_view language_code = ToLanguageCode(supported_language); - const bool installed = installed_packs.contains(key); - const bool preferred = IsInAcceptLanguage(accept_languages, language_code); - const bool popular = IsPopularLanguage(supported_language); - const size_t index = - GetLanguageCategoryIndex(installed, preferred, popular); - language_categories[index].push_back( - TranslatorLanguageCode::New(std::string(language_code))); - } - return language_categories; -} - -std::vector<LanguageCategory> CreateLanguageCategoryList() { - std::vector<LanguageCategory> list; - list.reserve(kLanguageCategoriesSize); - for (bool installed : {true, false}) { - for (bool preferred : {true, false}) { - for (bool popular : {true, false}) { - CHECK_EQ(GetLanguageCategoryIndex(installed, preferred, popular), - list.size()); - list.emplace_back(LanguageCategory{ - .installed = installed, - .preferred = preferred, - .popular = popular, - }); - } - } - } - return list; -} - -const std::vector<std::string_view> GetAcceptLanguages( - content::BrowserContext* browser_context) { - CHECK(browser_context); - - PrefService* profile_pref = - Profile::FromBrowserContext(browser_context)->GetPrefs(); - const std::vector<std::string_view> accept_languages = base::SplitStringPiece( - profile_pref->GetString(language::prefs::kAcceptLanguages), ",", - base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); - - return accept_languages; -} - -size_t GetLanguageCategoryIndex(bool installed, bool preferred, bool popular) { - return (installed ? 0 : 4) + (preferred ? 0 : 2) + (popular ? 0 : 1); -} +namespace { bool IsInAcceptLanguage(const std::vector<std::string_view>& accept_languages, const std::string_view lang) { @@ -168,6 +38,21 @@ return IsPopularLanguage(*supported_lang); } +} // namespace + +const std::vector<std::string_view> GetAcceptLanguages( + content::BrowserContext* browser_context) { + CHECK(browser_context); + + PrefService* profile_pref = + Profile::FromBrowserContext(browser_context)->GetPrefs(); + const std::vector<std::string_view> accept_languages = base::SplitStringPiece( + profile_pref->GetString(language::prefs::kAcceptLanguages), ",", + base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); + + return accept_languages; +} + bool IsTranslatorAllowed(content::BrowserContext* browser_context) { CHECK(browser_context); return Profile::FromBrowserContext(browser_context)
diff --git a/chrome/browser/on_device_translation/translation_manager_util.h b/chrome/browser/on_device_translation/translation_manager_util.h index 52e00e25..cac088f 100644 --- a/chrome/browser/on_device_translation/translation_manager_util.h +++ b/chrome/browser/on_device_translation/translation_manager_util.h
@@ -16,63 +16,10 @@ namespace on_device_translation { -using blink::mojom::TranslationAvailability; -using blink::mojom::TranslatorLanguageCodePtr; - -// `LanguageCategory` is used to represent the language category in the -// availability matrix. -struct LanguageCategory { - bool installed; - bool preferred; - bool popular; -}; - -// Calculates the translation availability for the given source and target -// language categories. -TranslationAvailability CalculateTranslationAvailability( - const LanguageCategory& source, - const LanguageCategory& target, - bool accept_languages_check_enabled, - size_t installable_package_count); - -// Creates the availability matrix for each language category. -std::vector<std::vector<TranslationAvailability>> CreateAvailabilityMatrix( - bool accept_languages_check_enabled, - size_t installable_package_count); - -// Creates the language categories for the availability matrix. -// The language categories are stored in the following order: -// 0. Installed and preferred popular languages -// 1. Installed and preferred non-popular languages -// 2. Installed and non-preferred popular languages -// 3. Installed and non-preferred non-popular languages -// 4. Not installed and preferred popular languages -// 5. Not installed and preferred non-popular languages -// 6. Not installed and non-preferred popular languages -// 7. Not installed and non-preferred non-popular languages -// Note: `preferred` means that the language an Accept Language. -std::vector<std::vector<TranslatorLanguageCodePtr>> CreateLanguageCategories( - const std::vector<std::string_view>& accept_languages, - const std::set<LanguagePackKey>& installed_packs, - bool is_en_preferred); - -// Creates the language category list for the availability matrix. -std::vector<LanguageCategory> CreateLanguageCategoryList(); - // Returns the Accept Languages for a given Profile. const std::vector<std::string_view> GetAcceptLanguages( content::BrowserContext* browser_context); -// Returns the index of the language category in the availability matrix. -size_t GetLanguageCategoryIndex(bool installed, bool preferred, bool popular); - -// Determines if a given language is an Accept Language. -bool IsInAcceptLanguage(const std::vector<std::string_view>& accept_languages, - const std::string_view lang); - -// Determines if a language is both a supported and a popular language. -bool IsSupportedPopularLanguage(const std::string& lang); - // Determines if the Translator API is enabled. bool IsTranslatorAllowed(content::BrowserContext* browser_context);
diff --git a/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer_browsertest.cc b/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer_browsertest.cc index b981efc..46bc356 100644 --- a/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer_browsertest.cc +++ b/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer_browsertest.cc
@@ -19,6 +19,7 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/subresource_filter/subresource_filter_browser_test_harness.h" #include "chrome/browser/ui/browser.h" +#include "chrome/browser/ui/views/frame/browser_view.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "components/heavy_ad_intervention/heavy_ad_features.h" @@ -60,6 +61,7 @@ #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/mojom/use_counter/metrics/web_feature.mojom.h" #include "ui/gfx/geometry/size.h" +#include "ui/views/test/widget_activation_waiter.h" #include "url/gurl.h" #include "url/url_constants.h" @@ -1684,6 +1686,15 @@ main_html_response->Send(std::string(1024, ' ')); main_html_response->Done(); + // Clipboard apis require that the calling context is focused. +#if BUILDFLAG(IS_MAC) + content::HandleMissingKeyWindow(); +#endif + browser()->tab_strip_model()->GetActiveWebContents()->Focus(); + views::test::WaitForWidgetActive( + BrowserView::GetBrowserViewForBrowser(browser())->GetWidget(), + /*active=*/true); + ad_script_response->WaitForRequest(); ad_script_response->Send(page_load_metrics::kHttpOkResponseHeader); // Get ad script to use a bunch of privacy sensitive features.
diff --git a/chrome/browser/page_load_metrics/observers/third_party_cookie_deprecation_metrics_observer_browsertest.cc b/chrome/browser/page_load_metrics/observers/third_party_cookie_deprecation_metrics_observer_browsertest.cc index baf992a..472895e 100644 --- a/chrome/browser/page_load_metrics/observers/third_party_cookie_deprecation_metrics_observer_browsertest.cc +++ b/chrome/browser/page_load_metrics/observers/third_party_cookie_deprecation_metrics_observer_browsertest.cc
@@ -15,6 +15,7 @@ #include "chrome/browser/content_settings/cookie_settings_factory.h" #include "chrome/browser/content_settings/host_content_settings_map_factory.h" #include "chrome/browser/net/storage_test_utils.h" +#include "chrome/browser/page_load_metrics/observers/third_party_cookie_deprecation_page_load_metrics_observer.h" #include "chrome/browser/privacy_sandbox/tracking_protection_onboarding_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/subresource_filter/subresource_filter_browser_test_harness.h" @@ -342,12 +343,11 @@ class ThirdPartyCookieDeprecationObserverBrowserTest : public ThirdPartyCookieDeprecationObserverBaseBrowserTest, - public testing::WithParamInterface<std::tuple<bool, bool>> { + public testing::WithParamInterface<std::tuple<bool, bool, bool>> { public: ThirdPartyCookieDeprecationObserverBrowserTest() : is_experiment_cookies_disabled_(std::get<0>(GetParam())), is_client_eligible_(std::get<1>(GetParam())) {} - ThirdPartyCookieDeprecationObserverBrowserTest( const ThirdPartyCookieDeprecationObserverBrowserTest&) = delete; ThirdPartyCookieDeprecationObserverBrowserTest& operator=( @@ -360,14 +360,22 @@ subresource_filter::SubresourceFilterBrowserTest::SetUp(); } - void SetUpThirdPartyCookieExperiment() { + virtual void SetUpThirdPartyCookieExperiment() { // Experiment feature param requests 3PCs blocked. - scoped_feature_list_.InitWithFeaturesAndParameters( - {{features::kCookieDeprecationFacilitatedTesting, - {{tpcd::experiment::kDisable3PCookiesName, - base::ToString(is_experiment_cookies_disabled_)}}}, - {subresource_filter::kTPCDAdHeuristicSubframeRequestTagging, {}}}, - {content_settings::features::kTrackingProtection3pcd}); + std::vector<base::test::FeatureRefAndParams> enabled_features = { + {features::kCookieDeprecationFacilitatedTesting, + {{tpcd::experiment::kDisable3PCookiesName, + base::ToString(is_experiment_cookies_disabled_)}}}, + {subresource_filter::kTPCDAdHeuristicSubframeRequestTagging, {}}}; + std::vector<base::test::FeatureRef> disabled_features = { + content_settings::features::kTrackingProtection3pcd}; + if (std::get<2>(GetParam())) { + enabled_features.push_back({network::features::kGetCookiesOnSet, {}}); + } else { + disabled_features.push_back(network::features::kGetCookiesOnSet); + } + scoped_feature_list_.InitWithFeaturesAndParameters(enabled_features, + disabled_features); } void SetUpThirdPartyCookieExperimentWithClientState() { @@ -405,7 +413,9 @@ INSTANTIATE_TEST_SUITE_P(, ThirdPartyCookieDeprecationObserverBrowserTest, - testing::Combine(testing::Bool(), testing::Bool())); + testing::Combine(testing::Bool(), + testing::Bool(), + testing::Bool())); IN_PROC_BROWSER_TEST_P(ThirdPartyCookieDeprecationObserverBrowserTest, FirstPartyCookiesReadAndWrite) {
diff --git a/chrome/browser/password_manager/chrome_password_manager_client.cc b/chrome/browser/password_manager/chrome_password_manager_client.cc index 47de9b5d..4388d45f 100644 --- a/chrome/browser/password_manager/chrome_password_manager_client.cc +++ b/chrome/browser/password_manager/chrome_password_manager_client.cc
@@ -191,6 +191,7 @@ using password_manager::BadMessageReason; using password_manager::ContentPasswordManagerDriverFactory; using password_manager::FieldInfoManager; +using password_manager::PasswordCredentialFillerImpl; using password_manager::PasswordForm; using password_manager::PasswordManagerClientHelper; using password_manager::PasswordManagerDriver; @@ -555,25 +556,24 @@ void ChromePasswordManagerClient::ShowKeyboardReplacingSurface( password_manager::PasswordManagerDriver* driver, - const password_manager::PasswordFillingParams& password_filling_params, - bool is_webauthn_form, - base::OnceCallback<void(bool)> shown_cb) { - if (keyboard_replacing_surface_visibility_controller_ && - !keyboard_replacing_surface_visibility_controller_->CanBeShown()) { - std::move(shown_cb).Run( - keyboard_replacing_surface_visibility_controller_->IsVisible()); - return; - } - + const autofill::PasswordSuggestionRequest& request) { password_manager::ContentPasswordManagerDriver* content_driver = static_cast<password_manager::ContentPasswordManagerDriver*>(driver); + if (keyboard_replacing_surface_visibility_controller_ && + !keyboard_replacing_surface_visibility_controller_->CanBeShown()) { + if (!keyboard_replacing_surface_visibility_controller_->IsVisible()) { + content_driver->ShowPasswordSuggestionsForField(request.field); + } + return; + } + if (GetOrCreateCredManController()->Show( GetWebAuthnCredManDelegateForDriver(driver), - std::make_unique<password_manager::PasswordCredentialFillerImpl>( - driver->AsWeakPtr(), password_filling_params), - content_driver->AsWeakPtrImpl(), is_webauthn_form)) { - std::move(shown_cb).Run(true); + std::make_unique<PasswordCredentialFillerImpl>(driver->AsWeakPtr(), + request), + content_driver->AsWeakPtrImpl(), + request.field.show_webauthn_credentials)) { return; } @@ -583,18 +583,22 @@ base::BindOnce(&ChromePasswordManagerClient:: ShowKeyboardReplacingSurfaceOnAccountStorageNoticeDone, base::Unretained(this), content_driver->AsWeakPtrImpl(), - password_filling_params, std::move(shown_cb))); + request.field, // Intentional & cheap copy. + std::make_unique<PasswordCredentialFillerImpl>( + driver->AsWeakPtr(), request))); } void ChromePasswordManagerClient:: ShowKeyboardReplacingSurfaceOnAccountStorageNoticeDone( base::WeakPtr<password_manager::ContentPasswordManagerDriver> weak_driver, - const password_manager::PasswordFillingParams& password_filling_params, - base::OnceCallback<void(bool)> shown_cb) { + autofill::TriggeringField triggering_field, + std::unique_ptr<PasswordCredentialFillerImpl> filler) { // TODO(crbug.com/346748438): Maybe don't show TTF if there was a navigation. if (!weak_driver) { - return std::move(shown_cb).Run(false); + // No further suggestions are possible: without the driver, there is no + // PasswordAutofillManager anymore. + return; } password_manager::ContentPasswordManagerDriver* driver = weak_driver.get(); @@ -609,16 +613,12 @@ webauthn_delegate->IsSecurityKeyOrHybridFlowAvailable(); } } - auto filler = - std::make_unique<password_manager::PasswordCredentialFillerImpl>( - driver->AsWeakPtr(), password_filling_params); const PasswordForm* form_to_fill = password_manager_.GetParsedObservedForm( - driver, password_filling_params.focused_field_renderer_id_); + driver, triggering_field.element_id); auto ttf_controller_autofill_delegate = std::make_unique<TouchToFillControllerAutofillDelegate>( this, GetDeviceAuthenticator(), webauthn_delegate->AsWeakPtr(), - std::move(filler), form_to_fill, - password_filling_params.focused_field_renderer_id_, + std::move(filler), form_to_fill, triggering_field.element_id, TouchToFillControllerAutofillDelegate::ShowHybridOption( should_show_hybrid_option)); @@ -628,10 +628,10 @@ .GetCredentialStore(URLToOrigin(driver->GetLastCommittedURL())) .GetCredentials(), std::move(passkeys), driver->AsWeakPtrImpl()); - const bool shown = - ttf_controller->Show(std::move(ttf_controller_autofill_delegate), - GetWebAuthnCredManDelegateForDriver(driver)); - std::move(shown_cb).Run(shown); + if (!ttf_controller->Show(std::move(ttf_controller_autofill_delegate), + GetWebAuthnCredManDelegateForDriver(driver))) { + driver->ShowPasswordSuggestionsForField(triggering_field); + } } #endif
diff --git a/chrome/browser/password_manager/chrome_password_manager_client.h b/chrome/browser/password_manager/chrome_password_manager_client.h index e893a0f..c1b45d3 100644 --- a/chrome/browser/password_manager/chrome_password_manager_client.h +++ b/chrome/browser/password_manager/chrome_password_manager_client.h
@@ -94,6 +94,7 @@ namespace password_manager { class FieldInfoManager; +class PasswordCredentialFillerImpl; class WebAuthnCredentialsDelegate; class CredManController; class KeyboardReplacingSurfaceVisibilityController; @@ -164,9 +165,7 @@ void ShowKeyboardReplacingSurface( password_manager::PasswordManagerDriver* driver, - const password_manager::PasswordFillingParams& password_filling_params, - bool is_webauthn_form, - base::OnceCallback<void(bool)> shown_cb) override; + const autofill::PasswordSuggestionRequest& request) override; #endif bool IsReauthBeforeFillingRequired( @@ -398,8 +397,8 @@ void ShowKeyboardReplacingSurfaceOnAccountStorageNoticeDone( base::WeakPtr<password_manager::ContentPasswordManagerDriver> weak_driver, - const password_manager::PasswordFillingParams& password_filling_params, - base::OnceCallback<void(bool)> shown_cb); + autofill::TriggeringField triggering_field, + std::unique_ptr<password_manager::PasswordCredentialFillerImpl> filler); #endif // content::WebContentsObserver overrides.
diff --git a/chrome/browser/password_manager/password_manager_interactive_uitest.cc b/chrome/browser/password_manager/password_manager_interactive_uitest.cc index 5cb440cd..dd60aee 100644 --- a/chrome/browser/password_manager/password_manager_interactive_uitest.cc +++ b/chrome/browser/password_manager/password_manager_interactive_uitest.cc
@@ -358,9 +358,11 @@ // Instruct Chrome to show the password dropdown. autofill::FormData form; driver->ShowPasswordSuggestions(autofill::PasswordSuggestionRequest( - kElementId, form, - autofill::AutofillSuggestionTriggerSource::kFormControlElementClicked, 0, - 0, base::i18n::LEFT_TO_RIGHT, std::u16string(), false, element_bounds)); + autofill::TriggeringField( + kElementId, + autofill::AutofillSuggestionTriggerSource::kFormControlElementClicked, + base::i18n::LEFT_TO_RIGHT, std::u16string(), false, element_bounds), + form, 0, 0)); autofill::AutofillSuggestionController* controller = nullptr; // Showing the Autofill Popup is an asynchronous task. EXPECT_TRUE(base::test::RunUntil([&]() { @@ -385,9 +387,11 @@ WaitForPasswordStore(); // Reshow the dropdown. driver->ShowPasswordSuggestions(autofill::PasswordSuggestionRequest( - kElementId, form, - autofill::AutofillSuggestionTriggerSource::kFormControlElementClicked, 0, - 0, base::i18n::LEFT_TO_RIGHT, std::u16string(), false, element_bounds)); + autofill::TriggeringField( + kElementId, + autofill::AutofillSuggestionTriggerSource::kFormControlElementClicked, + base::i18n::LEFT_TO_RIGHT, std::u16string(), false, element_bounds), + form, 0, 0)); // Showing the Autofill Popup is an asynchronous task. EXPECT_TRUE(base::test::RunUntil([&]() { return controller = @@ -409,9 +413,11 @@ WaitForPasswordStore(); // Reshow the dropdown won't work because there is nothing to suggest. driver->ShowPasswordSuggestions(autofill::PasswordSuggestionRequest( - kElementId, form, - autofill::AutofillSuggestionTriggerSource::kFormControlElementClicked, 0, - 0, base::i18n::LEFT_TO_RIGHT, std::u16string(), false, element_bounds)); + autofill::TriggeringField( + kElementId, + autofill::AutofillSuggestionTriggerSource::kFormControlElementClicked, + base::i18n::LEFT_TO_RIGHT, std::u16string(), false, element_bounds), + form, 0, 0)); // Showing the Autofill Popup is an asynchronous task. base::RunLoop().RunUntilIdle(); EXPECT_FALSE(autofill_client->suggestion_controller_for_testing());
diff --git a/chrome/browser/pdf/pdf_extension_accessibility_test.cc b/chrome/browser/pdf/pdf_extension_accessibility_test.cc index cc5f6b67..dd663e5 100644 --- a/chrome/browser/pdf/pdf_extension_accessibility_test.cc +++ b/chrome/browser/pdf/pdf_extension_accessibility_test.cc
@@ -32,7 +32,6 @@ #include "build/build_config.h" #include "build/chromeos_buildflags.h" #include "chrome/app/chrome_command_ids.h" -#include "chrome/browser/accessibility/accessibility_state_utils.h" #include "chrome/browser/pdf/pdf_extension_test_base.h" #include "chrome/browser/pdf/pdf_extension_test_util.h" #include "chrome/browser/renderer_context_menu/render_view_context_menu_browsertest_util.h"
diff --git a/chrome/browser/pdf/pdf_extension_test.cc b/chrome/browser/pdf/pdf_extension_test.cc index 13e8001..ebe39bc 100644 --- a/chrome/browser/pdf/pdf_extension_test.cc +++ b/chrome/browser/pdf/pdf_extension_test.cc
@@ -70,6 +70,7 @@ #include "components/zoom/zoom_controller.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/download_manager.h" +#include "content/public/browser/host_zoom_map.h" #include "content/public/browser/navigation_controller.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/plugin_service.h" @@ -110,6 +111,7 @@ #include "third_party/blink/public/common/input/web_input_event.h" #include "third_party/blink/public/common/input/web_mouse_event.h" #include "third_party/blink/public/common/messaging/transferable_message.h" +#include "third_party/blink/public/common/page/page_zoom.h" #include "ui/base/clipboard/clipboard.h" #include "ui/base/clipboard/clipboard_monitor.h" #include "ui/base/clipboard/clipboard_observer.h" @@ -285,6 +287,40 @@ EXPECT_EQ(extension_url, extension_host->GetLastCommittedURL()); } +// A test to verify that the presence of a pending NavigationEntry on the +// NavigationController of a WebContents hosting a PDF does not affect the +// value returned by WebContentsImpl::GetPendingZoomLevel() when called on +// the PDF extension frame's RenderWidgetHost. +IN_PROC_BROWSER_TEST_P(PDFExtensionTest, + ZoomNotAffectedByPendingNavigationEntry) { + // Set default zoom factor to 200%. + auto* web_contents = GetActiveWebContents(); + content::HostZoomMap::GetForWebContents(web_contents) + ->SetDefaultZoomLevel(blink::ZoomFactorToZoomLevel(2.0)); + + // Load PDF. + const GURL main_url(embedded_test_server()->GetURL("/pdf/test.pdf")); + content::RenderFrameHost* extension_host = LoadPdfGetExtensionHost(main_url); + ASSERT_TRUE(extension_host); + + // Verify PDF extension frame has zoom factor 100%. + EXPECT_EQ( + blink::ZoomFactorToZoomLevel(1.0), + content::GetPendingZoomLevel(extension_host->GetRenderWidgetHost())); + + // Navigate and immediately check GetPendingZoomLevel stays at factor 100%. + auto& controller = web_contents->GetController(); + controller.LoadURLWithParams(content::NavigationController::LoadURLParams( + embedded_test_server()->GetURL("/title1.html"))); + EXPECT_EQ( + blink::ZoomFactorToZoomLevel(1.0), + content::GetPendingZoomLevel(extension_host->GetRenderWidgetHost())); + // Verify the navigation is still pending. This gives assurance that the + // preceding call to GetPendingZoomLevel did encounter the condition being + // tested. + EXPECT_NE(nullptr, controller.GetPendingEntry()); +} + // Helper class to allow pausing the asynchronous attachment of an inner // WebContents between MimeHandlerViewAttachHelper's AttachToOuterWebContents() // and ResumeAttachOrDestroy(). This corresponds to the point where the inner
diff --git a/chrome/browser/performance_manager/policies/page_discarding_helper.cc b/chrome/browser/performance_manager/policies/page_discarding_helper.cc index c2ed693..0a06cb5 100644 --- a/chrome/browser/performance_manager/policies/page_discarding_helper.cc +++ b/chrome/browser/performance_manager/policies/page_discarding_helper.cc
@@ -163,92 +163,92 @@ page_node->GetTimeSinceLastVisibilityChange()); } - // Sorts with ascending importance. - std::sort(candidates.begin(), candidates.end()); + // Sorts with descending importance. + std::sort(candidates.rbegin(), candidates.rend()); UMA_HISTOGRAM_COUNTS_100("Discarding.DiscardCandidatesCount", candidates.size()); - // Returns early when candidate is empty to avoid infinite loop in - // DiscardMultiplePages. - if (candidates.empty()) { - return std::nullopt; + NodeFootprintMap page_node_footprint_kb; + if (reclaim_target) { + // Only compute the estimated memory footprint if needed. + page_node_footprint_kb = GetPageNodeFootprintEstimateKb(candidates); } - std::vector<const PageNode*> discard_attempts; - if (!reclaim_target) { - const PageNode* oldest = candidates[0].page_node(); - discard_attempts.emplace_back(oldest); + while (!candidates.empty()) { + std::vector<const PageNode*> discard_attempts; - // Record metrics about the tab that is about to be discarded. - RecordDiscardedTabMetrics(candidates[0]); - } else { - const uint64_t reclaim_target_kb_value = reclaim_target->target_kb; - uint64_t total_reclaim_kb = 0; - auto page_node_footprint_kb = GetPageNodeFootprintEstimateKb(candidates); - for (auto& candidate : candidates) { - if (total_reclaim_kb >= reclaim_target_kb_value) { - break; - } - const PageNode* node = candidate.page_node(); - discard_attempts.emplace_back(node); + if (!reclaim_target) { + const auto candidate = candidates.back(); + candidates.pop_back(); // Record metrics about the tab that is about to be discarded. RecordDiscardedTabMetrics(candidate); - // The node footprint value is updated by ProcessMetricsDecorator - // periodically. The footprint value is 0 for nodes that have never been - // updated, estimate the RSS value to 80 MiB for these nodes. 80 MiB is - // the average Memory.Renderer.PrivateMemoryFootprint histogram value on - // Windows in August 2021. - uint64_t node_reclaim_kb = (page_node_footprint_kb[node]) - ? page_node_footprint_kb[node] - : 80 * 1024; - total_reclaim_kb += node_reclaim_kb; + discard_attempts.emplace_back(candidate.page_node()); + } else { + const uint64_t reclaim_target_kb_value = reclaim_target->target_kb; + uint64_t total_reclaim_kb = 0; + while (total_reclaim_kb < reclaim_target_kb_value && + !candidates.empty()) { + const auto candidate = candidates.back(); + candidates.pop_back(); - LOG(WARNING) << "Queueing discard attempt, type=" - << performance_manager::PageNode::ToString(node->GetType()) - << ", flags=[" << (candidate.is_focused() ? " focused" : "") - << (candidate.is_protected() ? " protected" : "") - << (candidate.is_visible() ? " visible" : "") - << " ] to save " << node_reclaim_kb << " KiB"; + // Record metrics about the tab that is about to be discarded. + RecordDiscardedTabMetrics(candidate); + + const PageNode* node = candidate.page_node(); + discard_attempts.emplace_back(node); + + // The node footprint value is updated by ProcessMetricsDecorator + // periodically. The footprint value is 0 for nodes that have never been + // updated, estimate the RSS value to 80 MiB for these nodes. 80 MiB is + // the average Memory.Renderer.PrivateMemoryFootprint histogram value on + // Windows in August 2021. + uint64_t node_reclaim_kb = (page_node_footprint_kb[node]) + ? page_node_footprint_kb[node] + : 80 * 1024; + total_reclaim_kb += node_reclaim_kb; + + LOG(WARNING) << "Queueing discard attempt, type=" + << performance_manager::PageNode::ToString(node->GetType()) + << ", flags=[" + << (candidate.is_focused() ? " focused" : "") + << (candidate.is_protected() ? " protected" : "") + << (candidate.is_visible() ? " visible" : "") + << " ] to save " << node_reclaim_kb << " KiB"; + } } + + // Adorns the PageNodes with a discard attempt marker to make sure that we + // don't try to discard it multiple times if it fails to be discarded. In + // practice this should only happen to prerenderers. + for (auto* attempt : discard_attempts) { + DiscardEligibilityPolicy::AddDiscardAttemptMarker( + PageNodeImpl::FromNode(attempt)); + } + + // Do the discard. + std::vector<PageDiscarder::DiscardEvent> discard_events = + page_discarder_->DiscardPageNodes(discard_attempts, discard_reason); + + if (!discard_events.empty()) { + for (const auto& discard_event : discard_events) { + unnecessary_discard_monitor_.OnDiscard( + discard_event.estimated_memory_freed_kb, + discard_event.discard_time); + } + + unnecessary_discard_monitor_.OnReclaimTargetEnd(); + + return discard_events[0].discard_time; + } + + // Nothing was actually discarded, keep looping to try with more candidates. } - // Clear the candidates vector to avoid holding on to pointers of the pages - // that are about to be discarded. - candidates.clear(); - - if (discard_attempts.empty()) { - // No pages left that are available for discarding. - return std::nullopt; - } - - // Adorns the PageNodes with a discard attempt marker to make sure that we - // don't try to discard it multiple times if it fails to be discarded. In - // practice this should only happen to prerenderers. - for (auto* attempt : discard_attempts) { - DiscardEligibilityPolicy::AddDiscardAttemptMarker( - PageNodeImpl::FromNode(attempt)); - } - - std::vector<PageDiscarder::DiscardEvent> discard_events = - page_discarder_->DiscardPageNodes(discard_attempts, discard_reason); - - if (discard_events.empty()) { - // DiscardAttemptMarker will force the retry to choose different pages. - return DiscardMultiplePages(reclaim_target, discard_protected_tabs, - discard_reason, minimum_time_in_background); - } - - for (const auto& discard_event : discard_events) { - unnecessary_discard_monitor_.OnDiscard( - discard_event.estimated_memory_freed_kb, discard_event.discard_time); - } - - unnecessary_discard_monitor_.OnReclaimTargetEnd(); - - return discard_events[0].discard_time; + // Ran out of candidates. + return std::nullopt; } std::optional<base::TimeTicks>
diff --git a/chrome/browser/performance_manager/policies/page_discarding_helper_unittest.cc b/chrome/browser/performance_manager/policies/page_discarding_helper_unittest.cc index cb9f4a1..7fd8c8de 100644 --- a/chrome/browser/performance_manager/policies/page_discarding_helper_unittest.cc +++ b/chrome/browser/performance_manager/policies/page_discarding_helper_unittest.cc
@@ -282,12 +282,17 @@ PageDiscardingHelper::GetFromGraph(graph())->DiscardAPage( DiscardReason::URGENT); EXPECT_FALSE(first_discarded_at.has_value()); - // There should be 2 discard attempts, during the first one an attempt will be - // made to discard |page_node()|, on the second attempt no discard candidate - // should be found. + // On the first discard attempt, an attempt will be made to discard + // `page_node()`, which will render it uneligible for the next discard + // attempt. histogram_tester()->ExpectBucketCount("Discarding.DiscardCandidatesCount", 1, 1); + first_discarded_at = + PageDiscardingHelper::GetFromGraph(graph())->DiscardAPage( + DiscardReason::URGENT); + EXPECT_FALSE(first_discarded_at.has_value()); + // No eligible candidate found. histogram_tester()->ExpectBucketCount("Discarding.DiscardCandidatesCount", 0, 1); }
diff --git a/chrome/browser/permissions/permission_manager_factory.cc b/chrome/browser/permissions/permission_manager_factory.cc index 402913b..f98909f 100644 --- a/chrome/browser/permissions/permission_manager_factory.cc +++ b/chrome/browser/permissions/permission_manager_factory.cc
@@ -32,6 +32,7 @@ #include "components/permissions/contexts/automatic_fullscreen_permission_context.h" #include "components/permissions/contexts/keyboard_lock_permission_context.h" #include "components/permissions/contexts/local_fonts_permission_context.h" +#include "components/permissions/contexts/local_network_access_permission_context.h" #include "components/permissions/contexts/pointer_lock_permission_context.h" #include "components/permissions/contexts/speaker_selection_permission_context.h" #include "components/permissions/contexts/web_app_installation_permission_context.h" @@ -128,6 +129,11 @@ permission_contexts[ContentSettingsType::LOCAL_FONTS] = std::make_unique<LocalFontsPermissionContext>(profile); + // TODO(crbug.com/400455013): Move to CreateDefaultPermissionContexts() once + // support for Android is ready. + permission_contexts[ContentSettingsType::LOCAL_NETWORK_ACCESS] = + std::make_unique<LocalNetworkAccessPermissionContext>(profile); + // Depends on Chrome specific policies not available on WebLayer. permission_contexts[ContentSettingsType::MEDIASTREAM_CAMERA] = std::make_unique<MediaStreamDevicePermissionContext>(
diff --git a/chrome/browser/picture_in_picture/BUILD.gn b/chrome/browser/picture_in_picture/BUILD.gn index 19f1b66..30f3444 100644 --- a/chrome/browser/picture_in_picture/BUILD.gn +++ b/chrome/browser/picture_in_picture/BUILD.gn
@@ -101,6 +101,9 @@ "//ui/views", ] } + if (use_ozone) { + deps += [ "//ui/ozone" ] + } } source_set("unit_tests") { @@ -198,6 +201,9 @@ "//ui/aura", ] } + if (use_ozone) { + deps += [ "//ui/ozone" ] + } } }
diff --git a/chrome/browser/picture_in_picture/document_picture_in_picture_window_controller_browsertest.cc b/chrome/browser/picture_in_picture/document_picture_in_picture_window_controller_browsertest.cc index 6216bd4..dfc07bf9 100644 --- a/chrome/browser/picture_in_picture/document_picture_in_picture_window_controller_browsertest.cc +++ b/chrome/browser/picture_in_picture/document_picture_in_picture_window_controller_browsertest.cc
@@ -80,6 +80,10 @@ #include "ui/events/test/event_generator.h" #endif +#if BUILDFLAG(IS_OZONE) +#include "ui/ozone/public/ozone_platform.h" +#endif + using content::EvalJs; using content::ExecJs; using ::testing::_; @@ -683,6 +687,14 @@ IN_PROC_BROWSER_TEST_F(DocumentPictureInPictureWindowControllerBrowserTest, WindowBoundsAreCached) { +#if BUILDFLAG(IS_OZONE) + // Ozone/wayland doesn't support getting/setting window position in global + // screen coordinates. So this test is not applicable there as it essentially + // validates that. + if (ui::OzonePlatform::GetPlatformNameForTest() == "wayland") { + GTEST_SKIP(); + } +#endif // Create a Document PiP window with any size. We want to be sure that this // fits in the display comfortably. const gfx::Size size(400, 410);
diff --git a/chrome/browser/picture_in_picture/picture_in_picture_window_manager.cc b/chrome/browser/picture_in_picture/picture_in_picture_window_manager.cc index ea464638..9f82c7f 100644 --- a/chrome/browser/picture_in_picture/picture_in_picture_window_manager.cc +++ b/chrome/browser/picture_in_picture/picture_in_picture_window_manager.cc
@@ -36,6 +36,10 @@ #include "extensions/common/constants.h" #endif // BUILDFLAG(ENABLE_EXTENSIONS) +#if BUILDFLAG(IS_OZONE) +#include "ui/ozone/public/ozone_platform.h" +#endif + namespace { // The initial aspect ratio for Document Picture-in-Picture windows. This does // not apply to video Picture-in-Picture windows. @@ -345,6 +349,16 @@ excluded_margin, window_bounds); } +#if BUILDFLAG(IS_OZONE) + // Some platforms like ozone/wayland don't allow clients to control windows + // in global screen coordinates. So it is not possible to position windows in + // that case. + if (!ui::OzonePlatform::GetInstance() + ->GetPlatformProperties() + .supports_global_screen_coordinates) { + return window_bounds; + } +#endif // Position the window. int window_diff_width = work_area.right() - window_bounds.width(); int window_diff_height = work_area.bottom() - window_bounds.height();
diff --git a/chrome/browser/policy/messaging_layer/upload/file_upload_impl.cc b/chrome/browser/policy/messaging_layer/upload/file_upload_impl.cc index c2e9407..2ca19d1 100644 --- a/chrome/browser/policy/messaging_layer/upload/file_upload_impl.cc +++ b/chrome/browser/policy/messaging_layer/upload/file_upload_impl.cc
@@ -789,6 +789,7 @@ auto resource_request = std::make_unique<::network::ResourceRequest>(); resource_request->url = resumable_upload_url_; resource_request->headers.SetHeader(kUploadCommandHeader, "query"); + resource_request->credentials_mode = network::mojom::CredentialsMode::kOmit; url_loader_ = delegate()->CreatePostLoader(std::move(resource_request));
diff --git a/chrome/browser/policy/test/partitioned_blob_url_browsertest.cc b/chrome/browser/policy/test/partitioned_blob_url_browsertest.cc index 5f8c4fd..5805cb81 100644 --- a/chrome/browser/policy/test/partitioned_blob_url_browsertest.cc +++ b/chrome/browser/policy/test/partitioned_blob_url_browsertest.cc
@@ -4,12 +4,14 @@ #include "base/test/scoped_feature_list.h" #include "base/values.h" +#include "chrome/browser/content_settings/cookie_settings_factory.h" #include "chrome/browser/policy/policy_test_utils.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/pref_names.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" +#include "components/content_settings/core/browser/cookie_settings.h" #include "components/content_settings/core/common/content_settings.h" #include "components/policy/core/common/policy_map.h" #include "components/policy/core/common/policy_types.h" @@ -215,6 +217,15 @@ content::RenderFrameHost* rfh_b = content::ChildFrameAt(rfh_c, 0); content::RenderFrameHost* rfh_c_2 = content::ChildFrameAt(rfh_b, 0); + // The default cookie setting to BLOCK here to ensure that the + // cross-origin blob URL fetch will be blocked due to lack of storage + // access. If cookies are allowed, storage access might be granted, and the + // fetch would succeed even if the blob URL is cross-origin and + // kBlockCrossPartitionBlobUrlFetching is enabled. + content_settings::CookieSettings* settings = + CookieSettingsFactory::GetForProfile(browser()->profile()).get(); + settings->SetDefaultCookieSetting(CONTENT_SETTING_BLOCK); + bool fetch_results = FetchAndReadBlobUrl(rfh_c_2, blob_url); if (IsPolicyEnabled()) {
diff --git a/chrome/browser/preferences/android/java/src/org/chromium/chrome/browser/preferences/ChromePreferenceKeys.java b/chrome/browser/preferences/android/java/src/org/chromium/chrome/browser/preferences/ChromePreferenceKeys.java index 3de3e2f..96f3909a 100644 --- a/chrome/browser/preferences/android/java/src/org/chromium/chrome/browser/preferences/ChromePreferenceKeys.java +++ b/chrome/browser/preferences/android/java/src/org/chromium/chrome/browser/preferences/ChromePreferenceKeys.java
@@ -252,8 +252,16 @@ "Chrome.RequestDesktopSiteGlobalSetting.DefaultEnabled"; /** - * Indicates that Chrome should show an alert to the user about data privacy if the device - * lock is removed. + * Indicates the state of the Android-OS-provided advanced-protection setting when Chrome was + * last opened. Used to determine whether to show on startup a message informing the user about + * the setting change. + */ + public static final String DEFAULT_OS_ADVANCED_PROTECTION_SETTING = + "Chrome.OsAdvancedProtection.DefaultEnabled"; + + /** + * Indicates that Chrome should show an alert to the user about data privacy if the device lock + * is removed. */ public static final String DEVICE_LOCK_SHOW_ALERT_IF_REMOVED = "Chrome.DeviceLock.ShowAlertIfRemoved"; @@ -1005,6 +1013,7 @@ DEFAULT_BROWSER_PROMO_PROMOED_COUNT, DEFAULT_BROWSER_PROMO_SESSION_COUNT, DEFAULT_ENABLED_DESKTOP_SITE_GLOBAL_SETTING, + DEFAULT_OS_ADVANCED_PROTECTION_SETTING, DEPRECATED_HOMEPAGE_LOCATION_POLICY, DEPRECATED_HOMEPAGE_PARTNER_CUSTOMIZED_DEFAULT_URI, DEVICE_LOCK_SHOW_ALERT_IF_REMOVED,
diff --git a/chrome/browser/printing/pdf_to_emf_converter.cc b/chrome/browser/printing/pdf_to_emf_converter.cc index 7cce78f..d9bf283 100644 --- a/chrome/browser/printing/pdf_to_emf_converter.cc +++ b/chrome/browser/printing/pdf_to_emf_converter.cc
@@ -15,6 +15,7 @@ #include <utility> #include <vector> +#include "base/compiler_specific.h" #include "base/containers/queue.h" #include "base/functional/bind.h" #include "base/functional/callback.h" @@ -207,7 +208,7 @@ } PRINTER_LOG(EVENT) << "PdfConverter created. Mode: " << settings_.mode; - memcpy(memory.mapping.memory(), data->front(), data->size()); + UNSAFE_TODO(memcpy(memory.mapping.memory(), data->front(), data->size())); GetPrintingService()->BindPdfToEmfConverterFactory( pdf_to_emf_converter_factory_.BindNewPipeAndPassReceiver());
diff --git a/chrome/browser/quick_delete/android/javatests/src/org/chromium/chrome/browser/quick_delete/QuickDeleteControllerTest.java b/chrome/browser/quick_delete/android/javatests/src/org/chromium/chrome/browser/quick_delete/QuickDeleteControllerTest.java index 36c2036..92aa3de 100644 --- a/chrome/browser/quick_delete/android/javatests/src/org/chromium/chrome/browser/quick_delete/QuickDeleteControllerTest.java +++ b/chrome/browser/quick_delete/android/javatests/src/org/chromium/chrome/browser/quick_delete/QuickDeleteControllerTest.java
@@ -17,7 +17,6 @@ import org.junit.After; import org.junit.Before; -import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; @@ -44,8 +43,8 @@ import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.browser.tab.TabTestUtils; import org.chromium.chrome.test.ChromeJUnit4ClassRunner; -import org.chromium.chrome.test.ChromeTabbedActivityTestRule; -import org.chromium.chrome.test.transit.BlankCTATabInitialStatePublicTransitRule; +import org.chromium.chrome.test.transit.AutoResetCtaTransitTestRule; +import org.chromium.chrome.test.transit.ChromeTransitTestRules; import org.chromium.chrome.test.transit.hub.RegularTabSwitcherStation; import org.chromium.chrome.test.transit.page.WebPageStation; import org.chromium.chrome.test.transit.quick_delete.QuickDeleteDialogFacility; @@ -62,13 +61,9 @@ public class QuickDeleteControllerTest { private static final long FIFTEEN_MINUTES_IN_MS = TimeUnit.MINUTES.toMillis(15); - @ClassRule - public static ChromeTabbedActivityTestRule sActivityTestRule = - new ChromeTabbedActivityTestRule(); - @Rule - public BlankCTATabInitialStatePublicTransitRule mInitialStateRule = - new BlankCTATabInitialStatePublicTransitRule(sActivityTestRule); + public AutoResetCtaTransitTestRule mCtaTestRule = + ChromeTransitTestRules.autoResetCtaActivityRule(); @Rule public MockitoRule mMockitoRule = MockitoJUnit.rule(); @@ -79,7 +74,7 @@ @Before public void setUp() { - WebPageStation firstPage = mInitialStateRule.startOnBlankPage(); + WebPageStation firstPage = mCtaTestRule.startOnBlankPage(); BrowsingDataBridgeJni.setInstanceForTesting(mBrowsingDataBridgeMock); // Ensure that whenever the mock is asked to clear browsing data, the callback is
diff --git a/chrome/browser/quick_delete/android/javatests/src/org/chromium/chrome/browser/quick_delete/QuickDeleteDialogDelegateTest.java b/chrome/browser/quick_delete/android/javatests/src/org/chromium/chrome/browser/quick_delete/QuickDeleteDialogDelegateTest.java index 796e7af0..691cdc9 100644 --- a/chrome/browser/quick_delete/android/javatests/src/org/chromium/chrome/browser/quick_delete/QuickDeleteDialogDelegateTest.java +++ b/chrome/browser/quick_delete/android/javatests/src/org/chromium/chrome/browser/quick_delete/QuickDeleteDialogDelegateTest.java
@@ -16,7 +16,6 @@ import org.junit.After; import org.junit.Before; -import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; @@ -42,8 +41,8 @@ import org.chromium.chrome.browser.sync.SyncServiceFactory; import org.chromium.chrome.browser.tabmodel.TabClosureParams; import org.chromium.chrome.test.ChromeJUnit4ClassRunner; -import org.chromium.chrome.test.ChromeTabbedActivityTestRule; -import org.chromium.chrome.test.transit.BlankCTATabInitialStatePublicTransitRule; +import org.chromium.chrome.test.transit.AutoResetCtaTransitTestRule; +import org.chromium.chrome.test.transit.ChromeTransitTestRules; import org.chromium.chrome.test.transit.hub.RegularTabSwitcherStation; import org.chromium.chrome.test.transit.hub.TabGroupDialogFacility; import org.chromium.chrome.test.transit.page.WebPageStation; @@ -64,13 +63,9 @@ @CommandLineFlags.Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE}) @Batch(Batch.PER_CLASS) public class QuickDeleteDialogDelegateTest { - @ClassRule - public static ChromeTabbedActivityTestRule sActivityTestRule = - new ChromeTabbedActivityTestRule(); - @Rule - public BlankCTATabInitialStatePublicTransitRule mInitialStateRule = - new BlankCTATabInitialStatePublicTransitRule(sActivityTestRule); + public AutoResetCtaTransitTestRule mCtaTestRule = + ChromeTransitTestRules.autoResetCtaActivityRule(); @Rule public final SigninTestRule mSigninTestRule = new SigninTestRule(); @@ -92,8 +87,8 @@ SyncServiceFactory.setInstanceForTesting(mMockSyncService); setSyncable(false); - mPage = mInitialStateRule.startOnBlankPage(); - mActivity = sActivityTestRule.getActivity(); + mPage = mCtaTestRule.startOnBlankPage(); + mActivity = mCtaTestRule.getActivity(); } @After
diff --git a/chrome/browser/renderer_context_menu/accessibility_labels_menu_observer.cc b/chrome/browser/renderer_context_menu/accessibility_labels_menu_observer.cc index a305aee3..ce6374c19 100644 --- a/chrome/browser/renderer_context_menu/accessibility_labels_menu_observer.cc +++ b/chrome/browser/renderer_context_menu/accessibility_labels_menu_observer.cc
@@ -12,7 +12,6 @@ #include "chrome/app/chrome_command_ids.h" #include "chrome/browser/accessibility/accessibility_labels_service.h" #include "chrome/browser/accessibility/accessibility_labels_service_factory.h" -#include "chrome/browser/accessibility/accessibility_state_utils.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/renderer_context_menu/accessibility_labels_bubble_model.h" #include "chrome/browser/renderer_context_menu/render_view_context_menu.h" @@ -26,6 +25,7 @@ #include "content/public/browser/render_widget_host.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/web_contents.h" +#include "ui/accessibility/platform/ax_platform.h" #include "ui/base/l10n/l10n_util.h" #include "ui/gfx/geometry/rect.h" @@ -115,7 +115,7 @@ return false; } - return accessibility_state_utils::IsScreenReaderEnabled(); + return ui::AXPlatform::GetInstance().IsScreenReaderActive(); } void AccessibilityLabelsMenuObserver::ShowConfirmBubble(Profile* profile,
diff --git a/chrome/browser/renderer_context_menu/render_view_context_menu.cc b/chrome/browser/renderer_context_menu/render_view_context_menu.cc index 0c28b14..6ccb1e1 100644 --- a/chrome/browser/renderer_context_menu/render_view_context_menu.cc +++ b/chrome/browser/renderer_context_menu/render_view_context_menu.cc
@@ -31,7 +31,6 @@ #include "build/build_config.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/app/vector_icons/vector_icons.h" -#include "chrome/browser/accessibility/accessibility_state_utils.h" #include "chrome/browser/app_mode/app_mode_utils.h" #include "chrome/browser/apps/app_service/app_launch_params.h" #include "chrome/browser/apps/app_service/app_service_proxy.h"
diff --git a/chrome/browser/renderer_context_menu/render_view_context_menu_browsertest.cc b/chrome/browser/renderer_context_menu/render_view_context_menu_browsertest.cc index 432010b..adb60c4b 100644 --- a/chrome/browser/renderer_context_menu/render_view_context_menu_browsertest.cc +++ b/chrome/browser/renderer_context_menu/render_view_context_menu_browsertest.cc
@@ -31,7 +31,6 @@ #include "base/values.h" #include "build/build_config.h" #include "chrome/app/chrome_command_ids.h" -#include "chrome/browser/accessibility/accessibility_state_utils.h" #include "chrome/browser/apps/app_service/app_launch_params.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/pdf/pdf_extension_test_base.h"
diff --git a/chrome/browser/resources/chromeos/accessibility/BUILD.gn b/chrome/browser/resources/chromeos/accessibility/BUILD.gn index 04595a48..eaa91a1e9 100644 --- a/chrome/browser/resources/chromeos/accessibility/BUILD.gn +++ b/chrome/browser/resources/chromeos/accessibility/BUILD.gn
@@ -30,6 +30,7 @@ "enhanced_network_tts:build", "select_to_speak/mv2:build", "switch_access/mv2:build", + "switch_access/mv3:build", ] } @@ -92,5 +93,6 @@ "enhanced_network_tts:browser_tests", "select_to_speak/mv2:browser_tests", "switch_access/mv2:browser_tests", + "switch_access/mv3:browser_tests", ] }
diff --git a/chrome/browser/resources/chromeos/accessibility/switch_access/mv2/BUILD.gn b/chrome/browser/resources/chromeos/accessibility/switch_access/mv2/BUILD.gn index 4828480e..2ce800d 100644 --- a/chrome/browser/resources/chromeos/accessibility/switch_access/mv2/BUILD.gn +++ b/chrome/browser/resources/chromeos/accessibility/switch_access/mv2/BUILD.gn
@@ -18,7 +18,7 @@ } switch_access_dir = - "$root_out_dir/resources/chromeos/accessibility/switch_access" + "$root_out_dir/resources/chromeos/accessibility/switch_access/mv2" # Directory where typescript build will occur. ts_build_staging_dir = "$target_gen_dir/ts_build_staging"
diff --git a/chrome/browser/resources/chromeos/accessibility/switch_access/mv2/auto_scan_manager_test.js b/chrome/browser/resources/chromeos/accessibility/switch_access/mv2/auto_scan_manager_test.js index c83b4f9..9aa807fb 100644 --- a/chrome/browser/resources/chromeos/accessibility/switch_access/mv2/auto_scan_manager_test.js +++ b/chrome/browser/resources/chromeos/accessibility/switch_access/mv2/auto_scan_manager_test.js
@@ -7,7 +7,7 @@ UNDEFINED_INTERVAL_DELAY = -1; /** Test fixture for auto scan manager. */ -SwitchAccessAutoScanManagerTest = class extends SwitchAccessE2ETest { +SwitchAccessMV2AutoScanManagerTest = class extends SwitchAccessE2ETest { /** @override */ async setUpDeferred() { await super.setUpDeferred(); @@ -22,7 +22,7 @@ Navigator.byItem.moveForward.bind(Navigator.byItem); this.moveForwardCount = 0; - setInterval = function(func, delay) { + globalThis.setInterval = function(func, delay) { globalThis.intervalCount++; globalThis.intervalDelay = delay; @@ -30,7 +30,7 @@ return globalThis.defaultSetInterval(func, 0); }; - clearInterval = function(intervalId) { + globalThis.clearInterval = function(intervalId) { if (intervalId) { globalThis.intervalCount--; } @@ -48,7 +48,7 @@ }; // https://crbug.com/1452024: Flaky on linux-chromeos-rel/linux-chromeos-dbg -TEST_F('SwitchAccessAutoScanManagerTest', 'DISABLED_SetEnabled', function() { +TEST_F('SwitchAccessMV2AutoScanManagerTest', 'DISABLED_SetEnabled', function() { this.runWithLoadedDesktop(() => { assertFalse( AutoScanManager.instance.isRunning_(), @@ -82,7 +82,8 @@ GEN('#define MAYBE_SetEnabledMultiple SetEnabledMultiple'); GEN('#endif'); TEST_F( - 'SwitchAccessAutoScanManagerTest', 'MAYBE_SetEnabledMultiple', function() { + 'SwitchAccessMV2AutoScanManagerTest', 'MAYBE_SetEnabledMultiple', + function() { this.runWithLoadedDesktop(() => { assertFalse( AutoScanManager.instance.isRunning_(), @@ -103,7 +104,8 @@ // TODO(crbug.com/40888769): Test is flaky. TEST_F( - 'SwitchAccessAutoScanManagerTest', 'DISABLED_EnableAndDisable', function() { + 'SwitchAccessMV2AutoScanManagerTest', 'DISABLED_EnableAndDisable', + function() { this.runWithLoadedDesktop(() => { assertFalse( AutoScanManager.instance.isRunning_(), @@ -133,7 +135,7 @@ GEN('#endif'); TEST_F( - 'SwitchAccessAutoScanManagerTest', 'MAYBE_RestartIfRunningMultiple', + 'SwitchAccessMV2AutoScanManagerTest', 'MAYBE_RestartIfRunningMultiple', function() { this.runWithLoadedDesktop(() => { assertFalse( @@ -165,7 +167,7 @@ GEN('#endif'); TEST_F( - 'SwitchAccessAutoScanManagerTest', 'MAYBE_RestartIfRunningWhenOff', + 'SwitchAccessMV2AutoScanManagerTest', 'MAYBE_RestartIfRunningWhenOff', function() { this.runWithLoadedDesktop(() => { assertFalse( @@ -185,7 +187,7 @@ GEN('#define MAYBE_SetPrimaryScanTime SetPrimaryScanTime'); GEN('#endif'); -TEST_F('SwitchAccessAutoScanManagerTest', 'SetPrimaryScanTime', function() { +TEST_F('SwitchAccessMV2AutoScanManagerTest', 'SetPrimaryScanTime', function() { this.runWithLoadedDesktop(() => { assertFalse( AutoScanManager.instance.isRunning_(),
diff --git a/chrome/browser/resources/chromeos/accessibility/switch_access/mv2/focus_ring_manager_test.js b/chrome/browser/resources/chromeos/accessibility/switch_access/mv2/focus_ring_manager_test.js index 7939c242..17a4e363 100644 --- a/chrome/browser/resources/chromeos/accessibility/switch_access/mv2/focus_ring_manager_test.js +++ b/chrome/browser/resources/chromeos/accessibility/switch_access/mv2/focus_ring_manager_test.js
@@ -5,7 +5,7 @@ GEN_INCLUDE(['switch_access_e2e_test_base.js', 'test_utility.js']); /** Test fixture for the focus ring manager. */ -SwitchAccessFocusRingManagerTest = class extends SwitchAccessE2ETest { +SwitchAccessMV2FocusRingManagerTest = class extends SwitchAccessE2ETest { /** @override */ async setUpDeferred() { await super.setUpDeferred(); @@ -13,7 +13,7 @@ } }; -TEST_F('SwitchAccessFocusRingManagerTest', 'BackButtonFocus', function() { +TEST_F('SwitchAccessMV2FocusRingManagerTest', 'BackButtonFocus', function() { this.runWithLoadedDesktop(desktop => { // Focus the back button. Navigator.byItem.moveTo_( @@ -43,7 +43,7 @@ }); AX_TEST_F( - 'SwitchAccessFocusRingManagerTest', 'BackButtonForMenuFocus', + 'SwitchAccessMV2FocusRingManagerTest', 'BackButtonForMenuFocus', async function() { const site = '<input type="text">'; const rootWebArea = await this.runWithLoadedTree(site); @@ -71,52 +71,59 @@ assertEquals(0, preview.rects.length); }); -AX_TEST_F('SwitchAccessFocusRingManagerTest', 'ButtonFocus', async function() { - const site = '<button>Test</button>'; - const rootWebArea = await this.runWithLoadedTree(site); - const button = rootWebArea.find({role: chrome.automation.RoleType.BUTTON}); - Navigator.byItem.moveTo_(button); +AX_TEST_F( + 'SwitchAccessMV2FocusRingManagerTest', 'ButtonFocus', async function() { + const site = '<button>Test</button>'; + const rootWebArea = await this.runWithLoadedTree(site); + const button = + rootWebArea.find({role: chrome.automation.RoleType.BUTTON}); + Navigator.byItem.moveTo_(button); - const rings = FocusRingManager.instance.rings_; - const primary = rings[RingId.PRIMARY]; - const preview = rings[RingId.PREVIEW]; - assertEquals(1, primary.rects.length); - assertEquals(0, preview.rects.length); - // Primary focus should be on the button. - const focusLocation = primary.rects[0]; - const buttonLocation = button.location; - assertTrue(RectUtil.equal(buttonLocation, focusLocation)); -}); + const rings = FocusRingManager.instance.rings_; + const primary = rings[RingId.PRIMARY]; + const preview = rings[RingId.PREVIEW]; + assertEquals(1, primary.rects.length); + assertEquals(0, preview.rects.length); + // Primary focus should be on the button. + const focusLocation = primary.rects[0]; + const buttonLocation = button.location; + assertTrue(RectUtil.equal(buttonLocation, focusLocation)); + }); -AX_TEST_F('SwitchAccessFocusRingManagerTest', 'GroupFocus', async function() { - const site = ` +AX_TEST_F( + 'SwitchAccessMV2FocusRingManagerTest', 'GroupFocus', async function() { + const site = ` <div role="menu"> <div role="menuitem">Dog</div> <div role="menuitem">Cat</div> </div> `; - const rootWebArea = await this.runWithLoadedTree(site); - const menu = rootWebArea.find({role: chrome.automation.RoleType.MENU}); - const menuItem = rootWebArea.find( - {role: chrome.automation.RoleType.MENU_ITEM, attributes: {name: 'Dog'}}); - assertNotNullNorUndefined(menu); - assertNotNullNorUndefined(menuItem); - Navigator.byItem.moveTo_(menu); + const rootWebArea = await this.runWithLoadedTree(site); + const menu = rootWebArea.find({role: chrome.automation.RoleType.MENU}); + const menuItem = rootWebArea.find({ + role: chrome.automation.RoleType.MENU_ITEM, + attributes: {name: 'Dog'} + }); + assertNotNullNorUndefined(menu); + assertNotNullNorUndefined(menuItem); + Navigator.byItem.moveTo_(menu); - // Verify the number of rings. - const rings = FocusRingManager.instance.rings_; - const primary = rings[RingId.PRIMARY]; - const preview = rings[RingId.PREVIEW]; - assertEquals(1, primary.rects.length); - assertEquals(1, preview.rects.length); + // Verify the number of rings. + const rings = FocusRingManager.instance.rings_; + const primary = rings[RingId.PRIMARY]; + const preview = rings[RingId.PREVIEW]; + assertEquals(1, primary.rects.length); + assertEquals(1, preview.rects.length); - // Use ringNodesForTesting_ to verify the underlying nodes. - const ringNodes = FocusRingManager.instance.ringNodesForTesting_; - const primaryNode = ringNodes[RingId.PRIMARY].automationNode; - const previewNode = ringNodes[RingId.PREVIEW].automationNode; + // Use ringNodesForTesting_ to verify the underlying nodes. + const ringNodes = FocusRingManager.instance.ringNodesForTesting_; + const primaryNode = ringNodes[RingId.PRIMARY].automationNode; + const previewNode = ringNodes[RingId.PREVIEW].automationNode; - assertEquals( - menu, primaryNode, 'primary focus should be around the group (the menu)'); - assertEquals( - menuItem, previewNode, 'preview focus should be around the menu item'); -}); + assertEquals( + menu, primaryNode, + 'primary focus should be around the group (the menu)'); + assertEquals( + menuItem, previewNode, + 'preview focus should be around the menu item'); + });
diff --git a/chrome/browser/resources/chromeos/accessibility/switch_access/mv2/item_scan_manager_test.js b/chrome/browser/resources/chromeos/accessibility/switch_access/mv2/item_scan_manager_test.js index a549a20..e9be366 100644 --- a/chrome/browser/resources/chromeos/accessibility/switch_access/mv2/item_scan_manager_test.js +++ b/chrome/browser/resources/chromeos/accessibility/switch_access/mv2/item_scan_manager_test.js
@@ -5,7 +5,7 @@ GEN_INCLUDE(['switch_access_e2e_test_base.js']); /** Test fixture for the item scan manager. */ -SwitchAccessItemScanManagerTest = class extends SwitchAccessE2ETest { +SwitchAccessMV2ItemScanManagerTest = class extends SwitchAccessE2ETest { /** @override */ async setUpDeferred() { await super.setUpDeferred(); @@ -36,7 +36,7 @@ return Navigator.byItem.node_; } -AX_TEST_F('SwitchAccessItemScanManagerTest', 'MoveTo', async function() { +AX_TEST_F('SwitchAccessMV2ItemScanManagerTest', 'MoveTo', async function() { const website = `<div id="outerGroup"> <div id="group"> <input type="text"> @@ -100,7 +100,7 @@ 'Did not find the right group'); }); -AX_TEST_F('SwitchAccessItemScanManagerTest', 'JumpTo', async function() { +AX_TEST_F('SwitchAccessMV2ItemScanManagerTest', 'JumpTo', async function() { const website = `<div id="group1"> <input id="testinput" type="text"> <button></button> @@ -138,8 +138,10 @@ 'Did not jump back to the right group.'); }); -AX_TEST_F('SwitchAccessItemScanManagerTest', 'SelectButton', async function() { - const website = `<button id="test" aria-pressed=false>First Button</button> +AX_TEST_F( + 'SwitchAccessMV2ItemScanManagerTest', 'SelectButton', async function() { + const website = + `<button id="test" aria-pressed=false>First Button</button> <button>Second Button</button> <script> let state = false; @@ -150,25 +152,25 @@ }; </script>`; - const pageContents = await this.runWithLoadedTree(website); - this.moveToPageContents(pageContents); + const pageContents = await this.runWithLoadedTree(website); + this.moveToPageContents(pageContents); - const node = currentNode().automationNode; - assertNotNullNorUndefined(node, 'Node is invalid'); - assertEquals(node.name, 'First Button', 'Did not find the right node'); + const node = currentNode().automationNode; + assertNotNullNorUndefined(node, 'Node is invalid'); + assertEquals(node.name, 'First Button', 'Did not find the right node'); - node.addEventListener( - chrome.automation.EventType.CHECKED_STATE_CHANGED, - this.newCallback(event => { - assertEquals( - node.name, event.target.name, - 'Checked state changed on unexpected node'); - })); + node.addEventListener( + chrome.automation.EventType.CHECKED_STATE_CHANGED, + this.newCallback(event => { + assertEquals( + node.name, event.target.name, + 'Checked state changed on unexpected node'); + })); - Navigator.byItem.node_.performAction('select'); -}); + Navigator.byItem.node_.performAction('select'); + }); -AX_TEST_F('SwitchAccessItemScanManagerTest', 'EnterGroup', async function() { +AX_TEST_F('SwitchAccessMV2ItemScanManagerTest', 'EnterGroup', async function() { const website = `<div id="group"> <button></button> <button></button> @@ -197,109 +199,117 @@ 'Did not move back to the original group'); }); -AX_TEST_F('SwitchAccessItemScanManagerTest', 'MoveForward', async function() { - const website = `<div> +AX_TEST_F( + 'SwitchAccessMV2ItemScanManagerTest', 'MoveForward', async function() { + const website = `<div> <button id="button1"></button> <button id="button2"></button> <button id="button3"></button> </div>`; - const rootWebArea = await this.runWithLoadedTree(website); - Navigator.byItem.moveTo_(this.findNodeById('button1')); - const button1 = Navigator.byItem.node_; - assertFalse( - button1 instanceof BackButtonNode, - 'button1 should not be a BackButtonNode'); - assertEquals( - 'button1', button1.automationNode.htmlId, 'Current node is not button1'); + const rootWebArea = await this.runWithLoadedTree(website); + Navigator.byItem.moveTo_(this.findNodeById('button1')); + const button1 = Navigator.byItem.node_; + assertFalse( + button1 instanceof BackButtonNode, + 'button1 should not be a BackButtonNode'); + assertEquals( + 'button1', button1.automationNode.htmlId, + 'Current node is not button1'); - Navigator.byItem.moveForward(); - assertFalse( - button1.equals(Navigator.byItem.node_), - 'Still on button1 after moveForward()'); - const button2 = Navigator.byItem.node_; - assertFalse( - button2 instanceof BackButtonNode, - 'button2 should not be a BackButtonNode'); - assertEquals( - 'button2', button2.automationNode.htmlId, 'Current node is not button2'); + Navigator.byItem.moveForward(); + assertFalse( + button1.equals(Navigator.byItem.node_), + 'Still on button1 after moveForward()'); + const button2 = Navigator.byItem.node_; + assertFalse( + button2 instanceof BackButtonNode, + 'button2 should not be a BackButtonNode'); + assertEquals( + 'button2', button2.automationNode.htmlId, + 'Current node is not button2'); - Navigator.byItem.moveForward(); - assertFalse( - button1.equals(Navigator.byItem.node_), - 'Unexpected navigation to button1'); - assertFalse( - button2.equals(Navigator.byItem.node_), - 'Still on button2 after moveForward()'); - const button3 = Navigator.byItem.node_; - assertFalse( - button3 instanceof BackButtonNode, - 'button3 should not be a BackButtonNode'); - assertEquals( - 'button3', button3.automationNode.htmlId, 'Current node is not button3'); + Navigator.byItem.moveForward(); + assertFalse( + button1.equals(Navigator.byItem.node_), + 'Unexpected navigation to button1'); + assertFalse( + button2.equals(Navigator.byItem.node_), + 'Still on button2 after moveForward()'); + const button3 = Navigator.byItem.node_; + assertFalse( + button3 instanceof BackButtonNode, + 'button3 should not be a BackButtonNode'); + assertEquals( + 'button3', button3.automationNode.htmlId, + 'Current node is not button3'); - Navigator.byItem.moveForward(); - assertTrue( - Navigator.byItem.node_ instanceof BackButtonNode, - 'BackButtonNode should come after button3'); + Navigator.byItem.moveForward(); + assertTrue( + Navigator.byItem.node_ instanceof BackButtonNode, + 'BackButtonNode should come after button3'); - Navigator.byItem.moveForward(); - assertTrue( - button1.equals(Navigator.byItem.node_), - 'button1 should come after the BackButtonNode'); -}); - -AX_TEST_F('SwitchAccessItemScanManagerTest', 'MoveBackward', async function() { - const website = `<div> - <button id="button1"></button> - <button id="button2"></button> - <button id="button3"></button> - </div>`; - const rootWebArea = await this.runWithLoadedTree(website); - Navigator.byItem.moveTo_(this.findNodeById('button1')); - const button1 = Navigator.byItem.node_; - assertFalse( - button1 instanceof BackButtonNode, - 'button1 should not be a BackButtonNode'); - assertEquals( - 'button1', button1.automationNode.htmlId, 'Current node is not button1'); - - Navigator.byItem.moveBackward(); - assertTrue( - Navigator.byItem.node_ instanceof BackButtonNode, - 'BackButtonNode should come before button1'); - - Navigator.byItem.moveBackward(); - assertFalse( - button1.equals(Navigator.byItem.node_), - 'Unexpected navigation to button1'); - const button3 = Navigator.byItem.node_; - assertFalse( - button3 instanceof BackButtonNode, - 'button3 should not be a BackButtonNode'); - assertEquals( - 'button3', button3.automationNode.htmlId, 'Current node is not button3'); - - Navigator.byItem.moveBackward(); - assertFalse( - button3.equals(Navigator.byItem.node_), - 'Still on button3 after moveBackward()'); - assertFalse(button1.equals(Navigator.byItem.node_), 'Skipped button2'); - const button2 = Navigator.byItem.node_; - assertFalse( - button2 instanceof BackButtonNode, - 'button2 should not be a BackButtonNode'); - assertEquals( - 'button2', button2.automationNode.htmlId, 'Current node is not button2'); - - Navigator.byItem.moveBackward(); - assertTrue( - button1.equals(Navigator.byItem.node_), - 'button1 should come before button2'); -}); + Navigator.byItem.moveForward(); + assertTrue( + button1.equals(Navigator.byItem.node_), + 'button1 should come after the BackButtonNode'); + }); AX_TEST_F( - 'SwitchAccessItemScanManagerTest', 'NodeUndefinedBeforeTreeChangeRemoved', - async function() { + 'SwitchAccessMV2ItemScanManagerTest', 'MoveBackward', async function() { + const website = `<div> + <button id="button1"></button> + <button id="button2"></button> + <button id="button3"></button> + </div>`; + const rootWebArea = await this.runWithLoadedTree(website); + Navigator.byItem.moveTo_(this.findNodeById('button1')); + const button1 = Navigator.byItem.node_; + assertFalse( + button1 instanceof BackButtonNode, + 'button1 should not be a BackButtonNode'); + assertEquals( + 'button1', button1.automationNode.htmlId, + 'Current node is not button1'); + + Navigator.byItem.moveBackward(); + assertTrue( + Navigator.byItem.node_ instanceof BackButtonNode, + 'BackButtonNode should come before button1'); + + Navigator.byItem.moveBackward(); + assertFalse( + button1.equals(Navigator.byItem.node_), + 'Unexpected navigation to button1'); + const button3 = Navigator.byItem.node_; + assertFalse( + button3 instanceof BackButtonNode, + 'button3 should not be a BackButtonNode'); + assertEquals( + 'button3', button3.automationNode.htmlId, + 'Current node is not button3'); + + Navigator.byItem.moveBackward(); + assertFalse( + button3.equals(Navigator.byItem.node_), + 'Still on button3 after moveBackward()'); + assertFalse(button1.equals(Navigator.byItem.node_), 'Skipped button2'); + const button2 = Navigator.byItem.node_; + assertFalse( + button2 instanceof BackButtonNode, + 'button2 should not be a BackButtonNode'); + assertEquals( + 'button2', button2.automationNode.htmlId, + 'Current node is not button2'); + + Navigator.byItem.moveBackward(); + assertTrue( + button1.equals(Navigator.byItem.node_), + 'button1 should come before button2'); + }); + +AX_TEST_F( + 'SwitchAccessMV2ItemScanManagerTest', + 'NodeUndefinedBeforeTreeChangeRemoved', async function() { const website = `<div> <button id="button1"></button> </div>`; @@ -327,7 +337,7 @@ // TODO(crbug.com/336827654): Investigate failures. AX_TEST_F( - 'SwitchAccessItemScanManagerTest', 'DISABLED_ScanAndTypeVirtualKeyboard', + 'SwitchAccessMV2ItemScanManagerTest', 'DISABLED_ScanAndTypeVirtualKeyboard', async function() { const website = `<input type="text" id="testinput"></input>`; const rootWebArea = await this.runWithLoadedTree(website); @@ -363,7 +373,7 @@ // TODO(crbug.com/40946640): Test is flaky. AX_TEST_F( - 'SwitchAccessItemScanManagerTest', 'DISABLED_DismissVirtualKeyboard', + 'SwitchAccessMV2ItemScanManagerTest', 'DISABLED_DismissVirtualKeyboard', async function() { const website = `<input type="text" id="testinput"></input><button>ok</button>`; @@ -411,8 +421,8 @@ // TODO(crbug.com/1260231): Test is flaky. AX_TEST_F( - 'SwitchAccessItemScanManagerTest', 'DISABLED_ChildrenChangedDoesNotRefresh', - async function() { + 'SwitchAccessMV2ItemScanManagerTest', + 'DISABLED_ChildrenChangedDoesNotRefresh', async function() { const website = ` <div id="slider" role="slider"> <div role="group"><div></div></div> @@ -459,29 +469,30 @@ assertEquals(slider, Navigator.byItem.node_); }); -AX_TEST_F('SwitchAccessItemScanManagerTest', 'InitialFocus', async function() { - const website = `<input></input><button autofocus></button>`; - const rootWebArea = await this.runWithLoadedTree(website); - // The button should have initial focus. This ensures we move past the - // focus event below. - const button = - await this.untilFocusIs({role: chrome.automation.RoleType.BUTTON}); +AX_TEST_F( + 'SwitchAccessMV2ItemScanManagerTest', 'InitialFocus', async function() { + const website = `<input></input><button autofocus></button>`; + const rootWebArea = await this.runWithLoadedTree(website); + // The button should have initial focus. This ensures we move past the + // focus event below. + const button = + await this.untilFocusIs({role: chrome.automation.RoleType.BUTTON}); - // Build a new ItemScanManager to see what it sets as the initial node. - const desktop = rootWebArea.parent.root; - assertEquals( - chrome.automation.RoleType.DESKTOP, desktop.role, - `Unexpected desktop ${desktop.toString()}`); - const manager = new ItemScanManager(desktop); - manager.start(); - assertEquals( - button.automationNode, manager.node_.automationNode, - `Unexpected focus ${manager.node_.debugString()}`); -}); + // Build a new ItemScanManager to see what it sets as the initial node. + const desktop = rootWebArea.parent.root; + assertEquals( + chrome.automation.RoleType.DESKTOP, desktop.role, + `Unexpected desktop ${desktop.toString()}`); + const manager = new ItemScanManager(desktop); + manager.start(); + assertEquals( + button.automationNode, manager.node_.automationNode, + `Unexpected focus ${manager.node_.debugString()}`); + }); AX_TEST_F( - 'SwitchAccessItemScanManagerTest', 'SyncFocusToNewWindow', + 'SwitchAccessMV2ItemScanManagerTest', 'SyncFocusToNewWindow', async function() { const website1 = `<button autofocus>one</button>`; const website2 = `<button autofocus>two</button>`; @@ -552,8 +563,8 @@ // TODO(crbug.com/1219067): Unflake. AX_TEST_F( - 'SwitchAccessItemScanManagerTest', 'DISABLED_LockScreenBlocksUserSession', - async function() { + 'SwitchAccessMV2ItemScanManagerTest', + 'DISABLED_LockScreenBlocksUserSession', async function() { const website = `<button autofocus>kitties!</button>`; await this.runWithLoadedTree(website); let button =
diff --git a/chrome/browser/resources/chromeos/accessibility/switch_access/mv2/nodes/basic_node_test.js b/chrome/browser/resources/chromeos/accessibility/switch_access/mv2/nodes/basic_node_test.js index 92783d7..d24adad 100644 --- a/chrome/browser/resources/chromeos/accessibility/switch_access/mv2/nodes/basic_node_test.js +++ b/chrome/browser/resources/chromeos/accessibility/switch_access/mv2/nodes/basic_node_test.js
@@ -5,14 +5,14 @@ GEN_INCLUDE(['../switch_access_e2e_test_base.js']); /** Test fixture for the node wrapper type. */ -SwitchAccessBasicNodeTest = class extends SwitchAccessE2ETest { +SwitchAccessMV2BasicNodeTest = class extends SwitchAccessE2ETest { async setUpDeferred() { await super.setUpDeferred(); globalThis.MenuAction = chrome.accessibilityPrivate.SwitchAccessMenuAction; } }; -AX_TEST_F('SwitchAccessBasicNodeTest', 'AsRootNode', async function() { +AX_TEST_F('SwitchAccessMV2BasicNodeTest', 'AsRootNode', async function() { const website = `<div aria-label="outer"> <div aria-label="inner"> <input type="range"> @@ -45,7 +45,7 @@ 'Final child should be the back button'); }); -TEST_F('SwitchAccessBasicNodeTest', 'Equals', function() { +TEST_F('SwitchAccessMV2BasicNodeTest', 'Equals', function() { this.runWithLoadedDesktop(desktop => { const desktopNode = DesktopNode.build(desktop); @@ -115,7 +115,7 @@ }); }); -AX_TEST_F('SwitchAccessBasicNodeTest', 'Actions', async function() { +AX_TEST_F('SwitchAccessMV2BasicNodeTest', 'Actions', async function() { const website = `<input type="text"> <div role="button" aria-label="group"> <button>A</button>
diff --git a/chrome/browser/resources/chromeos/accessibility/switch_access/mv2/nodes/desktop_node_test.js b/chrome/browser/resources/chromeos/accessibility/switch_access/mv2/nodes/desktop_node_test.js index 4d25203..769cd16e 100644 --- a/chrome/browser/resources/chromeos/accessibility/switch_access/mv2/nodes/desktop_node_test.js +++ b/chrome/browser/resources/chromeos/accessibility/switch_access/mv2/nodes/desktop_node_test.js
@@ -5,9 +5,9 @@ GEN_INCLUDE(['../switch_access_e2e_test_base.js']); /** Test fixture for the desktop node. */ -SwitchAccessDesktopNodeTest = class extends SwitchAccessE2ETest {}; +SwitchAccessMV2DesktopNodeTest = class extends SwitchAccessE2ETest {}; -TEST_F('SwitchAccessDesktopNodeTest', 'Build', function() { +TEST_F('SwitchAccessMV2DesktopNodeTest', 'Build', function() { this.runWithLoadedDesktop(desktop => { const desktopNode = DesktopNode.build(desktop);
diff --git a/chrome/browser/resources/chromeos/accessibility/switch_access/mv2/nodes/group_node_test.js b/chrome/browser/resources/chromeos/accessibility/switch_access/mv2/nodes/group_node_test.js index 202f864..abcff85 100644 --- a/chrome/browser/resources/chromeos/accessibility/switch_access/mv2/nodes/group_node_test.js +++ b/chrome/browser/resources/chromeos/accessibility/switch_access/mv2/nodes/group_node_test.js
@@ -5,9 +5,9 @@ GEN_INCLUDE(['../switch_access_e2e_test_base.js']); /** Test fixture for the node wrapper type. */ -SwitchAccessGroupNodeTest = class extends SwitchAccessE2ETest {}; +SwitchAccessMV2GroupNodeTest = class extends SwitchAccessE2ETest {}; -TEST_F('SwitchAccessGroupNodeTest', 'NodesRemoved', function() { +TEST_F('SwitchAccessMV2GroupNodeTest', 'NodesRemoved', function() { const website = `<button></button>`; this.runWithLoadedTree(website, rootWebArea => { const button = rootWebArea.find({role: chrome.automation.RoleType.BUTTON});
diff --git a/chrome/browser/resources/chromeos/accessibility/switch_access/mv2/nodes/tab_node_test.js b/chrome/browser/resources/chromeos/accessibility/switch_access/mv2/nodes/tab_node_test.js index 132dbd7..b357e896 100644 --- a/chrome/browser/resources/chromeos/accessibility/switch_access/mv2/nodes/tab_node_test.js +++ b/chrome/browser/resources/chromeos/accessibility/switch_access/mv2/nodes/tab_node_test.js
@@ -5,14 +5,14 @@ GEN_INCLUDE(['../switch_access_e2e_test_base.js']); /** Test fixture for the tab node type. */ -SwitchAccessTabNodeTest = class extends SwitchAccessE2ETest { +SwitchAccessMV2TabNodeTest = class extends SwitchAccessE2ETest { async setUpDeferred() { await super.setUpDeferred(); globalThis.MenuAction = chrome.accessibilityPrivate.SwitchAccessMenuAction; } }; -AX_TEST_F('SwitchAccessTabNodeTest', 'FindCloseButton', async function() { +AX_TEST_F('SwitchAccessMV2TabNodeTest', 'FindCloseButton', async function() { await this.runWithLoadedTree(''); const tab = this.desktop_.find({role: chrome.automation.RoleType.TAB}); @@ -27,7 +27,7 @@ assertEquals(buttonCount, 1); }); -AX_TEST_F('SwitchAccessTabNodeTest', 'Construction', async function() { +AX_TEST_F('SwitchAccessMV2TabNodeTest', 'Construction', async function() { await this.runWithLoadedTree(''); const tabAutomationNode = this.desktop_.find({role: chrome.automation.RoleType.TAB});
diff --git a/chrome/browser/resources/chromeos/accessibility/switch_access/mv2/point_scan_manager_test.js b/chrome/browser/resources/chromeos/accessibility/switch_access/mv2/point_scan_manager_test.js index e44ef22..c77e489 100644 --- a/chrome/browser/resources/chromeos/accessibility/switch_access/mv2/point_scan_manager_test.js +++ b/chrome/browser/resources/chromeos/accessibility/switch_access/mv2/point_scan_manager_test.js
@@ -5,7 +5,7 @@ GEN_INCLUDE(['switch_access_e2e_test_base.js']); /** Test fixture for the point scan manager. */ -SwitchAccessPointScanManagerTest = class extends SwitchAccessE2ETest { +SwitchAccessMV2PointScanManagerTest = class extends SwitchAccessE2ETest { /** @override */ async setUpDeferred() { await super.setUpDeferred(); @@ -14,7 +14,8 @@ }; AX_TEST_F( - 'SwitchAccessPointScanManagerTest', 'PointScanLeftClick', async function() { + 'SwitchAccessMV2PointScanManagerTest', 'PointScanLeftClick', + async function() { const website = '<input type=checkbox style="width: 800px; height: 800px;">'; const rootWebArea = await this.runWithLoadedTree(website); @@ -41,7 +42,7 @@ }); AX_TEST_F( - 'SwitchAccessPointScanManagerTest', 'PointScanRightClick', + 'SwitchAccessMV2PointScanManagerTest', 'PointScanRightClick', async function() { const website = '<p>Kittens r cute</p>'; const rootWebArea = await this.runWithLoadedTree(website); @@ -71,7 +72,7 @@ // Verifies that chrome.accessibilityPrivate.setFocusRings() is not called when // point scanning is running. AX_TEST_F( - 'SwitchAccessPointScanManagerTest', 'PointScanNoFocusRings', + 'SwitchAccessMV2PointScanManagerTest', 'PointScanNoFocusRings', async function() { const sleep = () => { return new Promise(resolve => setTimeout(resolve, 2 * 1000));
diff --git a/chrome/browser/resources/chromeos/accessibility/switch_access/mv2/switch_access_predicate_test.js b/chrome/browser/resources/chromeos/accessibility/switch_access/mv2/switch_access_predicate_test.js index ea43c43..e0737175 100644 --- a/chrome/browser/resources/chromeos/accessibility/switch_access/mv2/switch_access_predicate_test.js +++ b/chrome/browser/resources/chromeos/accessibility/switch_access/mv2/switch_access_predicate_test.js
@@ -5,7 +5,7 @@ GEN_INCLUDE(['switch_access_e2e_test_base.js']); /** Test fixture for the Switch Access predicates. */ -SwitchAccessPredicateTest = class extends SwitchAccessE2ETest {}; +SwitchAccessMV2PredicateTest = class extends SwitchAccessE2ETest {}; function fakeLoc(x) { return {left: x, top: x, width: x, height: x}; @@ -81,7 +81,7 @@ }; } -AX_TEST_F('SwitchAccessPredicateTest', 'IsInteresting', async function() { +AX_TEST_F('SwitchAccessMV2PredicateTest', 'IsInteresting', async function() { const loadedPage = await this.runWithLoadedTree(testWebsite()); const t = getTree(loadedPage); const cache = new SACache(); @@ -130,7 +130,7 @@ 'Leaf7 should not be interesting'); }); -AX_TEST_F('SwitchAccessPredicateTest', 'IsGroup', async function() { +AX_TEST_F('SwitchAccessMV2PredicateTest', 'IsGroup', async function() { const loadedPage = await this.runWithLoadedTree(testWebsite()); const t = getTree(loadedPage); const cache = new SACache(); @@ -180,7 +180,7 @@ }); AX_TEST_F( - 'SwitchAccessPredicateTest', 'IsInterestingSubtree', async function() { + 'SwitchAccessMV2PredicateTest', 'IsInterestingSubtree', async function() { const loadedPage = await this.runWithLoadedTree(testWebsite()); const t = getTree(loadedPage); const cache = new SACache(); @@ -226,7 +226,7 @@ 'Leaf7 should not be an interesting subtree'); }); -AX_TEST_F('SwitchAccessPredicateTest', 'IsActionable', async function() { +AX_TEST_F('SwitchAccessMV2PredicateTest', 'IsActionable', async function() { const treeString = `<button style="position:absolute; top:-100px;">offscreen</button> <button disabled>disabled</button> @@ -290,7 +290,7 @@ }); AX_TEST_F( - 'SwitchAccessPredicateTest', 'IsActionableFocusableElements', + 'SwitchAccessMV2PredicateTest', 'IsActionableFocusableElements', async function() { const treeString = `<div id="noChildren" tabindex=0></div> <div id="oneInterestingChild" tabindex=0> @@ -344,7 +344,7 @@ 'Focusable element with uninteresting children should be actionable'); }); -AX_TEST_F('SwitchAccessPredicateTest', 'LeafPredicate', async function() { +AX_TEST_F('SwitchAccessMV2PredicateTest', 'LeafPredicate', async function() { const loadedPage = await this.runWithLoadedTree(testWebsite()); const t = getTree(loadedPage); const cache = new SACache(); @@ -370,7 +370,7 @@ assertTrue(leaf(t.leaf3), 'Leaf3 should be a leaf for lower1 tree'); }); -AX_TEST_F('SwitchAccessPredicateTest', 'RootPredicate', async function() { +AX_TEST_F('SwitchAccessMV2PredicateTest', 'RootPredicate', async function() { const loadedPage = await this.runWithLoadedTree(testWebsite()); const t = getTree(loadedPage); @@ -394,7 +394,7 @@ assertFalse(root(t.leaf3), 'Leaf3 should not be a root of the lower1 tree'); }); -AX_TEST_F('SwitchAccessPredicateTest', 'VisitPredicate', async function() { +AX_TEST_F('SwitchAccessMV2PredicateTest', 'VisitPredicate', async function() { const loadedPage = await this.runWithLoadedTree(testWebsite()); const t = getTree(loadedPage); const cache = new SACache(); @@ -426,7 +426,7 @@ assertFalse(visit(t.leaf7), 'Leaf7 should not be visited in lower1 tree'); }); -AX_TEST_F('SwitchAccessPredicateTest', 'Cache', async function() { +AX_TEST_F('SwitchAccessMV2PredicateTest', 'Cache', async function() { const loadedPage = await this.runWithLoadedTree(testWebsite()); const t = getTree(loadedPage); const cache = new SACache();
diff --git a/chrome/browser/resources/chromeos/accessibility/switch_access/mv2/switch_access_test.js b/chrome/browser/resources/chromeos/accessibility/switch_access/mv2/switch_access_test.js index 3f1425b..34ccc18 100644 --- a/chrome/browser/resources/chromeos/accessibility/switch_access/mv2/switch_access_test.js +++ b/chrome/browser/resources/chromeos/accessibility/switch_access/mv2/switch_access_test.js
@@ -5,7 +5,7 @@ GEN_INCLUDE(['switch_access_e2e_test_base.js']); /** Test fixture for the SwitchAccess class. */ -SwitchAccessSwitchAccessTest = class extends SwitchAccessE2ETest { +SwitchAccessMV2SwitchAccessTest = class extends SwitchAccessE2ETest { async waitForCallback() { return new Promise(resolve => this.promiseCallback = resolve); } @@ -17,7 +17,7 @@ } AX_TEST_F( - 'SwitchAccessSwitchAccessTest', 'NoFocusDefersInit', async function() { + 'SwitchAccessMV2SwitchAccessTest', 'NoFocusDefersInit', async function() { await this.runWithLoadedTree(''); // Build a new SwitchAccess instance with hooks. let initCount = 0;
diff --git a/chrome/browser/resources/chromeos/accessibility/switch_access/mv2/text_navigation_manager_test.js b/chrome/browser/resources/chromeos/accessibility/switch_access/mv2/text_navigation_manager_test.js index 78e824e..b665ab47a 100644 --- a/chrome/browser/resources/chromeos/accessibility/switch_access/mv2/text_navigation_manager_test.js +++ b/chrome/browser/resources/chromeos/accessibility/switch_access/mv2/text_navigation_manager_test.js
@@ -5,7 +5,7 @@ GEN_INCLUDE(['switch_access_e2e_test_base.js']); /** Text fixture for the text navigation manager. */ -SwitchAccessTextNavigationManagerTest = class extends SwitchAccessE2ETest { +SwitchAccessMV2TextNavigationManagerTest = class extends SwitchAccessE2ETest { /** @override */ async setUpDeferred() { await super.setUpDeferred(); @@ -207,7 +207,7 @@ // TODO(crbug.com/1268230): Re-enable test. AX_TEST_F( - 'SwitchAccessTextNavigationManagerTest', 'DISABLED_JumpToBeginning', + 'SwitchAccessMV2TextNavigationManagerTest', 'DISABLED_JumpToBeginning', async function() { await runTextNavigationTest(this, { content: 'hi there', @@ -221,7 +221,7 @@ // TODO(crbug.com/1268230): Re-enable test. AX_TEST_F( - 'SwitchAccessTextNavigationManagerTest', 'DISABLED_JumpToEnd', + 'SwitchAccessMV2TextNavigationManagerTest', 'DISABLED_JumpToEnd', async function() { await runTextNavigationTest(this, { content: 'hi there', @@ -235,7 +235,7 @@ // TODO(crbug.com/1177096) Renable test AX_TEST_F( - 'SwitchAccessTextNavigationManagerTest', 'DISABLED_MoveBackwardOneChar', + 'SwitchAccessMV2TextNavigationManagerTest', 'DISABLED_MoveBackwardOneChar', async function() { await runTextNavigationTest(this, { content: 'parrots!', @@ -249,7 +249,7 @@ // TODO(crbug.com/1268230): Re-enable test. AX_TEST_F( - 'SwitchAccessTextNavigationManagerTest', 'DISABLED_MoveBackwardOneWord', + 'SwitchAccessMV2TextNavigationManagerTest', 'DISABLED_MoveBackwardOneWord', async function() { await runTextNavigationTest(this, { content: 'more parrots!', @@ -263,7 +263,7 @@ // TODO(crbug.com/1268230): Re-enable test. AX_TEST_F( - 'SwitchAccessTextNavigationManagerTest', 'DISABLED_MoveForwardOneChar', + 'SwitchAccessMV2TextNavigationManagerTest', 'DISABLED_MoveForwardOneChar', async function() { await runTextNavigationTest(this, { content: 'hello', @@ -277,7 +277,7 @@ // TODO(crbug.com/1268230): Re-enable test. AX_TEST_F( - 'SwitchAccessTextNavigationManagerTest', 'DISABLED_MoveForwardOneWord', + 'SwitchAccessMV2TextNavigationManagerTest', 'DISABLED_MoveForwardOneWord', async function() { await runTextNavigationTest(this, { content: 'more parrots!', @@ -291,7 +291,7 @@ // TODO(crbug.com/1268230): Re-enable test. AX_TEST_F( - 'SwitchAccessTextNavigationManagerTest', 'DISABLED_MoveUpOneLine', + 'SwitchAccessMV2TextNavigationManagerTest', 'DISABLED_MoveUpOneLine', async function() { await runTextNavigationTest(this, { content: 'more parrots!', @@ -307,7 +307,7 @@ // TODO(crbug.com/1268230): Re-enable test. AX_TEST_F( - 'SwitchAccessTextNavigationManagerTest', 'DISABLED_MoveDownOneLine', + 'SwitchAccessMV2TextNavigationManagerTest', 'DISABLED_MoveDownOneLine', async function() { await runTextNavigationTest(this, { content: 'more parrots!', @@ -327,7 +327,7 @@ * selection start index. */ AX_TEST_F( - 'SwitchAccessTextNavigationManagerTest', 'DISABLED_SelectStart', + 'SwitchAccessMV2TextNavigationManagerTest', 'DISABLED_SelectStart', async function() { const website = generateWebsiteWithTextArea('test', 'test123', 3, 20, 'hard'); @@ -348,7 +348,7 @@ * bounds */ AX_TEST_F( - 'SwitchAccessTextNavigationManagerTest', 'DISABLED_SelectEnd', + 'SwitchAccessMV2TextNavigationManagerTest', 'DISABLED_SelectEnd', async function() { const website = generateWebsiteWithTextArea('test', 'test 123', 6, 20, 'hard'); @@ -372,7 +372,7 @@ * function. */ AX_TEST_F( - 'SwitchAccessTextNavigationManagerTest', 'DISABLED_SelectCharacter', + 'SwitchAccessMV2TextNavigationManagerTest', 'DISABLED_SelectCharacter', async function() { await runTextSelectionTest(this, { content: 'hello world!', @@ -392,7 +392,7 @@ * the moveBackwardOneWord function. */ AX_TEST_F( - 'SwitchAccessTextNavigationManagerTest', 'DISABLED_SelectWordBackward', + 'SwitchAccessMV2TextNavigationManagerTest', 'DISABLED_SelectWordBackward', async function() { await runTextSelectionTest(this, { content: 'hello world!',
diff --git a/chrome/browser/resources/chromeos/accessibility/switch_access/mv3/BUILD.gn b/chrome/browser/resources/chromeos/accessibility/switch_access/mv3/BUILD.gn index bc6f0ce..447ed695 100644 --- a/chrome/browser/resources/chromeos/accessibility/switch_access/mv3/BUILD.gn +++ b/chrome/browser/resources/chromeos/accessibility/switch_access/mv3/BUILD.gn
@@ -18,7 +18,7 @@ } switch_access_dir = - "$root_out_dir/resources/chromeos/accessibility/switch_access" + "$root_out_dir/resources/chromeos/accessibility/switch_access/mv3" # Directory where typescript build will occur. ts_build_staging_dir = "$target_gen_dir/ts_build_staging"
diff --git a/chrome/browser/resources/chromeos/accessibility/switch_access_manifest.json.jinja2 b/chrome/browser/resources/chromeos/accessibility/switch_access_manifest.json.jinja2 index a117611..d39707cc 100644 --- a/chrome/browser/resources/chromeos/accessibility/switch_access_manifest.json.jinja2 +++ b/chrome/browser/resources/chromeos/accessibility/switch_access_manifest.json.jinja2
@@ -6,13 +6,13 @@ "manifest_version": 3, "minimum_chrome_version": "93", "background": { - "service_worker": "switch_access/switch_access_loader.js", + "service_worker": "switch_access/mv3/switch_access_loader.js", "type": "module" }, {% else %} "manifest_version": 2, "background": { - "page": "switch_access/background.html" + "page": "switch_access/mv2/background.html" }, {% endif %} "name": "__MSG_SWITCH_ACCESS_NAME__",
diff --git a/chrome/browser/resources/glic/PRESUBMIT.py b/chrome/browser/resources/glic/PRESUBMIT.py index b93fb284..5014f85 100644 --- a/chrome/browser/resources/glic/PRESUBMIT.py +++ b/chrome/browser/resources/glic/PRESUBMIT.py
@@ -69,7 +69,7 @@ '** Your changelist is a backwards-incompatible Glic API change!\n' + '** Did you add a non-optional field or function, or change the\n' + '** type of an existing field or function?\n' + - '** Please fix, or add BYPASS_GLIC_API_COMPATIBILITY_CHECK=<reason>' + + '** Please fix, or add BYPASS_GLIC_API_COMPATIBILITY_CHECK: <reason>' + ' to your changelist description if this is intended. Error:\n ') tsc_cmd = [
diff --git a/chrome/browser/resources/pdf/constants.ts b/chrome/browser/resources/pdf/constants.ts index 979f4c9..88f39e8 100644 --- a/chrome/browser/resources/pdf/constants.ts +++ b/chrome/browser/resources/pdf/constants.ts
@@ -2,6 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +// <if expr="enable_pdf_ink2 or enable_ink"> +export enum AnnotationMode { + NONE = 'none', + DRAW = 'draw', + // <if expr="enable_pdf_ink2"> + TEXT = 'text', + // </if> +} +// </if> + // <if expr="enable_pdf_ink2"> // The different types of annotation brushes. export enum AnnotationBrushType {
diff --git a/chrome/browser/resources/pdf/elements/viewer_toolbar.css b/chrome/browser/resources/pdf/elements/viewer_toolbar.css index 2088c4f8..54a956a 100644 --- a/chrome/browser/resources/pdf/elements/viewer_toolbar.css +++ b/chrome/browser/resources/pdf/elements/viewer_toolbar.css
@@ -186,7 +186,7 @@ margin-inline-end: 4px; } -:host([annotation-mode]) #annotate { +:host([annotation-mode="draw"]) #annotate { background-color: var(--active-button-bg); border-radius: 50%; } @@ -203,7 +203,7 @@ margin-inline: 0; } -:host([annotation-mode]) #annotate-controls #annotate { +:host([annotation-mode="draw"]) #annotate-controls #annotate { --cr-icon-button-fill-color: var(--viewer-icon-ink-selected-fill-color); }
diff --git a/chrome/browser/resources/pdf/elements/viewer_toolbar.ts b/chrome/browser/resources/pdf/elements/viewer_toolbar.ts index 6217c70..b694629 100644 --- a/chrome/browser/resources/pdf/elements/viewer_toolbar.ts +++ b/chrome/browser/resources/pdf/elements/viewer_toolbar.ts
@@ -25,6 +25,9 @@ import {CrLitElement} from 'chrome://resources/lit/v3_0/lit.rollup.js'; import type {PropertyValues} from 'chrome://resources/lit/v3_0/lit.rollup.js'; +// <if expr="enable_pdf_ink2 or enable_ink"> +import {AnnotationMode} from '../constants.js'; +// </if> import {FittingType, FormFieldFocusType} from '../constants.js'; // <if expr="enable_pdf_ink2"> import {PluginController, PluginControllerEventType} from '../controller.js'; @@ -36,7 +39,7 @@ declare global { interface HTMLElementEventMap { - 'annotation-mode-toggled': CustomEvent<boolean>; + 'annotation-mode-updated': CustomEvent<AnnotationMode>; 'display-annotations-changed': CustomEvent<boolean>; 'fit-to-changed': CustomEvent<FittingType>; } @@ -69,7 +72,7 @@ // <if expr="enable_ink or enable_pdf_ink2"> annotationAvailable: {type: Boolean}, annotationMode: { - type: Boolean, + type: String, reflect: true, }, // </if> @@ -152,7 +155,7 @@ // <if expr="enable_ink or enable_pdf_ink2"> annotationAvailable: boolean = false; - annotationMode: boolean = false; + annotationMode: AnnotationMode = AnnotationMode.NONE; // </if> // <if expr="enable_ink"> @@ -275,7 +278,7 @@ } // </if> enable_pdf_ink2 - return this.annotationMode; + return this.annotationMode === AnnotationMode.DRAW; } // </if> enable_ink @@ -295,8 +298,9 @@ this.$.menu.close(); // <if expr="enable_ink"> - if (!this.displayAnnotations_ && this.annotationMode) { - this.toggleAnnotation(); + if (!this.displayAnnotations_ && + this.annotationMode === AnnotationMode.DRAW) { + this.setAnnotationMode(AnnotationMode.NONE); } // </if> } @@ -420,29 +424,36 @@ // <if expr="enable_ink"> protected onDialogClose_() { + // The dialog should only show if we are not in annotation mode and the + // user wants to transition to drawing annotations. + assert(this.annotationMode === AnnotationMode.NONE); const confirmed = this.shadowRoot.querySelector( 'viewer-annotations-mode-dialog')!.wasConfirmed(); this.showAnnotationsModeDialog_ = false; if (confirmed) { this.dispatchEvent(new CustomEvent('annotation-mode-dialog-confirmed')); - this.toggleAnnotation(); + this.setAnnotationMode(AnnotationMode.DRAW); } } // </if> // <if expr="enable_ink or enable_pdf_ink2"> protected onAnnotationClick_() { + const newAnnotationMode = this.annotationMode === AnnotationMode.DRAW ? + AnnotationMode.NONE : + AnnotationMode.DRAW; + // <if expr="enable_pdf_ink2"> if (this.pdfInk2Enabled) { - this.toggleAnnotation(); + this.setAnnotationMode(newAnnotationMode); return; } // </if> enable_pdf_ink2 // <if expr="enable_ink"> if (!this.rotated && !this.twoUpViewEnabled) { - this.toggleAnnotation(); + this.setAnnotationMode(newAnnotationMode); return; } @@ -450,10 +461,9 @@ // </if> enable_ink } - toggleAnnotation() { - const newAnnotationMode = !this.annotationMode; - this.dispatchEvent(new CustomEvent( - 'annotation-mode-toggled', {detail: newAnnotationMode})); + setAnnotationMode(annotationMode: AnnotationMode) { + this.dispatchEvent( + new CustomEvent('annotation-mode-updated', {detail: annotationMode})); // <if expr="enable_pdf_ink2"> // Don't toggle display annotations for Ink2. @@ -462,7 +472,7 @@ } // </if> enable_pdf_ink2 - if (newAnnotationMode && !this.displayAnnotations_) { + if (annotationMode !== AnnotationMode.NONE && !this.displayAnnotations_) { this.toggleDisplayAnnotations_(); } } @@ -561,7 +571,7 @@ */ protected presentationModeAvailable_(): boolean { // <if expr="enable_ink"> - return !this.annotationMode && !this.embeddedViewer; + return this.annotationMode === AnnotationMode.NONE && !this.embeddedViewer; // </if> // <if expr="not enable_ink"> return !this.embeddedViewer;
diff --git a/chrome/browser/resources/pdf/pdf_viewer.html b/chrome/browser/resources/pdf/pdf_viewer.html index 2ffd94f..401014a 100644 --- a/chrome/browser/resources/pdf/pdf_viewer.html +++ b/chrome/browser/resources/pdf/pdf_viewer.html
@@ -35,7 +35,7 @@ @zoom-changed="${this.onZoomChanged}" @zoom-in="${this.onZoomIn}" @zoom-out="${this.onZoomOut}" @rotate-left="${this.rotateCounterclockwise}" <if expr="enable_ink or enable_pdf_ink2"> - @annotation-mode-toggled="${this.onAnnotationModeToggled_}" + @annotation-mode-updated="${this.onAnnotationModeUpdated_}" </if> @print="${this.onPrint_}" @save="${this.onToolbarSave_}" <if expr="enable_pdf_ink2">
diff --git a/chrome/browser/resources/pdf/pdf_viewer.ts b/chrome/browser/resources/pdf/pdf_viewer.ts index 8c5bc61..19ce99e 100644 --- a/chrome/browser/resources/pdf/pdf_viewer.ts +++ b/chrome/browser/resources/pdf/pdf_viewer.ts
@@ -28,6 +28,9 @@ import type {Bookmark} from './bookmark_type.js'; import type {BrowserApi} from './browser_api.js'; import type {Attachment, DocumentMetadata, ExtendedKeyEvent, Point} from './constants.js'; +// <if expr="enable_ink or enable_pdf_ink2"> +import {AnnotationMode} from './constants.js'; +// </if> import {FittingType, FormFieldFocusType, SaveRequestType} from './constants.js'; import type {MessageData} from './controller.js'; import {PluginController} from './controller.js'; @@ -170,7 +173,7 @@ showErrorDialog: {type: Boolean}, strings: {type: Object}, - annotationMode_: {type: Boolean}, + annotationMode_: {type: String}, attachments_: {type: Array}, bookmarks_: {type: Array}, canSerializeDocument_: {type: Boolean}, @@ -222,7 +225,7 @@ } beepCount: number = 0; - protected annotationMode_: boolean = false; + protected annotationMode_: AnnotationMode = AnnotationMode.NONE; protected attachments_: Attachment[] = []; protected bookmarks_: Bookmark[] = []; private canSerializeDocument_: boolean = false; @@ -265,7 +268,7 @@ private pluginController_: PluginController = PluginController.getInstance(); protected printingEnabled_: boolean = false; // <if expr="enable_pdf_ink2"> - private restoreAnnotationMode_: boolean = false; + private restoreAnnotationMode_: AnnotationMode = AnnotationMode.NONE; // </if> // <if expr="enable_ink or enable_pdf_ink2"> private showBeforeUnloadDialog_: boolean = false; @@ -519,17 +522,28 @@ // <if expr="enable_ink or enable_pdf_ink2"> /** Handles the annotation mode being toggled on or off. */ - protected async onAnnotationModeToggled_(e: CustomEvent<boolean>) { + protected async onAnnotationModeUpdated_(e: CustomEvent<AnnotationMode>) { const annotationMode = e.detail; // <if expr="enable_pdf_ink2"> if (this.pdfInk2Enabled_) { - if (!this.restoreAnnotationMode_) { - record( - annotationMode ? UserAction.ENTER_INK2_ANNOTATION_MODE : - UserAction.EXIT_INK2_ANNOTATION_MODE); + if (this.restoreAnnotationMode_ === AnnotationMode.NONE) { + let action: UserAction; + switch (annotationMode) { + case AnnotationMode.DRAW: + action = UserAction.ENTER_INK2_ANNOTATION_MODE; + break; + case AnnotationMode.NONE: + action = UserAction.EXIT_INK2_ANNOTATION_MODE; + break; + default: + assertNotReached(); + } + record(action); } - this.pluginController_.setAnnotationMode(annotationMode); - if (!Ink2Manager.getInstance().isInitializationStarted()) { + this.pluginController_.setAnnotationMode( + annotationMode !== AnnotationMode.NONE); + if (annotationMode === AnnotationMode.DRAW && + !Ink2Manager.getInstance().isInitializationStarted()) { await Ink2Manager.getInstance().initializeBrush(); } this.annotationMode_ = annotationMode; @@ -538,7 +552,7 @@ // </if> enable_pdf_ink2 // <if expr="enable_ink"> - if (annotationMode) { + if (annotationMode === AnnotationMode.DRAW) { // Enter annotation mode. assert(this.pluginController_.isActive); assert(!this.inkController_.isActive); @@ -559,7 +573,7 @@ assert(result); record(UserAction.ENTER_ANNOTATION_MODE); - this.annotationMode_ = true; + this.annotationMode_ = AnnotationMode.DRAW; this.hasEnteredAnnotationMode_ = true; // TODO(dstockwell): feed real progress data from the Ink component this.updateProgress(50); @@ -575,7 +589,7 @@ assert(this.currentController === this.inkController_); // TODO(dstockwell): set ink read-only, begin transition this.updateProgress(0); - this.annotationMode_ = false; + this.annotationMode_ = AnnotationMode.NONE; // This runs separately to allow other consumers of `loaded` to queue // up after this task. this.loaded!.then(() => { @@ -598,8 +612,8 @@ if (!this.$.toolbar.annotationMode) { return; } - this.$.toolbar.toggleAnnotation(); - this.annotationMode_ = false; + this.$.toolbar.setAnnotationMode(AnnotationMode.NONE); + this.annotationMode_ = AnnotationMode.NONE; await this.restoreSidenav_(); await this.loaded; } @@ -613,11 +627,11 @@ private async enterPresentationMode_(): Promise<void> { // <if expr="enable_pdf_ink2"> // Exit annotation mode if it was enabled. - if (this.pdfInk2Enabled_ && this.annotationMode_) { - this.restoreAnnotationMode_ = true; - this.$.toolbar.toggleAnnotation(); - assert(!this.annotationMode_); + if (this.pdfInk2Enabled_ && this.annotationMode_ !== AnnotationMode.NONE) { + this.restoreAnnotationMode_ = this.annotationMode_; + this.$.toolbar.setAnnotationMode(AnnotationMode.NONE); } + assert(this.annotationMode_ === AnnotationMode.NONE); // </if> const scroller = this.$.scroller; @@ -657,10 +671,10 @@ // <if expr="enable_pdf_ink2"> // Enter annotation mode again if it was enabled before entering // Presentation mode. - if (this.restoreAnnotationMode_) { - this.$.toolbar.toggleAnnotation(); - assert(this.annotationMode_); - this.restoreAnnotationMode_ = false; + if (this.restoreAnnotationMode_ !== AnnotationMode.NONE) { + this.$.toolbar.setAnnotationMode(this.restoreAnnotationMode_); + assert(this.annotationMode_ !== AnnotationMode.NONE); + this.restoreAnnotationMode_ = AnnotationMode.NONE; } // </if> } @@ -1263,7 +1277,8 @@ // For Ink, request type original in annotation mode --> need to exit // annotation mode before saving. See https://crbug.com/919364. let shouldExitAnnotationMode = - this.annotationMode_ && requestType === SaveRequestType.ORIGINAL; + this.annotationMode_ !== AnnotationMode.NONE && + requestType === SaveRequestType.ORIGINAL; // Ink2 overrides Ink, and Ink2 does not need to exit annotation mode. // Only exit annotation mode if Ink2 is disabled. @@ -1274,7 +1289,7 @@ if (shouldExitAnnotationMode) { await this.exitAnnotationMode_(); - assert(!this.annotationMode_); + assert(this.annotationMode_ === AnnotationMode.NONE); } // </if> enable_ink @@ -1452,7 +1467,7 @@ * @returns Whether the PDF viewer has Ink2 enabled and is in annotation mode. */ private inInk2AnnotationMode_(): boolean { - return this.pdfInk2Enabled_ && this.annotationMode_; + return this.pdfInk2Enabled_ && this.annotationMode_ !== AnnotationMode.NONE; } // </if>
diff --git a/chrome/browser/resources/pdf/pdf_viewer_wrapper.ts b/chrome/browser/resources/pdf/pdf_viewer_wrapper.ts index cbe43d0..a896959 100644 --- a/chrome/browser/resources/pdf/pdf_viewer_wrapper.ts +++ b/chrome/browser/resources/pdf/pdf_viewer_wrapper.ts
@@ -15,6 +15,9 @@ // <if expr="enable_pdf_ink2"> export {AnnotationBrush, AnnotationBrushType, Color} from './constants.js'; // </if> +// <if expr="enable_pdf_ink2 or enable_ink"> +export {AnnotationMode} from './constants.js'; +// </if> export {Attachment, FittingType, FormFieldFocusType, Point, Rect, SaveRequestType} from './constants.js'; export {PluginController} from './controller.js'; // <if expr="enable_pdf_ink2">
diff --git a/chrome/browser/resources/privacy_sandbox/privacy_sandbox_privacy_policy_dialog.css b/chrome/browser/resources/privacy_sandbox/privacy_sandbox_privacy_policy_dialog.css index 781400f5..c8d7e18 100644 --- a/chrome/browser/resources/privacy_sandbox/privacy_sandbox_privacy_policy_dialog.css +++ b/chrome/browser/resources/privacy_sandbox/privacy_sandbox_privacy_policy_dialog.css
@@ -14,10 +14,12 @@ width: 96vw; padding-right: 24px; padding-left: 24px; + top: 0; + left: 0; } :host(:not([should-show])) iframe { - position: absolute; + position: fixed; z-index: -1; opacity: 0; }
diff --git a/chrome/browser/resources/settings/glic_page/glic_page.html b/chrome/browser/resources/settings/glic_page/glic_page.html index 86d25e1..c31bfd8 100644 --- a/chrome/browser/resources/settings/glic_page/glic_page.html +++ b/chrome/browser/resources/settings/glic_page/glic_page.html
@@ -108,12 +108,14 @@ <settings-toggle-button id="geolocationToggle" pref="{{prefs.glic.geolocation_enabled}}" label="$i18n{glicLocationToggle}" - sub-label="$i18n{glicLocationToggleSublabel}"> + sub-label="$i18n{glicLocationToggleSublabel}" + on-settings-boolean-control-change="onGeolocationToggleChange_"> </settings-toggle-button> <settings-toggle-button id="microphoneToggle" pref="{{prefs.glic.microphone_enabled}}" label="$i18n{glicMicrophoneToggle}" - sub-label="$i18n{glicMicrophoneToggleSublabel}"> + sub-label="$i18n{glicMicrophoneToggleSublabel}" + on-settings-boolean-control-change="onMicrophoneToggleChange_"> </settings-toggle-button> <settings-toggle-button id="tabAccessToggle" pref="{{prefs.glic.tab_context_enabled}}"
diff --git a/chrome/browser/resources/settings/glic_page/glic_page.ts b/chrome/browser/resources/settings/glic_page/glic_page.ts index 232652a4..b1079e9 100644 --- a/chrome/browser/resources/settings/glic_page/glic_page.ts +++ b/chrome/browser/resources/settings/glic_page/glic_page.ts
@@ -138,6 +138,18 @@ this.hideHelpBubble(OS_WIDGET_TOGGLE_ELEMENT_ID); } + private onGeolocationToggleChange_(event: Event) { + const enabled = (event.target as SettingsToggleButtonElement).checked; + this.metricsBrowserProxy_.recordAction( + 'Glic.Settings.Geolocation' + (enabled ? '.Enabled' : '.Disabled')); + } + + private onMicrophoneToggleChange_(event: Event) { + const enabled = (event.target as SettingsToggleButtonElement).checked; + this.metricsBrowserProxy_.recordAction( + 'Glic.Settings.Microphone' + (enabled ? '.Enabled' : '.Disabled')); + } + private async onShortcutUpdated_(event: CustomEvent<string>) { this.shortcutInput_ = event.detail; await this.browserProxy_.setGlicShortcut(this.shortcutInput_); @@ -183,7 +195,10 @@ private onTabAccessToggleChange_(event: CustomEvent) { const target = event.target as SettingsToggleButtonElement; - this.tabAccessToggleExpanded_ = target.checked; + const enabled = target.checked; + this.tabAccessToggleExpanded_ = enabled; + this.metricsBrowserProxy_.recordAction( + 'Glic.Settings.TabContext' + (enabled ? '.Enabled' : '.Disabled')); } private onActivityRowClick_() {
diff --git a/chrome/browser/resources/side_panel/read_anything/app.ts b/chrome/browser/resources/side_panel/read_anything/app.ts index 6f72fcc..f174b74f 100644 --- a/chrome/browser/resources/side_panel/read_anything/app.ts +++ b/chrome/browser/resources/side_panel/read_anything/app.ts
@@ -20,7 +20,7 @@ import {getHtml} from './app.html.js'; import {AppStyleUpdater} from './app_style_updater.js'; import type {SettingsPrefs} from './common.js'; -import {getCurrentSpeechRate, isWhitespace, minOverflowLengthToScroll, playFromSelectionTimeout} from './common.js'; +import {getCurrentSpeechRate, isHtmlElementVisible, isWhitespace, minOverflowLengthToScroll, playFromSelectionTimeout} from './common.js'; import type {LanguageToastElement} from './language_toast.js'; import {ReadAnythingLogger, TimeFrom} from './read_anything_logger.js'; import type {ReadAnythingToolbarElement} from './read_anything_toolbar.js'; @@ -219,6 +219,7 @@ private hiddenImageNodesIds_: Set<number> = new Set(); private imageNodeIdsToFetch_: Set<number> = new Set(); + private allowAutoScroll_ = true; private scrollingOnSelection_ = false; protected hasContent_ = false; protected emptyStateImagePath_?: string; @@ -470,6 +471,14 @@ this.$.containerParent.onscroll = () => { chrome.readingMode.onScroll(this.scrollingOnSelection_); this.scrollingOnSelection_ = false; + + // If the reading mode panel was scrolled while read aloud is speaking, + // we should disable autoscroll if the highlights are no longer visible, + // and we should re-enable autoscroll if the highlights are now + // visible. + if (this.speechPlayingState.isSpeechActive) { + this.allowAutoScroll_ = this.areHighlightsOnScreen(); + } }; // Pass copy commands to main page. Copy commands will not work if they are @@ -2206,6 +2215,16 @@ } private scrollHighlightIntoView() { + if (!this.allowAutoScroll_) { + if (!this.areHighlightsOnScreen()) { + return; + } + + // If we scrolled away from the current highlights but speech has + // caught up with the new scrolled position, resume autoscrolling. + this.allowAutoScroll_ = true; + } + // Ensure all the current highlights are in view. // TODO: crbug.com/40927698 - Handle if the highlight is longer than the // full height of the window (e.g. when font size is very large). Possibly @@ -2234,6 +2253,20 @@ } } + private areHighlightsOnScreen(): boolean { + assert(this.shadowRoot); + const currentHighlights = this.shadowRoot.querySelectorAll<HTMLElement>( + '.' + currentReadHighlightClass); + if (!currentHighlights || !currentHighlights.length) { + return false; + } + + const firstHighlight = currentHighlights.item(0); + const lastHighlight = currentHighlights.item(currentHighlights.length - 1); + return isHtmlElementVisible(firstHighlight) || + isHtmlElementVisible(lastHighlight); + } + private defaultUtteranceSettings(): UtteranceSettings { const lang = this.speechSynthesisLanguage;
diff --git a/chrome/browser/resources/side_panel/read_anything/common.ts b/chrome/browser/resources/side_panel/read_anything/common.ts index 4747d56..b69055cf 100644 --- a/chrome/browser/resources/side_panel/read_anything/common.ts +++ b/chrome/browser/resources/side_panel/read_anything/common.ts
@@ -96,3 +96,10 @@ export function isWhitespace(s: string): boolean { return /\s+/g.test(s); } + +export function isHtmlElementVisible(element: HTMLElement): boolean { + const boundingRect = element.getBoundingClientRect(); + return (boundingRect.bottom <= window.innerHeight || + boundingRect.bottom <= document.documentElement.clientHeight) && + boundingRect.top >= 0; +}
diff --git a/chrome/browser/resources/user_education_internals/BUILD.gn b/chrome/browser/resources/user_education_internals/BUILD.gn index a800f30..3fb1310 100644 --- a/chrome/browser/resources/user_education_internals/BUILD.gn +++ b/chrome/browser/resources/user_education_internals/BUILD.gn
@@ -29,6 +29,7 @@ mojo_files_deps = [ "//chrome/browser/ui/webui/user_education_internals:mojo_bindings_ts__generator" ] mojo_files = [ "$root_gen_dir/chrome/browser/ui/webui/user_education_internals/user_education_internals.mojom-webui.ts" ] + ts_tsconfig_base = "//tools/typescript/tsconfig_base_lit_389737066.json" ts_deps = [ "//third_party/lit/v3_0:build_ts", "//ui/webui/resources/cr_components/color_change_listener:build_ts",
diff --git a/chrome/browser/resources/user_education_internals/user_education_internals.ts b/chrome/browser/resources/user_education_internals/user_education_internals.ts index a847d26..a96c0fa 100644 --- a/chrome/browser/resources/user_education_internals/user_education_internals.ts +++ b/chrome/browser/resources/user_education_internals/user_education_internals.ts
@@ -79,15 +79,15 @@ }; } - filter: string = ''; - protected tutorials_: FeaturePromoDemoPageInfo[] = []; - protected featurePromos_: FeaturePromoDemoPageInfo[] = []; + accessor filter: string = ''; + protected accessor tutorials_: FeaturePromoDemoPageInfo[] = []; + protected accessor featurePromos_: FeaturePromoDemoPageInfo[] = []; protected newBadges_: FeaturePromoDemoPageInfo[] = []; protected whatsNewModules_: WhatsNewModuleDemoPageInfo[] = []; protected whatsNewEditions_: WhatsNewEditionDemoPageInfo[] = []; - protected featurePromoErrorMessage_: string = ''; - protected narrow_: boolean = false; - protected sessionExpanded_: boolean = false; + protected accessor featurePromoErrorMessage_: string = ''; + protected accessor narrow_: boolean = false; + protected accessor sessionExpanded_: boolean = false; protected sessionData_: FeaturePromoDemoPageData[] = []; private handler_: UserEducationInternalsPageHandlerInterface;
diff --git a/chrome/browser/resources/user_education_internals/user_education_internals_card.ts b/chrome/browser/resources/user_education_internals/user_education_internals_card.ts index fe927f3..19f3c7d 100644 --- a/chrome/browser/resources/user_education_internals/user_education_internals_card.ts +++ b/chrome/browser/resources/user_education_internals/user_education_internals_card.ts
@@ -45,10 +45,10 @@ }; } - promo: FeaturePromoDemoPageInfo|null = null; - showAction: boolean = false; - protected instructionsExpanded_: boolean = false; - protected dataExpanded_: boolean = false; + accessor promo: FeaturePromoDemoPageInfo|null = null; + accessor showAction: boolean = false; + protected accessor instructionsExpanded_: boolean = false; + protected accessor dataExpanded_: boolean = false; protected launchPromo_() { assert(this.promo);
diff --git a/chrome/browser/resources/user_education_internals/user_education_whats_new_internals_card.ts b/chrome/browser/resources/user_education_internals/user_education_whats_new_internals_card.ts index e79ab148..16807fe7 100644 --- a/chrome/browser/resources/user_education_internals/user_education_whats_new_internals_card.ts +++ b/chrome/browser/resources/user_education_internals/user_education_whats_new_internals_card.ts
@@ -42,9 +42,10 @@ }; } - item: WhatsNewModuleDemoPageInfo|WhatsNewEditionDemoPageInfo|null = null; - type: 'module'|'edition'|null = null; - protected dataExpanded_: boolean = false; + accessor item: WhatsNewModuleDemoPageInfo|WhatsNewEditionDemoPageInfo|null = + null; + accessor type: 'module'|'edition'|null = null; + protected accessor dataExpanded_: boolean = false; protected clearData_() { if (confirm(
diff --git a/chrome/browser/resources/webui_gallery/BUILD.gn b/chrome/browser/resources/webui_gallery/BUILD.gn index b5a40f22c..ef5c3d8 100644 --- a/chrome/browser/resources/webui_gallery/BUILD.gn +++ b/chrome/browser/resources/webui_gallery/BUILD.gn
@@ -99,6 +99,7 @@ html_to_wrapper_template = "detect" + ts_tsconfig_base = "//tools/typescript/tsconfig_base_lit_389737066.json" ts_deps = [ "//chrome/browser/resources/side_panel/shared:build_ts", "//third_party/lit/v3_0:build_ts",
diff --git a/chrome/browser/resources/webui_gallery/app.ts b/chrome/browser/resources/webui_gallery/app.ts index 1032c9a..ec15032 100644 --- a/chrome/browser/resources/webui_gallery/app.ts +++ b/chrome/browser/resources/webui_gallery/app.ts
@@ -46,7 +46,7 @@ }; } - protected demos_: Demo[] = [ + protected accessor demos_: Demo[] = [ { name: 'Accessibility Live Regions', path: 'a11y',
diff --git a/chrome/browser/resources/webui_gallery/demos/buttons/buttons_demo.ts b/chrome/browser/resources/webui_gallery/demos/buttons/buttons_demo.ts index b2449d1..c75c19b4 100644 --- a/chrome/browser/resources/webui_gallery/demos/buttons/buttons_demo.ts +++ b/chrome/browser/resources/webui_gallery/demos/buttons/buttons_demo.ts
@@ -33,7 +33,7 @@ }; } - protected expanded_: boolean = false; + protected accessor expanded_: boolean = false; protected onExpandedChanged_(e: CustomEvent<{value: boolean}>) { this.expanded_ = e.detail.value;
diff --git a/chrome/browser/resources/webui_gallery/demos/card/card_demo.ts b/chrome/browser/resources/webui_gallery/demos/card/card_demo.ts index 963002c..a9dcf38f 100644 --- a/chrome/browser/resources/webui_gallery/demos/card/card_demo.ts +++ b/chrome/browser/resources/webui_gallery/demos/card/card_demo.ts
@@ -34,7 +34,7 @@ }; } - protected expanded_: boolean = false; + protected accessor expanded_: boolean = false; protected onExternalLinkClick_() { window.open('https://chromium.org');
diff --git a/chrome/browser/resources/webui_gallery/demos/cr_a11y_announcer/cr_a11y_announcer_demo.ts b/chrome/browser/resources/webui_gallery/demos/cr_a11y_announcer/cr_a11y_announcer_demo.ts index 3bd4280..b780dd0 100644 --- a/chrome/browser/resources/webui_gallery/demos/cr_a11y_announcer/cr_a11y_announcer_demo.ts +++ b/chrome/browser/resources/webui_gallery/demos/cr_a11y_announcer/cr_a11y_announcer_demo.ts
@@ -40,7 +40,7 @@ } private announcementTextCount_: number = 0; - protected forceShowAnnouncer_: boolean = false; + protected accessor forceShowAnnouncer_: boolean = false; protected onAnnounceTextClick_() { const announcer = this.forceShowAnnouncer_ ?
diff --git a/chrome/browser/resources/webui_gallery/demos/cr_action_menu/cr_action_menu_demo.ts b/chrome/browser/resources/webui_gallery/demos/cr_action_menu/cr_action_menu_demo.ts index e3bfaa2..702d18e 100644 --- a/chrome/browser/resources/webui_gallery/demos/cr_action_menu/cr_action_menu_demo.ts +++ b/chrome/browser/resources/webui_gallery/demos/cr_action_menu/cr_action_menu_demo.ts
@@ -42,19 +42,18 @@ alignmentOptions_: {type: Array}, customAlignmentX_: {type: String}, customAlignmentY_: {type: String}, - statusText_: {type: String}, }; } - protected alignmentOptions_: AnchorAlignmentKey[] = [ + protected accessor alignmentOptions_: AnchorAlignmentKey[] = [ 'BEFORE_START', 'AFTER_START', 'CENTER', 'BEFORE_END', 'AFTER_END', ]; - protected customAlignmentX_: AnchorAlignmentKey = 'CENTER'; - protected customAlignmentY_: AnchorAlignmentKey = 'CENTER'; + protected accessor customAlignmentX_: AnchorAlignmentKey = 'CENTER'; + protected accessor customAlignmentY_: AnchorAlignmentKey = 'CENTER'; protected onShowAnchoredMenuClick_(event: MouseEvent) { this.$.menu.showAt(event.target as HTMLElement);
diff --git a/chrome/browser/resources/webui_gallery/demos/cr_checkbox/cr_checkbox_demo.ts b/chrome/browser/resources/webui_gallery/demos/cr_checkbox/cr_checkbox_demo.ts index 7154069..b671ba63a 100644 --- a/chrome/browser/resources/webui_gallery/demos/cr_checkbox/cr_checkbox_demo.ts +++ b/chrome/browser/resources/webui_gallery/demos/cr_checkbox/cr_checkbox_demo.ts
@@ -29,7 +29,7 @@ }; } - protected myValue_?: boolean; + protected accessor myValue_: boolean|undefined; protected onCheckedChanged_(e: CustomEvent<{value: boolean}>) { this.myValue_ = e.detail.value;
diff --git a/chrome/browser/resources/webui_gallery/demos/cr_dialog/cr_dialog_demo.ts b/chrome/browser/resources/webui_gallery/demos/cr_dialog/cr_dialog_demo.ts index 0ff8820..8e34ffb 100644 --- a/chrome/browser/resources/webui_gallery/demos/cr_dialog/cr_dialog_demo.ts +++ b/chrome/browser/resources/webui_gallery/demos/cr_dialog/cr_dialog_demo.ts
@@ -46,13 +46,13 @@ }; } - protected autofocusInput_: boolean = false; - protected isDialogOpen_: boolean = false; - protected showHeader_: boolean = false; - protected showFooter_: boolean = false; - protected showInputs_: boolean = false; - protected showScrollingBody_: boolean = false; - protected statusTexts_: string[] = []; + protected accessor autofocusInput_: boolean = false; + protected accessor isDialogOpen_: boolean = false; + protected accessor showHeader_: boolean = false; + protected accessor showFooter_: boolean = false; + protected accessor showInputs_: boolean = false; + protected accessor showScrollingBody_: boolean = false; + protected accessor statusTexts_: string[] = []; private getDialog_(): CrDialogElement|null { return this.shadowRoot.querySelector('cr-dialog');
diff --git a/chrome/browser/resources/webui_gallery/demos/cr_icons/cr_icons_demo.ts b/chrome/browser/resources/webui_gallery/demos/cr_icons/cr_icons_demo.ts index 701eca5..ba769ca 100644 --- a/chrome/browser/resources/webui_gallery/demos/cr_icons/cr_icons_demo.ts +++ b/chrome/browser/resources/webui_gallery/demos/cr_icons/cr_icons_demo.ts
@@ -37,7 +37,7 @@ }; } - protected crIcons_: string[] = [ + protected accessor crIcons_: string[] = [ 'icon-arrow-back', 'icon-arrow-dropdown', 'icon-cancel', 'icon-clear', 'icon-copy-content', 'icon-delete-gray', 'icon-edit', 'icon-folder-open', 'icon-picture-delete', @@ -46,9 +46,9 @@ 'icon-settings', 'icon-visibility', 'icon-visibility-off', 'subpage-arrow', ]; - protected iconColor_: string = '#000000'; - protected iconSize_: string = '24'; - protected icons_: string[] = []; + protected accessor iconColor_: string = '#000000'; + protected accessor iconSize_: string = '24'; + protected accessor icons_: string[] = []; override firstUpdated() { function getIconNames(iconset: CrIconsetElement) {
diff --git a/chrome/browser/resources/webui_gallery/demos/cr_input/cr_input_demo.ts b/chrome/browser/resources/webui_gallery/demos/cr_input/cr_input_demo.ts index 57a8f7d9..758cce7 100644 --- a/chrome/browser/resources/webui_gallery/demos/cr_input/cr_input_demo.ts +++ b/chrome/browser/resources/webui_gallery/demos/cr_input/cr_input_demo.ts
@@ -43,12 +43,12 @@ }; } - protected emailValue_?: string; - protected numberValue_?: string; - protected pinValue_?: string; - protected searchValue_?: string; - protected textValue_?: string; - protected textareaValue_?: string; + protected accessor emailValue_: string|undefined; + protected accessor numberValue_: string|undefined; + protected accessor pinValue_: string|undefined; + protected accessor searchValue_: string|undefined; + protected accessor textValue_: string|undefined; + protected accessor textareaValue_: string|undefined; protected onClearSearchClick_() { this.searchValue_ = '';
diff --git a/chrome/browser/resources/webui_gallery/demos/cr_radio/cr_radio_demo.ts b/chrome/browser/resources/webui_gallery/demos/cr_radio/cr_radio_demo.ts index c70a1f9..523bf8a4 100644 --- a/chrome/browser/resources/webui_gallery/demos/cr_radio/cr_radio_demo.ts +++ b/chrome/browser/resources/webui_gallery/demos/cr_radio/cr_radio_demo.ts
@@ -30,7 +30,7 @@ }; } - protected selectedRadioOption_?: string; + protected accessor selectedRadioOption_: string|undefined; protected onSelectedRadioOptionChanged_(e: CustomEvent<{value: string}>) { this.selectedRadioOption_ = e.detail.value;
diff --git a/chrome/browser/resources/webui_gallery/demos/cr_slider/cr_slider_demo.ts b/chrome/browser/resources/webui_gallery/demos/cr_slider/cr_slider_demo.ts index 464bc365..bb460fe 100644 --- a/chrome/browser/resources/webui_gallery/demos/cr_slider/cr_slider_demo.ts +++ b/chrome/browser/resources/webui_gallery/demos/cr_slider/cr_slider_demo.ts
@@ -47,17 +47,16 @@ static override get properties() { return { basicValue_: {type: Number}, - disabledTicks_: {type: Array}, showMarkers_: {type: Boolean}, tickedValue_: {type: Number}, ticks_: {type: Array}, }; } - protected basicValue_: number = 5; - protected showMarkers_: boolean = false; - protected tickedValue_: number = 0; - protected ticks_: SliderTick[] = createTicks(0, 5, 5); + protected accessor basicValue_: number = 5; + protected accessor showMarkers_: boolean = false; + protected accessor tickedValue_: number = 0; + protected accessor ticks_: SliderTick[] = createTicks(0, 5, 5); protected getMarkerCount_(): number { if (!this.showMarkers_) {
diff --git a/chrome/browser/resources/webui_gallery/demos/cr_tabs/cr_tabs_demo.ts b/chrome/browser/resources/webui_gallery/demos/cr_tabs/cr_tabs_demo.ts index f98688a6..ccd2e047f 100644 --- a/chrome/browser/resources/webui_gallery/demos/cr_tabs/cr_tabs_demo.ts +++ b/chrome/browser/resources/webui_gallery/demos/cr_tabs/cr_tabs_demo.ts
@@ -38,8 +38,8 @@ }; } - protected selectedTabIndex_: number = 0; - protected tabNames_: string[] = ['Tab 1', 'Tab 2', 'Tab 3']; + protected accessor selectedTabIndex_: number = 0; + protected accessor tabNames_: string[] = ['Tab 1', 'Tab 2', 'Tab 3']; protected onAddClick_() { this.tabNames_.push('Added');
diff --git a/chrome/browser/resources/webui_gallery/demos/cr_toast/cr_toast_demo.ts b/chrome/browser/resources/webui_gallery/demos/cr_toast/cr_toast_demo.ts index 7089199..b9b0144 100644 --- a/chrome/browser/resources/webui_gallery/demos/cr_toast/cr_toast_demo.ts +++ b/chrome/browser/resources/webui_gallery/demos/cr_toast/cr_toast_demo.ts
@@ -42,9 +42,9 @@ }; } - protected duration_: number = 0; - protected message_: string = 'Hello, world'; - protected showDismissButton_: boolean = false; + protected accessor duration_: number = 0; + protected accessor message_: string = 'Hello, world'; + protected accessor showDismissButton_: boolean = false; protected onHideToastClick_() { this.$.toast.hide();
diff --git a/chrome/browser/resources/webui_gallery/demos/cr_toggle/cr_toggle_demo.ts b/chrome/browser/resources/webui_gallery/demos/cr_toggle/cr_toggle_demo.ts index 92ae7027..9cd6b860 100644 --- a/chrome/browser/resources/webui_gallery/demos/cr_toggle/cr_toggle_demo.ts +++ b/chrome/browser/resources/webui_gallery/demos/cr_toggle/cr_toggle_demo.ts
@@ -29,7 +29,7 @@ }; } - protected checked_?: boolean; + protected accessor checked_: boolean|undefined; protected onCheckedChanged_(e: CustomEvent<{value: boolean}>) { this.checked_ = e.detail.value;
diff --git a/chrome/browser/resources/webui_gallery/demos/cr_toolbar/cr_toolbar_demo.ts b/chrome/browser/resources/webui_gallery/demos/cr_toolbar/cr_toolbar_demo.ts index 8e7e59b3..96429ba 100644 --- a/chrome/browser/resources/webui_gallery/demos/cr_toolbar/cr_toolbar_demo.ts +++ b/chrome/browser/resources/webui_gallery/demos/cr_toolbar/cr_toolbar_demo.ts
@@ -40,17 +40,17 @@ }; } - protected alwaysShowLogo_: boolean = true; - protected clearLabel_: string = 'Clear search'; - protected log_: string[] = []; - protected menuLabel_: string = 'Menu'; - protected narrow_?: boolean; - protected narrowThreshold_: number = 1000; - protected pageName_: string = 'Demo'; - protected searchPrompt_: string = 'Search through some content'; - protected showMenu_: boolean = true; - protected showSearch_: boolean = true; - protected showSlottedContent_: boolean = false; + protected accessor alwaysShowLogo_: boolean = true; + protected accessor clearLabel_: string = 'Clear search'; + protected accessor log_: string[] = []; + protected accessor menuLabel_: string = 'Menu'; + protected accessor narrow_: boolean|undefined; + protected accessor narrowThreshold_: number = 1000; + protected accessor pageName_: string = 'Demo'; + protected accessor searchPrompt_: string = 'Search through some content'; + protected accessor showMenu_: boolean = true; + protected accessor showSearch_: boolean = true; + protected accessor showSlottedContent_: boolean = false; protected onMenuClick_() { this.log_.push('Menu tapped.');
diff --git a/chrome/browser/resources/webui_gallery/demos/cr_tooltip/cr_tooltip_demo.ts b/chrome/browser/resources/webui_gallery/demos/cr_tooltip/cr_tooltip_demo.ts index b58b36e..0c4a44a101 100644 --- a/chrome/browser/resources/webui_gallery/demos/cr_tooltip/cr_tooltip_demo.ts +++ b/chrome/browser/resources/webui_gallery/demos/cr_tooltip/cr_tooltip_demo.ts
@@ -43,8 +43,8 @@ } // Default values. - protected tooltipPosition_: TooltipPosition = TooltipPosition.BOTTOM; - protected tooltipOffset_: number = 14; + protected accessor tooltipPosition_: TooltipPosition = TooltipPosition.BOTTOM; + protected accessor tooltipOffset_: number = 14; protected onTooltipPositionChange_(e: Event) { const position = (e.target as HTMLSelectElement).value;
diff --git a/chrome/browser/resources/webui_gallery/demos/md_select/md_select_demo.ts b/chrome/browser/resources/webui_gallery/demos/md_select/md_select_demo.ts index b2229aa..0e31ebb4 100644 --- a/chrome/browser/resources/webui_gallery/demos/md_select/md_select_demo.ts +++ b/chrome/browser/resources/webui_gallery/demos/md_select/md_select_demo.ts
@@ -33,7 +33,7 @@ }; } - protected selectedOption_: string = 'two'; + protected accessor selectedOption_: string = 'two'; protected onSelectValueChanged_() { this.selectedOption_ = this.$.select.value;
diff --git a/chrome/browser/resources/webui_gallery/demos/nav_menu/nav_menu.ts b/chrome/browser/resources/webui_gallery/demos/nav_menu/nav_menu.ts index bf7c075e..2e9f412 100644 --- a/chrome/browser/resources/webui_gallery/demos/nav_menu/nav_menu.ts +++ b/chrome/browser/resources/webui_gallery/demos/nav_menu/nav_menu.ts
@@ -48,26 +48,27 @@ }; } - protected menuItems_: Array<{icon: string, name: string, path: string}> = [ - { - icon: 'cr:person', - name: 'Menu item 1', - path: '/path-1', - }, - { - icon: 'cr:sync', - name: 'Menu item 2', - path: '/path-2', - }, - { - icon: 'cr:star', - name: 'Menu item 3', - path: '/path-3', - }, - ]; - selectedIndex?: number; - showIcons: boolean = false; - showRipples: boolean = false; + protected accessor menuItems_: + Array<{icon: string, name: string, path: string}> = [ + { + icon: 'cr:person', + name: 'Menu item 1', + path: '/path-1', + }, + { + icon: 'cr:sync', + name: 'Menu item 2', + path: '/path-2', + }, + { + icon: 'cr:star', + name: 'Menu item 3', + path: '/path-3', + }, + ]; + accessor selectedIndex: number|undefined; + accessor showIcons: boolean = false; + accessor showRipples: boolean = false; protected onSelectorClick_(e: MouseEvent) { e.preventDefault();
diff --git a/chrome/browser/resources/webui_gallery/demos/nav_menu/nav_menu_demo.ts b/chrome/browser/resources/webui_gallery/demos/nav_menu/nav_menu_demo.ts index 8d7f682..2b320a2 100644 --- a/chrome/browser/resources/webui_gallery/demos/nav_menu/nav_menu_demo.ts +++ b/chrome/browser/resources/webui_gallery/demos/nav_menu/nav_menu_demo.ts
@@ -42,10 +42,10 @@ }; } - protected isDrawerOpen_: boolean = false; - protected selectedIndex_?: number; - protected showIcons_: boolean = true; - protected showRipples_: boolean = true; + protected accessor isDrawerOpen_: boolean = false; + protected accessor selectedIndex_: number|undefined; + protected accessor showIcons_: boolean = true; + protected accessor showRipples_: boolean = true; protected showDrawerMenu_() { this.$.drawer.openDrawer();
diff --git a/chrome/browser/resources/webui_gallery/demos/scroll_view/scroll_view_demo.ts b/chrome/browser/resources/webui_gallery/demos/scroll_view/scroll_view_demo.ts index 0a014849..b41cbf2 100644 --- a/chrome/browser/resources/webui_gallery/demos/scroll_view/scroll_view_demo.ts +++ b/chrome/browser/resources/webui_gallery/demos/scroll_view/scroll_view_demo.ts
@@ -38,7 +38,7 @@ }; } - protected items_: number[] = [0, 1, 2, 3]; + protected accessor items_: number[] = [0, 1, 2, 3]; protected onItemsLengthChanged_() { const length = this.$.itemsLengthSlider.value;
diff --git a/chrome/browser/resources/webui_gallery/demos/side_panel/sp_components_demo.ts b/chrome/browser/resources/webui_gallery/demos/side_panel/sp_components_demo.ts index ff13c39a..585f5b3 100644 --- a/chrome/browser/resources/webui_gallery/demos/side_panel/sp_components_demo.ts +++ b/chrome/browser/resources/webui_gallery/demos/side_panel/sp_components_demo.ts
@@ -59,16 +59,16 @@ }; } - protected hideBackButton_: boolean = true; - protected itemSize_: CrUrlListItemSize = CrUrlListItemSize.COMPACT; - protected itemSizeOptions_: CrUrlListItemSize[] = [ + protected accessor hideBackButton_: boolean = true; + protected accessor itemSize_: CrUrlListItemSize = CrUrlListItemSize.COMPACT; + protected accessor itemSizeOptions_: CrUrlListItemSize[] = [ CrUrlListItemSize.COMPACT, CrUrlListItemSize.MEDIUM, CrUrlListItemSize.LARGE, ]; - protected showBadges_: boolean = false; - protected urlCount_: number = 15; - protected urls_: UrlItem[] = []; + protected accessor showBadges_: boolean = false; + protected accessor urlCount_: number = 15; + protected accessor urls_: UrlItem[] = []; override willUpdate(changedProperties: PropertyValues<this>) { super.willUpdate(changedProperties);
diff --git a/chrome/browser/resources/whats_new/BUILD.gn b/chrome/browser/resources/whats_new/BUILD.gn index c7505e0..63ee3e3 100644 --- a/chrome/browser/resources/whats_new/BUILD.gn +++ b/chrome/browser/resources/whats_new/BUILD.gn
@@ -14,6 +14,7 @@ ] css_files = [ "whats_new_app.css" ] + ts_tsconfig_base = "//tools/typescript/tsconfig_base_lit_389737066.json" ts_composite = true ts_deps = [ "//third_party/lit/v3_0:build_ts",
diff --git a/chrome/browser/resources/whats_new/whats_new_app.ts b/chrome/browser/resources/whats_new/whats_new_app.ts index ea181dc5..a504064d 100644 --- a/chrome/browser/resources/whats_new/whats_new_app.ts +++ b/chrome/browser/resources/whats_new/whats_new_app.ts
@@ -365,7 +365,7 @@ }; } - protected url_: string = ''; + protected accessor url_: string = ''; private isAutoOpen_: boolean = false; private eventTracker_: EventTracker = new EventTracker();
diff --git a/chrome/browser/safe_browsing/android/BUILD.gn b/chrome/browser/safe_browsing/android/BUILD.gn index 947aef5..7adfb06 100644 --- a/chrome/browser/safe_browsing/android/BUILD.gn +++ b/chrome/browser/safe_browsing/android/BUILD.gn
@@ -44,6 +44,8 @@ android_library("java") { sources = [ + "java/src/org/chromium/chrome/browser/safe_browsing/AdvancedProtectionCoordinator.java", + "java/src/org/chromium/chrome/browser/safe_browsing/AdvancedProtectionMediator.java", "java/src/org/chromium/chrome/browser/safe_browsing/SafeBrowsingBridge.java", "java/src/org/chromium/chrome/browser/safe_browsing/settings/EnhancedProtectionSettingsFragment.java", "java/src/org/chromium/chrome/browser/safe_browsing/settings/NoProtectionConfirmationDialog.java", @@ -55,6 +57,7 @@ deps = [ ":java_resources", "//base:base_java", + "//base:supplier_java", "//build/android:build_java", "//chrome/browser/feedback/android:java", "//chrome/browser/flags:java", @@ -65,6 +68,9 @@ "//components/browser_ui/settings/android:java", "//components/browser_ui/util/android:java", "//components/browser_ui/widget/android:java", + "//components/messages/android:java", + "//components/permissions/android:core_java", + "//components/permissions/android:java", "//components/prefs/android:java", "//components/user_prefs/android:java", "//content/public/android:content_java", @@ -129,6 +135,28 @@ ] } +robolectric_library("junit") { + sources = [ "java/src/org/chromium/chrome/browser/safe_browsing/AdvancedProtectionMediatorTest.java" ] + deps = [ + ":java", + "//base:base_java_test_support", + "//base:base_junit_test_support", + "//base:base_shared_preferences_java", + "//base:service_loader_java", + "//base:unowned_user_data_java", + "//chrome/browser/preferences:java", + "//components/messages/android:factory_java", + "//components/messages/android:java", + "//components/messages/android:manager_java", + "//components/permissions/android:core_java", + "//components/permissions/android:java", + "//third_party/androidx:androidx_annotation_annotation_java", + "//third_party/junit", + "//third_party/mockito:mockito_java", + "//ui/android:ui_java", + ] +} + android_resources("java_resources") { sources = [ "java/res/layout/radio_button_group_safe_browsing_preference.xml",
diff --git a/chrome/browser/safe_browsing/android/java/src/org/chromium/chrome/browser/safe_browsing/AdvancedProtectionCoordinator.java b/chrome/browser/safe_browsing/android/java/src/org/chromium/chrome/browser/safe_browsing/AdvancedProtectionCoordinator.java new file mode 100644 index 0000000..7df5e8a --- /dev/null +++ b/chrome/browser/safe_browsing/android/java/src/org/chromium/chrome/browser/safe_browsing/AdvancedProtectionCoordinator.java
@@ -0,0 +1,30 @@ +// Copyright 2025 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.safe_browsing; + +import org.chromium.ui.base.WindowAndroid; + +/** A class for showing UI whenever the Android-OS-supplied advanced-protection state changes. */ +public class AdvancedProtectionCoordinator { + private AdvancedProtectionMediator mMediator; + + public AdvancedProtectionCoordinator(WindowAndroid windowAndroid) { + mMediator = new AdvancedProtectionMediator(windowAndroid); + } + + public void destroy() { + mMediator.destroy(); + } + + /** + * Shows message-UI informing the user about the Android-OS requested advanced-protection state + * if the advanced-protection state has changed since Chrome was last open. + * + * @return whether message-UI was shown. + */ + public boolean showMessageOnStartupIfNeeded() { + return mMediator.showMessageOnStartupIfNeeded(); + } +}
diff --git a/chrome/browser/safe_browsing/android/java/src/org/chromium/chrome/browser/safe_browsing/AdvancedProtectionMediator.java b/chrome/browser/safe_browsing/android/java/src/org/chromium/chrome/browser/safe_browsing/AdvancedProtectionMediator.java new file mode 100644 index 0000000..66bee182 --- /dev/null +++ b/chrome/browser/safe_browsing/android/java/src/org/chromium/chrome/browser/safe_browsing/AdvancedProtectionMediator.java
@@ -0,0 +1,93 @@ +// Copyright 2025 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.safe_browsing; + +import static org.chromium.build.NullUtil.assumeNonNull; + +import androidx.annotation.NonNull; + +import org.chromium.chrome.browser.preferences.ChromePreferenceKeys; +import org.chromium.chrome.browser.preferences.ChromeSharedPreferences; +import org.chromium.components.messages.MessageDispatcherProvider; +import org.chromium.components.permissions.OsAdditionalSecurityPermissionProvider; +import org.chromium.components.permissions.OsAdditionalSecurityPermissionUtil; +import org.chromium.components.permissions.PermissionsAndroidFeatureList; +import org.chromium.components.permissions.PermissionsAndroidFeatureMap; +import org.chromium.ui.base.WindowAndroid; + +/** A class for showing UI whenever the Android-OS-supplied advanced-protection state changes. */ +public class AdvancedProtectionMediator implements OsAdditionalSecurityPermissionProvider.Observer { + private WindowAndroid mWindowAndroid; + + public AdvancedProtectionMediator(WindowAndroid windowAndroid) { + mWindowAndroid = windowAndroid; + + var provider = OsAdditionalSecurityPermissionUtil.getProviderInstance(); + if (provider != null + && !PermissionsAndroidFeatureMap.isEnabled( + PermissionsAndroidFeatureList + .OS_ADDITIONAL_SECURITY_PERMISSION_KILL_SWITCH)) { + provider.addObserver(this); + } + } + + public void destroy() { + var provider = OsAdditionalSecurityPermissionUtil.getProviderInstance(); + if (provider != null) { + provider.removeObserver(this); + } + } + + public boolean showMessageOnStartupIfNeeded() { + if (PermissionsAndroidFeatureMap.isEnabled( + PermissionsAndroidFeatureList.OS_ADDITIONAL_SECURITY_PERMISSION_KILL_SWITCH)) { + return false; + } + + var provider = OsAdditionalSecurityPermissionUtil.getProviderInstance(); + if (provider == null) return false; + + boolean cachedAdvancedProtectionSetting = + ChromeSharedPreferences.getInstance() + .readBoolean( + ChromePreferenceKeys.DEFAULT_OS_ADVANCED_PROTECTION_SETTING, + /* defaultValue= */ false); + if (cachedAdvancedProtectionSetting == provider.isAdvancedProtectionRequestedByOs()) { + return false; + } + + updatePref(provider); + enqueueMessage(provider); + return true; + } + + @Override + public void onAdvancedProtectionOsSettingChanged() { + var provider = OsAdditionalSecurityPermissionUtil.getProviderInstance(); + if (provider == null) return; + + updatePref(provider); + enqueueMessage(provider); + } + + private void enqueueMessage(@NonNull OsAdditionalSecurityPermissionProvider provider) { + var context = assumeNonNull(mWindowAndroid.getContext()).get(); + var propertyModel = + provider.buildAdvancedProtectionMessagePropertyModel( + context, /* primaryButtonAction= */ null); + if (propertyModel == null) { + return; + } + MessageDispatcherProvider.from(mWindowAndroid) + .enqueueWindowScopedMessage(propertyModel, /* highPriority= */ false); + } + + private void updatePref(@NonNull OsAdditionalSecurityPermissionProvider provider) { + ChromeSharedPreferences.getInstance() + .writeBoolean( + ChromePreferenceKeys.DEFAULT_OS_ADVANCED_PROTECTION_SETTING, + provider.isAdvancedProtectionRequestedByOs()); + } +}
diff --git a/chrome/browser/safe_browsing/android/java/src/org/chromium/chrome/browser/safe_browsing/AdvancedProtectionMediatorTest.java b/chrome/browser/safe_browsing/android/java/src/org/chromium/chrome/browser/safe_browsing/AdvancedProtectionMediatorTest.java new file mode 100644 index 0000000..05f2cb33 --- /dev/null +++ b/chrome/browser/safe_browsing/android/java/src/org/chromium/chrome/browser/safe_browsing/AdvancedProtectionMediatorTest.java
@@ -0,0 +1,226 @@ +// Copyright 2025 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.safe_browsing; + +import static org.junit.Assert.assertFalse; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import android.content.Context; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.robolectric.annotation.Config; + +import org.chromium.base.ContextUtils; +import org.chromium.base.ServiceLoaderUtil; +import org.chromium.base.ThreadUtils; +import org.chromium.base.UnownedUserDataHost; +import org.chromium.base.test.BaseRobolectricTestRunner; +import org.chromium.base.test.util.Features.DisableFeatures; +import org.chromium.base.test.util.Features.EnableFeatures; +import org.chromium.build.annotations.Nullable; +import org.chromium.chrome.browser.preferences.ChromePreferenceKeys; +import org.chromium.chrome.browser.preferences.ChromeSharedPreferences; +import org.chromium.components.messages.ManagedMessageDispatcher; +import org.chromium.components.messages.MessagesFactory; +import org.chromium.components.permissions.OsAdditionalSecurityPermissionProvider; +import org.chromium.components.permissions.OsAdditionalSecurityPermissionUtil; +import org.chromium.components.permissions.PermissionsAndroidFeatureList; +import org.chromium.ui.base.WindowAndroid; +import org.chromium.ui.modelutil.PropertyModel; + +import java.lang.ref.WeakReference; + +/** Tests for {@link AdvancedProtectionMediator}. */ +@RunWith(BaseRobolectricTestRunner.class) +@DisableFeatures(PermissionsAndroidFeatureList.OS_ADDITIONAL_SECURITY_PERMISSION_KILL_SWITCH) +@Config(manifest = Config.NONE) +public class AdvancedProtectionMediatorTest { + @Mock private WindowAndroid mWindowAndroid; + @Mock private Context mContext; + private WeakReference<Context> mWeakContext = new WeakReference<Context>(mContext); + private final UnownedUserDataHost mWindowUserDataHost = new UnownedUserDataHost(); + + @Mock private ManagedMessageDispatcher mMessageDispatcher; + + private static class TestPermissionProvider extends OsAdditionalSecurityPermissionProvider { + private boolean mIsAdvancedProtectionRequestedByOs; + private Observer mObserver; + + public TestPermissionProvider(boolean isAdvancedProtectionRequestedByOs) { + mIsAdvancedProtectionRequestedByOs = isAdvancedProtectionRequestedByOs; + } + + @Override + public void addObserver(Observer observer) { + assert mObserver == null; + mObserver = observer; + } + + @Override + public boolean isAdvancedProtectionRequestedByOs() { + return mIsAdvancedProtectionRequestedByOs; + } + + @Override + public @Nullable PropertyModel buildAdvancedProtectionMessagePropertyModel( + Context context, Runnable primaryButtonAction) { + return new PropertyModel(); + } + + public void setAdvancedProtectionRequestedByOs(boolean isAdvancedProtectionRequestedByOs) { + mIsAdvancedProtectionRequestedByOs = isAdvancedProtectionRequestedByOs; + if (mObserver != null) { + mObserver.onAdvancedProtectionOsSettingChanged(); + } + } + } + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + when(mWindowAndroid.getUnownedUserDataHost()).thenReturn(mWindowUserDataHost); + when(mWindowAndroid.getContext()).thenReturn(mWeakContext); + MessagesFactory.attachMessageDispatcher(mWindowAndroid, mMessageDispatcher); + + ContextUtils.getAppSharedPreferences().edit().clear(); + OsAdditionalSecurityPermissionUtil.resetForTesting(); + } + + private TestPermissionProvider setPermissionProvider( + boolean isAdvancedProtectionRequestedByOs) { + var provider = new TestPermissionProvider(isAdvancedProtectionRequestedByOs); + ThreadUtils.runOnUiThreadBlocking( + () -> { + ServiceLoaderUtil.setInstanceForTesting( + OsAdditionalSecurityPermissionProvider.class, provider); + }); + return provider; + } + + private void verifyEnqueuedMessage() { + verify(mMessageDispatcher, times(1)).enqueueWindowScopedMessage(any(), anyBoolean()); + } + + private void verifyDidNotEnqueueMessage() { + verify(mMessageDispatcher, times(0)).enqueueWindowScopedMessage(any(), anyBoolean()); + } + + /** + * Test that {@link AdvancedProtectionCoordinator#showMessageOnStartupIfNeeded()} does not show + * a message if the pref is not stored and advanced-protection-mode is off. + */ + @Test + public void testDontShowMessageNoPrefAdvancedProtectionOff() { + setPermissionProvider(/* isAdvancedProtectionRequestedByOs= */ false); + + var coordinator = new AdvancedProtectionCoordinator(mWindowAndroid); + coordinator.showMessageOnStartupIfNeeded(); + verifyDidNotEnqueueMessage(); + + coordinator.destroy(); + } + + /** + * Test that {@link AdvancedProtectionCoordinator#showMessageOnStartupIfNeeded()} shows a + * message if the pref is not stored and advanced-protection-mode is on. + */ + @Test + public void testShowMessageNoPrefAdvancedProtectionOn() { + setPermissionProvider(/* isAdvancedProtectionRequestedByOs= */ true); + + var coordinator = new AdvancedProtectionCoordinator(mWindowAndroid); + coordinator.showMessageOnStartupIfNeeded(); + verifyEnqueuedMessage(); + + coordinator.destroy(); + } + + /** + * Test that {@link AdvancedProtectionCoordinator#showMessageOnStartupIfNeeded()} does not show + * a message if a pref is stored and its value matches the current advanced-protection-mode + * state. + */ + @Test + public void testDontShowMessagePrefMatches() { + ChromeSharedPreferences.getInstance() + .writeBoolean(ChromePreferenceKeys.DEFAULT_OS_ADVANCED_PROTECTION_SETTING, true); + setPermissionProvider(/* isAdvancedProtectionRequestedByOs= */ true); + + var coordinator = new AdvancedProtectionCoordinator(mWindowAndroid); + coordinator.showMessageOnStartupIfNeeded(); + verifyDidNotEnqueueMessage(); + + coordinator.destroy(); + } + + /** + * Test that {@link AdvancedProtectionCoordinator#showMessageOnStartupIfNeeded()} shows a + * message if a pref is stored and its value does not match the current advanced-protection-mode + * state. + */ + @Test + public void testShowMessagePrefDiffers() { + var sharedPreferences = ChromeSharedPreferences.getInstance(); + sharedPreferences.writeBoolean( + ChromePreferenceKeys.DEFAULT_OS_ADVANCED_PROTECTION_SETTING, true); + setPermissionProvider(/* isAdvancedProtectionRequestedByOs= */ false); + + var coordinator = new AdvancedProtectionCoordinator(mWindowAndroid); + coordinator.showMessageOnStartupIfNeeded(); + verifyEnqueuedMessage(); + + assertFalse( + sharedPreferences.readBoolean( + ChromePreferenceKeys.DEFAULT_OS_ADVANCED_PROTECTION_SETTING, + /* defaultValue= */ false)); + + coordinator.destroy(); + } + + /** + * Test that message is shown when advanced-protection-state is changed while Chrome is running. + */ + @Test + public void testShowMessageOnStateChange() { + var sharedPreferences = ChromeSharedPreferences.getInstance(); + sharedPreferences.writeBoolean( + ChromePreferenceKeys.DEFAULT_OS_ADVANCED_PROTECTION_SETTING, true); + var provider = setPermissionProvider(/* isAdvancedProtectionRequestedByOs= */ true); + + var coordinator = new AdvancedProtectionCoordinator(mWindowAndroid); + coordinator.showMessageOnStartupIfNeeded(); + verifyDidNotEnqueueMessage(); + provider.setAdvancedProtectionRequestedByOs(/* isAdvancedProtectionRequestedByOs= */ false); + verifyEnqueuedMessage(); + + coordinator.destroy(); + } + + /** Test that a message is not shown when the feature-kill-switch is set. */ + @Test + @EnableFeatures({PermissionsAndroidFeatureList.OS_ADDITIONAL_SECURITY_PERMISSION_KILL_SWITCH}) + public void testDontShowMessageKillSwitch() { + var sharedPreferences = ChromeSharedPreferences.getInstance(); + sharedPreferences.writeBoolean( + ChromePreferenceKeys.DEFAULT_OS_ADVANCED_PROTECTION_SETTING, true); + var provider = setPermissionProvider(/* isAdvancedProtectionRequestedByOs= */ false); + + var coordinator = new AdvancedProtectionCoordinator(mWindowAndroid); + coordinator.showMessageOnStartupIfNeeded(); + verifyDidNotEnqueueMessage(); + provider.setAdvancedProtectionRequestedByOs(/* isAdvancedProtectionRequestedByOs= */ true); + verifyDidNotEnqueueMessage(); + + coordinator.destroy(); + } +}
diff --git a/chrome/browser/signin/bound_session_credentials/fake_keyed_unexportable_key_service.cc b/chrome/browser/signin/bound_session_credentials/fake_keyed_unexportable_key_service.cc index 337f4c4..4b8e77e 100644 --- a/chrome/browser/signin/bound_session_credentials/fake_keyed_unexportable_key_service.cc +++ b/chrome/browser/signin/bound_session_credentials/fake_keyed_unexportable_key_service.cc
@@ -35,6 +35,7 @@ const unexportable_keys::UnexportableKeyId& key_id, base::span<const uint8_t> data, unexportable_keys::BackgroundTaskPriority priority, + size_t max_retries, base::OnceCallback<void( unexportable_keys::ServiceErrorOr<std::vector<uint8_t>>)> callback) { std::move(callback).Run(
diff --git a/chrome/browser/signin/bound_session_credentials/fake_keyed_unexportable_key_service.h b/chrome/browser/signin/bound_session_credentials/fake_keyed_unexportable_key_service.h index 3c5e6b6..c1665498 100644 --- a/chrome/browser/signin/bound_session_credentials/fake_keyed_unexportable_key_service.h +++ b/chrome/browser/signin/bound_session_credentials/fake_keyed_unexportable_key_service.h
@@ -29,6 +29,7 @@ const unexportable_keys::UnexportableKeyId& key_id, base::span<const uint8_t> data, unexportable_keys::BackgroundTaskPriority priority, + size_t max_retries, base::OnceCallback<void( unexportable_keys::ServiceErrorOr<std::vector<uint8_t>>)> callback) override;
diff --git a/chrome/browser/signin/bound_session_credentials/fake_keyed_unexportable_key_service_unittest.cc b/chrome/browser/signin/bound_session_credentials/fake_keyed_unexportable_key_service_unittest.cc index 3337961..90e16f5 100644 --- a/chrome/browser/signin/bound_session_credentials/fake_keyed_unexportable_key_service_unittest.cc +++ b/chrome/browser/signin/bound_session_credentials/fake_keyed_unexportable_key_service_unittest.cc
@@ -86,7 +86,7 @@ FakeKeyedUnexportableKeyService fake_service; unexportable_keys::UnexportableKeyId key_id; std::vector<uint8_t> data = {1, 2, 3}; - fake_service.SignSlowlyAsync(key_id, data, kTaskPriority, + fake_service.SignSlowlyAsync(key_id, data, kTaskPriority, /*max_retries=*/0, future.GetCallback()); EXPECT_TRUE(future.IsReady());
diff --git a/chrome/browser/signin/bound_session_credentials/keyed_unexportable_key_service_impl.cc b/chrome/browser/signin/bound_session_credentials/keyed_unexportable_key_service_impl.cc index 5ce9186..31a4ac2 100644 --- a/chrome/browser/signin/bound_session_credentials/keyed_unexportable_key_service_impl.cc +++ b/chrome/browser/signin/bound_session_credentials/keyed_unexportable_key_service_impl.cc
@@ -37,10 +37,11 @@ const unexportable_keys::UnexportableKeyId& key_id, base::span<const uint8_t> data, unexportable_keys::BackgroundTaskPriority priority, + size_t max_retries, base::OnceCallback<void( unexportable_keys::ServiceErrorOr<std::vector<uint8_t>>)> callback) { key_service_implementation_.SignSlowlyAsync(key_id, data, priority, - std::move(callback)); + max_retries, std::move(callback)); } unexportable_keys::ServiceErrorOr<std::vector<uint8_t>>
diff --git a/chrome/browser/signin/bound_session_credentials/keyed_unexportable_key_service_impl.h b/chrome/browser/signin/bound_session_credentials/keyed_unexportable_key_service_impl.h index dfe9bb6..a3aabfd 100644 --- a/chrome/browser/signin/bound_session_credentials/keyed_unexportable_key_service_impl.h +++ b/chrome/browser/signin/bound_session_credentials/keyed_unexportable_key_service_impl.h
@@ -39,6 +39,7 @@ const unexportable_keys::UnexportableKeyId& key_id, base::span<const uint8_t> data, unexportable_keys::BackgroundTaskPriority priority, + size_t max_retries, base::OnceCallback<void( unexportable_keys::ServiceErrorOr<std::vector<uint8_t>>)> callback) override;
diff --git a/chrome/browser/signin/bound_session_credentials/registration_token_helper.cc b/chrome/browser/signin/bound_session_credentials/registration_token_helper.cc index fc27a68..3b0aa793 100644 --- a/chrome/browser/signin/bound_session_credentials/registration_token_helper.cc +++ b/chrome/browser/signin/bound_session_credentials/registration_token_helper.cc
@@ -127,6 +127,7 @@ unexportable_key_service_->SignSlowlyAsync( *binding_key, base::as_byte_span(*header_and_payload), kTaskPriority, + /*max_retries=*/0, base::BindOnce(&RegistrationTokenHelper::CreateRegistrationToken, weak_ptr_factory_.GetWeakPtr(), std::string(*header_and_payload), *binding_key,
diff --git a/chrome/browser/signin/bound_session_credentials/session_binding_helper.cc b/chrome/browser/signin/bound_session_credentials/session_binding_helper.cc index 67e15fe..a60b5caa 100644 --- a/chrome/browser/signin/bound_session_credentials/session_binding_helper.cc +++ b/chrome/browser/signin/bound_session_credentials/session_binding_helper.cc
@@ -128,7 +128,7 @@ unexportable_key_service_->SignSlowlyAsync( *binding_key, base::as_byte_span(*header_and_payload), - kSessionBindingPriority, + kSessionBindingPriority, /*max_retries=*/0, base::BindOnce(&CreateAssertionToken, *header_and_payload, algorithm, std::move(public_key)) .Then(std::move(callback)));
diff --git a/chrome/browser/signin/bound_session_credentials/session_binding_helper_unittest.cc b/chrome/browser/signin/bound_session_credentials/session_binding_helper_unittest.cc index 6de1d267..7bf7241 100644 --- a/chrome/browser/signin/bound_session_credentials/session_binding_helper_unittest.cc +++ b/chrome/browser/signin/bound_session_credentials/session_binding_helper_unittest.cc
@@ -166,7 +166,8 @@ EXPECT_CALL(mock_unexportable_key_service, FromWrappedSigningKeySlowlyAsync(base::span(wrapped_key), _, _)) .WillOnce(RunOnceCallback<2>(key_id)); - EXPECT_CALL(mock_unexportable_key_service, SignSlowlyAsync(key_id, _, _, _)) + EXPECT_CALL(mock_unexportable_key_service, + SignSlowlyAsync(key_id, _, _, _, _)) .WillOnce(Invoke( &unexportable_key_service(), &unexportable_keys::UnexportableKeyService::SignSlowlyAsync));
diff --git a/chrome/browser/ui/ash/birch/birch_most_visited_provider_unittest.cc b/chrome/browser/ui/ash/birch/birch_most_visited_provider_unittest.cc index b212d20..c4160bd9 100644 --- a/chrome/browser/ui/ash/birch/birch_most_visited_provider_unittest.cc +++ b/chrome/browser/ui/ash/birch/birch_most_visited_provider_unittest.cc
@@ -29,7 +29,9 @@ base::CancelableTaskTracker::TaskId QueryMostVisitedURLs( int result_count, QueryMostVisitedURLsCallback callback, - base::CancelableTaskTracker* tracker) override { + base::CancelableTaskTracker* tracker, + const std::optional<std::string>& recency_factor_name, + std::optional<size_t> recency_window_days) override { did_query_most_visited_urls_ = true; return base::CancelableTaskTracker::TaskId(); }
diff --git a/chrome/browser/ui/autofill/autofill_popup_controller_impl.cc b/chrome/browser/ui/autofill/autofill_popup_controller_impl.cc index 5b230bb..831d745 100644 --- a/chrome/browser/ui/autofill/autofill_popup_controller_impl.cc +++ b/chrome/browser/ui/autofill/autofill_popup_controller_impl.cc
@@ -23,7 +23,6 @@ #include "base/task/sequenced_task_runner.h" #include "base/time/time.h" #include "build/build_config.h" -#include "chrome/browser/accessibility/accessibility_state_utils.h" #include "chrome/browser/ui/autofill/autofill_popup_view.h" #include "chrome/browser/ui/autofill/autofill_suggestion_controller_utils.h" #include "chrome/browser/ui/autofill/next_idle_barrier.h"
diff --git a/chrome/browser/ui/autofill/autofill_suggestion_controller_unittest.cc b/chrome/browser/ui/autofill/autofill_suggestion_controller_unittest.cc index 91a3fc8..5390f87 100644 --- a/chrome/browser/ui/autofill/autofill_suggestion_controller_unittest.cc +++ b/chrome/browser/ui/autofill/autofill_suggestion_controller_unittest.cc
@@ -17,7 +17,6 @@ #include "base/test/task_environment.h" #include "base/time/time.h" #include "build/build_config.h" -#include "chrome/browser/accessibility/accessibility_state_utils.h" #include "chrome/browser/ui/autofill/autofill_popup_controller_impl.h" #include "chrome/browser/ui/autofill/autofill_popup_view.h" #include "chrome/browser/ui/autofill/autofill_suggestion_controller_test_base.h"
diff --git a/chrome/browser/ui/browser_actions.cc b/chrome/browser/ui/browser_actions.cc index 697050b..a97d2a1 100644 --- a/chrome/browser/ui/browser_actions.cc +++ b/chrome/browser/ui/browser_actions.cc
@@ -319,6 +319,7 @@ kPerformanceSpeedometerIcon, ui::kColorIcon, ui::SimpleMenuModel::kDefaultIconSize)) .SetEnabled(true) + .SetProperty(views::kElementIdentifierKey, kMemorySaverChipElementId) .Build()); root_action_item_->AddChild(
diff --git a/chrome/browser/ui/browser_navigator_browsertest.cc b/chrome/browser/ui/browser_navigator_browsertest.cc index da9efd6a..7307eee 100644 --- a/chrome/browser/ui/browser_navigator_browsertest.cc +++ b/chrome/browser/ui/browser_navigator_browsertest.cc
@@ -75,6 +75,10 @@ #include "ui/display/test/display_manager_test_api.h" #endif // BUILDFLAG(IS_CHROMEOS) +#if BUILDFLAG(IS_OZONE) +#include "ui/ozone/public/ozone_platform.h" +#endif + using content::WebContents; namespace { @@ -2822,6 +2826,19 @@ Navigate(¶ms); // The PiP window should also be on display 2. +#if BUILDFLAG(IS_OZONE) + if (!ui::OzonePlatform::GetInstance() + ->GetPlatformProperties() + .supports_global_screen_coordinates) { + // Since we cannot get the global coordinates of the window, check + // if the window is in the correct display without relying on bounds. + const auto pip_window_display = + display::Screen::GetScreen()->GetDisplayNearestWindow( + params.browser->window()->GetNativeWindow()); + ASSERT_EQ(display2.id(), pip_window_display.id()); + return; + } +#endif EXPECT_TRUE( display2.work_area().Contains(params.browser->window()->GetBounds())); }
diff --git a/chrome/browser/ui/lens/lens_overlay_controller.cc b/chrome/browser/ui/lens/lens_overlay_controller.cc index 0780ecb..161712d 100644 --- a/chrome/browser/ui/lens/lens_overlay_controller.cc +++ b/chrome/browser/ui/lens/lens_overlay_controller.cc
@@ -493,7 +493,8 @@ // not overlay UI, this flow does a lot of unnecessary work. There should be // a new flow that can contextualize without the overlay UI being // initialized. - ShowUI(lens::LensOverlayInvocationSource::kOmnibox); + StartContextualizationWithoutOverlay( + lens::LensOverlayInvocationSource::kOmnibox); } // Hold the request until the overlay has finished initializing. @@ -511,6 +512,12 @@ OnSuggestionAccepted(destination_url, match_type, is_zero_prefix_suggestion); } +void LensOverlayController::StartContextualizationWithoutOverlay( + lens::LensOverlayInvocationSource invocation_source) { + should_show_overlay_ = false; + ShowUI(invocation_source); +} + void LensOverlayController::ShowUIWithPendingRegion( lens::LensOverlayInvocationSource invocation_source, const gfx::Rect& tab_bounds, @@ -536,8 +543,7 @@ } void LensOverlayController::ShowUI( - lens::LensOverlayInvocationSource invocation_source, - bool should_start_focused) { + lens::LensOverlayInvocationSource invocation_source) { // If UI is already showing or in the process of showing, do nothing. if (state_ != State::kOff) { return; @@ -555,7 +561,6 @@ } invocation_source_ = invocation_source; - should_start_focused_ = should_start_focused; // Request user permission before grabbing a screenshot. CHECK(pref_service_); @@ -573,8 +578,7 @@ permission_bubble_controller_->RequestPermission( tab_->GetContents(), base::BindRepeating(&LensOverlayController::ShowUI, - weak_factory_.GetWeakPtr(), invocation_source, - should_start_focused)); + weak_factory_.GetWeakPtr(), invocation_source)); return; } @@ -2244,10 +2248,16 @@ // Grab the tab contents web view and disable mouse and keyboard inputs to it. auto* contents_web_view = tab_->GetBrowserWindowInterface()->GetWebView(); CHECK(contents_web_view); - contents_web_view->SetEnabled(false); + if (should_show_overlay_) { + contents_web_view->SetEnabled(false); + } // If the view already exists, we just need to reshow it. if (overlay_view_) { + // Exit early to avoid reshowing the overlay if it should not be shown. + if (!should_show_overlay_) { + return; + } // Restore the state to show the overlay. overlay_view_->SetVisible(true); preselection_widget_anchor_->SetVisible(true); @@ -2262,9 +2272,11 @@ return; } - // Create the views that will house our UI. + // Create the views that will house our UI. The overlay view might not + // actually be shown, as dictated by `should_show_overlay_`. It still needs to + // be created so the initialization process completes. overlay_view_ = CreateViewForOverlay(); - overlay_view_->SetVisible(true); + overlay_view_->SetVisible(should_show_overlay_); // Sanity check that the overlay view is above the contents web view. auto* parent_view = contents_web_view->parent(); @@ -2276,7 +2288,7 @@ // The overlay needs to be focused on show to immediately begin // receiving key events. - if (should_start_focused_) { + if (should_show_overlay_) { CHECK(overlay_web_view_); overlay_web_view_->RequestFocus(); } @@ -2413,6 +2425,7 @@ } lens_selection_type_ = lens::UNKNOWN_SELECTION_TYPE; + should_show_overlay_ = true; state_ = State::kOff; @@ -2484,8 +2497,7 @@ // Show the preselection overlay now that the overlay is initialized and ready // to be shown. - if (!pending_region_ && - !search::IsOmniboxInputInProgress(tab_->GetContents())) { + if (!pending_region_ && should_show_overlay_) { ShowPreselectionBubble(); } @@ -3265,6 +3277,11 @@ } void LensOverlayController::ShowPreselectionBubble() { + // Don't show the preselection bubble if the overlay is not being shown. + if (!should_show_overlay_) { + return; + } + #if BUILDFLAG(IS_MAC) // On Mac, the kShowFullscreenToolbar pref is used to determine whether the // toolbar is always shown. This causes the toolbar to never unreveal, meaning
diff --git a/chrome/browser/ui/lens/lens_overlay_controller.h b/chrome/browser/ui/lens/lens_overlay_controller.h index 51e31ee5..03765a5 100644 --- a/chrome/browser/ui/lens/lens_overlay_controller.h +++ b/chrome/browser/ui/lens/lens_overlay_controller.h
@@ -200,6 +200,16 @@ AutocompleteMatchType::Type match_type, bool is_zero_prefix_suggestion); + // Starts the contextualization flow without the overlay being shown to the + // user. + // TODO(crbug.com/404941800): This still goes through the entire + // initialization flow for the overlay. This is not efficeient, but is being + // done to unblock the contextual searchbox prototype. This should be + // refactored to be done in the LensSearchController to not go through the + // overlay controller. + void StartContextualizationWithoutOverlay( + lens::LensOverlayInvocationSource invocation_source); + // Sets a region to search after the overlay loads, then calls ShowUI(). // All units are in device pixels. region_bitmap contains the high definition // image bytes to use for the search instead of cropping the region from the @@ -222,13 +232,7 @@ // is not kOff. This has no effect if the tab is not in the foreground. If the // overlay is successfully invoked, then the value of `invocation_source` will // be recorded in the relevant metrics. - // TODO(402931381): `should_start_focused` was added to support opening the - // Lens Overlay while the user is typing in the omnibox. To make this easy, - // the param was giving a default to avoid changing all callsites. If this - // functionality is kept, revisit if the default should be changed in favor - // of an explicit param at each callsite. - void ShowUI(lens::LensOverlayInvocationSource invocation_source, - bool should_start_focused = true); + void ShowUI(lens::LensOverlayInvocationSource invocation_source); // Starts the closing process of the overlay. This is an asynchronous process // with the following sequence: @@ -1180,7 +1184,7 @@ // points since the state of the overlay has changed. void UpdateEntryPointsState(); - // Owns this class. + // Owns the LensSearchController which owns this class raw_ptr<tabs::TabInterface> tab_; // A monotonically increasing id. This is used to differentiate between @@ -1205,8 +1209,10 @@ lens::LensOverlayInvocationSource invocation_source_ = lens::LensOverlayInvocationSource::kAppMenu; - // Whether the overlay should request focus when it is shown. - bool should_start_focused_ = false; + // Whether the overlay should be visible when it is opened. This is a hacky + // approach to start contextual searchbox flow without the overlay UI being + // shown. See StartContextualizationWithoutOverlay todo for more details. + bool should_show_overlay_ = true; // A pending url to be loaded in the side panel. Needed when the side // panel is not bound at the time of a text request.
diff --git a/chrome/browser/ui/lens/lens_overlay_controller_browsertest.cc b/chrome/browser/ui/lens/lens_overlay_controller_browsertest.cc index 049d376..22ee034e 100644 --- a/chrome/browser/ui/lens/lens_overlay_controller_browsertest.cc +++ b/chrome/browser/ui/lens/lens_overlay_controller_browsertest.cc
@@ -67,6 +67,7 @@ #include "chrome/browser/ui/lens/lens_overlay_untrusted_ui.h" #include "chrome/browser/ui/lens/lens_overlay_url_builder.h" #include "chrome/browser/ui/lens/lens_permission_bubble_controller.h" +#include "chrome/browser/ui/lens/lens_search_controller.h" #include "chrome/browser/ui/lens/lens_side_panel_untrusted_ui.h" #include "chrome/browser/ui/lens/test_lens_overlay_query_controller.h" #include "chrome/browser/ui/location_bar/location_bar.h" @@ -510,8 +511,7 @@ signin::IdentityManager* identity_manager, PrefService* pref_service, syncer::SyncService* sync_service, - ThemeService* theme_service, - Profile* profile) + ThemeService* theme_service) : LensOverlayController(tab, variations_client, identity_manager, @@ -621,22 +621,37 @@ &fake_overlay_page_}; }; +class LensSearchControllerFake : public LensSearchController { + public: + explicit LensSearchControllerFake(tabs::TabInterface* tab) + : LensSearchController(tab) {} + + protected: + std::unique_ptr<LensOverlayController> CreateLensOverlayController( + tabs::TabInterface* tab, + variations::VariationsClient* variations_client, + signin::IdentityManager* identity_manager, + PrefService* pref_service, + syncer::SyncService* sync_service, + ThemeService* theme_service) override { + // Set browser color scheme to light mode for consistency. + theme_service->SetBrowserColorScheme( + ThemeService::BrowserColorScheme::kLight); + + return std::make_unique<LensOverlayControllerFake>( + tab, variations_client, identity_manager, pref_service, sync_service, + theme_service); + } +}; + class TabFeaturesFake : public tabs::TabFeatures { public: TabFeaturesFake() = default; protected: - std::unique_ptr<LensOverlayController> CreateLensController( - tabs::TabInterface* tab, - Profile* profile) override { - auto* theme_service = ThemeServiceFactory::GetForProfile(profile); - // Set browser color scheme to light mode for consistency. - theme_service->SetBrowserColorScheme( - ThemeService::BrowserColorScheme::kLight); - return std::make_unique<LensOverlayControllerFake>( - tab, profile->GetVariationsClient(), - IdentityManagerFactory::GetForProfile(profile), profile->GetPrefs(), - SyncServiceFactory::GetForProfile(profile), theme_service, profile); + std::unique_ptr<LensSearchController> CreateLensController( + tabs::TabInterface* tab) override { + return std::make_unique<LensSearchControllerFake>(tab); } };
diff --git a/chrome/browser/ui/lens/lens_overlay_controller_interactive_uitest.cc b/chrome/browser/ui/lens/lens_overlay_controller_interactive_uitest.cc index 0d58557..fc79878 100644 --- a/chrome/browser/ui/lens/lens_overlay_controller_interactive_uitest.cc +++ b/chrome/browser/ui/lens/lens_overlay_controller_interactive_uitest.cc
@@ -19,6 +19,7 @@ #include "chrome/browser/ui/browser_element_identifiers.h" #include "chrome/browser/ui/lens/lens_overlay_controller.h" #include "chrome/browser/ui/lens/lens_overlay_gen204_controller.h" +#include "chrome/browser/ui/lens/lens_search_controller.h" #include "chrome/browser/ui/lens/test_lens_overlay_query_controller.h" #include "chrome/browser/ui/tabs/public/tab_features.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" @@ -92,8 +93,7 @@ signin::IdentityManager* identity_manager, PrefService* pref_service, syncer::SyncService* sync_service, - ThemeService* theme_service, - Profile* profile) + ThemeService* theme_service) : LensOverlayController(tab, variations_client, identity_manager, @@ -144,22 +144,36 @@ } }; +class LensSearchControllerFake : public LensSearchController { + public: + explicit LensSearchControllerFake(tabs::TabInterface* tab) + : LensSearchController(tab) {} + + std::unique_ptr<LensOverlayController> CreateLensOverlayController( + tabs::TabInterface* tab, + variations::VariationsClient* variations_client, + signin::IdentityManager* identity_manager, + PrefService* pref_service, + syncer::SyncService* sync_service, + ThemeService* theme_service) override { + // Set browser color scheme to light mode for consistency. + theme_service->SetBrowserColorScheme( + ThemeService::BrowserColorScheme::kLight); + + return std::make_unique<LensOverlayControllerFake>( + tab, variations_client, identity_manager, pref_service, sync_service, + theme_service); + } +}; + class TabFeaturesFake : public tabs::TabFeatures { public: TabFeaturesFake() = default; protected: - std::unique_ptr<LensOverlayController> CreateLensController( - tabs::TabInterface* tab, - Profile* profile) override { - auto* theme_service = ThemeServiceFactory::GetForProfile(profile); - // Set browser color scheme to light mode for consistency. - theme_service->SetBrowserColorScheme( - ThemeService::BrowserColorScheme::kLight); - return std::make_unique<LensOverlayControllerFake>( - tab, profile->GetVariationsClient(), - IdentityManagerFactory::GetForProfile(profile), profile->GetPrefs(), - SyncServiceFactory::GetForProfile(profile), theme_service, profile); + std::unique_ptr<LensSearchController> CreateLensController( + tabs::TabInterface* tab) override { + return std::make_unique<LensSearchControllerFake>(tab); } };
diff --git a/chrome/browser/ui/lens/lens_search_controller.cc b/chrome/browser/ui/lens/lens_search_controller.cc index c693561..3eca5678 100644 --- a/chrome/browser/ui/lens/lens_search_controller.cc +++ b/chrome/browser/ui/lens/lens_search_controller.cc
@@ -4,5 +4,44 @@ #include "chrome/browser/ui/lens/lens_search_controller.h" -LensSearchController::LensSearchController() = default; +#include "base/check.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/lens/lens_overlay_controller.h" + +LensSearchController::LensSearchController(tabs::TabInterface* tab) + : tab_(tab) {} LensSearchController::~LensSearchController() = default; + +void LensSearchController::Initialize( + variations::VariationsClient* variations_client, + signin::IdentityManager* identity_manager, + PrefService* pref_service, + syncer::SyncService* sync_service, + ThemeService* theme_service) { + CHECK(!initialized_); + initialized_ = true; + + lens_overlay_controller_ = + CreateLensOverlayController(tab_, variations_client, identity_manager, + pref_service, sync_service, theme_service); +} + +LensOverlayController* LensSearchController::lens_overlay_controller() { + CHECK(initialized_) + << "The LensSearchController has not been initialized. Initialize() must " + "be called before using the LensSearchController."; + return lens_overlay_controller_.get(); +} + +std::unique_ptr<LensOverlayController> +LensSearchController::CreateLensOverlayController( + tabs::TabInterface* tab, + variations::VariationsClient* variations_client, + signin::IdentityManager* identity_manager, + PrefService* pref_service, + syncer::SyncService* sync_service, + ThemeService* theme_service) { + return std::make_unique<LensOverlayController>(tab, variations_client, + identity_manager, pref_service, + sync_service, theme_service); +}
diff --git a/chrome/browser/ui/lens/lens_search_controller.h b/chrome/browser/ui/lens/lens_search_controller.h index e6bea74..c7a5cf8 100644 --- a/chrome/browser/ui/lens/lens_search_controller.h +++ b/chrome/browser/ui/lens/lens_search_controller.h
@@ -5,14 +5,63 @@ #ifndef CHROME_BROWSER_UI_LENS_LENS_SEARCH_CONTROLLER_H_ #define CHROME_BROWSER_UI_LENS_LENS_SEARCH_CONTROLLER_H_ +#include "base/memory/raw_ptr.h" +#include "components/tab_collections/public/tab_interface.h" + +class LensOverlayController; + +namespace variations { +class VariationsClient; +} // namespace variations + +namespace signin { +class IdentityManager; +} // namespace signin + +namespace syncer { +class SyncService; +} // namespace syncer + +class PrefService; +class ThemeService; + // Controller for all Lens Search features in Chrome. All external entry points // should go through this controller. +// This migration is still in progress. Follow progress via crbug.com/404941800. class LensSearchController { public: - LensSearchController(); - ~LensSearchController(); + explicit LensSearchController(tabs::TabInterface* tab); + virtual ~LensSearchController(); + + // Initializes all the necessary dependencies for the LensSearchController. + void Initialize(variations::VariationsClient* variations_client, + signin::IdentityManager* identity_manager, + PrefService* pref_service, + syncer::SyncService* sync_service, + ThemeService* theme_service); + + // Returns the LensOverlayController. + LensOverlayController* lens_overlay_controller(); + + protected: + // Override these methods to stub out individual feature controllers for + // testing. + virtual std::unique_ptr<LensOverlayController> CreateLensOverlayController( + tabs::TabInterface* tab, + variations::VariationsClient* variations_client, + signin::IdentityManager* identity_manager, + PrefService* pref_service, + syncer::SyncService* sync_service, + ThemeService* theme_service); private: + // Whether the LensSearchController has been initialized. + bool initialized_ = false; + + std::unique_ptr<LensOverlayController> lens_overlay_controller_; + + // Owns this class. + raw_ptr<tabs::TabInterface> tab_; }; #endif // CHROME_BROWSER_UI_LENS_LENS_SEARCH_CONTROLLER_H_
diff --git a/chrome/browser/ui/passwords/password_generation_popup_controller_impl.cc b/chrome/browser/ui/passwords/password_generation_popup_controller_impl.cc index 33b2d0c..ced412a3 100644 --- a/chrome/browser/ui/passwords/password_generation_popup_controller_impl.cc +++ b/chrome/browser/ui/passwords/password_generation_popup_controller_impl.cc
@@ -20,7 +20,6 @@ #include "base/strings/utf_string_conversion_utils.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" -#include "chrome/browser/accessibility/accessibility_state_utils.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/signin/identity_manager_factory.h" #include "chrome/browser/ui/passwords/password_generation_popup_controller.h" @@ -44,6 +43,7 @@ #include "content/public/browser/render_widget_host.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/web_contents.h" +#include "ui/accessibility/platform/ax_platform.h" #include "ui/base/l10n/l10n_util.h" #include "ui/events/keycodes/keyboard_codes.h" #include "ui/gfx/geometry/rect_conversions.h" @@ -287,7 +287,7 @@ driver_->PreviewGenerationSuggestion(current_generated_password_); // For the screen reader users, move the focus to the accept button on show. - if (accessibility_state_utils::IsScreenReaderEnabled()) { + if (ui::AXPlatform::GetInstance().IsScreenReaderActive()) { SelectElement(PasswordGenerationPopupElement::kAcceptButton); } }
diff --git a/chrome/browser/ui/performance_controls/memory_saver_bubble_controller.cc b/chrome/browser/ui/performance_controls/memory_saver_bubble_controller.cc index 102f548..3cb6185 100644 --- a/chrome/browser/ui/performance_controls/memory_saver_bubble_controller.cc +++ b/chrome/browser/ui/performance_controls/memory_saver_bubble_controller.cc
@@ -38,7 +38,7 @@ CHECK_NE(browser_view, nullptr); views::View* anchor_view = browser_view->toolbar_button_provider()->GetAnchorView(std::nullopt); - MemorySaverBubbleView::ShowBubble(browser, anchor_view, this); + bubble_ = MemorySaverBubbleView::ShowBubble(browser, anchor_view, this); } void MemorySaverBubbleController::OnBubbleShown() { @@ -51,6 +51,7 @@ if (action_item_) { action_item_->SetIsShowingBubble(false); } + bubble_ = nullptr; } } // namespace memory_saver
diff --git a/chrome/browser/ui/performance_controls/memory_saver_bubble_controller.h b/chrome/browser/ui/performance_controls/memory_saver_bubble_controller.h index 886789a..c171eb5 100644 --- a/chrome/browser/ui/performance_controls/memory_saver_bubble_controller.h +++ b/chrome/browser/ui/performance_controls/memory_saver_bubble_controller.h
@@ -12,6 +12,10 @@ class ActionItem; } +namespace views { +class BubbleDialogModelHost; +} + class Browser; class BrowserWindowInterface; @@ -34,8 +38,11 @@ void OnBubbleShown() override; void OnBubbleHidden() override; + views::BubbleDialogModelHost* bubble_for_testing() { return bubble_; } + private: base::WeakPtr<actions::ActionItem> action_item_; + raw_ptr<views::BubbleDialogModelHost> bubble_ = nullptr; }; } // namespace memory_saver
diff --git a/chrome/browser/ui/sharing_hub/screenshot/screenshot_captured_bubble_controller.cc b/chrome/browser/ui/sharing_hub/screenshot/screenshot_captured_bubble_controller.cc index bdba9ad..0aac171 100644 --- a/chrome/browser/ui/sharing_hub/screenshot/screenshot_captured_bubble_controller.cc +++ b/chrome/browser/ui/sharing_hub/screenshot/screenshot_captured_bubble_controller.cc
@@ -5,13 +5,13 @@ #include "chrome/browser/ui/sharing_hub/screenshot/screenshot_captured_bubble_controller.h" #include "base/feature_list.h" -#include "chrome/browser/accessibility/accessibility_state_utils.h" #include "chrome/browser/image_editor/screenshot_flow.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/grit/generated_resources.h" #include "content/public/browser/web_contents.h" +#include "ui/accessibility/platform/ax_platform.h" #include "ui/base/clipboard/scoped_clipboard_writer.h" namespace sharing_hub { @@ -68,7 +68,7 @@ }, web_contents->GetWeakPtr()); - if (accessibility_state_utils::IsScreenReaderEnabled()) { + if (ui::AXPlatform::GetInstance().IsScreenReaderActive()) { screenshot_flow_->StartFullscreenCapture(std::move(callback)); } else { screenshot_flow_->Start(std::move(callback));
diff --git a/chrome/browser/ui/tabs/BUILD.gn b/chrome/browser/ui/tabs/BUILD.gn index ddef0ab..ac12f3a 100644 --- a/chrome/browser/ui/tabs/BUILD.gn +++ b/chrome/browser/ui/tabs/BUILD.gn
@@ -510,7 +510,6 @@ "existing_comparison_table_sub_menu_model_unittest.cc", "existing_tab_group_sub_menu_model_unittest.cc", "existing_window_sub_menu_model_unittest.cc", - "pinned_tab_service_unittest.cc", "tab_collection_storage_unittest.cc", "tab_collection_unittest.cc", "tab_group_deletion_dialog_controller_unittest.cc",
diff --git a/chrome/browser/ui/tabs/pinned_tab_service_browsertest.cc b/chrome/browser/ui/tabs/pinned_tab_service_browsertest.cc index e9d015b..479e331 100644 --- a/chrome/browser/ui/tabs/pinned_tab_service_browsertest.cc +++ b/chrome/browser/ui/tabs/pinned_tab_service_browsertest.cc
@@ -79,3 +79,38 @@ PinnedTabTestUtils::TabsToString(PinnedTabCodec::ReadPinnedTabs(profile)); EXPECT_EQ("https://www.google.com/:pinned", result); } + +// Makes sure closing a popup triggers writing pinned tabs. +IN_PROC_BROWSER_TEST_F(PinnedTabServiceBrowserTest, Popup) { + Profile* profile = browser()->profile(); + EXPECT_TRUE(PinnedTabServiceFactory::GetForProfile(profile)); + EXPECT_TRUE(profile->GetPrefs()); + + GURL url("http://www.google.com"); + NavigateParams params(browser(), url, ui::PAGE_TRANSITION_TYPED); + ui_test_utils::NavigateToURL(¶ms); + + TabStripModel* tab_strip_model = browser()->tab_strip_model(); + tab_strip_model->SetTabPinned(0, true); + + // Create a popup browser. + Browser* popup_browser = Browser::Create( + Browser::CreateParams(Browser::TYPE_POPUP, browser()->profile(), true)); + ASSERT_TRUE(popup_browser->is_type_popup()); + + // Close the browser. This should trigger saving the tabs. No need to destroy + // the browser (this happens automatically in the test destructor). + browser()->OnWindowClosing(); + + std::string result = + PinnedTabTestUtils::TabsToString(PinnedTabCodec::ReadPinnedTabs(profile)); + EXPECT_EQ("https://www.google.com/:pinned", result); + + // Close the popup browser. This shouldn't reset the saved state. + popup_browser->tab_strip_model()->CloseAllTabs(); + + // Check the state to make sure it hasn't changed. + result = + PinnedTabTestUtils::TabsToString(PinnedTabCodec::ReadPinnedTabs(profile)); + EXPECT_EQ("https://www.google.com/:pinned", result); +}
diff --git a/chrome/browser/ui/tabs/pinned_tab_service_unittest.cc b/chrome/browser/ui/tabs/pinned_tab_service_unittest.cc deleted file mode 100644 index 7919f963..0000000 --- a/chrome/browser/ui/tabs/pinned_tab_service_unittest.cc +++ /dev/null
@@ -1,82 +0,0 @@ -// Copyright 2012 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/ui/tabs/pinned_tab_service.h" - -#include <memory> -#include <string> -#include <vector> - -#include "base/functional/bind.h" -#include "base/memory/raw_ptr.h" -#include "chrome/browser/ui/browser.h" -#include "chrome/browser/ui/browser_tabstrip.h" -#include "chrome/browser/ui/tabs/pinned_tab_codec.h" -#include "chrome/browser/ui/tabs/pinned_tab_service_factory.h" -#include "chrome/browser/ui/tabs/pinned_tab_test_utils.h" -#include "chrome/browser/ui/tabs/tab_strip_model.h" -#include "chrome/test/base/browser_with_test_window_test.h" -#include "chrome/test/base/testing_profile.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace { - -std::unique_ptr<KeyedService> BuildPinnedTabService( - content::BrowserContext* profile) { - return std::make_unique<PinnedTabService>(static_cast<Profile*>(profile)); -} - -PinnedTabService* BuildForProfile(Profile* profile) { - return static_cast<PinnedTabService*>( - PinnedTabServiceFactory::GetInstance()->SetTestingFactoryAndUse( - profile, base::BindRepeating(&BuildPinnedTabService))); -} - -class PinnedTabServiceTest : public BrowserWithTestWindowTest { - public: - PinnedTabServiceTest() : pinned_tab_service_(nullptr) {} - PinnedTabServiceTest(const PinnedTabServiceTest&) = delete; - PinnedTabServiceTest& operator=(const PinnedTabServiceTest&) = delete; - - protected: - TestingProfile* CreateProfile(const std::string& profile_name) override { - TestingProfile* profile = - BrowserWithTestWindowTest::CreateProfile(profile_name); - pinned_tab_service_ = BuildForProfile(profile); - return profile; - } - - private: - raw_ptr<PinnedTabService, DanglingUntriaged> pinned_tab_service_; -}; - -// Makes sure closing a popup triggers writing pinned tabs. -TEST_F(PinnedTabServiceTest, Popup) { - GURL url("http://www.google.com"); - AddTab(browser(), url); - browser()->tab_strip_model()->SetTabPinned(0, true); - - // Create a popup. - Browser::CreateParams params(Browser::TYPE_POPUP, profile(), true); - std::unique_ptr<Browser> popup(CreateBrowserWithTestWindowForParams(params)); - - // Close the browser. This should trigger saving the tabs. No need to destroy - // the browser (this happens automatically in the test destructor). - browser()->OnWindowClosing(); - - std::string result = PinnedTabTestUtils::TabsToString( - PinnedTabCodec::ReadPinnedTabs(profile())); - EXPECT_EQ("http://www.google.com/:pinned", result); - - // Close the popup. This shouldn't reset the saved state. - popup->tab_strip_model()->CloseAllTabs(); - popup.reset(); - - // Check the state to make sure it hasn't changed. - result = PinnedTabTestUtils::TabsToString( - PinnedTabCodec::ReadPinnedTabs(profile())); - EXPECT_EQ("http://www.google.com/:pinned", result); -} - -} // namespace
diff --git a/chrome/browser/ui/tabs/public/tab_features.h b/chrome/browser/ui/tabs/public/tab_features.h index 7af8b8c..1ae6d0b 100644 --- a/chrome/browser/ui/tabs/public/tab_features.h +++ b/chrome/browser/ui/tabs/public/tab_features.h
@@ -15,6 +15,7 @@ class ChromeAutofillAiClient; class LensOverlayController; +class LensSearchController; class PinnedTranslateActionListener; class Profile; class ReadAnythingSidePanelController; @@ -112,8 +113,8 @@ base::RepeatingCallback<std::unique_ptr<TabFeatures>()>; static void ReplaceTabFeaturesForTesting(TabFeaturesFactory factory); - LensOverlayController* lens_overlay_controller() { - return lens_overlay_controller_.get(); + LensSearchController* lens_search_controller() { + return lens_search_controller_.get(); } enterprise_data_protection::DataProtectionNavigationController* @@ -189,6 +190,8 @@ return memory_saver_chip_controller_.get(); } + LensOverlayController* lens_overlay_controller(); + // Called exactly once to initialize features. // Can be overridden in tests to initialize nothing. virtual void Init(TabInterface& tab, Profile* profile); @@ -198,9 +201,8 @@ // Override these methods to stub out individual feature controllers for // testing. - virtual std::unique_ptr<LensOverlayController> CreateLensController( - TabInterface* tab, - Profile* profile); + virtual std::unique_ptr<LensSearchController> CreateLensController( + TabInterface* tab); virtual std::unique_ptr<commerce::CommerceUiTabHelper> CreateCommerceUiTabHelper(content::WebContents* web_contents, @@ -224,7 +226,7 @@ permission_indicators_tab_data_; std::unique_ptr<SidePanelRegistry> side_panel_registry_; - std::unique_ptr<LensOverlayController> lens_overlay_controller_; + std::unique_ptr<LensSearchController> lens_search_controller_; // Responsible for the customize chrome tab-scoped side panel. std::unique_ptr<customize_chrome::SidePanelController>
diff --git a/chrome/browser/ui/tabs/saved_tab_groups/collaboration_messaging_observer.cc b/chrome/browser/ui/tabs/saved_tab_groups/collaboration_messaging_observer.cc index 0aa8c218..9b64a8c 100644 --- a/chrome/browser/ui/tabs/saved_tab_groups/collaboration_messaging_observer.cc +++ b/chrome/browser/ui/tabs/saved_tab_groups/collaboration_messaging_observer.cc
@@ -191,6 +191,7 @@ HandleChip(message, display); break; case PersistentNotificationType::TOMBSTONED: + case PersistentNotificationType::INSTANT_MESSAGE: case PersistentNotificationType::UNDEFINED: // These notifications have no associated UI on Desktop. // Ignore gracefully. @@ -249,9 +250,9 @@ const InstantMessage& message = instant_message_queue_processor_.GetCurrentMessage(); - CHECK(message.attribution.has_value()); - auto tab_metadata = message.attribution->tab_metadata; - auto tab_group_metadata = message.attribution->tab_group_metadata; + const auto& attribution = message.attributions[0]; + auto tab_metadata = attribution.tab_metadata; + auto tab_group_metadata = attribution.tab_group_metadata; if (!tab_metadata || !tab_group_metadata) { return; } @@ -279,8 +280,7 @@ const InstantMessage& message = instant_message_queue_processor_.GetCurrentMessage(); - CHECK(message.attribution.has_value()); - auto tab_group_metadata = message.attribution->tab_group_metadata; + auto tab_group_metadata = message.attributions[0].tab_group_metadata; if (!tab_group_metadata) { return; }
diff --git a/chrome/browser/ui/tabs/saved_tab_groups/collaboration_messaging_observer_browsertest.cc b/chrome/browser/ui/tabs/saved_tab_groups/collaboration_messaging_observer_browsertest.cc index b0ef9d4..2e61654 100644 --- a/chrome/browser/ui/tabs/saved_tab_groups/collaboration_messaging_observer_browsertest.cc +++ b/chrome/browser/ui/tabs/saved_tab_groups/collaboration_messaging_observer_browsertest.cc
@@ -113,12 +113,13 @@ attribution.tab_group_metadata = tab_group_metadata; InstantMessage message; - message.attribution = attribution; + message.attributions.emplace_back(attribution); message.type = event == CollaborationEvent::TAB_REMOVED ? InstantNotificationType::CONFLICT_TAB_REMOVED : InstantNotificationType::UNDEFINED; message.level = InstantNotificationLevel::BROWSER; message.collaboration_event = event; + message.localized_message = u"Sample instant message"; return message; } @@ -458,7 +459,7 @@ auto message = CreateInstantMessage( "User", CollaborationEvent::COLLABORATION_MEMBER_ADDED, test_url, "Chrome Settings", std::nullopt, "Vacation"); - message.attribution->tab_group_metadata->sync_tab_group_id = + message.attributions[0].tab_group_metadata->sync_tab_group_id = sync_tab_group_id; EXPECT_CALL(cb, Run(true));
diff --git a/chrome/browser/ui/tabs/saved_tab_groups/instant_message_queue_processor.cc b/chrome/browser/ui/tabs/saved_tab_groups/instant_message_queue_processor.cc index 29989583..655c5dc 100644 --- a/chrome/browser/ui/tabs/saved_tab_groups/instant_message_queue_processor.cc +++ b/chrome/browser/ui/tabs/saved_tab_groups/instant_message_queue_processor.cc
@@ -27,8 +27,7 @@ // Returns the local tab group ID from the InstantMessage. std::optional<LocalTabGroupID> UnwrapTabGroupID(InstantMessage message) { - CHECK(message.attribution.has_value()); - auto tab_group_metadata = message.attribution->tab_group_metadata; + auto tab_group_metadata = message.attributions[0].tab_group_metadata; if (tab_group_metadata.has_value()) { return tab_group_metadata->local_tab_group_id; } @@ -60,6 +59,10 @@ return; } + if (message.localized_message.empty()) { + return; + } + instant_message_queue_.emplace(message, std::move(success_callback)); MaybeShowInstantMessage(); } @@ -175,60 +178,21 @@ const InstantMessage& message) { using collaboration::messaging::TabGroupMessageMetadata; using collaboration::messaging::TabMessageMetadata; - CHECK(message.attribution.has_value()); switch (message.collaboration_event) { case CollaborationEvent::TAB_REMOVED: { - std::optional<data_sharing::GroupMember> user = - message.attribution->triggering_user; - std::optional<TabMessageMetadata> tab_metadata = - message.attribution->tab_metadata; - const bool has_title = tab_metadata.has_value() && - tab_metadata->last_known_title.has_value(); - if (!user.has_value() || !has_title) { - return std::nullopt; - } - ToastParams params(ToastId::kTabGroupSyncTabRemoved); - params.body_string_replacement_params = { - base::UTF8ToUTF16(user->given_name), - base::UTF8ToUTF16(tab_metadata->last_known_title.value()), - }; + params.body_string_override = message.localized_message; return params; } case CollaborationEvent::COLLABORATION_MEMBER_ADDED: { - std::optional<data_sharing::GroupMember> user = - message.attribution->affected_user; - std::optional<TabGroupMessageMetadata> tab_group_metadata = - message.attribution->tab_group_metadata; - const bool has_group_title = - tab_group_metadata.has_value() && - tab_group_metadata->last_known_title.has_value(); - if (!user.has_value() || !has_group_title) { - return std::nullopt; - } - ToastParams params(ToastId::kTabGroupSyncUserJoined); - params.body_string_replacement_params = { - base::UTF8ToUTF16(user->given_name), - base::UTF8ToUTF16(tab_group_metadata->last_known_title.value()), - }; + params.body_string_override = message.localized_message; return params; } case CollaborationEvent::TAB_GROUP_REMOVED: { - std::optional<TabGroupMessageMetadata> tab_group_metadata = - message.attribution->tab_group_metadata; - const bool has_group_title = - tab_group_metadata.has_value() && - tab_group_metadata->last_known_title.has_value(); - if (!has_group_title) { - return std::nullopt; - } - ToastParams params(ToastId::kTabGroupSyncRemovedFromGroup); - params.body_string_replacement_params = { - base::UTF8ToUTF16(tab_group_metadata->last_known_title.value()), - }; + params.body_string_override = message.localized_message; return params; } default:
diff --git a/chrome/browser/ui/tabs/saved_tab_groups/instant_message_queue_processor_unittest.cc b/chrome/browser/ui/tabs/saved_tab_groups/instant_message_queue_processor_unittest.cc index b02f37e0..2d9cb38 100644 --- a/chrome/browser/ui/tabs/saved_tab_groups/instant_message_queue_processor_unittest.cc +++ b/chrome/browser/ui/tabs/saved_tab_groups/instant_message_queue_processor_unittest.cc
@@ -56,12 +56,13 @@ attribution.tab_group_metadata = tab_group_metadata; InstantMessage message; - message.attribution = attribution; + message.attributions.emplace_back(attribution); message.collaboration_event = event; message.level = InstantNotificationLevel::BROWSER; message.type = event == CollaborationEvent::TAB_REMOVED ? InstantNotificationType::CONFLICT_TAB_REMOVED : InstantNotificationType::UNDEFINED; + message.localized_message = u"Message content"; return message; } @@ -132,7 +133,7 @@ auto message = CreateMessage(CollaborationEvent::TAB_REMOVED); // Remove user so that toast cannot be created from message. - message.attribution->triggering_user = std::nullopt; + message.attributions[0].triggering_user = std::nullopt; base::MockCallback<SuccessCallback> callback;
diff --git a/chrome/browser/ui/tabs/tab_features.cc b/chrome/browser/ui/tabs/tab_features.cc index 84d27fa..58c276d 100644 --- a/chrome/browser/ui/tabs/tab_features.cc +++ b/chrome/browser/ui/tabs/tab_features.cc
@@ -32,6 +32,7 @@ #include "chrome/browser/ui/browser_actions.h" #include "chrome/browser/ui/commerce/commerce_ui_tab_helper.h" #include "chrome/browser/ui/lens/lens_overlay_controller.h" +#include "chrome/browser/ui/lens/lens_search_controller.h" #include "chrome/browser/ui/page_action/page_action_icon_type.h" #include "chrome/browser/ui/performance_controls/memory_saver_chip_controller.h" #include "chrome/browser/ui/tabs/public/tab_dialog_manager.h" @@ -100,6 +101,13 @@ f = std::move(factory); } +LensOverlayController* TabFeatures::lens_overlay_controller() { + // LensSearchController won't exist on non-normal windows. + return lens_search_controller_ + ? lens_search_controller_->lens_overlay_controller() + : nullptr; +} + void TabFeatures::Init(TabInterface& tab, Profile* profile) { CHECK(!initialized_); initialized_ = true; @@ -120,7 +128,12 @@ // Features that are only enabled for normal browser windows. By default most // features should be instantiated in this block. if (tab.IsInNormalWindow()) { - lens_overlay_controller_ = CreateLensController(&tab, profile); + lens_search_controller_ = CreateLensController(&tab); + lens_search_controller_->Initialize( + profile->GetVariationsClient(), + IdentityManagerFactory::GetForProfile(profile), profile->GetPrefs(), + SyncServiceFactory::GetForProfile(profile), + ThemeServiceFactory::GetForProfile(profile)); // Each time a new tab is created, validate the topics calculation schedule // to help investigate a scheduling bug (crbug.com/343750866). @@ -263,14 +276,9 @@ TabFeatures::TabFeatures() = default; -std::unique_ptr<LensOverlayController> TabFeatures::CreateLensController( - TabInterface* tab, - Profile* profile) { - return std::make_unique<LensOverlayController>( - tab, profile->GetVariationsClient(), - IdentityManagerFactory::GetForProfile(profile), profile->GetPrefs(), - SyncServiceFactory::GetForProfile(profile), - ThemeServiceFactory::GetForProfile(profile)); +std::unique_ptr<LensSearchController> TabFeatures::CreateLensController( + TabInterface* tab) { + return std::make_unique<LensSearchController>(tab); } std::unique_ptr<commerce::CommerceUiTabHelper>
diff --git a/chrome/browser/ui/views/device_id/pen_id_browsertest_win.cc b/chrome/browser/ui/views/device_id/pen_id_browsertest_win.cc index a4ea4c79..5d02339 100644 --- a/chrome/browser/ui/views/device_id/pen_id_browsertest_win.cc +++ b/chrome/browser/ui/views/device_id/pen_id_browsertest_win.cc
@@ -8,6 +8,7 @@ #include <string> #include <vector> +#include "base/compiler_specific.h" #include "base/functional/bind.h" #include "base/functional/callback.h" #include "base/functional/callback_forward.h" @@ -125,7 +126,7 @@ long offset_y = container_bounds.y(); POINTER_PEN_INFO pen_info; - memset(&pen_info, 0, sizeof(POINTER_PEN_INFO)); + UNSAFE_TODO(memset(&pen_info, 0, sizeof(POINTER_PEN_INFO))); pen_info.pointerInfo.pointerType = PT_PEN; pen_info.pointerInfo.ButtonChangeType = POINTER_CHANGE_FIRSTBUTTON_DOWN; // Since, SimulatePenEventForTesting considers the coordinates in relation
diff --git a/chrome/browser/ui/views/frame/picture_in_picture_browser_frame_view_interactive_uitest.cc b/chrome/browser/ui/views/frame/picture_in_picture_browser_frame_view_interactive_uitest.cc index 402bf54..7db42fd 100644 --- a/chrome/browser/ui/views/frame/picture_in_picture_browser_frame_view_interactive_uitest.cc +++ b/chrome/browser/ui/views/frame/picture_in_picture_browser_frame_view_interactive_uitest.cc
@@ -39,6 +39,10 @@ #include "ui/linux/linux_ui_getter.h" #endif +#if BUILDFLAG(IS_OZONE) +#include "ui/ozone/public/ozone_platform.h" +#endif + namespace { using ::testing::WithParamInterface; @@ -116,6 +120,16 @@ ui::mojom::ModalType modal_type_; }; +bool PlatformSupportsScreenCoordinates() { +#if BUILDFLAG(IS_OZONE) + return ui::OzonePlatform::GetInstance() + ->GetPlatformProperties() + .supports_global_screen_coordinates; +#else + return true; +#endif // BUILDFLAG(IS_OZONE) +} + class PictureInPictureBrowserFrameViewTest : public WebRtcTestBase, public AnimationTimingTest { public: @@ -483,6 +497,9 @@ IN_PROC_BROWSER_TEST_F(PictureInPictureBrowserFrameViewTest, RespectsUserLocationChangesAfterChildDialogCloses) { + if (!PlatformSupportsScreenCoordinates()) { + GTEST_SKIP() << "Global screen coordinates unavailable"; + } ASSERT_NO_FATAL_FAILURE(SetUpDocumentPIP()); gfx::Rect initial_pip_bounds = @@ -544,8 +561,11 @@ gfx::Rect moved_bounds = new_pip_bounds; moved_bounds.set_width(moved_bounds.width() + 10); moved_bounds.set_height(moved_bounds.height() + 10); - moved_bounds.set_x(moved_bounds.x() - 10); - moved_bounds.set_y(moved_bounds.y() - 10); + + if (PlatformSupportsScreenCoordinates()) { + moved_bounds.set_x(moved_bounds.x() - 10); + moved_bounds.set_y(moved_bounds.y() - 10); + } pip_frame_view()->GetWidget()->SetBounds(moved_bounds); // Close the dialog. @@ -763,9 +783,13 @@ // Move mouse to the top-left corner of the main browser window (out side of // the pip window) should deactivate the title. gfx::Point outside = gfx::Point(); - views::View::ConvertPointToScreen( - static_cast<BrowserView*>(browser()->window()), &outside); - ASSERT_FALSE(IsPointInPIPFrameView(outside)); + if (PlatformSupportsScreenCoordinates()) { + views::View::ConvertPointToScreen( + static_cast<BrowserView*>(browser()->window()), &outside); + // This check only makes sense in platforms that support global screen + // coordinates. + ASSERT_FALSE(IsPointInPIPFrameView(outside)); + } UpdateTopBarView(outside); AnimationWaiter hide_animation_waiter(
diff --git a/chrome/browser/ui/views/performance_controls/memory_saver_interactive_ui_test.cc b/chrome/browser/ui/views/performance_controls/memory_saver_interactive_ui_test.cc index 6b78f80..d8808ea 100644 --- a/chrome/browser/ui/views/performance_controls/memory_saver_interactive_ui_test.cc +++ b/chrome/browser/ui/views/performance_controls/memory_saver_interactive_ui_test.cc
@@ -15,13 +15,19 @@ #include "chrome/browser/resource_coordinator/tab_lifecycle_unit.h" #include "chrome/browser/resource_coordinator/tab_manager.h" #include "chrome/browser/resource_coordinator/utils.h" +#include "chrome/browser/ui/actions/chrome_action_id.h" #include "chrome/browser/ui/browser_element_identifiers.h" +#include "chrome/browser/ui/browser_window/public/browser_window_features.h" #include "chrome/browser/ui/chrome_pages.h" +#include "chrome/browser/ui/performance_controls/memory_saver_bubble_controller.h" #include "chrome/browser/ui/performance_controls/test_support/memory_saver_interactive_test_mixin.h" #include "chrome/browser/ui/recently_audible_helper.h" +#include "chrome/browser/ui/ui_features.h" #include "chrome/browser/ui/views/frame/browser_view.h" +#include "chrome/browser/ui/views/frame/toolbar_button_provider.h" #include "chrome/browser/ui/views/location_bar/location_bar_view.h" #include "chrome/browser/ui/views/page_action/page_action_icon_controller.h" +#include "chrome/browser/ui/views/page_action/page_action_view.h" #include "chrome/browser/ui/views/performance_controls/memory_saver_bubble_view.h" #include "chrome/browser/ui/views/performance_controls/memory_saver_chip_view.h" #include "chrome/browser/ui/views/performance_controls/memory_saver_resource_view.h" @@ -51,6 +57,7 @@ #include "third_party/blink/public/common/switches.h" #include "ui/base/interaction/element_identifier.h" #include "ui/base/interaction/element_tracker.h" +#include "ui/base/interaction/polling_state_observer.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/text/bytes_formatting.h" #include "ui/gfx/animation/animation.h" @@ -66,6 +73,8 @@ DEFINE_LOCAL_ELEMENT_IDENTIFIER_VALUE(kThirdTabContents); DEFINE_LOCAL_ELEMENT_IDENTIFIER_VALUE(kPerformanceSettingsTab); DEFINE_LOCAL_CUSTOM_ELEMENT_EVENT_TYPE(kAudioIsAudible); +DEFINE_LOCAL_STATE_IDENTIFIER_VALUE(ui::test::PollingStateObserver<bool>, + kPageActionButtonVisible); constexpr char kSkipPixelTestsReason[] = "Should only run in pixel_tests."; @@ -73,6 +82,10 @@ constexpr char kDocumentWithVideo[] = "/media/bigbuck-player.html"; constexpr char kDocumentWithForm[] = "/form_interaction.html"; +// Any Chrome page that can be reliably discarded. This was previously the NTP, +// but NTP is sometimes ineligible for proactive tab discard. +constexpr std::string_view kChromePage = chrome::kChromeUIVersionURL; + } // namespace // Tests Discarding on pages with various types of content @@ -154,7 +167,7 @@ embedded_test_server()->GetURL(kDocumentWithVideo)), ExecuteJsAt(kFirstTabContents, video, kPlayVideo), WaitForStateChange(kFirstTabContents, video_is_playing), - AddInstrumentedTab(kSecondTabContents, GURL(chrome::kChromeUINewTabURL)), + AddInstrumentedTab(kSecondTabContents, GURL(kChromePage)), TryDiscardTab(0), CheckTabIsDiscarded(0, false)); } @@ -177,7 +190,7 @@ embedded_test_server()->GetURL(kDocumentWithAudio)), ExecuteJsAt(kFirstTabContents, audio, "(el) => { el.play(); }"), WaitForEvent(kFirstTabContents, kAudioIsAudible), - AddInstrumentedTab(kSecondTabContents, GURL(chrome::kChromeUINewTabURL)), + AddInstrumentedTab(kSecondTabContents, GURL(kChromePage)), TryDiscardTab(0), CheckTabIsDiscarded(0, false)); } @@ -219,8 +232,7 @@ WaitForStateChange(kFirstTabContents, input_is_focused), PressKeyboard(), WaitForStateChange(kFirstTabContents, input_value_updated), - AddInstrumentedTab(kSecondTabContents, GURL(chrome::kChromeUINewTabURL), - 1), + AddInstrumentedTab(kSecondTabContents, GURL(kChromePage), 1), TryDiscardTab(0), CheckTabIsDiscarded(0, false)); } @@ -237,42 +249,101 @@ HostContentSettingsMapFactory::GetForProfile(browser()->profile()) ->SetDefaultContentSetting(ContentSettingsType::NOTIFICATIONS, ContentSetting::CONTENT_SETTING_ALLOW); - RunTestSequence( - InstrumentTab(kFirstTabContents, 0), - NavigateWebContents( - kFirstTabContents, - https_server.GetURL("a.test", - "/notifications/notification_tester.html")), - AddInstrumentedTab(kSecondTabContents, GURL(chrome::kChromeUINewTabURL)), - TryDiscardTab(0), CheckTabIsDiscarded(0, false)); + RunTestSequence(InstrumentTab(kFirstTabContents, 0), + NavigateWebContents( + kFirstTabContents, + https_server.GetURL( + "a.test", "/notifications/notification_tester.html")), + AddInstrumentedTab(kSecondTabContents, GURL(kChromePage)), + TryDiscardTab(0), CheckTabIsDiscarded(0, false)); } +struct MemorySaverChipInteractiveTestParams { + bool web_contents_discard = false; + bool page_actions_migration_enabled = false; +}; + // Tests the functionality of the Memory Saver page action chip class MemorySaverChipInteractiveTest : public MemorySaverInteractiveTestMixin<InteractiveBrowserTest>, - public ::testing::WithParamInterface<bool> { + public ::testing::WithParamInterface< + MemorySaverChipInteractiveTestParams> { public: MemorySaverChipInteractiveTest() { - scoped_feature_list_.InitWithFeatureState(features::kWebContentsDiscard, - GetParam()); + scoped_feature_list_.InitWithFeatureStates({ + {features::kWebContentsDiscard, GetParam().web_contents_discard}, + {features::kPageActionsMigration, IsPageActionMigrationEnabled()}, + }); } + ~MemorySaverChipInteractiveTest() override = default; + bool IsPageActionMigrationEnabled() const { + return GetParam().page_actions_migration_enabled; + } + void SetUpOnMainThread() override { MemorySaverInteractiveTestMixin::SetUpOnMainThread(); SetMemorySaverModeEnabled(true); } - PageActionIconView* GetPageActionIconView() { - return BrowserView::GetBrowserViewForBrowser(browser()) - ->GetLocationBarView() - ->page_action_icon_controller() - ->GetIconView(PageActionIconType::kMemorySaver); + views::BubbleDialogDelegate* GetMemorySaverBubble() { + return IsPageActionMigrationEnabled() + ? browser() + ->browser_window_features() + ->memory_saver_bubble_controller() + ->bubble_for_testing() + : BrowserView::GetBrowserViewForBrowser(browser()) + ->GetLocationBarView() + ->page_action_icon_controller() + ->GetIconView(PageActionIconType::kMemorySaver) + ->GetBubble(); + } + + // Utility to reliably wait for the page action view to be visible. When + // animating between icon and suggestion chip, the view passes through a state + // where its width is 0. If layout runs (for any reason) in that state, layout + // sets the view to invisible. In turn, if a test is asserting that the View + // is visible, the temporary switch to invisible state will fail the test + // assertion. Animation isn't always used, so emitting a custom event when + // the view has reached its target state isn't trivial. So, resort to polling + // the View for when its reached a stable visible state. + auto WaitForPageActionButtonVisible() { + MultiStep steps; + if (IsPageActionMigrationEnabled()) { + steps += Steps( + PollState(kPageActionButtonVisible, + [this]() { + auto* view = + BrowserView::GetBrowserViewForBrowser(browser()) + ->toolbar_button_provider() + ->GetPageActionView(kActionShowMemorySaverChip); + return view->GetVisible() && !view->is_animating_label(); + }), + WaitForState(kPageActionButtonVisible, true), + StopObservingState(kPageActionButtonVisible)); + } else { + steps += WaitForShow(kMemorySaverChipElementId); + AddDescriptionPrefix(steps, "WaitForPageActionButtonVisible()"); + } + return steps; } auto CheckChipIsExpandedState(bool is_expanded) { - return CheckViewProperty(kMemorySaverChipElementId, - &PageActionIconView::ShouldShowLabel, is_expanded); + MultiStep steps; + if (IsPageActionMigrationEnabled()) { + steps += Steps( + WaitForPageActionButtonVisible(), + CheckViewProperty(kMemorySaverChipElementId, + &page_actions::PageActionView::ShouldShowLabel, + is_expanded)); + } else { + steps += + CheckViewProperty(kMemorySaverChipElementId, + &PageActionIconView::ShouldShowLabel, is_expanded); + } + AddDescriptionPrefix(steps, "CheckChipIsExpandedState()"); + return steps; } // Discard and reload the tab at discard_tab_index the number of times the @@ -282,14 +353,42 @@ size_t discard_tab_index, size_t non_discard_tab_index, const ui::ElementIdentifier& contents_id) { - MultiStep result; + MultiStep steps; for (int i = 0; i < MemorySaverChipTabHelper::kChipAnimationCount; i++) { - result += Steps(SelectTab(kTabStripElementId, non_discard_tab_index), - DiscardAndReloadTab(discard_tab_index, contents_id), - CheckChipIsExpandedState(true)); + steps += Steps(SelectTab(kTabStripElementId, non_discard_tab_index), + DiscardAndReloadTab(discard_tab_index, contents_id), + CheckChipIsExpandedState(true)); } + AddDescriptionPrefix(steps, "DiscardTabUntilChipStopsExpanding()"); + return steps; + } - return result; + auto PressPageActionButton() { + MultiStep steps; + if (IsPageActionMigrationEnabled()) { + steps += Steps(WaitForPageActionButtonVisible(), + PressButton(kMemorySaverChipElementId)); + } else { + steps += PressButton(kMemorySaverChipElementId); + } + AddDescriptionPrefix(steps, "PressPageActionButton()"); + return steps; + } + + // With the new page action framework, a few tests explicitly require a + // mouse-driven button press. Eg, in practice mouse click on the chip will + // dismiss the associated bubble. Sending a key event directly to the chip + // in tests will not. See crbug.com/395901614. + auto MousePressPageActionButton() { + MultiStep steps; + if (IsPageActionMigrationEnabled()) { + steps += Steps(WaitForPageActionButtonVisible(), + MoveMouseTo(kMemorySaverChipElementId), ClickMouse()); + } else { + steps += PressButton(kMemorySaverChipElementId); + } + AddDescriptionPrefix(steps, "MousePressPageActionButton()"); + return steps; } auto NameTab(size_t index, std::string name) { @@ -307,16 +406,15 @@ // Page Action Chip should appear expanded the first three times a tab is // discarded and collapse all subsequent times IN_PROC_BROWSER_TEST_P(MemorySaverChipInteractiveTest, PageActionChipShows) { - RunTestSequence( - InstrumentTab(kFirstTabContents, 0), - NavigateWebContents(kFirstTabContents, GetURL()), - AddInstrumentedTab(kSecondTabContents, GURL(chrome::kChromeUINewTabURL)), - SelectTab(kTabStripElementId, 0), - EnsureNotPresent(kMemorySaverChipElementId), - DiscardTabUntilChipStopsExpanding(0, 1, kFirstTabContents), - SelectTab(kTabStripElementId, 1), - DiscardAndReloadTab(0, kFirstTabContents), - CheckChipIsExpandedState(false)); + RunTestSequence(InstrumentTab(kFirstTabContents, 0), + NavigateWebContents(kFirstTabContents, GetURL()), + AddInstrumentedTab(kSecondTabContents, GURL(kChromePage)), + SelectTab(kTabStripElementId, 0), + EnsureNotPresent(kMemorySaverChipElementId), + DiscardTabUntilChipStopsExpanding(0, 1, kFirstTabContents), + SelectTab(kTabStripElementId, 1), + DiscardAndReloadTab(0, kFirstTabContents), + CheckChipIsExpandedState(false)); } // Page Action chip should collapses after navigating to a tab without a chip @@ -360,18 +458,18 @@ // Page Action chip should only show on discarded non-chrome pages IN_PROC_BROWSER_TEST_P(MemorySaverChipInteractiveTest, ChipShowsOnNonChromeSites) { - RunTestSequence( - InstrumentTab(kFirstTabContents, 0), - NavigateWebContents(kFirstTabContents, GetURL()), - AddInstrumentedTab(kSecondTabContents, GURL(chrome::kChromeUINewTabURL)), - // Discards tab on non-chrome page - DiscardAndReloadTab(0, kFirstTabContents), - WaitForShow(kMemorySaverChipElementId), + RunTestSequence(InstrumentTab(kFirstTabContents, 0), + NavigateWebContents(kFirstTabContents, GetURL()), + AddInstrumentedTab(kSecondTabContents, GURL(kChromePage)), - // Discards tab on chrome://newtab page - TryDiscardTab(1), CheckTabIsDiscarded(1, true), - SelectTab(kTabStripElementId, 1), - EnsureNotPresent(kMemorySaverChipElementId)); + // Discards tab on non-chrome page + DiscardAndReloadTab(0, kFirstTabContents), + WaitForPageActionButtonVisible(), + + // Discards tab on chrome:// page + TryDiscardTab(1), CheckTabIsDiscarded(1, true), + SelectTab(kTabStripElementId, 1), + EnsureNotPresent(kMemorySaverChipElementId)); } // Memory Saver Dialog bubble should close after clicking the "OK" button @@ -380,9 +478,8 @@ RunTestSequence( InstrumentTab(kFirstTabContents, 0), NavigateWebContents(kFirstTabContents, GetURL()), - AddInstrumentedTab(kSecondTabContents, GURL(chrome::kChromeUINewTabURL)), - DiscardAndReloadTab(0, kFirstTabContents), - PressButton(kMemorySaverChipElementId), + AddInstrumentedTab(kSecondTabContents, GURL(kChromePage)), + DiscardAndReloadTab(0, kFirstTabContents), PressPageActionButton(), WaitForShow(MemorySaverBubbleView::kMemorySaverDialogBodyElementId), PressButton(MemorySaverBubbleView::kMemorySaverDialogOkButton), WaitForHide(MemorySaverBubbleView::kMemorySaverDialogBodyElementId)); @@ -397,16 +494,14 @@ RunTestSequence( InstrumentTab(kFirstTabContents, 0), NavigateWebContents(kFirstTabContents, GetURL()), - AddInstrumentedTab(kSecondTabContents, GURL(chrome::kChromeUINewTabURL)), - DiscardAndReloadTab(0, kFirstTabContents), - PressButton(kMemorySaverChipElementId), + AddInstrumentedTab(kSecondTabContents, GURL(kChromePage)), + DiscardAndReloadTab(0, kFirstTabContents), PressPageActionButton(), WaitForShow(MemorySaverBubbleView::kMemorySaverDialogBodyElementId), - NameView(kDialogCloseButton, base::BindLambdaForTesting([&]() { - return static_cast<views::View*>(GetPageActionIconView() - ->GetBubble() - ->GetBubbleFrameView() - ->close_button()); - })), + NameView( + kDialogCloseButton, base::BindLambdaForTesting([&]() { + return static_cast<views::View*>( + GetMemorySaverBubble()->GetBubbleFrameView()->close_button()); + })), PressButton(kDialogCloseButton), EnsureNotPresent(MemorySaverBubbleView::kMemorySaverDialogBodyElementId)); } @@ -417,11 +512,10 @@ RunTestSequence( InstrumentTab(kFirstTabContents, 0), NavigateWebContents(kFirstTabContents, GetURL()), - AddInstrumentedTab(kSecondTabContents, GURL(chrome::kChromeUINewTabURL)), - DiscardAndReloadTab(0, kFirstTabContents), - PressButton(kMemorySaverChipElementId), + AddInstrumentedTab(kSecondTabContents, GURL(kChromePage)), + DiscardAndReloadTab(0, kFirstTabContents), PressPageActionButton(), WaitForShow(MemorySaverBubbleView::kMemorySaverDialogBodyElementId), - PressButton(kMemorySaverChipElementId), + MousePressPageActionButton(), EnsureNotPresent(MemorySaverBubbleView::kMemorySaverDialogBodyElementId)); } @@ -433,9 +527,8 @@ RunTestSequence( InstrumentTab(kFirstTabContents, 0), NavigateWebContents(kFirstTabContents, GetURL()), - AddInstrumentedTab(kSecondTabContents, GURL(chrome::kChromeUINewTabURL)), - DiscardAndReloadTab(0, kFirstTabContents), - PressButton(kMemorySaverChipElementId), + AddInstrumentedTab(kSecondTabContents, GURL(kChromePage)), + DiscardAndReloadTab(0, kFirstTabContents), PressPageActionButton(), WaitForShow(MemorySaverBubbleView::kMemorySaverDialogBodyElementId), NameTab(1, kSecondTab), MoveMouseTo(kSecondTab), ClickMouse(), WaitForHide(MemorySaverBubbleView::kMemorySaverDialogBodyElementId)); @@ -446,10 +539,9 @@ RunTestSequence( InstrumentTab(kFirstTabContents, 0), NavigateWebContents(kFirstTabContents, GetURL()), - AddInstrumentedTab(kSecondTabContents, GURL(chrome::kChromeUINewTabURL)), + AddInstrumentedTab(kSecondTabContents, GURL(kChromePage)), ForceRefreshMemoryMetrics(), DiscardAndReloadTab(0, kFirstTabContents), - WaitForShow(kMemorySaverChipElementId), - PressButton(kMemorySaverChipElementId), + PressPageActionButton(), WaitForShow(MemorySaverResourceView:: kMemorySaverResourceViewMemorySavingsElementId), CheckView( @@ -479,9 +571,8 @@ RunTestSequence( InstrumentTab(kFirstTabContents, 0), NavigateWebContents(kFirstTabContents, GetURL()), - AddInstrumentedTab(kSecondTabContents, GURL(chrome::kChromeUINewTabURL)), - DiscardAndReloadTab(0, kFirstTabContents), - PressButton(kMemorySaverChipElementId), + AddInstrumentedTab(kSecondTabContents, GURL(kChromePage)), + DiscardAndReloadTab(0, kFirstTabContents), PressPageActionButton(), WaitForShow(MemorySaverBubbleView::kMemorySaverDialogBodyElementId), CheckViewProperty( MemorySaverBubbleView::kMemorySaverDialogCancelButton, @@ -508,7 +599,7 @@ // Dialog's cancel button should now allow users to navigate to the // performance settings page - PressButton(kMemorySaverChipElementId), + PressPageActionButton(), WaitForShow(MemorySaverBubbleView::kMemorySaverDialogBodyElementId), CheckViewProperty( MemorySaverBubbleView::kMemorySaverDialogCancelButton, @@ -527,41 +618,41 @@ // Memory Saver Dialog bubble's cancel button's state should be preserved // for that tab even when navigating to another tab. IN_PROC_BROWSER_TEST_P(MemorySaverChipInteractiveTest, - CancelButtonStatePreseveredWhenSwitchingTabs) { + CancelButtonStatePreservedWhenSwitchingTabs) { RunTestSequence( InstrumentTab(kFirstTabContents, 0), NavigateWebContents(kFirstTabContents, GetURL("a.test", "/title1.html")), AddInstrumentedTab(kSecondTabContents, GetURL("b.test", "/title1.html")), DiscardAndReloadTab(0, kFirstTabContents), TryDiscardTab(1), - PressButton(kMemorySaverChipElementId), + PressPageActionButton(), WaitForShow(MemorySaverBubbleView::kMemorySaverDialogBodyElementId), // Add site to the exceptions list PressButton(MemorySaverBubbleView::kMemorySaverDialogCancelButton), WaitForHide(MemorySaverBubbleView::kMemorySaverDialogBodyElementId), // Check that the cancel button can go to settings page - PressButton(kMemorySaverChipElementId), + PressPageActionButton(), WaitForShow(MemorySaverBubbleView::kMemorySaverDialogBodyElementId), CheckViewProperty( MemorySaverBubbleView::kMemorySaverDialogCancelButton, &views::LabelButton::GetText, l10n_util::GetStringUTF16(IDS_MEMORY_SAVER_DIALOG_SETTINGS_BUTTON)), - PressButton(kMemorySaverChipElementId), + MousePressPageActionButton(), WaitForHide(MemorySaverBubbleView::kMemorySaverDialogBodyElementId), // Second tab's cancel button should allow users to exclude the site // since this tab's site wasn't excluded yet - SelectTab(kTabStripElementId, 1), PressButton(kMemorySaverChipElementId), + SelectTab(kTabStripElementId, 1), PressPageActionButton(), WaitForShow(MemorySaverBubbleView::kMemorySaverDialogBodyElementId), CheckViewProperty( MemorySaverBubbleView::kMemorySaverDialogCancelButton, &views::LabelButton::GetText, l10n_util::GetStringUTF16( IDS_MEMORY_SAVER_DIALOG_BUTTON_ADD_TO_EXCLUSION_LIST)), - PressButton(kMemorySaverChipElementId), + MousePressPageActionButton(), WaitForHide(MemorySaverBubbleView::kMemorySaverDialogBodyElementId), // Ensure that the first tab's cancel button continues to allow users // to navigate to the settings page even after we selected another tab - SelectTab(kTabStripElementId, 0), PressButton(kMemorySaverChipElementId), + SelectTab(kTabStripElementId, 0), PressPageActionButton(), WaitForShow(MemorySaverBubbleView::kMemorySaverDialogBodyElementId), CheckViewProperty( MemorySaverBubbleView::kMemorySaverDialogCancelButton, @@ -578,7 +669,7 @@ kSkipPixelTestsReason), InstrumentTab(kFirstTabContents, 0), NavigateWebContents(kFirstTabContents, GetURL()), - AddInstrumentedTab(kSecondTabContents, GURL(chrome::kChromeUINewTabURL)), + AddInstrumentedTab(kSecondTabContents, GURL(kChromePage)), ForceRefreshMemoryMetrics(), DiscardAndReloadTab(0, kFirstTabContents), Do(base::BindLambdaForTesting([&]() { content::WebContents* web_contents = @@ -589,7 +680,7 @@ pre_discard_resource_usage->UpdateDiscardInfo( 135 * 1024, ::mojom::LifecycleUnitDiscardReason::PROACTIVE); })), - PressButton(kMemorySaverChipElementId), + PressPageActionButton(), WaitForShow( MemorySaverBubbleView::kMemorySaverDialogResourceViewElementId), Screenshot(MemorySaverBubbleView::kMemorySaverDialogResourceViewElementId, @@ -624,7 +715,7 @@ RunTestSequence( InstrumentTab(kFirstTabContents, 0), NavigateWebContents(kFirstTabContents, GetURL()), - AddInstrumentedTab(kSecondTabContents, GURL(chrome::kChromeUINewTabURL)), + AddInstrumentedTab(kSecondTabContents, GURL(kChromePage)), TryDiscardTab(0), CheckTabIsDiscarded(0, true), WaitForPromo(feature_engagement::kIPHDiscardRingFeature), PressNonDefaultPromoButton(), InstrumentTab(kThirdTabContents, 2), @@ -675,7 +766,7 @@ kSkipPixelTestsReason), InstrumentTab(kFirstTabContents, 0), NavigateWebContents(kFirstTabContents, GetURL()), - AddInstrumentedTab(kSecondTabContents, GURL(chrome::kChromeUINewTabURL)), + AddInstrumentedTab(kSecondTabContents, GURL(kChromePage)), Do(base::BindLambdaForTesting( [=, this]() { GetTabStrip()->StopAnimating(true); })), TryDiscardTab(0), CheckTabIsDiscarded(0, true), @@ -734,13 +825,27 @@ return info.param ? "RetainedWebContents" : "UnretainedWebContents"; }); +// TODO(crbug.com/404543902): Add cases for new Page Action framework. INSTANTIATE_TEST_SUITE_P(, MemorySaverChipInteractiveTest, - ::testing::Values(false, true), + ::testing::Values( + MemorySaverChipInteractiveTestParams{ + .web_contents_discard = false, + .page_actions_migration_enabled = false}, + MemorySaverChipInteractiveTestParams{ + .web_contents_discard = true, + .page_actions_migration_enabled = false}), + [](const ::testing::TestParamInfo< MemorySaverChipInteractiveTest::ParamType>& info) { - return info.param ? "RetainedWebContents" - : "UnretainedWebContents"; + return base::StrCat( + {info.param.web_contents_discard + ? "RetainedWebContents" + : "UnretainedWebContents", + "_", + info.param.page_actions_migration_enabled + ? "NewPageAction" + : "OriginalPageAction"}); }); INSTANTIATE_TEST_SUITE_P(
diff --git a/chrome/browser/ui/views/privacy_sandbox/privacy_sandbox_dialog_view.h b/chrome/browser/ui/views/privacy_sandbox/privacy_sandbox_dialog_view.h index 247d0c28..7e90182 100644 --- a/chrome/browser/ui/views/privacy_sandbox/privacy_sandbox_dialog_view.h +++ b/chrome/browser/ui/views/privacy_sandbox/privacy_sandbox_dialog_view.h
@@ -43,6 +43,7 @@ friend class PrivacySandboxDialogViewPrivacyPolicyBrowserTest; friend class PrivacySandboxDialogViewAdsApiUxEnhancementPrivacyPolicyBrowserTest; + friend class PrivacySandboxDialogViewAdsApiUxEnhancementsLearnMoreBrowserTest; content::WebContents* GetWebContentsForTesting(); raw_ptr<views::WebView> web_view_;
diff --git a/chrome/browser/ui/views/privacy_sandbox/privacy_sandbox_dialog_view_browsertest.cc b/chrome/browser/ui/views/privacy_sandbox/privacy_sandbox_dialog_view_browsertest.cc index 0f5cc768..c361383 100644 --- a/chrome/browser/ui/views/privacy_sandbox/privacy_sandbox_dialog_view_browsertest.cc +++ b/chrome/browser/ui/views/privacy_sandbox/privacy_sandbox_dialog_view_browsertest.cc
@@ -34,6 +34,83 @@ constexpr int kAverageBrowserWidth = 800; constexpr int kAverageBrowserHeight = 700; constexpr base::TimeDelta kMaxWaitTime = base::Seconds(30); + +std::string ScrollToBottomScript() { + return R"```( + (async () => { + return new Promise(async (resolve) => { + requestIdleCallback(async () => { + let dialogElement = document.querySelector("body > "+$1); + if ($2 !== "") dialogElement = dialogElement.shadowRoot.querySelector($2); + const scrollable = dialogElement.shadowRoot.querySelector('[scrollable]'); + scrollFunction = () => new Promise(scrollResolve => { + let timeout = setTimeout(() => { + scrollable.removeEventListener('scrollend', scrollEndCallback); + scrollResolve(); + }, 2000); + const scrollEndCallback = () => { + clearTimeout(timeout); + scrollable.removeEventListener('scrollend', scrollEndCallback); + scrollResolve(); + }; + scrollable.addEventListener('scrollend', scrollEndCallback); + scrollable.scrollTop = scrollable.scrollHeight; + }); + waitUntilHidden = (el) => { + return new Promise(overlayResolve => { + const observer = new MutationObserver(mutations => + mutations.some(mutation => mutation.type === 'attributes' && + mutation.attributeName === 'hidden' && el.hasAttribute('hidden')) && + requestAnimationFrame(() => (observer.disconnect(), overlayResolve())) + ); + el.hasAttribute('hidden') + ? requestAnimationFrame(overlayResolve) + : observer.observe(el, { attributes: true, attributeFilter: ['hidden'] }); + }); + }; + await scrollFunction(); + await waitUntilHidden(dialogElement.shadowRoot.querySelector('#showMoreOverlay')); + requestAnimationFrame(resolve); + }); + }); + })(); + )```"; +} + +std::string ClickLearnMoreButton3TimesScript() { + return R"( + (async () => { + return new Promise(async (resolve) => { + requestAnimationFrame(async () => { + dialogElement = document.querySelector("body > "+$1); + if($2 !== "") dialogElement = dialogElement.shadowRoot.querySelector($2); + const learnMoreElement = dialogElement.shadowRoot.querySelector($3); + const expandButtonElement = learnMoreElement.shadowRoot.querySelector('div > cr-expand-button'); + const scrollable = dialogElement.shadowRoot.querySelector('[scrollable]'); + waitForEndScroll = (el) => new Promise(scrollResolve => { + let timeout = setTimeout(() => { + el.removeEventListener('scrollend', scrollEndCallback); + scrollResolve(); + }, 2000); + const scrollEndCallback = () => { + clearTimeout(timeout); + el.removeEventListener('scrollend', scrollEndCallback); + scrollResolve(); + }; + el.addEventListener('scrollend', scrollEndCallback); + expandButtonElement.click(); + }); + await waitForEndScroll(scrollable); + expandButtonElement.click(); + await waitForEndScroll(scrollable); + expandButtonElement.blur(); + setTimeout(resolve,0); + }); + }); + })(); + )"; +} + } // namespace class PrivacySandboxDialogViewBrowserTest : public DialogBrowserTest { @@ -294,3 +371,124 @@ InvokeUi_PrivacyPolicy) { ShowAndVerifyUi(); } + +// TODO(crbug.com/378886088): Refactor file to reduce code duplication between +// different test classes. +class PrivacySandboxDialogViewAdsApiUxEnhancementsLearnMoreBrowserTest + : public PrivacySandboxDialogViewBrowserTest { + public: + PrivacySandboxDialogViewAdsApiUxEnhancementsLearnMoreBrowserTest() { + scoped_feature_list_.InitWithFeatures( + // Enabled Features + {privacy_sandbox::kPrivacySandboxAdsApiUxEnhancements}, + // Disabled Features + {privacy_sandbox::kPrivacySandboxAdTopicsContentParity, + privacy_sandbox::kPrivacySandboxEqualizedPromptButtons}); + } + + // DialogBrowserTest: + void ShowUi(const std::string& name) override { + // Resize the browser window to guarantee enough space for the dialog. + BrowserView::GetBrowserViewForBrowser(browser())->GetWidget()->SetBounds( + {0, 0, kAverageBrowserWidth, kAverageBrowserHeight}); + + views::NamedWidgetShownWaiter waiter( + views::test::AnyWidgetTestPasskey{}, + PrivacySandboxDialogView::kViewClassName); + ShowPrivacySandboxDialog(browser(), GetPromptType(name)); + views::Widget* dialog_widget = waiter.WaitIfNeededAndGet(); + views::test::WidgetVisibleWaiter(dialog_widget).Wait(); + ASSERT_TRUE(dialog_widget->IsVisible()); + + auto* privacy_sandbox_dialog_view = static_cast<PrivacySandboxDialogView*>( + dialog_widget->widget_delegate()->GetContentsView()); + + auto [primary_selector, secondary_selector] = + GetDialogElementSelector(name); + + // Open, close, and reopen the learn more section. This ensures that there + // is no behind the scenes rendering that could cause a layout issue. This + // adds test coverage for a past regression where only the second expand + // caused a layout issue (crbug.com/388420268). + EXPECT_TRUE( + content::ExecJs(privacy_sandbox_dialog_view->GetWebContentsForTesting(), + content::JsReplace(ClickLearnMoreButton3TimesScript(), + primary_selector, secondary_selector, + GetLearnMoreElementSelector(name)))); + + // Scroll the view to the bottom before taking a screenshot. + EXPECT_TRUE(content::ExecJs( + privacy_sandbox_dialog_view->GetWebContentsForTesting(), + content::JsReplace(ScrollToBottomScript(), primary_selector, + secondary_selector))); + } + + private: + PrivacySandboxService::PromptType GetPromptType(std::string_view name) { + if (name == "ConsentEEA") { + return PrivacySandboxService::PromptType::kM1Consent; + } + if (name == "NoticeEEAsiteSuggestedAds" || + name == "NoticeEEAadsMeasurementLearnMore") { + return PrivacySandboxService::PromptType::kM1NoticeEEA; + } + if (name == "NoticeROW") { + return PrivacySandboxService::PromptType::kM1NoticeROW; + } + NOTREACHED(); + } + + std::pair<std::string, std::string> GetDialogElementSelector( + const std::string& name) { + if (name == "ConsentEEA") { + return std::make_pair("privacy-sandbox-combined-dialog-app", "#consent"); + } + if (name == "NoticeEEAsiteSuggestedAds" || + name == "NoticeEEAadsMeasurementLearnMore") { + return std::make_pair("privacy-sandbox-combined-dialog-app", "#notice"); + } + if (name == "NoticeROW") { + return std::make_pair("privacy-sandbox-notice-dialog-app", ""); + } + NOTREACHED(); + } + + std::string GetLearnMoreElementSelector(const std::string& name) { + if (name == "NoticeEEAsiteSuggestedAds") { + return "#siteSuggestedAdsLearnMore"; + } + if (name == "NoticeEEAadsMeasurementLearnMore") { + return "#adsMeasurementLearnMore"; + } + if (name == "ConsentEEA" || name == "NoticeROW") { + return "privacy-sandbox-dialog-learn-more"; + } + NOTREACHED(); + } + + base::test::ScopedFeatureList scoped_feature_list_; +}; + +IN_PROC_BROWSER_TEST_F( + PrivacySandboxDialogViewAdsApiUxEnhancementsLearnMoreBrowserTest, + InvokeUi_ConsentEEA) { + ShowAndVerifyUi(); +} + +IN_PROC_BROWSER_TEST_F( + PrivacySandboxDialogViewAdsApiUxEnhancementsLearnMoreBrowserTest, + InvokeUi_NoticeEEAsiteSuggestedAds) { + ShowAndVerifyUi(); +} + +IN_PROC_BROWSER_TEST_F( + PrivacySandboxDialogViewAdsApiUxEnhancementsLearnMoreBrowserTest, + InvokeUi_NoticeEEAadsMeasurementLearnMore) { + ShowAndVerifyUi(); +} + +IN_PROC_BROWSER_TEST_F( + PrivacySandboxDialogViewAdsApiUxEnhancementsLearnMoreBrowserTest, + InvokeUi_NoticeROW) { + ShowAndVerifyUi(); +}
diff --git a/chrome/browser/ui/views/status_icons/status_icon_win.cc b/chrome/browser/ui/views/status_icons/status_icon_win.cc index 81e394f..1423e69 100644 --- a/chrome/browser/ui/views/status_icons/status_icon_win.cc +++ b/chrome/browser/ui/views/status_icons/status_icon_win.cc
@@ -6,6 +6,7 @@ #include <string.h> +#include "base/compiler_specific.h" #include "base/logging.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" @@ -116,7 +117,7 @@ NOTIFYICONDATA icon_data; InitIconData(&icon_data); icon_data.uFlags = NIF_TIP; - wcscpy_s(icon_data.szTip, base::as_wcstr(tool_tip)); + UNSAFE_TODO(wcscpy_s(icon_data.szTip, base::as_wcstr(tool_tip))); BOOL result = Shell_NotifyIcon(NIM_MODIFY, &icon_data); if (!result) { LOG(WARNING) << "Unable to set tooltip for status tray icon"; @@ -132,8 +133,8 @@ InitIconData(&icon_data); icon_data.uFlags = NIF_INFO; icon_data.dwInfoFlags = NIIF_INFO; - wcscpy_s(icon_data.szInfoTitle, base::as_wcstr(title)); - wcscpy_s(icon_data.szInfo, base::as_wcstr(contents)); + UNSAFE_TODO(wcscpy_s(icon_data.szInfoTitle, base::as_wcstr(title))); + UNSAFE_TODO(wcscpy_s(icon_data.szInfo, base::as_wcstr(contents))); icon_data.uTimeout = 0; if (!icon.isNull()) { @@ -164,7 +165,7 @@ } void StatusIconWin::InitIconData(NOTIFYICONDATA* icon_data) { - memset(icon_data, 0, sizeof(NOTIFYICONDATA)); + UNSAFE_TODO(memset(icon_data, 0, sizeof(NOTIFYICONDATA))); icon_data->cbSize = sizeof(NOTIFYICONDATA); icon_data->hWnd = window_;
diff --git a/chrome/browser/ui/views/user_education/impl/browser_feature_promo_preconditions.cc b/chrome/browser/ui/views/user_education/impl/browser_feature_promo_preconditions.cc index 7510ddf..a4c0871 100644 --- a/chrome/browser/ui/views/user_education/impl/browser_feature_promo_preconditions.cc +++ b/chrome/browser/ui/views/user_education/impl/browser_feature_promo_preconditions.cc
@@ -184,10 +184,7 @@ // watching events at all. event_monitor_ = views::EventMonitor::CreateWindowMonitor( this, browser_view_->GetWidget()->GetTopLevelWidget()->GetNativeWindow(), - {ui::EventType::kKeyPressed, ui::EventType::kKeyReleased, - ui::EventType::kMousePressed, ui::EventType::kMouseReleased, - ui::EventType::kTouchPressed, ui::EventType::kTouchReleased, - ui::EventType::kGestureBegin, ui::EventType::kGestureEnd}); + {ui::EventType::kKeyPressed, ui::EventType::kKeyReleased}); } void UserNotActivePrecondition::OnEvent(const ui::Event& event) { @@ -197,10 +194,18 @@ user_education::FeaturePromoResult UserNotActivePrecondition::CheckPrecondition( ComputedData&) const { - const auto elapsed = time_provider_->GetCurrentTime() - last_active_time_; - return elapsed < user_education::features::GetIdleTimeBeforeHeavyweightPromo() - ? user_education::FeaturePromoResult::kBlockedByUi - : user_education::FeaturePromoResult::Success(); + // Only do check if min idle time is nonzero and positive; otherwise this is a + // no-op. Explicitly verify this in case of non-monotonic clock weirdness. + const auto min_idle_time = + user_education::features::GetIdleTimeBeforeHeavyweightPromo(); + if (min_idle_time.is_positive()) { + const auto elapsed = time_provider_->GetCurrentTime() - last_active_time_; + return elapsed < min_idle_time + ? user_education::FeaturePromoResult::kBlockedByUi + : user_education::FeaturePromoResult::Success(); + } else { + return user_education::FeaturePromoResult::Success(); + } } void UserNotActivePrecondition::OnViewAddedToWidget(
diff --git a/chrome/browser/ui/views/user_education/impl/browser_feature_promo_preconditions_interactive_uitest.cc b/chrome/browser/ui/views/user_education/impl/browser_feature_promo_preconditions_interactive_uitest.cc index 430aef1..130a8fdd 100644 --- a/chrome/browser/ui/views/user_education/impl/browser_feature_promo_preconditions_interactive_uitest.cc +++ b/chrome/browser/ui/views/user_education/impl/browser_feature_promo_preconditions_interactive_uitest.cc
@@ -271,18 +271,26 @@ } class UserNotActivePreconditionUiTest - : public BrowserFeaturePromoPreconditionsUiTest { + : public BrowserFeaturePromoPreconditionsUiTest, + public testing::WithParamInterface<base::TimeDelta> { public: UserNotActivePreconditionUiTest() = default; ~UserNotActivePreconditionUiTest() override = default; + void SetUp() override { + feature_list_.InitAndEnableFeatureWithParameters( + user_education::features::kUserEducationExperienceVersion2Point5, + {{"idle_before_heavyweight", + base::StringPrintf("%dms", GetParam().InMilliseconds())}}); + less_than_activity_time_ = GetParam() / 2; + more_than_activity_time_ = GetParam() + base::Seconds(1); + + BrowserFeaturePromoPreconditionsUiTest::SetUp(); + } + void SetUpOnMainThread() override { BrowserFeaturePromoPreconditionsUiTest::SetUpOnMainThread(); - less_than_activity_time_ = - user_education::features::GetIdleTimeBeforeHeavyweightPromo() / 2; - more_than_activity_time_ = - user_education::features::GetIdleTimeBeforeHeavyweightPromo() + - base::Seconds(1); + auto* const browser_view = BrowserView::GetBrowserViewForBrowser(browser()); time_provider_.set_clock_for_testing(&test_clock_); precondition_ = std::make_unique<UserNotActivePrecondition>(*browser_view, @@ -317,59 +325,33 @@ base::TimeDelta less_than_activity_time_; base::TimeDelta more_than_activity_time_; + base::test::ScopedFeatureList feature_list_; base::SimpleTestClock test_clock_; user_education::UserEducationTimeProvider time_provider_; std::unique_ptr<UserNotActivePrecondition> precondition_; std::unique_ptr<ui::test::EventGenerator> event_generator_; }; -IN_PROC_BROWSER_TEST_F(UserNotActivePreconditionUiTest, ReturnsSuccess) { +INSTANTIATE_TEST_SUITE_P( + , + UserNotActivePreconditionUiTest, + testing::Values(base::Seconds(0), base::Seconds(5)), + [](const testing::TestParamInfo<base::TimeDelta>& param_info) { + return base::StringPrintf("%dms", param_info.param.InMilliseconds()); + }); + +IN_PROC_BROWSER_TEST_P(UserNotActivePreconditionUiTest, ReturnsSuccess) { RunTestSequence( WaitForShow(kBrowserViewElementId), CheckPrecondResult(user_education::FeaturePromoResult::Success())); } -IN_PROC_BROWSER_TEST_F(UserNotActivePreconditionUiTest, - ReturnsBlockedAfterMouseClick) { - RunTestSequence( - WaitForShow(kBrowserViewElementId), - MoveMouseTo(ContentsWebView::kContentsWebViewElementId), ClickMouse(), - CheckPrecondResult(user_education::FeaturePromoResult::kBlockedByUi), - Advance(less_than_activity_time_), - CheckPrecondResult(user_education::FeaturePromoResult::kBlockedByUi), - Advance(more_than_activity_time_), - CheckPrecondResult(user_education::FeaturePromoResult::Success())); -} - -IN_PROC_BROWSER_TEST_F(UserNotActivePreconditionUiTest, - ReturnsSuccessWhenHoveringOutsideTopContainer) { - gfx::Point start; - gfx::Point finish; - RunTestSequence( - WaitForShow(kBrowserViewElementId), - WithView(ContentsWebView::kContentsWebViewElementId, - [&](views::View* contents) { - // Pick a start and end point at opposite corners of the - // contents pane, inset into the pane slightly. - auto bounds = contents->GetBoundsInScreen(); - bounds.Inset(3); - start = bounds.origin(); - finish = bounds.bottom_right(); - }), - // Move to the starting point. - MoveMouseTo(std::ref(start)), - // Since the move might pass through the top container, wait long enough - // that it doesn't matter. - Advance(more_than_activity_time_), - CheckPrecondResult(user_education::FeaturePromoResult::Success()), - // Move to the ending point. Since the move does not pass through the top - // container, this should not affect the precondition. - MoveMouseTo(std::ref(finish)), - CheckPrecondResult(user_education::FeaturePromoResult::Success())); -} - -IN_PROC_BROWSER_TEST_F(UserNotActivePreconditionUiTest, +IN_PROC_BROWSER_TEST_P(UserNotActivePreconditionUiTest, ReturnsBlockedAfterKeyPress) { + const auto expected_result = + GetParam().is_zero() ? user_education::FeaturePromoResult::Success() + : user_education::FeaturePromoResult::kBlockedByUi; + RunTestSequence( WaitForShow(kBrowserViewElementId), Check([this]() { // Use a keypress that is is not an accelerator but won't open the @@ -378,9 +360,7 @@ ui::KeyboardCode::VKEY_SPACE, false, false, false, false); }), - CheckPrecondResult(user_education::FeaturePromoResult::kBlockedByUi), - Advance(less_than_activity_time_), - CheckPrecondResult(user_education::FeaturePromoResult::kBlockedByUi), - Advance(more_than_activity_time_), + CheckPrecondResult(expected_result), Advance(less_than_activity_time_), + CheckPrecondResult(expected_result), Advance(more_than_activity_time_), CheckPrecondResult(user_education::FeaturePromoResult::Success())); }
diff --git a/chrome/browser/ui/views/webauthn/authenticator_request_sheet_view.cc b/chrome/browser/ui/views/webauthn/authenticator_request_sheet_view.cc index 3387161..747bb99 100644 --- a/chrome/browser/ui/views/webauthn/authenticator_request_sheet_view.cc +++ b/chrome/browser/ui/views/webauthn/authenticator_request_sheet_view.cc
@@ -17,13 +17,13 @@ #include "build/branding_buildflags.h" #include "build/build_config.h" #include "cc/paint/skottie_wrapper.h" -#include "chrome/browser/accessibility/accessibility_state_utils.h" #include "chrome/browser/ui/views/accessibility/non_accessible_image_view.h" #include "chrome/browser/ui/views/chrome_layout_provider.h" #include "chrome/browser/ui/views/chrome_typography.h" #include "chrome/browser/ui/webauthn/authenticator_request_sheet_model.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/accessibility/ax_enums.mojom.h" +#include "ui/accessibility/platform/ax_platform.h" #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/base/models/image_model.h" #include "ui/base/resource/resource_bundle.h" @@ -107,7 +107,7 @@ if (should_focus_step_specific_content_ == AutoFocus::kYes) { return child_views_.step_specific_content_; } - if (accessibility_state_utils::IsScreenReaderEnabled()) { + if (ui::AXPlatform::GetInstance().IsScreenReaderActive()) { // Focus the title label if a screen reader is detected to nudge it to // announce the title when the sheet changes. return child_views_.title_label_; @@ -223,7 +223,7 @@ title_label->SetHorizontalAlignment(gfx::ALIGN_LEFT); title_label->GetViewAccessibility().SetRole(ax::mojom::Role::kHeading); title_label->SetAllowCharacterBreak(true); - if (accessibility_state_utils::IsScreenReaderEnabled() && + if (ui::AXPlatform::GetInstance().IsScreenReaderActive() && should_focus_step_specific_content_ == AutoFocus::kNo) { title_label->SetFocusBehavior(FocusBehavior::ALWAYS); }
diff --git a/chrome/browser/ui/views/webid/account_selection_bubble_view.cc b/chrome/browser/ui/views/webid/account_selection_bubble_view.cc index 4344e36..cfb7a445 100644 --- a/chrome/browser/ui/views/webid/account_selection_bubble_view.cc +++ b/chrome/browser/ui/views/webid/account_selection_bubble_view.cc
@@ -12,7 +12,6 @@ #include "base/memory/raw_ptr.h" #include "base/memory/weak_ptr.h" #include "chrome/app/vector_icons/vector_icons.h" -#include "chrome/browser/accessibility/accessibility_state_utils.h" #include "chrome/browser/image_fetcher/image_decoder_impl.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/monogram_utils.h"
diff --git a/chrome/browser/ui/views/webid/account_selection_modal_view.cc b/chrome/browser/ui/views/webid/account_selection_modal_view.cc index 12940892..2126f939 100644 --- a/chrome/browser/ui/views/webid/account_selection_modal_view.cc +++ b/chrome/browser/ui/views/webid/account_selection_modal_view.cc
@@ -13,7 +13,6 @@ #include "base/functional/bind.h" #include "base/i18n/case_conversion.h" #include "chrome/app/vector_icons/vector_icons.h" -#include "chrome/browser/accessibility/accessibility_state_utils.h" #include "chrome/browser/image_fetcher/image_decoder_impl.h" #include "chrome/browser/net/system_network_context_manager.h" #include "chrome/browser/ui/monogram_utils.h"
diff --git a/chrome/browser/ui/views/webid/fedcm_account_selection_view_desktop.cc b/chrome/browser/ui/views/webid/fedcm_account_selection_view_desktop.cc index 6759fc1..b0ce0f8 100644 --- a/chrome/browser/ui/views/webid/fedcm_account_selection_view_desktop.cc +++ b/chrome/browser/ui/views/webid/fedcm_account_selection_view_desktop.cc
@@ -7,7 +7,6 @@ #include "base/functional/bind.h" #include "base/metrics/histogram_functions.h" #include "base/metrics/histogram_macros.h" -#include "chrome/browser/accessibility/accessibility_state_utils.h" #include "chrome/browser/net/system_network_context_manager.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/tabs/tab_strip_model_delegate.h"
diff --git a/chrome/browser/ui/webui/ash/settings/pages/a11y/accessibility_section.cc b/chrome/browser/ui/webui/ash/settings/pages/a11y/accessibility_section.cc index b7cdafb9..de72cb9 100644 --- a/chrome/browser/ui/webui/ash/settings/pages/a11y/accessibility_section.cc +++ b/chrome/browser/ui/webui/ash/settings/pages/a11y/accessibility_section.cc
@@ -20,7 +20,6 @@ #include "base/containers/span.h" #include "base/feature_list.h" #include "base/metrics/histogram_functions.h" -#include "chrome/browser/accessibility/accessibility_state_utils.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/speech/extension_api/tts_engine_extension_observer_chromeos.h" #include "chrome/browser/speech/extension_api/tts_engine_extension_observer_chromeos_factory.h" @@ -44,6 +43,7 @@ #include "extensions/browser/extension_system.h" #include "ui/accessibility/accessibility_features.h" #include "ui/accessibility/accessibility_switches.h" +#include "ui/accessibility/platform/ax_platform.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/webui/web_ui_util.h" #include "ui/events/ash/keyboard_layout_util.h" @@ -2034,7 +2034,7 @@ void AccessibilitySection::UpdateSearchTags() { SearchTagRegistry::ScopedTagUpdater updater = registry()->StartUpdate(); - if (accessibility_state_utils::IsScreenReaderEnabled()) { + if (ui::AXPlatform::GetInstance().IsScreenReaderActive()) { updater.AddSearchTags(GetA11yLabelsSearchConcepts()); } else { updater.RemoveSearchTags(GetA11yLabelsSearchConcepts());
diff --git a/chrome/browser/ui/webui/settings/accessibility_main_handler.cc b/chrome/browser/ui/webui/settings/accessibility_main_handler.cc index 5dbbb275c..329f2ec 100644 --- a/chrome/browser/ui/webui/settings/accessibility_main_handler.cc +++ b/chrome/browser/ui/webui/settings/accessibility_main_handler.cc
@@ -8,7 +8,6 @@ #include "base/functional/bind.h" #include "base/values.h" -#include "chrome/browser/accessibility/accessibility_state_utils.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/renderer_context_menu/accessibility_labels_bubble_model.h" #include "chrome/browser/ui/confirm_bubble.h" @@ -18,6 +17,7 @@ #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" #include "ui/accessibility/accessibility_features.h" +#include "ui/accessibility/platform/ax_platform.h" namespace settings { @@ -99,9 +99,9 @@ const base::Value& callback_id = args[0]; AllowJavascript(); // Get the current install state and send it back to a UI callback. - base::Value is_screen_reader_enabled( - accessibility_state_utils::IsScreenReaderEnabled()); - ResolveJavascriptCallback(callback_id, is_screen_reader_enabled); + base::Value is_screen_reader_active( + ui::AXPlatform::GetInstance().IsScreenReaderActive()); + ResolveJavascriptCallback(callback_id, is_screen_reader_active); } void AccessibilityMainHandler::HandleCheckAccessibilityImageLabels( @@ -122,13 +122,15 @@ } void AccessibilityMainHandler::SendScreenReaderStateChanged() { - base::Value result(accessibility_state_utils::IsScreenReaderEnabled()); + base::Value result(ui::AXPlatform::GetInstance().IsScreenReaderActive()); FireWebUIListener("screen-reader-state-changed", result); } #if BUILDFLAG(IS_CHROMEOS) void AccessibilityMainHandler::OnAccessibilityStatusChanged( const ash::AccessibilityStatusEventDetails& details) { + // TODO(accessibility): Listen to assistive tech changes across all platforms + // using AXModeObserver::OnAssistiveTechChanged(). if (details.notification_type == ash::AccessibilityNotificationType::kToggleSpokenFeedback) { SendScreenReaderStateChanged();
diff --git a/chrome/build/android-arm32.pgo.txt b/chrome/build/android-arm32.pgo.txt index ba52ecb..ad0d1795 100644 --- a/chrome/build/android-arm32.pgo.txt +++ b/chrome/build/android-arm32.pgo.txt
@@ -1 +1 @@ -chrome-android32-main-1742817397-e3a083b9da290cf243e976eb4e488c0d1caf0fda-fbe631cbc5d4909cba43f5eed375a8d27e8a536b.profdata +chrome-android32-main-1742839181-968acc22c0ea0bac86ca8311efc8814765aaf400-5e5a0303cdac3133c1ca1df63851d9f459c9cc80.profdata
diff --git a/chrome/build/android-arm64.pgo.txt b/chrome/build/android-arm64.pgo.txt index e9e7f7f7..458eac3 100644 --- a/chrome/build/android-arm64.pgo.txt +++ b/chrome/build/android-arm64.pgo.txt
@@ -1 +1 @@ -chrome-android64-main-1742822139-e3485f65255f53ee94f6fd23e65dd69a2ed65000-5508a3bc09a449ed1a0051c02d26e35f32b44cd1.profdata +chrome-android64-main-1742834266-ca4f83e46e7d232ce4f46b717f8513f3693619fc-4d8048f78a1e148bb2a1d860299b5b375b2dc793.profdata
diff --git a/chrome/build/mac-arm.pgo.txt b/chrome/build/mac-arm.pgo.txt index 104b855..41d05c7c 100644 --- a/chrome/build/mac-arm.pgo.txt +++ b/chrome/build/mac-arm.pgo.txt
@@ -1 +1 @@ -chrome-mac-arm-main-1742824760-2ba8e758cbc1f55bea12862cb60f219acb220364-4340c670214e50002c3081d210205db85a2e6f76.profdata +chrome-mac-arm-main-1742839181-bbc62cb77213ec9c3b483f845ba0cacaa7c7274a-5e5a0303cdac3133c1ca1df63851d9f459c9cc80.profdata
diff --git a/chrome/build/win-arm64.pgo.txt b/chrome/build/win-arm64.pgo.txt index d7752dd..a1cf103 100644 --- a/chrome/build/win-arm64.pgo.txt +++ b/chrome/build/win-arm64.pgo.txt
@@ -1 +1 @@ -chrome-win-arm64-main-1742793798-9b90bca00f040f150225582bbd7981349d2ea24c-4744b0d6b60f12b4cf8d6f16bb0c0764533b109c.profdata +chrome-win-arm64-main-1742839181-ee6e1e92effa65cfbd99b8553af72b5f4ba26435-5e5a0303cdac3133c1ca1df63851d9f459c9cc80.profdata
diff --git a/chrome/build/win32.pgo.txt b/chrome/build/win32.pgo.txt index 2f9341d..7e0a0b2d 100644 --- a/chrome/build/win32.pgo.txt +++ b/chrome/build/win32.pgo.txt
@@ -1 +1 @@ -chrome-win32-main-1742806739-8f8b663d5eb56892def5da5aecccef14b7dbe98c-c31daa891a2c9718a575164e5ef594e7a58e2e33.profdata +chrome-win32-main-1742817397-bf5b7f6b3091a78afacb26561c50bdaafbef5969-fbe631cbc5d4909cba43f5eed375a8d27e8a536b.profdata
diff --git a/chrome/common/win/delay_load_notify_hook_unittest.cc b/chrome/common/win/delay_load_notify_hook_unittest.cc index 04993444..25ee952 100644 --- a/chrome/common/win/delay_load_notify_hook_unittest.cc +++ b/chrome/common/win/delay_load_notify_hook_unittest.cc
@@ -2,6 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#ifdef UNSAFE_BUFFERS_BUILD +// TODO(crbug.com/390223051): Remove C-library calls to fix the errors. +#pragma allow_unsafe_libc_calls +#endif + #include "chrome/common/win/delay_load_notify_hook.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/chrome/credential_provider/gaiacp/gaia_credential_base.cc b/chrome/credential_provider/gaiacp/gaia_credential_base.cc index de425ed..58ee02b 100644 --- a/chrome/credential_provider/gaiacp/gaia_credential_base.cc +++ b/chrome/credential_provider/gaiacp/gaia_credential_base.cc
@@ -14,6 +14,7 @@ #include <utility> #include "base/command_line.h" +#include "base/compiler_specific.h" #include "base/containers/contains.h" #include "base/files/file_path.h" #include "base/files/file_util.h" @@ -448,7 +449,7 @@ &existing_sid, error_text); if (SUCCEEDED(hr)) - wcscpy_s(sid, sid_length, existing_sid.c_str()); + UNSAFE_TODO(wcscpy_s(sid, sid_length, existing_sid.c_str())); return hr; } @@ -548,7 +549,8 @@ } LOGFN(VERBOSE) << "No existing user found associated to gaia id:" << *gaia_id; - wcscpy_s(domain, domain_length, OSUserManager::GetLocalDomain().c_str()); + UNSAFE_TODO( + wcscpy_s(domain, domain_length, OSUserManager::GetLocalDomain().c_str())); username[0] = 0; sid[0] = 0; @@ -605,11 +607,12 @@ // Replace invalid characters. While @ is not strictly invalid according to // MSDN docs, it causes trouble. for (auto& c : os_username) { - if (wcschr(L"@\\[]:|<>+=;?*", c) != nullptr || c < 32) + if (UNSAFE_TODO(wcschr(L"@\\[]:|<>+=;?*", c)) != nullptr || c < 32) { c = L'_'; + } } - wcscpy_s(username, username_length, os_username.c_str()); + UNSAFE_TODO(wcscpy_s(username, username_length, os_username.c_str())); return S_OK; } @@ -1513,7 +1516,7 @@ *status_text = nullptr; *status_icon = CPSI_NONE; - memset(cpcs, 0, sizeof(*cpcs)); + UNSAFE_TODO(memset(cpcs, 0, sizeof(*cpcs))); // This may be a long running function so disable user input while processing. if (events_) {
diff --git a/chrome/credential_provider/gaiacp/gaia_credential_base_unittests.cc b/chrome/credential_provider/gaiacp/gaia_credential_base_unittests.cc index 42de1ff..cd5237a 100644 --- a/chrome/credential_provider/gaiacp/gaia_credential_base_unittests.cc +++ b/chrome/credential_provider/gaiacp/gaia_credential_base_unittests.cc
@@ -16,6 +16,7 @@ #include "base/base64.h" #include "base/base_paths_win.h" +#include "base/compiler_specific.h" #include "base/files/scoped_temp_dir.h" #include "base/json/json_writer.h" #include "base/memory/raw_ptr.h" @@ -1785,7 +1786,7 @@ SUCCEEDED(GetUserProperty(sid_str.c_str(), base::UTF8ToWide(kKeyDomain), domain_reg, &domain_reg_length))); ASSERT_TRUE(domain_reg[0]); - EXPECT_TRUE(wcscmp(domain_reg, domain_name) == 0); + EXPECT_TRUE(UNSAFE_TODO(wcscmp(domain_reg, domain_name)) == 0); // Verify that the registry entry for the username was created. wchar_t username_reg[256]; @@ -1794,7 +1795,7 @@ SUCCEEDED(GetUserProperty(sid_str.c_str(), base::UTF8ToWide(kKeyUsername), username_reg, &username_reg_length))); ASSERT_TRUE(username_reg[0]); - EXPECT_TRUE(wcscmp(username_reg, user_name) == 0); + EXPECT_TRUE(UNSAFE_TODO(wcscmp(username_reg, user_name)) == 0); // Verify that the authentication results dictionary is now empty. ASSERT_TRUE(test->IsAuthenticationResultsEmpty());
diff --git a/chrome/credential_provider/gaiacp/os_process_manager.cc b/chrome/credential_provider/gaiacp/os_process_manager.cc index 9d498c85..444ab37 100644 --- a/chrome/credential_provider/gaiacp/os_process_manager.cc +++ b/chrome/credential_provider/gaiacp/os_process_manager.cc
@@ -24,6 +24,7 @@ #include <memory> #include "base/command_line.h" +#include "base/compiler_specific.h" #include "base/files/file_path.h" #include "base/process/launch.h" #include "base/scoped_native_library.h" @@ -448,8 +449,9 @@ base::win::ScopedProcessInformation* procinfo) { // CreateProcessWithTokenW() expects the command line to be non-const, so make // a copy here. - std::unique_ptr<wchar_t, void (*)(void*)> - cmdline(wcsdup(command_line.GetCommandLineString().c_str()), std::free); + std::unique_ptr<wchar_t, void (*)(void*)> cmdline( + UNSAFE_TODO(wcsdup(command_line.GetCommandLineString().c_str())), + std::free); PROCESS_INFORMATION temp_procinfo = {}; if (!::CreateProcessWithTokenW(logon_token.Get(), LOGON_WITH_PROFILE,
diff --git a/chrome/credential_provider/gaiacp/scoped_user_profile.cc b/chrome/credential_provider/gaiacp/scoped_user_profile.cc index 16512ae3..aeb2edb 100644 --- a/chrome/credential_provider/gaiacp/scoped_user_profile.cc +++ b/chrome/credential_provider/gaiacp/scoped_user_profile.cc
@@ -20,6 +20,7 @@ #include <utility> #include <vector> +#include "base/compiler_specific.h" #include "base/files/file_util.h" #include "base/functional/bind.h" #include "base/functional/callback.h" @@ -537,8 +538,8 @@ // but administrators and SYSTEM can. { wchar_t key_name[128]; - swprintf_s(key_name, std::size(key_name), L"%s\\%s\\%s", sid.c_str(), - kRegHkcuAccountsPath, id.c_str()); + UNSAFE_TODO(swprintf_s(key_name, std::size(key_name), L"%s\\%s\\%s", + sid.c_str(), kRegHkcuAccountsPath, id.c_str())); LOGFN(VERBOSE) << "HKU\\" << key_name; base::win::RegKey key; @@ -641,8 +642,8 @@ // but administrators and SYSTEM can. base::win::RegKey key; wchar_t key_name[128]; - swprintf_s(key_name, std::size(key_name), L"%s\\%s", sid.c_str(), - kRegHkcuAccountsPath); + UNSAFE_TODO(swprintf_s(key_name, std::size(key_name), L"%s\\%s", sid.c_str(), + kRegHkcuAccountsPath)); LOGFN(VERBOSE) << "HKU\\" << key_name; for (int i = 0; i < kWaitForProfileCreationRetryCount; ++i) {
diff --git a/chrome/credential_provider/test/com_fakes.cc b/chrome/credential_provider/test/com_fakes.cc index 579fc1fc..e3bcde5 100644 --- a/chrome/credential_provider/test/com_fakes.cc +++ b/chrome/credential_provider/test/com_fakes.cc
@@ -7,6 +7,7 @@ #include <sddl.h> #include "base/check.h" +#include "base/compiler_specific.h" #include "chrome/credential_provider/gaiacp/gaia_credential.h" #include "chrome/credential_provider/gaiacp/gaia_credential_other_user.h" #include "chrome/credential_provider/gaiacp/os_user_manager.h" @@ -86,7 +87,7 @@ HRESULT FakeCredentialProviderUser::GetSid(wchar_t** sid) { DWORD length = sid_.length() + 1; *sid = static_cast<wchar_t*>(::CoTaskMemAlloc(length * sizeof(wchar_t))); - EXPECT_EQ(0, wcscpy_s(*sid, length, sid_.c_str())); + EXPECT_EQ(0, UNSAFE_TODO(wcscpy_s(*sid, length, sid_.c_str()))); return S_OK; } @@ -101,7 +102,7 @@ DWORD length = username_.length() + 1; *value = static_cast<wchar_t*>(::CoTaskMemAlloc(length * sizeof(wchar_t))); - EXPECT_EQ(0, wcscpy_s(*value, length, username_.c_str())); + EXPECT_EQ(0, UNSAFE_TODO(wcscpy_s(*value, length, username_.c_str()))); return S_OK; }
diff --git a/chrome/enterprise_companion/crash_client.cc b/chrome/enterprise_companion/crash_client.cc index 6b9bc6a..451a6844 100644 --- a/chrome/enterprise_companion/crash_client.cc +++ b/chrome/enterprise_companion/crash_client.cc
@@ -217,7 +217,7 @@ GetGlobalConstants()->CrashUploadURL().spec(), annotations, MakeCrashHandlerArgs(), /*restartable=*/true, - /*asynchronous_start=*/false)) { + /*asynchronous_start=*/false, attachments)) { VLOG(1) << "Failed to start handler."; return false; }
diff --git a/chrome/release_scripts b/chrome/release_scripts index 7bc6ee8..4cee7d5 160000 --- a/chrome/release_scripts +++ b/chrome/release_scripts
@@ -1 +1 @@ -Subproject commit 7bc6ee818946760972db2112e46f97b5ea0fe1dd +Subproject commit 4cee7d5d76a131b09b4f80dea737b1aecbe66dd4
diff --git a/chrome/renderer/autofill/password_autofill_agent_browsertest.cc b/chrome/renderer/autofill/password_autofill_agent_browsertest.cc index f1ccc7a1..617f8a1 100644 --- a/chrome/renderer/autofill/password_autofill_agent_browsertest.cc +++ b/chrome/renderer/autofill/password_autofill_agent_browsertest.cc
@@ -809,8 +809,9 @@ << __func__ << " called from " << location.ToString()); EXPECT_CALL(fake_driver_, ShowPasswordSuggestions(AllOf( - Field(&autofill::PasswordSuggestionRequest::typed_username, - expected_username)))) + Field(&autofill::PasswordSuggestionRequest::field, + Field(&autofill::TriggeringField::typed_username, + expected_username))))) .Times(NumShowSuggestionsCalls()); base::RunLoop().RunUntilIdle(); } @@ -2510,9 +2511,10 @@ // Now simulate a user typing in a saved username. The list is filtered. EXPECT_CALL(fake_driver_, - ShowPasswordSuggestions( - Field(&autofill::PasswordSuggestionRequest::element_id, - form_util::GetFieldRendererId(username_element_)))) + ShowPasswordSuggestions(Field( + &autofill::PasswordSuggestionRequest::field, + Field(&autofill::TriggeringField::element_id, + form_util::GetFieldRendererId(username_element_))))) .Times(NumShowSuggestionsCalls()); SimulateUsernameTyping(kAliceUsername); }
diff --git a/chrome/test/android/BUILD.gn b/chrome/test/android/BUILD.gn index 784f1d6cc..6bc7f50 100644 --- a/chrome/test/android/BUILD.gn +++ b/chrome/test/android/BUILD.gn
@@ -198,6 +198,7 @@ sources = [ "javatests/src/org/chromium/chrome/test/transit/AppMenuFacility.java", + "javatests/src/org/chromium/chrome/test/transit/AutoResetCtaTransitTestRule.java", "javatests/src/org/chromium/chrome/test/transit/BaseCtaTransitTestRule.java", "javatests/src/org/chromium/chrome/test/transit/BlankCTATabInitialStatePublicTransitRule.java", "javatests/src/org/chromium/chrome/test/transit/ChromeTabbedActivityEntryPoints.java",
diff --git a/chrome/test/android/javatests/src/org/chromium/chrome/test/transit/AutoResetCtaTransitTestRule.java b/chrome/test/android/javatests/src/org/chromium/chrome/test/transit/AutoResetCtaTransitTestRule.java new file mode 100644 index 0000000..68f79cb --- /dev/null +++ b/chrome/test/android/javatests/src/org/chromium/chrome/test/transit/AutoResetCtaTransitTestRule.java
@@ -0,0 +1,81 @@ +// Copyright 2025 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.test.transit; + +import org.junit.rules.RuleChain; +import org.junit.rules.TestRule; +import org.junit.runner.Description; +import org.junit.runners.model.Statement; + +import org.chromium.base.test.transit.BatchedPublicTransitRule; +import org.chromium.base.test.transit.EntryPointSentinelStation; +import org.chromium.base.test.transit.Station; +import org.chromium.base.test.transit.TrafficControl; +import org.chromium.build.annotations.NullMarked; +import org.chromium.chrome.test.batch.BlankCTATabInitialStateRule; +import org.chromium.chrome.test.transit.ntp.RegularNewTabPageStation; +import org.chromium.chrome.test.transit.page.PageStation; +import org.chromium.chrome.test.transit.page.WebPageStation; +import org.chromium.components.embedder_support.util.UrlConstants; + +/** + * Rule for integration tests that reuse a ChromeTabbedActivity but reset tab state between cases. + * + * <p>Tests using this should be batched. + */ +@NullMarked +public class AutoResetCtaTransitTestRule extends BaseCtaTransitTestRule implements TestRule { + private final BlankCTATabInitialStateRule mInitialStateRule; + private final BatchedPublicTransitRule<PageStation> mBatchedRule; + private final RuleChain mChain; + + /** Create with {@link ChromeTransitTestRules#autoResetCtaActivityRule()}. */ + AutoResetCtaTransitTestRule() { + super(); + mBatchedRule = + new BatchedPublicTransitRule<>(PageStation.class, /* expectResetByTest= */ false); + mInitialStateRule = new BlankCTATabInitialStateRule(mActivityTestRule, true); + mChain = + RuleChain.outerRule(mActivityTestRule) + .around(mInitialStateRule) + .around(mBatchedRule); + } + + @Override + public Statement apply(Statement statement, Description description) { + return mChain.apply(statement, description); + } + + /** + * Start the batched test in a blank page. + * + * <p>From the second test onwards, state was reset by {@link BlankCTATabInitialStateRule}. + */ + public WebPageStation startOnBlankPage() { + // Null in the first test, non-null from the second test onwards. + Station<?> homeStation = TrafficControl.getActiveStation(); + if (homeStation == null) { + EntryPointSentinelStation entryPoint = new EntryPointSentinelStation(); + entryPoint.setAsEntryPoint(); + homeStation = entryPoint; + } + + WebPageStation entryPageStation = WebPageStation.newBuilder().withEntryPoint().build(); + + // Wait for the Conditions to be met to return an active PageStation. + return homeStation.travelToSync(entryPageStation, /* trigger= */ null); + } + + /** + * Start the batched test in an NTP. + * + * <p>From the second test onwards, state was reset by {@link BlankCTATabInitialStateRule}. + */ + public RegularNewTabPageStation startOnNtp() { + WebPageStation blankPage = startOnBlankPage(); + return blankPage.loadPageProgrammatically( + UrlConstants.NTP_URL, RegularNewTabPageStation.newBuilder()); + } +}
diff --git a/chrome/test/android/javatests/src/org/chromium/chrome/test/transit/BaseCtaTransitTestRule.java b/chrome/test/android/javatests/src/org/chromium/chrome/test/transit/BaseCtaTransitTestRule.java index 9f10346..1e4716e 100644 --- a/chrome/test/android/javatests/src/org/chromium/chrome/test/transit/BaseCtaTransitTestRule.java +++ b/chrome/test/android/javatests/src/org/chromium/chrome/test/transit/BaseCtaTransitTestRule.java
@@ -33,4 +33,8 @@ public EmbeddedTestServer getTestServer() { return mActivityTestRule.getTestServer(); } + + public int tabsCount(boolean incognito) { + return mActivityTestRule.tabsCount(incognito); + } }
diff --git a/chrome/test/android/javatests/src/org/chromium/chrome/test/transit/BlankCTATabInitialStatePublicTransitRule.java b/chrome/test/android/javatests/src/org/chromium/chrome/test/transit/BlankCTATabInitialStatePublicTransitRule.java index 785fd087..35cd91c 100644 --- a/chrome/test/android/javatests/src/org/chromium/chrome/test/transit/BlankCTATabInitialStatePublicTransitRule.java +++ b/chrome/test/android/javatests/src/org/chromium/chrome/test/transit/BlankCTATabInitialStatePublicTransitRule.java
@@ -19,7 +19,14 @@ import org.chromium.chrome.test.transit.page.WebPageStation; import org.chromium.components.embedder_support.util.UrlConstants; -/** Wraps BlankCTATabInitialStateRule to be used in Public Transit batched tests. */ +/** + * Wraps BlankCTATabInitialStateRule to be used in Public Transit batched tests. + * + * <p>TODO(crbug.com/404294940): Remove this after migrating all usages. + * + * @deprecated Use {@link ChromeTransitTestRules#autoResetCtaActivityRule()} instead. + */ +@Deprecated public class BlankCTATabInitialStatePublicTransitRule implements TestRule { private final ChromeTabbedActivityTestRule mActivityTestRule; @@ -29,6 +36,7 @@ public final BlankCTATabInitialStateRule mInitialStateRule; private final RuleChain mChain; + @Deprecated public BlankCTATabInitialStatePublicTransitRule(ChromeTabbedActivityTestRule activityTestRule) { mActivityTestRule = activityTestRule; mBatchedRule =
diff --git a/chrome/test/android/javatests/src/org/chromium/chrome/test/transit/ChromeTransitTestRules.java b/chrome/test/android/javatests/src/org/chromium/chrome/test/transit/ChromeTransitTestRules.java index f438b44..2c48459 100644 --- a/chrome/test/android/javatests/src/org/chromium/chrome/test/transit/ChromeTransitTestRules.java +++ b/chrome/test/android/javatests/src/org/chromium/chrome/test/transit/ChromeTransitTestRules.java
@@ -31,6 +31,11 @@ RegularNewTabPageStation.class, ChromeTabbedActivityEntryPoints::startOnNtp); } + /** Auto reset the state of the ChromeTabbedActivity and reuse it within the batch. */ + public static AutoResetCtaTransitTestRule autoResetCtaActivityRule() { + return new AutoResetCtaTransitTestRule(); + } + /** * Starts each test case in a fresh ChromeTabbedActivity. *
diff --git a/chrome/test/base/chrome_test_launcher.cc b/chrome/test/base/chrome_test_launcher.cc index 4f7dccc..cc5944d7 100644 --- a/chrome/test/base/chrome_test_launcher.cc +++ b/chrome/test/base/chrome_test_launcher.cc
@@ -22,6 +22,7 @@ #include "base/run_loop.h" #include "base/sampling_heap_profiler/poisson_allocation_sampler.h" #include "base/strings/string_util.h" +#include "base/test/allow_check_is_test_for_testing.h" #include "base/test/task_environment.h" #include "base/test/test_file_util.h" #include "base/test/test_switches.h" @@ -267,6 +268,8 @@ content::TestLauncherDelegate* delegate, int argc, char** argv) { + base::test::AllowCheckIsTestForTesting(); + #if BUILDFLAG(IS_MAC) // Set up the path to the framework so resources can be loaded. This is also // performed in ChromeTestSuite, but in browser tests that only affects the
diff --git a/chrome/test/base/chromeos/crosier/chromeos_test_launcher.cc b/chrome/test/base/chromeos/crosier/chromeos_test_launcher.cc index adbb002..2955e96 100644 --- a/chrome/test/base/chromeos/crosier/chromeos_test_launcher.cc +++ b/chrome/test/base/chromeos/crosier/chromeos_test_launcher.cc
@@ -7,6 +7,7 @@ #include <string_view> #include "base/profiler/thread_group_profiler.h" +#include "base/test/allow_check_is_test_for_testing.h" #include "base/test/task_environment.h" #include "base/types/pass_key.h" #include "chrome/app/chrome_crash_reporter_client.h" @@ -124,6 +125,7 @@ int LaunchChromeOSTests(content::TestLauncherDelegate* delegate, int argc, char** argv) { + base::test::AllowCheckIsTestForTesting(); ChromeCrashReporterClient::Create(); // Setup a working test environment for the network service in case it's used. // Only create this object in the utility process, so that its members don't
diff --git a/chrome/test/data/pdf/annotations_feature_enabled_test.ts b/chrome/test/data/pdf/annotations_feature_enabled_test.ts index 66aeec2..e18b571e 100644 --- a/chrome/test/data/pdf/annotations_feature_enabled_test.ts +++ b/chrome/test/data/pdf/annotations_feature_enabled_test.ts
@@ -3,7 +3,7 @@ // found in the LICENSE file. import type {AnnotationTool, ViewerInkHostElement} from 'chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/pdf_viewer_wrapper.js'; -import {SaveRequestType} from 'chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/pdf_viewer_wrapper.js'; +import {AnnotationMode, SaveRequestType} from 'chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/pdf_viewer_wrapper.js'; import {assert} from 'chrome://resources/js/assert.js'; import {loadTimeData} from 'chrome://resources/js/load_time_data.js'; @@ -24,7 +24,7 @@ } function isAnnotationMode(): boolean { - return viewer.$.toolbar.annotationMode; + return viewer.$.toolbar.annotationMode === AnnotationMode.DRAW; } chrome.test.runTests([ @@ -39,7 +39,7 @@ chrome.test.assertEq('EMBED', contentElement().tagName); // Enter annotation mode. - viewer.$.toolbar.toggleAnnotation(); + viewer.$.toolbar.setAnnotationMode(AnnotationMode.DRAW); await viewer.loaded; chrome.test.assertEq('VIEWER-INK-HOST', contentElement().tagName); chrome.test.succeed(); @@ -444,7 +444,7 @@ async function testExitAnnotationMode() { chrome.test.assertTrue(isAnnotationMode()); // Exit annotation mode. - viewer.$.toolbar.toggleAnnotation(); + viewer.$.toolbar.setAnnotationMode(AnnotationMode.NONE); await viewer.loaded; chrome.test.assertEq('EMBED', contentElement().tagName); chrome.test.succeed();
diff --git a/chrome/test/data/pdf/annotations_toolbar_test.ts b/chrome/test/data/pdf/annotations_toolbar_test.ts index 542c9d5..d67020f 100644 --- a/chrome/test/data/pdf/annotations_toolbar_test.ts +++ b/chrome/test/data/pdf/annotations_toolbar_test.ts
@@ -3,6 +3,7 @@ // found in the LICENSE file. import type {CrIconButtonElement} from 'chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/pdf_viewer_wrapper.js'; +import {AnnotationMode} from 'chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/pdf_viewer_wrapper.js'; import {eventToPromise, microtasksFinished} from 'chrome://webui-test/test_util.js'; function createToolbar() { @@ -15,11 +16,11 @@ const tests = [ async function testHidingAnnotationsExitsAnnotationsMode() { const toolbar = createToolbar(); - toolbar.toggleAnnotation(); + toolbar.setAnnotationMode(AnnotationMode.DRAW); // This is normally done by the parent in response to the event fired by - // toggleAnnotation(). - toolbar.annotationMode = true; + // setAnnotationMode(). + toolbar.annotationMode = AnnotationMode.DRAW; await microtasksFinished(); toolbar.addEventListener('display-annotations-changed', e => { @@ -31,38 +32,38 @@ }, function testEnteringAnnotationsModeShowsAnnotations() { const toolbar = createToolbar(); - chrome.test.assertFalse(toolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.NONE, toolbar.annotationMode); // Hide annotations. toolbar.shadowRoot.querySelector<HTMLElement>( '#show-annotations-button')!.click(); - toolbar.addEventListener('annotation-mode-toggled', e => { - chrome.test.assertTrue(e.detail); + toolbar.addEventListener('annotation-mode-updated', e => { + chrome.test.assertEq(AnnotationMode.DRAW, e.detail); chrome.test.succeed(); }); - toolbar.toggleAnnotation(); + toolbar.setAnnotationMode(AnnotationMode.DRAW); }, async function testEnteringAnnotationsModeDisablesPresentationMode() { const toolbar = createToolbar(); - chrome.test.assertFalse(toolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.NONE, toolbar.annotationMode); - toolbar.toggleAnnotation(); + toolbar.setAnnotationMode(AnnotationMode.DRAW); // This is normally done by the parent in response to the event fired by - // toggleAnnotation(). - toolbar.annotationMode = true; + // setAnnotationMode(). + toolbar.annotationMode = AnnotationMode.DRAW; await microtasksFinished(); chrome.test.assertTrue(toolbar.$['present-button'].disabled); chrome.test.succeed(); }, async function testEnteringAnnotationsModeDisablesTwoUp() { const toolbar = createToolbar(); - chrome.test.assertFalse(toolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.NONE, toolbar.annotationMode); - toolbar.toggleAnnotation(); + toolbar.setAnnotationMode(AnnotationMode.DRAW); // This is normally done by the parent in response to the event fired by - // toggleAnnotation(). - toolbar.annotationMode = true; + // setAnnotationMode(). + toolbar.annotationMode = AnnotationMode.DRAW; await microtasksFinished(); chrome.test.assertTrue(toolbar.$['two-page-view-button'].disabled); chrome.test.succeed(); @@ -75,7 +76,7 @@ toolbar.twoUpViewEnabled = false; await microtasksFinished(); - chrome.test.assertFalse(toolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.NONE, toolbar.annotationMode); // If rotation is enabled clicking the button shows the dialog. toolbar.rotated = true;
diff --git a/chrome/test/data/pdf/ink2_before_unload_stroke_test.ts b/chrome/test/data/pdf/ink2_before_unload_stroke_test.ts index 1c9d197e..8739b58 100644 --- a/chrome/test/data/pdf/ink2_before_unload_stroke_test.ts +++ b/chrome/test/data/pdf/ink2_before_unload_stroke_test.ts
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import {PluginController} from 'chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/pdf_viewer_wrapper.js'; +import {AnnotationMode, PluginController} from 'chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/pdf_viewer_wrapper.js'; import {microtasksFinished} from 'chrome://webui-test/test_util.js'; import {finishInkStroke, getNewTestBeforeUnloadProxy, setupTestMockPluginForInk} from './test_util.js'; @@ -15,11 +15,11 @@ const toolbar = document.body.querySelector('pdf-viewer')!.$.toolbar; - chrome.test.assertFalse(toolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.NONE, toolbar.annotationMode); - toolbar.toggleAnnotation(); + toolbar.setAnnotationMode(AnnotationMode.DRAW); await microtasksFinished(); - chrome.test.assertTrue(toolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.DRAW, toolbar.annotationMode); finishInkStroke(PluginController.getInstance());
diff --git a/chrome/test/data/pdf/ink2_before_unload_undo_test.ts b/chrome/test/data/pdf/ink2_before_unload_undo_test.ts index 57b31329..4375041 100644 --- a/chrome/test/data/pdf/ink2_before_unload_undo_test.ts +++ b/chrome/test/data/pdf/ink2_before_unload_undo_test.ts
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import {PluginController} from 'chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/pdf_viewer_wrapper.js'; +import {AnnotationMode, PluginController} from 'chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/pdf_viewer_wrapper.js'; import {microtasksFinished} from 'chrome://webui-test/test_util.js'; import {finishInkStroke, getNewTestBeforeUnloadProxy, setupTestMockPluginForInk} from './test_util.js'; @@ -15,11 +15,11 @@ const toolbar = document.body.querySelector('pdf-viewer')!.$.toolbar; - chrome.test.assertFalse(toolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.NONE, toolbar.annotationMode); - toolbar.toggleAnnotation(); + toolbar.setAnnotationMode(AnnotationMode.DRAW); await microtasksFinished(); - chrome.test.assertTrue(toolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.DRAW, toolbar.annotationMode); finishInkStroke(PluginController.getInstance()); await microtasksFinished();
diff --git a/chrome/test/data/pdf/ink2_bottom_toolbar_test.ts b/chrome/test/data/pdf/ink2_bottom_toolbar_test.ts index bbaf70a..96a92c2 100644 --- a/chrome/test/data/pdf/ink2_bottom_toolbar_test.ts +++ b/chrome/test/data/pdf/ink2_bottom_toolbar_test.ts
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import {AnnotationBrushType, UserAction} from 'chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/pdf_viewer_wrapper.js'; +import {AnnotationBrushType, AnnotationMode, UserAction} from 'chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/pdf_viewer_wrapper.js'; import type {InkColorSelectorElement, InkSizeSelectorElement, ViewerBottomToolbarDropdownElement, ViewerBottomToolbarElement} from 'chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/pdf_viewer_wrapper.js'; import {microtasksFinished} from 'chrome://webui-test/test_util.js'; @@ -58,10 +58,10 @@ async function testOpenBottomToolbar() { const mockMetricsPrivate = setupMockMetricsPrivate(); - viewer.$.toolbar.toggleAnnotation(); + viewer.$.toolbar.setAnnotationMode(AnnotationMode.DRAW); await microtasksFinished(); - chrome.test.assertTrue(viewer.$.toolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.DRAW, viewer.$.toolbar.annotationMode); chrome.test.assertTrue( !!viewer.shadowRoot.querySelector('viewer-bottom-toolbar')); mockMetricsPrivate.assertCount(UserAction.OPEN_INK2_SIDE_PANEL, 0); @@ -70,7 +70,7 @@ }, async function testSelectPen() { - chrome.test.assertTrue(viewer.$.toolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.DRAW, viewer.$.toolbar.annotationMode); // Default to a black pen. Cannot use assertAnnotationBrush() yet, since // there's no need to set the brush in the backend immediately after getting @@ -108,7 +108,7 @@ // Test that the eraser can be selected. async function testSelectEraser() { - chrome.test.assertTrue(viewer.$.toolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.DRAW, viewer.$.toolbar.annotationMode); // Switch to eraser. setGetAnnotationBrushReply(mockPlugin, AnnotationBrushType.ERASER); @@ -131,7 +131,7 @@ // Test that the highlighter can be selected. async function testSelectHighlighter() { - chrome.test.assertTrue(viewer.$.toolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.DRAW, viewer.$.toolbar.annotationMode); // Switch to highlighter. setGetAnnotationBrushReply(
diff --git a/chrome/test/data/pdf/ink2_save_test.ts b/chrome/test/data/pdf/ink2_save_test.ts index 8466018..ab1226c 100644 --- a/chrome/test/data/pdf/ink2_save_test.ts +++ b/chrome/test/data/pdf/ink2_save_test.ts
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import {PluginController, SaveRequestType, UserAction} from 'chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/pdf_viewer_wrapper.js'; +import {AnnotationMode, PluginController, SaveRequestType, UserAction} from 'chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/pdf_viewer_wrapper.js'; import {assert} from 'chrome://resources/js/assert.js'; import {eventToPromise, microtasksFinished} from 'chrome://webui-test/test_util.js'; @@ -51,9 +51,9 @@ mockPlugin.clearMessages(); mockMetricsPrivate.reset(); - viewerToolbar.toggleAnnotation(); + viewerToolbar.setAnnotationMode(AnnotationMode.DRAW); await microtasksFinished(); - chrome.test.assertTrue(viewerToolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.DRAW, viewerToolbar.annotationMode); const downloadControls = getDownloadControls(); const downloadButton = downloadControls.$.download; @@ -68,7 +68,7 @@ chrome.test.assertTrue(saveMessage !== undefined); chrome.test.assertEq(saveMessage.saveRequestType, SaveRequestType.ORIGINAL); chrome.test.assertFalse(actionMenu.open); - chrome.test.assertTrue(viewerToolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.DRAW, viewerToolbar.annotationMode); mockMetricsPrivate.assertCount(UserAction.SAVE_ORIGINAL_ONLY, 1); chrome.test.succeed(); }, @@ -131,14 +131,14 @@ // Tests that while outside of annotation mode, on a PDF with an ink stroke, // clicking the download button will prompt the download menu. async function testSaveMenuWithStrokeExitAnnotationMode() { - chrome.test.assertTrue(viewerToolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.DRAW, viewerToolbar.annotationMode); mockPlugin.clearMessages(); mockMetricsPrivate.reset(); - viewerToolbar.toggleAnnotation(); + viewerToolbar.setAnnotationMode(AnnotationMode.NONE); await microtasksFinished(); - chrome.test.assertFalse(viewerToolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.NONE, viewerToolbar.annotationMode); const downloadControls = getDownloadControls(); downloadControls.$.menu.close(); @@ -153,14 +153,14 @@ // while in annotation mode, after an undo operation, clicking the download // button will save the PDF as original. async function testSaveOriginalAfterUndo() { - chrome.test.assertFalse(viewerToolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.NONE, viewerToolbar.annotationMode); mockPlugin.clearMessages(); mockMetricsPrivate.reset(); - viewerToolbar.toggleAnnotation(); + viewerToolbar.setAnnotationMode(AnnotationMode.DRAW); await microtasksFinished(); - chrome.test.assertTrue(viewerToolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.DRAW, viewerToolbar.annotationMode); const undoButton = getRequiredElement<HTMLButtonElement>(viewerToolbar, '#undo');
diff --git a/chrome/test/data/pdf/ink2_side_panel_test.ts b/chrome/test/data/pdf/ink2_side_panel_test.ts index 9302b0e..83a66e77 100644 --- a/chrome/test/data/pdf/ink2_side_panel_test.ts +++ b/chrome/test/data/pdf/ink2_side_panel_test.ts
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import {AnnotationBrushType, UserAction} from 'chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/pdf_viewer_wrapper.js'; +import {AnnotationBrushType, AnnotationMode, UserAction} from 'chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/pdf_viewer_wrapper.js'; import type {InkColorSelectorElement, InkSizeSelectorElement} from 'chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/pdf_viewer_wrapper.js'; import {microtasksFinished} from 'chrome://webui-test/test_util.js'; @@ -31,10 +31,10 @@ async function testOpenSidePanel() { const mockMetricsPrivate = setupMockMetricsPrivate(); - viewer.$.toolbar.toggleAnnotation(); + viewer.$.toolbar.setAnnotationMode(AnnotationMode.DRAW); await microtasksFinished(); - chrome.test.assertTrue(viewer.$.toolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.DRAW, viewer.$.toolbar.annotationMode); chrome.test.assertTrue( !!viewer.shadowRoot.querySelector('viewer-side-panel')); mockMetricsPrivate.assertCount(UserAction.OPEN_INK2_SIDE_PANEL, 1); @@ -45,7 +45,7 @@ // Test that the pen can be selected. Test that its size and color can be // selected. async function testSelectPen() { - chrome.test.assertTrue(viewer.$.toolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.DRAW, viewer.$.toolbar.annotationMode); // Default to a black pen. Cannot use assertAnnotationBrush() yet, since // there's no need to set the brush in the backend immediately after getting @@ -82,7 +82,7 @@ // Test that the eraser can be selected. async function testSelectEraser() { - chrome.test.assertTrue(viewer.$.toolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.DRAW, viewer.$.toolbar.annotationMode); // Switch to eraser. setGetAnnotationBrushReply(mockPlugin, AnnotationBrushType.ERASER); @@ -105,7 +105,7 @@ // Test that the highlighter can be selected. async function testSelectHighlighter() { - chrome.test.assertTrue(viewer.$.toolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.DRAW, viewer.$.toolbar.annotationMode); // Switch to highlighter. setGetAnnotationBrushReply(
diff --git a/chrome/test/data/pdf/ink2_test.ts b/chrome/test/data/pdf/ink2_test.ts index 506d581..23cd1e4 100644 --- a/chrome/test/data/pdf/ink2_test.ts +++ b/chrome/test/data/pdf/ink2_test.ts
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import {UserAction} from 'chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/pdf_viewer_wrapper.js'; +import {AnnotationMode, UserAction} from 'chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/pdf_viewer_wrapper.js'; import {assert} from 'chrome://resources/js/assert.js'; import {loadTimeData} from 'chrome://resources/js/load_time_data.js'; import {isVisible, microtasksFinished} from 'chrome://webui-test/test_util.js'; @@ -23,20 +23,20 @@ chrome.test.succeed(); }, - // Test that annotation mode can be toggled. - async function testToggleAnnotationMode() { + // Test that annotation mode can be set. + async function testSetAnnotationMode() { mockMetricsPrivate.reset(); - chrome.test.assertFalse(viewerToolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.NONE, viewerToolbar.annotationMode); - viewer.$.toolbar.toggleAnnotation(); + viewer.$.toolbar.setAnnotationMode(AnnotationMode.DRAW); await microtasksFinished(); - chrome.test.assertTrue(viewerToolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.DRAW, viewerToolbar.annotationMode); mockMetricsPrivate.assertCount(UserAction.ENTER_INK2_ANNOTATION_MODE, 1); - viewer.$.toolbar.toggleAnnotation(); + viewer.$.toolbar.setAnnotationMode(AnnotationMode.NONE); await microtasksFinished(); - chrome.test.assertFalse(viewerToolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.NONE, viewerToolbar.annotationMode); mockMetricsPrivate.assertCount(UserAction.EXIT_INK2_ANNOTATION_MODE, 1); chrome.test.succeed(); }, @@ -46,24 +46,24 @@ async function testSidePanelVisible() { mockMetricsPrivate.reset(); - chrome.test.assertFalse(viewerToolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.NONE, viewerToolbar.annotationMode); - viewerToolbar.toggleAnnotation(); + viewerToolbar.setAnnotationMode(AnnotationMode.DRAW); await microtasksFinished(); mockMetricsPrivate.assertCount(UserAction.ENTER_INK2_ANNOTATION_MODE, 1); const sidePanel = viewer.shadowRoot.querySelector('viewer-side-panel'); assert(sidePanel); // The side panel should be visible when annotation mode is enabled. - chrome.test.assertTrue(viewerToolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.DRAW, viewerToolbar.annotationMode); chrome.test.assertTrue(isVisible(sidePanel)); - viewerToolbar.toggleAnnotation(); + viewerToolbar.setAnnotationMode(AnnotationMode.NONE); await microtasksFinished(); mockMetricsPrivate.assertCount(UserAction.EXIT_INK2_ANNOTATION_MODE, 1); // The side panel should be hidden when annotation mode is disabled. - chrome.test.assertFalse(viewerToolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.NONE, viewerToolbar.annotationMode); chrome.test.assertFalse(isVisible(sidePanel)); chrome.test.succeed();
diff --git a/chrome/test/data/pdf/ink2_viewer_toolbar_test.ts b/chrome/test/data/pdf/ink2_viewer_toolbar_test.ts index 693676a..4a634c7 100644 --- a/chrome/test/data/pdf/ink2_viewer_toolbar_test.ts +++ b/chrome/test/data/pdf/ink2_viewer_toolbar_test.ts
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import {PluginController, UserAction} from 'chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/pdf_viewer_wrapper.js'; +import {AnnotationMode, PluginController, UserAction} from 'chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/pdf_viewer_wrapper.js'; import {isMac} from 'chrome://resources/js/platform.js'; import {keyDownOn} from 'chrome://webui-test/keyboard_mock_interactions.js'; import {eventToPromise, microtasksFinished} from 'chrome://webui-test/test_util.js'; @@ -22,35 +22,35 @@ chrome.test.runTests([ // Test that clicking the annotation button toggles annotation mode. async function testAnnotationButton() { - chrome.test.assertFalse(viewerToolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.NONE, viewerToolbar.annotationMode); const annotateButton = getRequiredElement(viewerToolbar, '#annotate'); annotateButton.click(); await microtasksFinished(); - chrome.test.assertTrue(viewerToolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.DRAW, viewerToolbar.annotationMode); annotateButton.click(); await microtasksFinished(); - chrome.test.assertFalse(viewerToolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.NONE, viewerToolbar.annotationMode); chrome.test.succeed(); }, // <if expr="enable_ink"> // Test that the original Ink annotation bar is not used. async function testInkAnnotationBarNotVisible() { - chrome.test.assertFalse(viewerToolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.NONE, viewerToolbar.annotationMode); - viewerToolbar.toggleAnnotation(); + viewerToolbar.setAnnotationMode(AnnotationMode.DRAW); await microtasksFinished(); - chrome.test.assertTrue(viewerToolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.DRAW, viewerToolbar.annotationMode); chrome.test.assertTrue( !viewerToolbar.shadowRoot.querySelector('viewer-annotations-bar')); - viewerToolbar.toggleAnnotation(); + viewerToolbar.setAnnotationMode(AnnotationMode.NONE); await microtasksFinished(); - chrome.test.assertFalse(viewerToolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.NONE, viewerToolbar.annotationMode); chrome.test.assertTrue( !viewerToolbar.shadowRoot.querySelector('viewer-annotations-bar')); chrome.test.succeed(); @@ -59,9 +59,9 @@ // not have the same limitations. Test that these buttons are still enabled in // Ink2 annotation mode. async function testInk1DisabledButtonsAreEnabled() { - chrome.test.assertFalse(viewerToolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.NONE, viewerToolbar.annotationMode); - viewerToolbar.toggleAnnotation(); + viewerToolbar.setAnnotationMode(AnnotationMode.DRAW); await microtasksFinished(); const rotationButton = @@ -69,15 +69,15 @@ const twoPageViewButton = getRequiredElement<HTMLButtonElement>( viewerToolbar, '#two-page-view-button'); - chrome.test.assertTrue(viewerToolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.DRAW, viewerToolbar.annotationMode); chrome.test.assertFalse(viewerToolbar.$.sidenavToggle.disabled); chrome.test.assertFalse(rotationButton.disabled); chrome.test.assertFalse(twoPageViewButton.disabled); - viewerToolbar.toggleAnnotation(); + viewerToolbar.setAnnotationMode(AnnotationMode.NONE); await microtasksFinished(); - chrome.test.assertFalse(viewerToolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.NONE, viewerToolbar.annotationMode); chrome.test.assertFalse(viewerToolbar.$.sidenavToggle.disabled); chrome.test.assertFalse(rotationButton.disabled); chrome.test.assertFalse(twoPageViewButton.disabled); @@ -90,20 +90,20 @@ await openToolbarMenu(viewerToolbar); // Start the test with annotation mode disabled and annotations displayed. - chrome.test.assertFalse(viewerToolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.NONE, viewerToolbar.annotationMode); const showAnnotationsButton = getRequiredElement(viewerToolbar, '#show-annotations-button'); assertCheckboxMenuButton(viewerToolbar, showAnnotationsButton, true); // Enabling and disabling annotation mode shouldn't affect displaying // annotations. - viewerToolbar.toggleAnnotation(); + viewerToolbar.setAnnotationMode(AnnotationMode.DRAW); await microtasksFinished(); - chrome.test.assertTrue(viewerToolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.DRAW, viewerToolbar.annotationMode); assertCheckboxMenuButton(viewerToolbar, showAnnotationsButton, true); - viewerToolbar.toggleAnnotation(); + viewerToolbar.setAnnotationMode(AnnotationMode.NONE); await microtasksFinished(); - chrome.test.assertFalse(viewerToolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.NONE, viewerToolbar.annotationMode); assertCheckboxMenuButton(viewerToolbar, showAnnotationsButton, true); // Hide annotations. @@ -117,23 +117,23 @@ // Enabling and disabling annotation mode shouldn't affect displaying // annotations. - viewerToolbar.toggleAnnotation(); + viewerToolbar.setAnnotationMode(AnnotationMode.DRAW); await microtasksFinished(); - chrome.test.assertTrue(viewerToolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.DRAW, viewerToolbar.annotationMode); assertCheckboxMenuButton(viewerToolbar, showAnnotationsButton, false); - viewerToolbar.toggleAnnotation(); + viewerToolbar.setAnnotationMode(AnnotationMode.NONE); await microtasksFinished(); - chrome.test.assertFalse(viewerToolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.NONE, viewerToolbar.annotationMode); assertCheckboxMenuButton(viewerToolbar, showAnnotationsButton, false); chrome.test.succeed(); }, // Test that toggling annotation mode sends a message to the PDF content. async function testToggleAnnotationModeSendsMessage() { - chrome.test.assertFalse(viewerToolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.NONE, viewerToolbar.annotationMode); - viewerToolbar.toggleAnnotation(); + viewerToolbar.setAnnotationMode(AnnotationMode.DRAW); await microtasksFinished(); - chrome.test.assertTrue(viewerToolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.DRAW, viewerToolbar.annotationMode); const enableMessage = mockPlugin.findMessage('setAnnotationMode'); chrome.test.assertTrue(enableMessage !== null); @@ -141,9 +141,9 @@ mockPlugin.clearMessages(); - viewerToolbar.toggleAnnotation(); + viewerToolbar.setAnnotationMode(AnnotationMode.NONE); await microtasksFinished(); - chrome.test.assertFalse(viewerToolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.NONE, viewerToolbar.annotationMode); const disableMessage = mockPlugin.findMessage('setAnnotationMode'); chrome.test.assertTrue(disableMessage !== null); @@ -155,29 +155,29 @@ async function testPresentationModeExitsAnnotationMode() { // First, check that there's no interaction with toggling presentation mode // when annotation mode is disabled. - chrome.test.assertFalse(viewerToolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.NONE, viewerToolbar.annotationMode); await enterFullscreenWithUserGesture(); - chrome.test.assertFalse(viewerToolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.NONE, viewerToolbar.annotationMode); document.exitFullscreen(); await eventToPromise('fullscreenchange', viewer.$.scroller); - chrome.test.assertFalse(viewerToolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.NONE, viewerToolbar.annotationMode); // Now, check the interaction of toggling presentation mode when annotation // mode is enabled. - viewerToolbar.toggleAnnotation(); + viewerToolbar.setAnnotationMode(AnnotationMode.DRAW); await microtasksFinished(); - chrome.test.assertTrue(viewerToolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.DRAW, viewerToolbar.annotationMode); // Entering presentation mode should disable annotation mode. await enterFullscreenWithUserGesture(); - chrome.test.assertFalse(viewerToolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.NONE, viewerToolbar.annotationMode); // Exiting presentation mode should re-enable annotation mode. document.exitFullscreen(); await eventToPromise('fullscreenchange', viewer.$.scroller); - chrome.test.assertTrue(viewerToolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.DRAW, viewerToolbar.annotationMode); chrome.test.succeed(); }, // Test the behavior of the undo and redo buttons. @@ -256,13 +256,13 @@ async function testUndoRedoButtonsDisabledOnFormFieldFocus() { mockPlugin.clearMessages(); - chrome.test.assertTrue(viewerToolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.DRAW, viewerToolbar.annotationMode); // Exit annotation mode, since form fields can only be focused outside of // annotation mode. - viewerToolbar.toggleAnnotation(); + viewerToolbar.setAnnotationMode(AnnotationMode.NONE); await microtasksFinished(); - chrome.test.assertFalse(viewerToolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.NONE, viewerToolbar.annotationMode); const undoButton = getRequiredElement<HTMLButtonElement>(viewerToolbar, '#undo'); @@ -318,12 +318,12 @@ mockPlugin.clearMessages(); mockMetricsPrivate.reset(); - chrome.test.assertFalse(viewerToolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.NONE, viewerToolbar.annotationMode); // Enable annotation mode. - viewerToolbar.toggleAnnotation(); + viewerToolbar.setAnnotationMode(AnnotationMode.DRAW); await microtasksFinished(); - chrome.test.assertTrue(viewerToolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.DRAW, viewerToolbar.annotationMode); finishInkStroke(controller); @@ -354,7 +354,7 @@ mockPlugin.clearMessages(); mockMetricsPrivate.reset(); - chrome.test.assertTrue(viewerToolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.DRAW, viewerToolbar.annotationMode); // Draw two strokes and undo, so that both undo and redo buttons are // enabled. @@ -368,9 +368,9 @@ // Exit annotation mode, since form fields can only be focused outside of // annotation mode. - viewerToolbar.toggleAnnotation(); + viewerToolbar.setAnnotationMode(AnnotationMode.NONE); await microtasksFinished(); - chrome.test.assertFalse(viewerToolbar.annotationMode); + chrome.test.assertEq(AnnotationMode.NONE, viewerToolbar.annotationMode); mockPlugin.clearMessages();
diff --git a/chrome/test/data/webui/settings/glic_page_test.ts b/chrome/test/data/webui/settings/glic_page_test.ts index a34c604..6c4439b5 100644 --- a/chrome/test/data/webui/settings/glic_page_test.ts +++ b/chrome/test/data/webui/settings/glic_page_test.ts
@@ -6,13 +6,14 @@ import type {CrCollapseElement} from 'chrome://settings/lazy_load.js'; import type {SettingsGlicPageElement, SettingsPrefsElement, SettingsToggleButtonElement} from 'chrome://settings/settings.js'; -import {CrSettingsPrefs, GlicBrowserProxyImpl, loadTimeData, OpenWindowProxyImpl, resetRouterForTesting, Router, routes, SettingsGlicPageFeaturePrefName as PrefName} from 'chrome://settings/settings.js'; +import {CrSettingsPrefs, GlicBrowserProxyImpl, loadTimeData, MetricsBrowserProxyImpl, OpenWindowProxyImpl, resetRouterForTesting, Router, routes, SettingsGlicPageFeaturePrefName as PrefName} from 'chrome://settings/settings.js'; import {assertEquals, assertFalse, assertTrue} from 'chrome://webui-test/chai_assert.js'; import {flushTasks} from 'chrome://webui-test/polymer_test_util.js'; import {TestOpenWindowProxy} from 'chrome://webui-test/test_open_window_proxy.js'; import {isVisible} from 'chrome://webui-test/test_util.js'; import {TestGlicBrowserProxy} from './test_glic_browser_proxy.js'; +import {TestMetricsBrowserProxy} from './test_metrics_browser_proxy.js'; const POLICY_ENABLED_VALUE = 0; const POLICY_DISABLED_VALUE = 1; @@ -26,9 +27,12 @@ let settingsPrefs: SettingsPrefsElement; let glicBrowserProxy: TestGlicBrowserProxy; let openWindowProxy: TestOpenWindowProxy; + let metricsBrowserProxy: TestMetricsBrowserProxy; function createGlicPage(initialShortcut: string) { document.body.innerHTML = window.trustedTypes!.emptyHTML; + metricsBrowserProxy = new TestMetricsBrowserProxy(); + MetricsBrowserProxyImpl.setInstance(metricsBrowserProxy); glicBrowserProxy = new TestGlicBrowserProxy(); glicBrowserProxy.setGlicShortcutResponse(initialShortcut); @@ -381,4 +385,55 @@ assertTrue(!!infoCard); assertFalse(infoCard.opened); }); + + suite('Metrics', () => { + async function verifyUserAction(userAction: string) { + const userActions = await metricsBrowserProxy.getArgs('recordAction'); + assertEquals(1, userActions.length); + assertTrue(userActions.includes(userAction)); + metricsBrowserProxy.reset(); + } + + test('GeolocationToggle', async () => { + page.setPrefValue(PrefName.GEOLOCATION_ENABLED, false); + + const geolocationToggle = + $<SettingsToggleButtonElement>('geolocationToggle')!; + assertTrue(!!geolocationToggle); + + geolocationToggle.click(); + await verifyUserAction('Glic.Settings.Geolocation.Enabled'); + + geolocationToggle.click(); + await verifyUserAction('Glic.Settings.Geolocation.Disabled'); + }); + + test('MicrophoneToggle', async () => { + page.setPrefValue(PrefName.MICROPHONE_ENABLED, false); + + const microphoneToggle = + $<SettingsToggleButtonElement>('microphoneToggle')!; + assertTrue(!!microphoneToggle); + + microphoneToggle.click(); + await verifyUserAction('Glic.Settings.Microphone.Enabled'); + + microphoneToggle.click(); + await verifyUserAction('Glic.Settings.Microphone.Disabled'); + }); + + test('TabContextToggle', async () => { + page.setPrefValue(PrefName.TAB_CONTEXT_ENABLED, false); + + const tabAccessToggle = + $<SettingsToggleButtonElement>('tabAccessToggle')!; + assertTrue(!!tabAccessToggle); + + tabAccessToggle.click(); + await verifyUserAction('Glic.Settings.TabContext.Enabled'); + + tabAccessToggle.click(); + await verifyUserAction('Glic.Settings.TabContext.Disabled'); + }); + }); });
diff --git a/chrome/test/delayload/delayload_hook_browsertest.cc b/chrome/test/delayload/delayload_hook_browsertest.cc index 47ad002..c1f034f 100644 --- a/chrome/test/delayload/delayload_hook_browsertest.cc +++ b/chrome/test/delayload/delayload_hook_browsertest.cc
@@ -7,6 +7,7 @@ #include <delayimp.h> #include <roerrorapi.h> +#include "base/compiler_specific.h" #include "base/run_loop.h" #include "chrome/common/win/delay_load_notify_hook.h" #include "chrome/test/base/in_process_browser_test.h" @@ -36,8 +37,8 @@ if (delay_load_event == dliNotePreGetProcAddress && base::EqualsCaseInsensitiveASCII( delay_load_info->szDll, "api-ms-win-core-winrt-error-l1-1-0.dll") && - strcmp(delay_load_info->dlp.szProcName, "RoFailFastWithErrorContext") == - 0) { + UNSAFE_TODO(strcmp(delay_load_info->dlp.szProcName, + "RoFailFastWithErrorContext")) == 0) { return reinterpret_cast<FARPROC>(RoFailFastWithErrorContextPatch); }
diff --git a/chrome/updater/app/server/win/com_classes_util.cc b/chrome/updater/app/server/win/com_classes_util.cc index 7e49c0c..b893c26 100644 --- a/chrome/updater/app/server/win/com_classes_util.cc +++ b/chrome/updater/app/server/win/com_classes_util.cc
@@ -7,6 +7,7 @@ #include <optional> #include <string> +#include "base/compiler_specific.h" #include "base/files/file_path.h" #include "base/logging.h" #include "base/strings/utf_string_conversions.h" @@ -45,7 +46,9 @@ std::optional<std::string> ValidateStringEmptyNotOk(const wchar_t* value, size_t max_length) { std::string value_s; - return value && base::WideToUTF8(value, wcslen(value), &value_s) && + return value && + base::WideToUTF8(value, UNSAFE_TODO(wcslen(value)), + &value_s) && !value_s.empty() && (value_s.length() <= max_length) ? std::make_optional(value_s) : std::nullopt; @@ -55,7 +58,7 @@ size_t max_length) { std::string value_s; return !value ? std::make_optional(value_s) - : base::WideToUTF8(value, wcslen(value), &value_s) && + : base::WideToUTF8(value, UNSAFE_TODO(wcslen(value)), &value_s) && (value_s.length() <= max_length) ? std::make_optional(value_s) : std::nullopt;
diff --git a/chrome/updater/configurator.cc b/chrome/updater/configurator.cc index aec87aa..60e5d686 100644 --- a/chrome/updater/configurator.cc +++ b/chrome/updater/configurator.cc
@@ -80,7 +80,8 @@ GetNetworkFetcherFactory(); #endif static crash_reporter::CrashKeyString<6> crash_key_managed("managed"); - crash_key_managed.Set(base::ToString(is_managed_device_)); + crash_key_managed.Set(is_managed_device_ ? base::ToString(*is_managed_device_) + : "n/a"); } Configurator::~Configurator() = default;
diff --git a/chrome/updater/win/setup/setup_util.cc b/chrome/updater/win/setup/setup_util.cc index 5149075..d62ce229 100644 --- a/chrome/updater/win/setup/setup_util.cc +++ b/chrome/updater/win/setup/setup_util.cc
@@ -20,6 +20,7 @@ #include "base/check.h" #include "base/command_line.h" +#include "base/compiler_specific.h" #include "base/containers/flat_map.h" #include "base/files/file_path.h" #include "base/logging.h" @@ -448,7 +449,7 @@ std::wstring GetProgIdForClsid(REFCLSID clsid) { auto clsid_comparator = [](REFCLSID a, REFCLSID b) { - return std::memcmp(&a, &b, sizeof(a)) < 0; + return UNSAFE_TODO(std::memcmp(&a, &b, sizeof(a))) < 0; }; const base::flat_map<CLSID, std::wstring, decltype(clsid_comparator)>
diff --git a/chrome/utility/importer/edge_database_reader_unittest_win.cc b/chrome/utility/importer/edge_database_reader_unittest_win.cc index b83f2a33..973941f3 100644 --- a/chrome/utility/importer/edge_database_reader_unittest_win.cc +++ b/chrome/utility/importer/edge_database_reader_unittest_win.cc
@@ -10,6 +10,7 @@ #include <array> +#include "base/compiler_specific.h" #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" #include "base/path_service.h" @@ -168,8 +169,8 @@ GUID guid_col_value = {}; GUID expected_guid_col_value = {}; EXPECT_TRUE(table_enum->RetrieveColumn(L"GuidCol", &guid_col_value)); - memset(&expected_guid_col_value, row_count, - sizeof(expected_guid_col_value)); + UNSAFE_TODO(memset(&expected_guid_col_value, row_count, + sizeof(expected_guid_col_value))); EXPECT_EQ(expected_guid_col_value, guid_col_value); FILETIME filetime_col_value = {}; @@ -331,9 +332,10 @@ GUID guid_col_value = {}; GUID expected_guid_col_value = {}; - memset(&guid_col_value, 0x1, sizeof(guid_col_value)); + UNSAFE_TODO(memset(&guid_col_value, 0x1, sizeof(guid_col_value))); EXPECT_TRUE(table_enum->RetrieveColumn(L"GuidCol", &guid_col_value)); - memset(&expected_guid_col_value, 0, sizeof(expected_guid_col_value)); + UNSAFE_TODO( + memset(&expected_guid_col_value, 0, sizeof(expected_guid_col_value))); EXPECT_EQ(expected_guid_col_value, guid_col_value); FILETIME filetime_col_value = {1, 1};
diff --git a/chrome/utility/importer/edge_database_reader_win.cc b/chrome/utility/importer/edge_database_reader_win.cc index 52612e656..bcb86756 100644 --- a/chrome/utility/importer/edge_database_reader_win.cc +++ b/chrome/utility/importer/edge_database_reader_win.cc
@@ -2,6 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#ifdef UNSAFE_BUFFERS_BUILD +// TODO(crbug.com/390223051): Remove C-library calls to fix the errors. +#pragma allow_unsafe_libc_calls +#endif + #include "chrome/utility/importer/edge_database_reader_win.h" #include <windows.h>
diff --git a/chrome/utility/importer/edge_importer_win.cc b/chrome/utility/importer/edge_importer_win.cc index fe19ad9..0d4ed0f6 100644 --- a/chrome/utility/importer/edge_importer_win.cc +++ b/chrome/utility/importer/edge_importer_win.cc
@@ -13,6 +13,7 @@ #include <tuple> #include <vector> +#include "base/compiler_specific.h" #include "base/files/file_enumerator.h" #include "base/files/file_path.h" #include "base/files/file_util.h" @@ -100,7 +101,7 @@ struct GuidComparator { bool operator()(const GUID& a, const GUID& b) const { - return memcmp(&a, &b, sizeof(a)) < 0; + return UNSAFE_TODO(memcmp(&a, &b, sizeof(a))) < 0; } };
diff --git a/chrome/utility/importer/ie_importer_win.cc b/chrome/utility/importer/ie_importer_win.cc index f97e552a..13c16f6 100644 --- a/chrome/utility/importer/ie_importer_win.cc +++ b/chrome/utility/importer/ie_importer_win.cc
@@ -20,6 +20,7 @@ #include <string> #include <vector> +#include "base/compiler_specific.h" #include "base/containers/contains.h" #include "base/files/file_enumerator.h" #include "base/files/file_path.h" @@ -76,7 +77,7 @@ bool BinaryRead(T* data, size_t offset, const std::vector<uint8_t>& blob) { if (offset + sizeof(T) > blob.size()) return false; - memcpy(data, &blob[offset], sizeof(T)); + UNSAFE_TODO(memcpy(data, &blob[offset], sizeof(T))); return true; }
diff --git a/chromeos/CHROMEOS_LKGM b/chromeos/CHROMEOS_LKGM index ba05ff4e..621ee8e96 100644 --- a/chromeos/CHROMEOS_LKGM +++ b/chromeos/CHROMEOS_LKGM
@@ -1 +1 @@ -16230.0.0-1067701 \ No newline at end of file +16231.0.0-1067707 \ No newline at end of file
diff --git a/chromeos/ash/components/boca/babelorca/soda_installer.cc b/chromeos/ash/components/boca/babelorca/soda_installer.cc index 4b656cbd..d7081ad1 100644 --- a/chromeos/ash/components/boca/babelorca/soda_installer.cc +++ b/chromeos/ash/components/boca/babelorca/soda_installer.cc
@@ -30,7 +30,13 @@ return; } - callback_ = std::move(callback); + callbacks_.push(std::move(callback)); + + if (installing_) { + return; + } + installing_ = true; + soda_installer->AddObserver(this); // if no other SODA features are currently active @@ -48,27 +54,30 @@ // This event is triggered whenever any language pack or the SODA binary is // installed, but we should only begin speech recognition when the language // pack associated with BabelOrca is installed. - if (callback_.is_null() || + if (callbacks_.empty() || language_code != speech::GetLanguageCode(language_)) { return; } - std::move(callback_).Run(true); + FlushCallbacks(true); + speech::SodaInstaller::GetInstance()->RemoveObserver(this); + installing_ = false; } void SodaInstaller::OnSodaInstallError( speech::LanguageCode language_code, speech::SodaInstaller::ErrorCode error_code) { - if (callback_.is_null()) { + if (callbacks_.empty()) { return; } // If the language code is kNone then the binary failed to install. if (language_code == speech::GetLanguageCode(language_) || language_code == speech::LanguageCode::kNone) { - std::move(callback_).Run(false); + FlushCallbacks(false); speech::SodaInstaller::GetInstance()->RemoveObserver(this); + installing_ = false; } } @@ -77,4 +86,11 @@ void SodaInstaller::OnSodaProgress(speech::LanguageCode language_code, int progress) {} +void SodaInstaller::FlushCallbacks(bool result) { + while (!callbacks_.empty()) { + std::move(callbacks_.front()).Run(result); + callbacks_.pop(); + } +} + } // namespace ash::babelorca
diff --git a/chromeos/ash/components/boca/babelorca/soda_installer.h b/chromeos/ash/components/boca/babelorca/soda_installer.h index a032c215..e3d2c5a 100644 --- a/chromeos/ash/components/boca/babelorca/soda_installer.h +++ b/chromeos/ash/components/boca/babelorca/soda_installer.h
@@ -5,6 +5,8 @@ #ifndef CHROMEOS_ASH_COMPONENTS_BOCA_BABELORCA_SODA_INSTALLER_H_ #define CHROMEOS_ASH_COMPONENTS_BOCA_BABELORCA_SODA_INSTALLER_H_ +#include <queue> + #include "base/functional/callback_forward.h" #include "components/prefs/pref_service.h" #include "components/soda/constants.h" @@ -37,7 +39,10 @@ int progress) override; private: - AvailabilityCallback callback_; + void FlushCallbacks(bool result); + + std::queue<AvailabilityCallback> callbacks_; + bool installing_ = false; const std::string language_; raw_ptr<PrefService> global_prefs_; raw_ptr<PrefService> profile_prefs_;
diff --git a/chromeos/ash/components/boca/babelorca/soda_installer_unittest.cc b/chromeos/ash/components/boca/babelorca/soda_installer_unittest.cc index 03659df..ad645ec 100644 --- a/chromeos/ash/components/boca/babelorca/soda_installer_unittest.cc +++ b/chromeos/ash/components/boca/babelorca/soda_installer_unittest.cc
@@ -208,4 +208,51 @@ speech::GetLanguageCode(kDefaultLanguage), speech::SodaInstaller::ErrorCode::kUnspecifiedError); } + +TEST_F(BabelOrcaSodaInstallerTest, HandlesMultipleInstallationObservers) { + bool speech_recognition_available_one = false; + bool speech_recognition_available_two = false; + + EXPECT_CALL(soda_installer_, InstallSoda).Times(1); + EXPECT_CALL(soda_installer_, InstallLanguage).Times(2); + + installer_under_test_->GetAvailabilityOrInstall(base::BindLambdaForTesting( + [&speech_recognition_available_one](bool available) { + speech_recognition_available_one = available; + })); + installer_under_test_->GetAvailabilityOrInstall(base::BindLambdaForTesting( + [&speech_recognition_available_two](bool available) { + speech_recognition_available_two = available; + })); + speech::SodaInstaller::GetInstance()->NotifySodaInstalledForTesting(); + speech::SodaInstaller::GetInstance()->NotifySodaInstalledForTesting( + speech::GetLanguageCode(kDefaultLanguage)); + + ASSERT_TRUE(speech_recognition_available_one); + ASSERT_TRUE(speech_recognition_available_two); +} + +TEST_F(BabelOrcaSodaInstallerTest, + HandlesMultipleInstallationObserversOnFailure) { + bool speech_recognition_available_one = true; + bool speech_recognition_available_two = true; + + EXPECT_CALL(soda_installer_, InstallSoda).Times(1); + EXPECT_CALL(soda_installer_, InstallLanguage).Times(2); + + installer_under_test_->GetAvailabilityOrInstall(base::BindLambdaForTesting( + [&speech_recognition_available_one](bool available) { + speech_recognition_available_one = available; + })); + installer_under_test_->GetAvailabilityOrInstall(base::BindLambdaForTesting( + [&speech_recognition_available_two](bool available) { + speech_recognition_available_two = available; + })); + speech::SodaInstaller::GetInstance()->NotifySodaInstalledForTesting(); + speech::SodaInstaller::GetInstance()->NotifySodaErrorForTesting( + speech::GetLanguageCode(kDefaultLanguage)); + + ASSERT_FALSE(speech_recognition_available_one); + ASSERT_FALSE(speech_recognition_available_two); +} } // namespace ash::babelorca
diff --git a/chromeos/printing/printer_translator_unittest.cc b/chromeos/printing/printer_translator_unittest.cc index 9e604ec4..91ae7916 100644 --- a/chromeos/printing/printer_translator_unittest.cc +++ b/chromeos/printing/printer_translator_unittest.cc
@@ -297,7 +297,8 @@ // generic printer does not have the URI field set. CheckPrinterInfoUri(printer_info, "ipp", "", ""); - ExpectDictBooleanValue(false, printer_info, "printerPpdReference.autoconf"); + EXPECT_EQ(printer_info.FindBoolByDottedPath("printerPpdReference.autoconf"), + false); } TEST(PrinterTranslatorTest, GetCupsPrinterInfoGenericPrinterWithUri) { @@ -309,7 +310,8 @@ CheckPrinterInfoUri(printer_info, "ipp", "printy.domain.co:555", "ipp/print"); - ExpectDictBooleanValue(false, printer_info, "printerPpdReference.autoconf"); + EXPECT_EQ(printer_info.FindBoolByDottedPath("printerPpdReference.autoconf"), + false); } TEST(PrinterTranslatorTest, GetCupsPrinterInfoGenericPrinterWithUsbUri) { @@ -321,7 +323,8 @@ CheckPrinterInfoUri(printer_info, "usb", "1234", "af9d?serial=ink1"); - ExpectDictBooleanValue(false, printer_info, "printerPpdReference.autoconf"); + EXPECT_EQ(printer_info.FindBoolByDottedPath("printerPpdReference.autoconf"), + false); } TEST(PrinterTranslatorTest, GetCupsPrinterInfoAutoconfPrinter) { @@ -335,18 +338,19 @@ // Since this is an autoconf printer we expect "printerPpdReference.autoconf" // to be true. - ExpectDictBooleanValue(true, printer_info, "printerPpdReference.autoconf"); + EXPECT_EQ(printer_info.FindBoolByDottedPath("printerPpdReference.autoconf"), + true); } TEST(PrinterTranslatorTest, GetCupsPrinterInfoManagedPrinter) { Printer printer = CreateGenericPrinter(); printer.set_source(Printer::Source::SRC_USER_PREFS); base::Value::Dict printer_info = GetCupsPrinterInfo(printer); - ExpectDictBooleanValue(false, printer_info, "isManaged"); + EXPECT_EQ(printer_info.FindBool("isManaged"), false); printer.set_source(Printer::Source::SRC_POLICY); printer_info = GetCupsPrinterInfo(printer); - ExpectDictBooleanValue(true, printer_info, "isManaged"); + EXPECT_EQ(printer_info.FindBool("isManaged"), true); } } // namespace chromeos
diff --git a/clank b/clank index 6b91d2b..3caed26 160000 --- a/clank +++ b/clank
@@ -1 +1 @@ -Subproject commit 6b91d2bd0932898c7335092d8cb758efacbd61c8 +Subproject commit 3caed26bf65373a93272f352981764ff9e3b6209
diff --git a/components/autofill/content/renderer/password_autofill_agent.cc b/components/autofill/content/renderer/password_autofill_agent.cc index adbe8607..33481e5 100644 --- a/components/autofill/content/renderer/password_autofill_agent.cc +++ b/components/autofill/content/renderer/password_autofill_agent.cc
@@ -1835,12 +1835,13 @@ const bool show_webauthn_credentials = field.parsed_autocomplete() && field.parsed_autocomplete()->webauthn; GetPasswordManagerDriver().ShowPasswordSuggestions(PasswordSuggestionRequest( - field.renderer_id(), form, trigger_source, - GetIndexOfElement(form, username_element), - GetIndexOfElement(form, password_element), field.text_direction(), - typed_username, show_webauthn_credentials, - gfx::RectF(render_frame()->ConvertViewportToWindow( - user_input.BoundsInWidget())))); + TriggeringField(field.renderer_id(), trigger_source, + field.text_direction(), typed_username, + show_webauthn_credentials, + gfx::RectF(render_frame()->ConvertViewportToWindow( + user_input.BoundsInWidget()))), + form, GetIndexOfElement(form, username_element), + GetIndexOfElement(form, password_element))); } void PasswordAutofillAgent::CleanupOnDocumentShutdown() {
diff --git a/components/autofill/core/common/mojom/autofill_types.mojom b/components/autofill/core/common/mojom/autofill_types.mojom index 4c4f179..9b28011 100644 --- a/components/autofill/core/common/mojom/autofill_types.mojom +++ b/components/autofill/core/common/mojom/autofill_types.mojom
@@ -508,20 +508,26 @@ bool generation_rejected; }; -// autofill::PasswordSuggestionRequest +// autofill::TriggeringField // (components/autofill/core/common/password_form_fill_data.h) -struct PasswordSuggestionRequest { +struct TriggeringField { FieldRendererId element_id; - FormData form_data; AutofillSuggestionTriggerSource trigger_source; - uint64 username_field_index; - uint64 password_field_index; mojo_base.mojom.TextDirection text_direction; mojo_base.mojom.String16 typed_username; bool show_webauthn_credentials; gfx.mojom.RectF bounds; }; +// autofill::PasswordSuggestionRequest +// (components/autofill/core/common/password_form_fill_data.h) +struct PasswordSuggestionRequest { + TriggeringField field; + FormData form_data; + uint64 username_field_index; + uint64 password_field_index; +}; + // autofill::ParsingResult // (components/autofill/core/common/password_form_fill_data.h) struct ParsingResult {
diff --git a/components/autofill/core/common/mojom/autofill_types_mojom_traits.cc b/components/autofill/core/common/mojom/autofill_types_mojom_traits.cc index 45b34c3..dc59762 100644 --- a/components/autofill/core/common/mojom/autofill_types_mojom_traits.cc +++ b/components/autofill/core/common/mojom/autofill_types_mojom_traits.cc
@@ -631,20 +631,28 @@ } // static +bool StructTraits<autofill::mojom::TriggeringFieldDataView, + autofill::TriggeringField>:: + Read(autofill::mojom::TriggeringFieldDataView data, + autofill::TriggeringField* out) { + out->show_webauthn_credentials = data.show_webauthn_credentials(); + + return data.ReadElementId(&out->element_id) && + data.ReadTriggerSource(&out->trigger_source) && + data.ReadTextDirection(&out->text_direction) && + data.ReadTypedUsername(&out->typed_username) && + data.ReadBounds(&out->bounds); +} + +// static bool StructTraits<autofill::mojom::PasswordSuggestionRequestDataView, autofill::PasswordSuggestionRequest>:: Read(autofill::mojom::PasswordSuggestionRequestDataView data, autofill::PasswordSuggestionRequest* out) { out->username_field_index = data.username_field_index(); out->password_field_index = data.password_field_index(); - out->show_webauthn_credentials = data.show_webauthn_credentials(); - return data.ReadElementId(&out->element_id) && - data.ReadFormData(&out->form_data) && - data.ReadTriggerSource(&out->trigger_source) && - data.ReadTextDirection(&out->text_direction) && - data.ReadTypedUsername(&out->typed_username) && - data.ReadBounds(&out->bounds); + return data.ReadField(&out->field) && data.ReadFormData(&out->form_data); } bool StructTraits<
diff --git a/components/autofill/core/common/mojom/autofill_types_mojom_traits.h b/components/autofill/core/common/mojom/autofill_types_mojom_traits.h index 5e7c89297..a4728aca 100644 --- a/components/autofill/core/common/mojom/autofill_types_mojom_traits.h +++ b/components/autofill/core/common/mojom/autofill_types_mojom_traits.h
@@ -714,11 +714,46 @@ }; template <> +struct StructTraits<autofill::mojom::TriggeringFieldDataView, + autofill::TriggeringField> { + static autofill::FieldRendererId element_id( + const autofill::TriggeringField& r) { + return r.element_id; + } + + static autofill::AutofillSuggestionTriggerSource trigger_source( + const autofill::TriggeringField& r) { + return r.trigger_source; + } + + static base::i18n::TextDirection text_direction( + const autofill::TriggeringField& r) { + return r.text_direction; + } + + static const std::u16string& typed_username( + const autofill::TriggeringField& r) { + return r.typed_username; + } + + static int show_webauthn_credentials(const autofill::TriggeringField& r) { + return r.show_webauthn_credentials; + } + + static const gfx::RectF& bounds(const autofill::TriggeringField& r) { + return r.bounds; + } + + static bool Read(autofill::mojom::TriggeringFieldDataView data, + autofill::TriggeringField* out); +}; + +template <> struct StructTraits<autofill::mojom::PasswordSuggestionRequestDataView, autofill::PasswordSuggestionRequest> { - static autofill::FieldRendererId element_id( + static autofill::TriggeringField field( const autofill::PasswordSuggestionRequest& r) { - return r.element_id; + return r.field; } static const autofill::FormData& form_data( @@ -726,11 +761,6 @@ return r.form_data; } - static autofill::AutofillSuggestionTriggerSource trigger_source( - const autofill::PasswordSuggestionRequest& r) { - return r.trigger_source; - } - static uint64_t username_field_index( const autofill::PasswordSuggestionRequest& r) { return r.username_field_index; @@ -741,26 +771,6 @@ return r.password_field_index; } - static base::i18n::TextDirection text_direction( - const autofill::PasswordSuggestionRequest& r) { - return r.text_direction; - } - - static const std::u16string& typed_username( - const autofill::PasswordSuggestionRequest& r) { - return r.typed_username; - } - - static int show_webauthn_credentials( - const autofill::PasswordSuggestionRequest& r) { - return r.show_webauthn_credentials; - } - - static const gfx::RectF& bounds( - const autofill::PasswordSuggestionRequest& r) { - return r.bounds; - } - static bool Read(autofill::mojom::PasswordSuggestionRequestDataView data, autofill::PasswordSuggestionRequest* out); };
diff --git a/components/autofill/core/common/mojom/autofill_types_mojom_traits_unittest.cc b/components/autofill/core/common/mojom/autofill_types_mojom_traits_unittest.cc index ac1d792..d17552e 100644 --- a/components/autofill/core/common/mojom/autofill_types_mojom_traits_unittest.cc +++ b/components/autofill/core/common/mojom/autofill_types_mojom_traits_unittest.cc
@@ -92,17 +92,20 @@ data->form_data = test::CreateTestAddressFormData(); } -void CreatePasswordSuggestionRequest(PasswordSuggestionRequest* data) { +void CreateTriggeringField(TriggeringField* data) { data->element_id = FieldRendererId(123); - data->form_data = test::CreateTestAddressFormData(); data->trigger_source = AutofillSuggestionTriggerSource::kFormControlElementClicked; - data->username_field_index = 0ul; - data->password_field_index = 1ul; data->text_direction = base::i18n::RIGHT_TO_LEFT; data->typed_username = u"username"; data->show_webauthn_credentials = true; +} + +void CreatePasswordSuggestionRequest(PasswordSuggestionRequest* data) { + CreateTriggeringField(&data->field); data->form_data = test::CreateTestAddressFormData(); + data->username_field_index = 0ul; + data->password_field_index = 1ul; } void CheckEqualPasswordFormFillData(const PasswordFormFillData& expected, @@ -130,15 +133,10 @@ test::WithoutUnserializedData(expected.form_data), actual.form_data)); } -void CheckEqualPasswordSuggestionRequest( - const PasswordSuggestionRequest& expected, - const PasswordSuggestionRequest& actual) { +void CheckEqualTriggeringField(const TriggeringField& expected, + const TriggeringField& actual) { EXPECT_EQ(expected.element_id, actual.element_id); - EXPECT_TRUE(FormData::DeepEqual( - test::WithoutUnserializedData(expected.form_data), actual.form_data)); EXPECT_EQ(expected.trigger_source, actual.trigger_source); - EXPECT_EQ(expected.username_field_index, actual.username_field_index); - EXPECT_EQ(expected.password_field_index, actual.password_field_index); EXPECT_EQ(expected.text_direction, actual.text_direction); EXPECT_EQ(expected.typed_username, actual.typed_username); EXPECT_EQ(expected.show_webauthn_credentials, @@ -146,6 +144,16 @@ EXPECT_EQ(expected.bounds, actual.bounds); } +void CheckEqualPasswordSuggestionRequest( + const PasswordSuggestionRequest& expected, + const PasswordSuggestionRequest& actual) { + CheckEqualTriggeringField(expected.field, actual.field); + EXPECT_TRUE(FormData::DeepEqual( + test::WithoutUnserializedData(expected.form_data), actual.form_data)); + EXPECT_EQ(expected.username_field_index, actual.username_field_index); + EXPECT_EQ(expected.password_field_index, actual.password_field_index); +} + class AutofillTypeTraitsTestImpl : public testing::Test, public mojom::TypeTraitsTest { public:
diff --git a/components/autofill/core/common/password_form_fill_data.cc b/components/autofill/core/common/password_form_fill_data.cc index da054b43..b9191133 100644 --- a/components/autofill/core/common/password_form_fill_data.cc +++ b/components/autofill/core/common/password_form_fill_data.cc
@@ -21,26 +21,36 @@ default; PasswordAndMetadata::~PasswordAndMetadata() = default; -PasswordSuggestionRequest::PasswordSuggestionRequest( - FieldRendererId element_id, - const FormData& form_data, - AutofillSuggestionTriggerSource trigger_source, - uint64_t username_field_index, - uint64_t password_field_index, - base::i18n::TextDirection text_direction, - const std::u16string& typed_username, - bool show_webauthn_credentials, - const gfx::RectF& bounds) +TriggeringField::TriggeringField(FieldRendererId element_id, + AutofillSuggestionTriggerSource trigger_source, + base::i18n::TextDirection text_direction, + const std::u16string& typed_username, + bool show_webauthn_credentials, + const gfx::RectF& bounds) : element_id(element_id), - form_data(form_data), trigger_source(trigger_source), - username_field_index(username_field_index), - password_field_index(password_field_index), text_direction(text_direction), typed_username(typed_username), show_webauthn_credentials(show_webauthn_credentials), bounds(bounds) {} +TriggeringField::TriggeringField() = default; +TriggeringField::TriggeringField(const TriggeringField&) = default; +TriggeringField& TriggeringField::operator=(const TriggeringField&) = default; +TriggeringField::TriggeringField(TriggeringField&&) = default; +TriggeringField& TriggeringField::operator=(TriggeringField&&) = default; +TriggeringField::~TriggeringField() = default; + +PasswordSuggestionRequest::PasswordSuggestionRequest( + TriggeringField field, + const FormData& form_data, + uint64_t username_field_index, + uint64_t password_field_index) + : field(field), + form_data(form_data), + username_field_index(username_field_index), + password_field_index(password_field_index) {} + PasswordSuggestionRequest::PasswordSuggestionRequest() = default; PasswordSuggestionRequest::PasswordSuggestionRequest( const PasswordSuggestionRequest&) = default; @@ -64,17 +74,19 @@ PasswordFormFillData MaybeClearPasswordValues( const PasswordFormFillData& data) { - // In case when there is a username on a page (for example in a hidden field), - // credentials from |additional_logins| could be used for filling on load. So - // in case of filling on load nor |password_field| nor |additional_logins| - // can't be cleared + // In case when there is a username on a page (for example in a hidden + // field), credentials from |additional_logins| could be used for filling + // on load. So in case of filling on load nor |password_field| nor + // |additional_logins| can't be cleared bool is_fallback = data.password_element_renderer_id.is_null(); - if (!data.wait_for_username && !is_fallback) + if (!data.wait_for_username && !is_fallback) { return data; + } PasswordFormFillData result(data); result.preferred_login.password_value.clear(); - for (auto& credentials : result.additional_logins) + for (auto& credentials : result.additional_logins) { credentials.password_value.clear(); + } return result; }
diff --git a/components/autofill/core/common/password_form_fill_data.h b/components/autofill/core/common/password_form_fill_data.h index 14dc382..8f5d2794 100644 --- a/components/autofill/core/common/password_form_fill_data.h +++ b/components/autofill/core/common/password_form_fill_data.h
@@ -37,39 +37,26 @@ bool is_grouped_affiliation = false; }; -// Structure used to trigger password suggestion generation. -struct PasswordSuggestionRequest { - PasswordSuggestionRequest(FieldRendererId element_id, - const FormData& form_data, - AutofillSuggestionTriggerSource trigger_source, - uint64_t username_field_index, - uint64_t password_field_index, - base::i18n::TextDirection text_direction, - const std::u16string& typed_username, - bool show_webauthn_credentials, - const gfx::RectF& bounds); - - PasswordSuggestionRequest(); - PasswordSuggestionRequest(const PasswordSuggestionRequest&); - PasswordSuggestionRequest& operator=(const PasswordSuggestionRequest&); - PasswordSuggestionRequest(PasswordSuggestionRequest&&); - PasswordSuggestionRequest& operator=(PasswordSuggestionRequest&&); - ~PasswordSuggestionRequest(); +// Minimal struct that describes and identifies a form field which triggered a +// `PasswordSuggestionRequest`. Should be a password or username field. +struct TriggeringField { + TriggeringField(FieldRendererId element_id, + AutofillSuggestionTriggerSource trigger_source, + base::i18n::TextDirection text_direction, + const std::u16string& typed_username, + bool show_webauthn_credentials, + const gfx::RectF& bounds); + TriggeringField(); + TriggeringField(const TriggeringField&); + TriggeringField& operator=(const TriggeringField&); + TriggeringField(TriggeringField&&); + TriggeringField& operator=(TriggeringField&&); + ~TriggeringField(); // The unique renderer id of the field that the user has clicked. FieldRendererId element_id; - // A web form extracted from the DOM that contains the triggering field. - FormData form_data; - // Describes the way suggestion generation was triggered. + // Describes the way suggestion generation for this field was triggered. AutofillSuggestionTriggerSource trigger_source; - // The index of the username field in the `form_data.fields`. If the password - // form doesn't contain the username field, this value will be equal to - // `form_data.fields.size()`. - uint64_t username_field_index; - // The index of the password field in the `form_data.fields`. If the password - // form doesn't contain the password field, this value will be equal to - // `form_data.fields.size()`. - uint64_t password_field_index; // Direction of the text for the triggering field. base::i18n::TextDirection text_direction; // The value of the username field. This will be empty if the suggestion @@ -81,6 +68,36 @@ gfx::RectF bounds; }; +// Structure used to trigger password suggestion generation. +struct PasswordSuggestionRequest { + PasswordSuggestionRequest(TriggeringField field, + const FormData& form_data, + uint64_t username_field_index, + uint64_t password_field_index); + + PasswordSuggestionRequest(); + PasswordSuggestionRequest(const PasswordSuggestionRequest&); + PasswordSuggestionRequest& operator=(const PasswordSuggestionRequest&); + PasswordSuggestionRequest(PasswordSuggestionRequest&&); + PasswordSuggestionRequest& operator=(PasswordSuggestionRequest&&); + ~PasswordSuggestionRequest(); + + // Information to identify and locate the triggering field. + TriggeringField field; + // A web form extracted from the DOM that contains the triggering field. + FormData form_data; + // The index of the username field in the `form_data.fields`. If the password + // form doesn't contain the username field, this value will be equal to + // `form_data.fields.size()`. Either this or `password_field_index` should be + // available. + uint64_t username_field_index; + // The index of the password field in the `form_data.fields`. If the password + // form doesn't contain the password field, this value will be equal to + // `form_data.fields.size()`. Either this or `username_field_index` should be + // available. + uint64_t password_field_index; +}; + // Structure used for autofilling password forms. Note that the realms in this // struct are only set when the password's realm differs from the realm of the // form that we are filling.
diff --git a/components/browser_ui/site_settings/android/java/src/org/chromium/components/browser_ui/site_settings/AllSiteSettings.java b/components/browser_ui/site_settings/android/java/src/org/chromium/components/browser_ui/site_settings/AllSiteSettings.java index 917ba3f..f37c0bb 100644 --- a/components/browser_ui/site_settings/android/java/src/org/chromium/components/browser_ui/site_settings/AllSiteSettings.java +++ b/components/browser_ui/site_settings/android/java/src/org/chromium/components/browser_ui/site_settings/AllSiteSettings.java
@@ -77,7 +77,6 @@ // should only be All Sites or Storage. public static final String EXTRA_CATEGORY = "category"; public static final String EXTRA_TITLE = "title"; - public static final String EXTRA_SEARCH = "search"; /** * If present, the list of websites will be filtered by domain using {@link @@ -86,8 +85,6 @@ public static final String EXTRA_SELECTED_DOMAINS = "selected_domains"; public static final String PREF_CLEAR_BROWSING_DATA = "clear_browsing_data_link"; - // Prefix for Related Website Sets search filter (mobile-desktop feature parity) - public static final String RWS_SEARCH_PREFIX = "related:"; // The clear button displayed in the Storage view. private @Nullable Button mClearButton; @@ -363,11 +360,6 @@ ? new HashSet<>(getArguments().getStringArrayList(EXTRA_SELECTED_DOMAINS)) : null; - mSearch = - getArguments().containsKey(EXTRA_SEARCH) - ? RWS_SEARCH_PREFIX + getArguments().getString(EXTRA_SEARCH) - : mSearch; - setHasOptionsMenu(true); super.onActivityCreated(savedInstanceState); @@ -502,7 +494,7 @@ List<WebsiteRowPreference> preferences = new ArrayList<>(); // Find entries matching the current search. for (WebsiteEntry entry : entries) { - if (filterSearchResult(entry)) { + if (mSearch == null || mSearch.isEmpty() || entry.matches(mSearch)) { WebsiteRowPreference preference = new WebsiteRowPreference( getStyledContext(), @@ -543,21 +535,6 @@ } } - private boolean filterSearchResult(WebsiteEntry entry) { - if (getSiteSettingsDelegate().shouldShowPrivacySandboxRwsUi() - && mSearch != null - && mSearch.startsWith(RWS_SEARCH_PREFIX)) { - return entry.isPartOfRws() - && assumeNonNull(entry.getRwsOwner()) - .contains( - mSearch.replace( - RWS_SEARCH_PREFIX, - "")); // no need to check empty and null - } else { - return mSearch == null || mSearch.isEmpty() || entry.matches(mSearch); - } - } - private Context getStyledContext() { return getPreferenceManager().getContext(); }
diff --git a/components/browser_ui/widget/android/BUILD.gn b/components/browser_ui/widget/android/BUILD.gn index 86b2ac3..cf6f669 100644 --- a/components/browser_ui/widget/android/BUILD.gn +++ b/components/browser_ui/widget/android/BUILD.gn
@@ -220,6 +220,7 @@ "java/res/drawable/bg_white_dialog.xml", "java/res/drawable/bottom_sheet_background.xml", "java/res/drawable/card_with_corners_background.xml", + "java/res/drawable/custom_tile_background.xml", "java/res/drawable/home_surface_ui_background.xml", "java/res/drawable/ic_arrow_back_24dp.xml", "java/res/drawable/ic_check_googblue_24dp_animated.xml",
diff --git a/components/browser_ui/widget/android/java/res/drawable/custom_tile_background.xml b/components/browser_ui/widget/android/java/res/drawable/custom_tile_background.xml new file mode 100644 index 0000000..b7d91387 --- /dev/null +++ b/components/browser_ui/widget/android/java/res/drawable/custom_tile_background.xml
@@ -0,0 +1,12 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- +Copyright 2025 The Chromium Authors +Use of this source code is governed by a BSD-style license that can be +found in the LICENSE file. +--> + +<shape + xmlns:android="http://schemas.android.com/apk/res/android" + android:shape="oval"> + <solid android:color="@color/custom_tile_background_color_placeholder" /> +</shape>
diff --git a/components/browser_ui/widget/android/java/res/layout/loading_fullscreen.xml b/components/browser_ui/widget/android/java/res/layout/loading_fullscreen.xml index 4bcba2fb..463b14c 100644 --- a/components/browser_ui/widget/android/java/res/layout/loading_fullscreen.xml +++ b/components/browser_ui/widget/android/java/res/layout/loading_fullscreen.xml
@@ -5,7 +5,7 @@ found in the LICENSE file. --> -<LinearLayout +<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/loading_fullscreen_container" android:layout_width="match_parent" @@ -14,29 +14,15 @@ android:paddingEnd="@dimen/left_right_padding" android:paddingTop="@dimen/top_bottom_padding" android:paddingBottom="@dimen/top_bottom_padding" - android:orientation="vertical" android:visibility="gone" > - <org.chromium.ui.widget.ChromeImageButton - android:src="@drawable/btn_close" - android:id="@+id/loading_close_button" - android:layout_height="24dp" - android:layout_width="24dp" - android:background="@android:color/transparent" - android:tint="@color/default_icon_color_secondary_tint_list" /> - <LinearLayout - android:layout_width="match_parent" - android:layout_height="match_parent" + android:id="@+id/progress_spinner_container" + android:layout_width="wrap_content" + android:layout_height="wrap_content" android:orientation="vertical" - android:gravity="center"> - - <TextView - android:id="@+id/loading_text" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:paddingBottom="@dimen/text_bottom_padding" - android:textAppearance="@style/TextAppearance.TextMedium.Secondary" /> + android:gravity="center" + android:layout_centerInParent="true"> <include android:id="@+id/progress_spinner" @@ -44,4 +30,13 @@ </LinearLayout> -</LinearLayout> + <org.chromium.ui.widget.ButtonCompat + android:id="@+id/loading_cancel_button" + style="@style/TextButton" + android:text="@string/cancel" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_alignParentBottom="true" + android:layout_centerHorizontal="true" /> + +</RelativeLayout>
diff --git a/components/browser_ui/widget/android/java/res/values/dimens.xml b/components/browser_ui/widget/android/java/res/values/dimens.xml index 3104d83..30208f1b 100644 --- a/components/browser_ui/widget/android/java/res/values/dimens.xml +++ b/components/browser_ui/widget/android/java/res/values/dimens.xml
@@ -230,5 +230,4 @@ <!-- Loading Fullscreen dimens --> <dimen name="left_right_padding">16dp</dimen> <dimen name="top_bottom_padding">18dp</dimen> - <dimen name="text_bottom_padding">30dp</dimen> </resources>
diff --git a/components/browser_ui/widget/android/java/src/org/chromium/components/browser_ui/widget/loading/LoadingFullscreenCoordinator.java b/components/browser_ui/widget/android/java/src/org/chromium/components/browser_ui/widget/loading/LoadingFullscreenCoordinator.java index 596524f..cfc6cdb 100644 --- a/components/browser_ui/widget/android/java/src/org/chromium/components/browser_ui/widget/loading/LoadingFullscreenCoordinator.java +++ b/components/browser_ui/widget/android/java/src/org/chromium/components/browser_ui/widget/loading/LoadingFullscreenCoordinator.java
@@ -7,7 +7,6 @@ import android.app.Activity; import android.view.View; import android.view.ViewGroup; -import android.widget.TextView; import androidx.annotation.ColorInt; @@ -44,17 +43,20 @@ * * @param onFinishCallback The callback to call when the loading screen exits. */ - public void startLoading(String loadingText, Runnable onFinishCallback) { + public void startLoading(Runnable onFinishCallback) { @ColorInt int backgroundColor = SemanticColorUtils.getDefaultBgColor(mActivity); - TextView textView = mContainer.findViewById(R.id.loading_text); - textView.setText(loadingText); - View.OnClickListener closeButtonClickListener = + View.OnClickListener cancelButtonClickListener = (view) -> { onFinishCallback.run(); }; mContainer - .findViewById(R.id.loading_close_button) - .setOnClickListener(closeButtonClickListener); + .findViewById(R.id.loading_cancel_button) + .setOnClickListener(cancelButtonClickListener); + + // Do not stack two loading screens. + if (mPropertyModel != null) { + closeLoadingScreen(); + } mPropertyModel = new PropertyModel.Builder(ScrimProperties.ALL_KEYS)
diff --git a/components/browser_ui/widget/android/java/src/org/chromium/components/browser_ui/widget/loading/LoadingFullscreenCoordinatorUnitTest.java b/components/browser_ui/widget/android/java/src/org/chromium/components/browser_ui/widget/loading/LoadingFullscreenCoordinatorUnitTest.java index 1beea54..c0efa2b 100644 --- a/components/browser_ui/widget/android/java/src/org/chromium/components/browser_ui/widget/loading/LoadingFullscreenCoordinatorUnitTest.java +++ b/components/browser_ui/widget/android/java/src/org/chromium/components/browser_ui/widget/loading/LoadingFullscreenCoordinatorUnitTest.java
@@ -4,14 +4,12 @@ package org.chromium.components.browser_ui.widget.loading; -import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; import android.app.Activity; -import android.widget.LinearLayout; -import android.widget.TextView; +import android.widget.RelativeLayout; import org.junit.Before; import org.junit.Rule; @@ -28,7 +26,7 @@ import org.chromium.chrome.R; import org.chromium.components.browser_ui.widget.scrim.ScrimManager; import org.chromium.ui.modelutil.PropertyModel; -import org.chromium.ui.widget.ChromeImageButton; +import org.chromium.ui.widget.ButtonCompat; /** Unit tests for {@link LoadingFullscreenCoordinator}. */ @RunWith(BaseRobolectricTestRunner.class) @@ -50,27 +48,23 @@ @Test public void testShowLoading() { - LinearLayout layout = - (LinearLayout) + RelativeLayout layout = + (RelativeLayout) mActivity.getLayoutInflater().inflate(R.layout.loading_fullscreen, null); - ChromeImageButton closeButton = layout.findViewById(R.id.loading_close_button); - TextView text = layout.findViewById(R.id.loading_text); - assertNotNull(layout); + ButtonCompat cancelButton = layout.findViewById(R.id.loading_cancel_button); + assertNotNull(cancelButton); LoadingFullscreenCoordinator loadingCoordinator = new LoadingFullscreenCoordinator(mActivity, mScrimManager, layout); - String loadingText = "loading_text"; loadingCoordinator.startLoading( - loadingText, () -> { loadingCoordinator.closeLoadingScreen(); }); verify(mScrimManager).showScrim(mPropertyModelArgumentCaptor.capture()); PropertyModel propertyModel = mPropertyModelArgumentCaptor.getValue(); - closeButton.performClick(); + cancelButton.performClick(); verify(mScrimManager).hideScrim(eq(propertyModel), eq(true)); - assertEquals(loadingText, text.getText().toString()); } }
diff --git a/components/browser_ui/widget/android/java/src/org/chromium/components/browser_ui/widget/tile/TileView.java b/components/browser_ui/widget/android/java/src/org/chromium/components/browser_ui/widget/tile/TileView.java index 0410501f..23c268d4 100644 --- a/components/browser_ui/widget/android/java/src/org/chromium/components/browser_ui/widget/tile/TileView.java +++ b/components/browser_ui/widget/android/java/src/org/chromium/components/browser_ui/widget/tile/TileView.java
@@ -98,6 +98,11 @@ mTitleView.setText(title); } + /** Changes the appearance of a tile to indicate that it's a Custom Tile. */ + protected void setStyleForCustomTile() { + mIconBackgroundView.setBackgroundResource(R.drawable.custom_tile_background); + } + /** Specify the handler that will be invoked when this tile is highlighted by the user. */ void setOnFocusViaSelectionListener(Runnable listener) { mOnFocusViaSelectionListener = listener;
diff --git a/components/collaboration/components_unittests.filter b/components/collaboration/components_unittests.filter index b22ce73..dcb2b28 100644 --- a/components/collaboration/components_unittests.filter +++ b/components/collaboration/components_unittests.filter
@@ -1,6 +1,7 @@ *CollaborationServiceImplTest.* *CollaborationControllerTest.* *EmptyCollaborationServiceTest.* +*InstantMessageProcessorImplTest.* *MessagingBackendServiceBridgeTest.* *MessagingBackendServiceImplTest.* *MessagingBackendStoreTest.*
diff --git a/components/collaboration/internal/BUILD.gn b/components/collaboration/internal/BUILD.gn index 7349db47..ff0395b 100644 --- a/components/collaboration/internal/BUILD.gn +++ b/components/collaboration/internal/BUILD.gn
@@ -86,6 +86,9 @@ "messaging/data_sharing_change_notifier_impl.h", "messaging/empty_messaging_backend_service.cc", "messaging/empty_messaging_backend_service.h", + "messaging/instant_message_processor.h", + "messaging/instant_message_processor_impl.cc", + "messaging/instant_message_processor_impl.h", "messaging/messaging_backend_service_impl.cc", "messaging/messaging_backend_service_impl.h", "messaging/storage/collaboration_message_util.cc", @@ -175,6 +178,7 @@ testonly = true sources = [ "messaging/data_sharing_change_notifier_impl_unittest.cc", + "messaging/instant_message_processor_impl_unittest.cc", "messaging/messaging_backend_service_impl_unittest.cc", "messaging/storage/messaging_backend_database_impl_unittest.cc", "messaging/storage/messaging_backend_store_impl_unittest.cc", @@ -184,6 +188,7 @@ ":messaging_internal", "//base", "//base/test:test_support", + "//components/collaboration:test_support", "//components/collaboration/internal/messaging/storage/protocol", "//components/collaboration/public:messaging_public", "//components/data_sharing:test_support",
diff --git a/components/collaboration/internal/android/java/src/org/chromium/components/collaboration/messaging/MessagingBackendServiceBridgeUnitTestCompanion.java b/components/collaboration/internal/android/java/src/org/chromium/components/collaboration/messaging/MessagingBackendServiceBridgeUnitTestCompanion.java index 4cb5a675..6fc394c6 100644 --- a/components/collaboration/internal/android/java/src/org/chromium/components/collaboration/messaging/MessagingBackendServiceBridgeUnitTestCompanion.java +++ b/components/collaboration/internal/android/java/src/org/chromium/components/collaboration/messaging/MessagingBackendServiceBridgeUnitTestCompanion.java
@@ -154,11 +154,10 @@ Assert.assertEquals(InstantNotificationType.CONFLICT_TAB_REMOVED, message.type); Assert.assertEquals(CollaborationEvent.TAB_REMOVED, message.collaborationEvent); Assert.assertEquals("Message content - single message", message.localizedMessage); - Assert.assertNotNull(message.attribution); - Assert.assertNull(message.aggregatedData); // MessageAttribution. - MessageAttribution attribution = message.attribution; + Assert.assertTrue(message.isSingleMessage()); + MessageAttribution attribution = message.attributions.get(0); Assert.assertEquals("cf07d904-88d4-4bc9-989d-57a9ab9e17a7", attribution.id); Assert.assertEquals("my group", attribution.collaborationId); Assert.assertEquals(new GaiaId("affected"), attribution.affectedUser.gaiaId); @@ -191,19 +190,18 @@ Assert.assertEquals(InstantNotificationType.CONFLICT_TAB_REMOVED, message.type); Assert.assertEquals(CollaborationEvent.TAB_REMOVED, message.collaborationEvent); Assert.assertEquals("Message content - aggregated message", message.localizedMessage); - Assert.assertNull(message.attribution); - Assert.assertNotNull(message.aggregatedData); - Assert.assertEquals(2, message.aggregatedData.attributions.size()); + Assert.assertFalse(message.isSingleMessage()); + Assert.assertEquals(2, message.attributions.size()); // Attribution 1. - MessageAttribution attribution1 = message.aggregatedData.attributions.get(0); + MessageAttribution attribution1 = message.attributions.get(0); Assert.assertEquals("cf07d904-88d4-4bc9-989d-57a9ab9e17a7", attribution1.id); Assert.assertEquals("my group", attribution1.collaborationId); Assert.assertEquals(new GaiaId("affected"), attribution1.affectedUser.gaiaId); Assert.assertEquals(new GaiaId("triggering"), attribution1.triggeringUser.gaiaId); // Attribution 2. - MessageAttribution attribution2 = message.aggregatedData.attributions.get(1); + MessageAttribution attribution2 = message.attributions.get(1); Assert.assertEquals("24ed7c34-41a3-47c2-aad4-5ea42a1765d5", attribution2.id); Assert.assertEquals("my group", attribution2.collaborationId); Assert.assertEquals(new GaiaId("affected 2"), attribution2.affectedUser.gaiaId);
diff --git a/components/collaboration/internal/android/java/src/org/chromium/components/collaboration/messaging/bridge/ConversionUtils.java b/components/collaboration/internal/android/java/src/org/chromium/components/collaboration/messaging/bridge/ConversionUtils.java index b4cfb7b..9df36b74 100644 --- a/components/collaboration/internal/android/java/src/org/chromium/components/collaboration/messaging/bridge/ConversionUtils.java +++ b/components/collaboration/internal/android/java/src/org/chromium/components/collaboration/messaging/bridge/ConversionUtils.java
@@ -12,7 +12,6 @@ import org.chromium.build.annotations.NullMarked; import org.chromium.build.annotations.Nullable; import org.chromium.components.collaboration.messaging.ActivityLogItem; -import org.chromium.components.collaboration.messaging.AggregatedMessageData; import org.chromium.components.collaboration.messaging.CollaborationEvent; import org.chromium.components.collaboration.messaging.InstantMessage; import org.chromium.components.collaboration.messaging.InstantNotificationLevel; @@ -28,6 +27,7 @@ import org.chromium.components.tab_groups.TabGroupColorId; import java.util.ArrayList; +import java.util.List; import java.util.Optional; /** @@ -116,27 +116,25 @@ @InstantNotificationLevel int level, @InstantNotificationType int type, String localizedMessage, - @Nullable MessageAttribution attribution, - @Nullable AggregatedMessageData aggregatedData) { + List<MessageAttribution> attributions) { InstantMessage message = new InstantMessage(); message.collaborationEvent = collaborationEvent; message.level = level; message.type = type; message.localizedMessage = localizedMessage; - message.attribution = attribution; - message.aggregatedData = aggregatedData; + message.attributions = attributions; return message; } @CalledByNative - private static AggregatedMessageData addAttributionToAggregatedMessageData( - @Nullable AggregatedMessageData aggregatedMessageData, MessageAttribution attribution) { - if (aggregatedMessageData == null) { - aggregatedMessageData = new AggregatedMessageData(); + private static List<MessageAttribution> addAttributionToList( + @Nullable List<MessageAttribution> attributions, MessageAttribution attribution) { + if (attributions == null) { + attributions = new ArrayList<>(); } - aggregatedMessageData.attributions.add(attribution); - return aggregatedMessageData; + attributions.add(attribution); + return attributions; } @CalledByNative
diff --git a/components/collaboration/internal/android/messaging/conversion_utils.cc b/components/collaboration/internal/android/messaging/conversion_utils.cc index c0ffb7b2..bc58a5e 100644 --- a/components/collaboration/internal/android/messaging/conversion_utils.cc +++ b/components/collaboration/internal/android/messaging/conversion_utils.cc
@@ -122,19 +122,18 @@ return jmessage; } -ScopedJavaLocalRef<jobject> AggregatedMessageMetadataToJava( +ScopedJavaLocalRef<jobject> AttributionListToJava( JNIEnv* env, - const AggregatedMessageData& aggregated_data) { - ScopedJavaLocalRef<jobject> j_aggregated_data; + const std::vector<MessageAttribution>& attributions) { + ScopedJavaLocalRef<jobject> j_attribution_list; - for (const auto& attribution : aggregated_data.attributions) { + for (const auto& attribution : attributions) { auto j_attribution = MessageAttributionToJava(env, attribution); - j_aggregated_data = - Java_ConversionUtils_addAttributionToAggregatedMessageData( - env, j_aggregated_data, j_attribution); + j_attribution_list = Java_ConversionUtils_addAttributionToList( + env, j_attribution_list, j_attribution); } - return j_aggregated_data; + return j_attribution_list; } } // namespace @@ -161,20 +160,13 @@ ScopedJavaLocalRef<jobject> InstantMessageToJava( JNIEnv* env, const InstantMessage& message) { - ScopedJavaLocalRef<jobject> j_attribution = - message.attribution.has_value() - ? MessageAttributionToJava(env, message.attribution.value()) - : ScopedJavaLocalRef<jobject>(); - ScopedJavaLocalRef<jobject> j_aggregated_data = - message.aggregated_data.has_value() - ? AggregatedMessageMetadataToJava(env, - message.aggregated_data.value()) - : ScopedJavaLocalRef<jobject>(); + ScopedJavaLocalRef<jobject> j_attribution_list = + AttributionListToJava(env, message.attributions); return Java_ConversionUtils_createInstantMessage( env, static_cast<int>(message.collaboration_event), static_cast<int>(message.level), static_cast<int>(message.type), - ConvertUTF16ToJavaString(env, message.localized_message), j_attribution, - j_aggregated_data); + ConvertUTF16ToJavaString(env, message.localized_message), + j_attribution_list); } ScopedJavaLocalRef<jobject> ActivityLogItemsToJava(
diff --git a/components/collaboration/internal/android/messaging/messaging_backend_service_bridge_unittest.cc b/components/collaboration/internal/android/messaging/messaging_backend_service_bridge_unittest.cc index 369975c..f6af5f6 100644 --- a/components/collaboration/internal/android/messaging/messaging_backend_service_bridge_unittest.cc +++ b/components/collaboration/internal/android/messaging/messaging_backend_service_bridge_unittest.cc
@@ -241,7 +241,7 @@ message.collaboration_event = CollaborationEvent::TAB_REMOVED; message.localized_message = u"Message content - single message"; - message.attribution = CreateAttribution1(); + message.attributions.emplace_back(CreateAttribution1()); return message; } @@ -277,10 +277,9 @@ message.type = InstantNotificationType::CONFLICT_TAB_REMOVED; message.collaboration_event = CollaborationEvent::TAB_REMOVED; message.localized_message = u"Message content - aggregated message"; - AggregatedMessageData aggregated_data; - aggregated_data.attributions.emplace_back(CreateAttribution1()); - aggregated_data.attributions.emplace_back(CreateAttribution2()); - message.aggregated_data = aggregated_data; + message.attributions.clear(); + message.attributions.emplace_back(CreateAttribution1()); + message.attributions.emplace_back(CreateAttribution2()); DisplayInstantaneousMessage(message, /*success=*/true);
diff --git a/components/collaboration/internal/messaging/instant_message_processor.h b/components/collaboration/internal/messaging/instant_message_processor.h new file mode 100644 index 0000000..54f19c9 --- /dev/null +++ b/components/collaboration/internal/messaging/instant_message_processor.h
@@ -0,0 +1,39 @@ +// Copyright 2025 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_COLLABORATION_INTERNAL_MESSAGING_INSTANT_MESSAGE_PROCESSOR_H_ +#define COMPONENTS_COLLABORATION_INTERNAL_MESSAGING_INSTANT_MESSAGE_PROCESSOR_H_ + +#include "components/collaboration/public/messaging/message.h" +#include "components/collaboration/public/messaging/messaging_backend_service.h" + +namespace collaboration::messaging { +using InstantMessageDelegate = MessagingBackendService::InstantMessageDelegate; + +// Queues and processes instant messages. Performs aggregation whenever there +// are similar types of messages available. +class InstantMessageProcessor { + public: + virtual ~InstantMessageProcessor() = default; + + // Must be invoked after construction. + virtual void SetMessagingBackendService( + MessagingBackendService* messaging_backend_service) = 0; + + // Must be invoked to set the platform specific delegate that is + // responsible for displaying the message in the UI. + virtual void SetInstantMessageDelegate( + InstantMessageDelegate* instant_message_delegate) = 0; + + // Whether instant messaging is enabled for the platform yet. + virtual bool IsEnabled() const = 0; + + // Notifies the InstantMessageDelegate to display the message for all the + // provided levels. + virtual void DisplayInstantMessage(const InstantMessage& message) = 0; +}; + +} // namespace collaboration::messaging + +#endif // COMPONENTS_COLLABORATION_INTERNAL_MESSAGING_INSTANT_MESSAGE_PROCESSOR_H_
diff --git a/components/collaboration/internal/messaging/instant_message_processor_impl.cc b/components/collaboration/internal/messaging/instant_message_processor_impl.cc new file mode 100644 index 0000000..a06d3f9 --- /dev/null +++ b/components/collaboration/internal/messaging/instant_message_processor_impl.cc
@@ -0,0 +1,247 @@ +// Copyright 2025 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/collaboration/internal/messaging/instant_message_processor_impl.h" + +#include <optional> +#include <unordered_map> +#include <vector> + +#include "base/functional/callback_helpers.h" +#include "base/hash/hash.h" +#include "base/strings/utf_string_conversions.h" +#include "base/task/single_thread_task_runner.h" +#include "components/collaboration/public/messaging/message.h" +#include "components/collaboration/public/messaging/messaging_backend_service.h" +#include "components/data_sharing/public/group_data.h" +#include "components/strings/grit/components_strings.h" +#include "ui/base/l10n/l10n_util.h" + +namespace collaboration::messaging { + +struct MessageAggregationKey { + InstantNotificationLevel level; + CollaborationEvent event; + std::optional<data_sharing::GroupId> collaboration_id; + + bool operator==(const MessageAggregationKey& other) const { + return level == other.level && event == other.event && + collaboration_id == other.collaboration_id; + } +}; + +struct MessageAggregationKeyHash { + MessageAggregationKeyHash() = default; + ~MessageAggregationKeyHash() = default; + size_t operator()(const MessageAggregationKey& k) const { + size_t hash = 0; + return base::HashCombine(hash, k.level, k.event, k.collaboration_id); + } +}; + +} // namespace collaboration::messaging + +namespace collaboration::messaging { +namespace { +constexpr base::TimeDelta kQueueInterval = base::Seconds(1); + +bool ShouldAggregate(const InstantMessage& message) { + switch (message.collaboration_event) { + case CollaborationEvent::TAB_UPDATED: + case CollaborationEvent::TAB_REMOVED: + return false; + case CollaborationEvent::TAB_GROUP_REMOVED: + case CollaborationEvent::COLLABORATION_MEMBER_ADDED: + return true; + case CollaborationEvent::UNDEFINED: + case CollaborationEvent::TAB_ADDED: + case CollaborationEvent::TAB_GROUP_ADDED: + case CollaborationEvent::TAB_GROUP_NAME_UPDATED: + case CollaborationEvent::TAB_GROUP_COLOR_UPDATED: + case CollaborationEvent::COLLABORATION_ADDED: + case CollaborationEvent::COLLABORATION_REMOVED: + case CollaborationEvent::COLLABORATION_MEMBER_REMOVED: + CHECK(false) << "Unexpected event in instant message " + << static_cast<int>(message.collaboration_event); + } +} + +// All key constructions should happen via this method. +MessageAggregationKey CreateMessageAggregationKey( + const InstantMessage& message) { + CHECK(ShouldAggregate(message)); + + MessageAggregationKey key; + key.level = message.level; + key.event = message.collaboration_event; + if (message.collaboration_event == + CollaborationEvent::COLLABORATION_MEMBER_ADDED) { + key.collaboration_id = message.attributions[0].collaboration_id; + } + + return key; +} + +} // namespace + +InstantMessageProcessorImpl::InstantMessageProcessorImpl() = default; + +InstantMessageProcessorImpl::~InstantMessageProcessorImpl() = default; + +void InstantMessageProcessorImpl::SetMessagingBackendService( + MessagingBackendService* messaging_backend_service) { + CHECK(!messaging_backend_service_); + CHECK(messaging_backend_service); + messaging_backend_service_ = messaging_backend_service; +} + +void InstantMessageProcessorImpl::SetInstantMessageDelegate( + InstantMessageDelegate* instant_message_delegate) { + // We must be either setting a delegate where there was none before or + // we should be resetting a non-null delegate. + CHECK((instant_message_delegate_ == nullptr && + instant_message_delegate != nullptr) || + (instant_message_delegate_ != nullptr && + instant_message_delegate == nullptr)); + instant_message_delegate_ = instant_message_delegate; +} + +bool InstantMessageProcessorImpl::IsEnabled() const { + return !!instant_message_delegate_; +} + +void InstantMessageProcessorImpl::DisplayInstantMessage( + const InstantMessage& message) { + message_queue_.push_back(message); + ScheduleProcessing(); +} + +void InstantMessageProcessorImpl::ScheduleProcessing() { + if (processing_scheduled_) { + return; + } + processing_scheduled_ = true; + + base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask( + FROM_HERE, + base::BindOnce(&InstantMessageProcessorImpl::ProcessQueue, + weak_ptr_factory_.GetWeakPtr()), + kQueueInterval); +} + +void InstantMessageProcessorImpl::ProcessQueue() { + processing_scheduled_ = false; + std::vector<InstantMessage> aggregated_messages = + AggregateMessages(message_queue_); + message_queue_.clear(); + + for (const auto& message : aggregated_messages) { + std::vector<base::Uuid> message_ids; + for (const auto& attribution : message.attributions) { + CHECK(attribution.id.has_value()); + message_ids.emplace_back(attribution.id.value()); + } + instant_message_delegate_->DisplayInstantaneousMessage( + message, + base::BindOnce(&InstantMessageProcessorImpl::OnMessageDisplayed, + weak_ptr_factory_.GetWeakPtr(), message_ids)); + } +} + +std::vector<InstantMessage> InstantMessageProcessorImpl::AggregateMessages( + const std::vector<InstantMessage>& messages) { + std::unordered_map<MessageAggregationKey, std::vector<const InstantMessage*>, + MessageAggregationKeyHash> + aggregation_map; + std::vector<InstantMessage> aggregated_messages; + std::vector<InstantMessage> non_aggregated_messages; + + // Populate the aggregation map. + for (const auto& message : messages) { + CHECK(IsSingleMessage(message)); + if (!ShouldAggregate(message)) { + non_aggregated_messages.emplace_back(message); + continue; + } + + MessageAggregationKey key = CreateMessageAggregationKey(message); + aggregation_map[key].emplace_back(&message); + } + + // Process the aggregation map. + for (const auto& [key, message_ptrs] : aggregation_map) { + if (message_ptrs.size() == 1) { + non_aggregated_messages.push_back(*message_ptrs[0]); + } else { + // Aggregated message case. + std::vector<InstantMessage> aggregated_msgs_temp; + for (const auto* message_ptr : message_ptrs) { + aggregated_msgs_temp.push_back(*message_ptr); + } + aggregated_messages.push_back( + CreateAggregatedMessage(aggregated_msgs_temp)); + } + } + + // Combine with non-aggregated messages as a single list and return. + aggregated_messages.insert(aggregated_messages.end(), + non_aggregated_messages.begin(), + non_aggregated_messages.end()); + return aggregated_messages; +} + +InstantMessage InstantMessageProcessorImpl::CreateAggregatedMessage( + const std::vector<InstantMessage>& messages) { + CHECK(messages.size() > 1u); + InstantMessage aggregated_message; + aggregated_message.collaboration_event = messages[0].collaboration_event; + aggregated_message.level = messages[0].level; + aggregated_message.type = messages[0].type; + + // Populate message attributions for the aggregated message. + for (const auto& message : messages) { + CHECK(IsSingleMessage(message)); + aggregated_message.attributions.emplace_back(message.attributions[0]); + } + + // Create message string for aggregation based on message type. + switch (messages[0].collaboration_event) { + case CollaborationEvent::COLLABORATION_MEMBER_ADDED: { + std::string group_name = + messages[0] + .attributions[0] + .tab_group_metadata->last_known_title.value(); + aggregated_message.localized_message = l10n_util::GetStringFUTF16( + IDS_DATA_SHARING_TOAST_NEW_MEMBER_MULTIPLE_MEMBERS, + base::UTF8ToUTF16(base::ToString(messages.size())), + base::UTF8ToUTF16(group_name)); + break; + } + case CollaborationEvent::TAB_GROUP_REMOVED: { + aggregated_message.localized_message = l10n_util::GetStringFUTF16( + IDS_DATA_SHARING_TOAST_BLOCK_LEAVE_MULTIPLE_GROUPS, + base::UTF8ToUTF16(base::ToString(messages.size()))); + break; + } + default: + CHECK(false); + } + + return aggregated_message; +} + +void InstantMessageProcessorImpl::OnMessageDisplayed( + const std::vector<base::Uuid>& message_ids, + bool success) { + if (!success) { + return; + } + + for (const base::Uuid& message_id : message_ids) { + messaging_backend_service_->ClearPersistentMessage( + message_id, PersistentNotificationType::INSTANT_MESSAGE); + } +} + +} // namespace collaboration::messaging
diff --git a/components/collaboration/internal/messaging/instant_message_processor_impl.h b/components/collaboration/internal/messaging/instant_message_processor_impl.h new file mode 100644 index 0000000..cc0479a48 --- /dev/null +++ b/components/collaboration/internal/messaging/instant_message_processor_impl.h
@@ -0,0 +1,60 @@ +// Copyright 2025 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_COLLABORATION_INTERNAL_MESSAGING_INSTANT_MESSAGE_PROCESSOR_IMPL_H_ +#define COMPONENTS_COLLABORATION_INTERNAL_MESSAGING_INSTANT_MESSAGE_PROCESSOR_IMPL_H_ + +#include <memory> +#include <vector> + +#include "base/memory/raw_ptr.h" +#include "base/memory/weak_ptr.h" +#include "base/uuid.h" +#include "components/collaboration/internal/messaging/instant_message_processor.h" +#include "components/collaboration/public/messaging/message.h" +#include "components/collaboration/public/messaging/messaging_backend_service.h" + +namespace collaboration::messaging { +using InstantMessageDelegate = MessagingBackendService::InstantMessageDelegate; + +class InstantMessageProcessorImpl : public InstantMessageProcessor { + public: + InstantMessageProcessorImpl(); + ~InstantMessageProcessorImpl() override; + + // InstantMessageProcessor implementation. + void SetMessagingBackendService( + MessagingBackendService* messaging_backend_service) override; + void SetInstantMessageDelegate( + InstantMessageDelegate* instant_message_delegate) override; + bool IsEnabled() const override; + void DisplayInstantMessage(const InstantMessage& message) override; + + private: + void ScheduleProcessing(); + void ProcessQueue(); + std::vector<InstantMessage> AggregateMessages( + const std::vector<InstantMessage>& messages); + void OnMessageDisplayed(const std::vector<base::Uuid>& message_ids, + bool success); + InstantMessage CreateAggregatedMessage( + const std::vector<InstantMessage>& messages); + + // The messaging backend service. Used for clearing the message from DB when + // the message successfully shows in the UI. + raw_ptr<MessagingBackendService> messaging_backend_service_; + + // The single delegate for when we need to inform the UI about instant + // (one-off) messages. + raw_ptr<InstantMessageDelegate> instant_message_delegate_; + + std::vector<InstantMessage> message_queue_; + bool processing_scheduled_ = false; + + base::WeakPtrFactory<InstantMessageProcessorImpl> weak_ptr_factory_{this}; +}; + +} // namespace collaboration::messaging + +#endif // COMPONENTS_COLLABORATION_INTERNAL_MESSAGING_INSTANT_MESSAGE_PROCESSOR_IMPL_H_
diff --git a/components/collaboration/internal/messaging/instant_message_processor_impl_unittest.cc b/components/collaboration/internal/messaging/instant_message_processor_impl_unittest.cc new file mode 100644 index 0000000..1597597 --- /dev/null +++ b/components/collaboration/internal/messaging/instant_message_processor_impl_unittest.cc
@@ -0,0 +1,420 @@ +// Copyright 2025 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/collaboration/internal/messaging/instant_message_processor_impl.h" + +#include <optional> +#include <vector> + +#include "base/functional/callback_forward.h" +#include "base/functional/callback_helpers.h" +#include "base/task/single_thread_task_runner.h" +#include "base/test/gmock_callback_support.h" +#include "base/test/gmock_move_support.h" +#include "base/test/task_environment.h" +#include "components/collaboration/public/messaging/message.h" +#include "components/collaboration/public/messaging/messaging_backend_service.h" +#include "components/collaboration/test_support/mock_messaging_backend_service.h" +#include "components/saved_tab_groups/test_support/saved_tab_group_test_utils.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" + +using testing::_; +using testing::DoAll; +using testing::Eq; +using testing::Return; +using testing::SaveArg; + +namespace collaboration::messaging { + +class MockInstantMessageDelegate + : public MessagingBackendService::InstantMessageDelegate { + public: + MOCK_METHOD(void, + DisplayInstantaneousMessage, + (InstantMessage message, SuccessCallback success_callback), + (override)); +}; + +class InstantMessageProcessorImplTest : public testing::Test { + public: + InstantMessageProcessorImplTest() + : task_environment_(base::test::TaskEnvironment::TimeSource::MOCK_TIME) {} + ~InstantMessageProcessorImplTest() override = default; + + void SetUp() override { + processor_ = std::make_unique<InstantMessageProcessorImpl>(); + processor_->SetMessagingBackendService(&messaging_backend_service_); + } + + void TearDown() override {} + + void SetupInstantMessageDelegate() { + EXPECT_FALSE(processor_->IsEnabled()); + processor_->SetInstantMessageDelegate(&mock_instant_message_delegate_); + EXPECT_TRUE(processor_->IsEnabled()); + } + + MessageAttribution CreateAttribution1() { + MessageAttribution attribution; + attribution.id = msg_id1_; + attribution.collaboration_id = data_sharing::GroupId("foo group"); + // GroupMember has its own conversion utils, so only check a single field. + attribution.affected_user = data_sharing::GroupMember(); + attribution.affected_user->gaia_id = GaiaId("affected"); + attribution.triggering_user = data_sharing::GroupMember(); + attribution.triggering_user->gaia_id = GaiaId("triggering"); + + // TabGroupMessageMetadata. + attribution.tab_group_metadata = TabGroupMessageMetadata(); + attribution.tab_group_metadata->local_tab_group_id = + tab_groups::test::GenerateRandomTabGroupID(); + attribution.tab_group_metadata->sync_tab_group_id = + base::Uuid::ParseLowercase("a1b2c3d4-e5f6-7890-1234-567890abcdef"); + attribution.tab_group_metadata->last_known_title = "My Awesome Group"; + attribution.tab_group_metadata->last_known_color = + tab_groups::TabGroupColorId::kOrange; + + // TabMessageMetadata. + attribution.tab_metadata = TabMessageMetadata(); + attribution.tab_metadata->local_tab_id = std::make_optional(499897179); + attribution.tab_metadata->sync_tab_id = + base::Uuid::ParseLowercase("fedcba09-8765-4321-0987-6f5e4d3c2b1a"); + attribution.tab_metadata->last_known_url = "https://example.com/"; + attribution.tab_metadata->last_known_title = "last known tab title"; + + return attribution; + } + + InstantMessage CreateInstantMessage() { + InstantMessage message; + message.level = InstantNotificationLevel::SYSTEM; + message.type = InstantNotificationType::CONFLICT_TAB_REMOVED; + message.collaboration_event = CollaborationEvent::TAB_REMOVED; + + message.attributions.emplace_back(CreateAttribution1()); + return message; + } + + protected: + base::test::SingleThreadTaskEnvironment task_environment_; + MockInstantMessageDelegate mock_instant_message_delegate_; + MockMessagingBackendService messaging_backend_service_; + std::unique_ptr<InstantMessageProcessorImpl> processor_; + base::Uuid msg_id1_ = + base::Uuid::ParseLowercase("cf07d904-88d4-4bc9-989d-57a9ab9e17a7"); + base::Uuid msg_id2_ = + base::Uuid::ParseLowercase("fedcba09-8765-4321-0987-6f5e4d3c2b1a"); + base::Uuid msg_id3_ = + base::Uuid::ParseLowercase("1b687a61-8a17-4f98-bf9d-74d2b50abf3e"); +}; + +TEST_F(InstantMessageProcessorImplTest, SingleMemberAddedMessage) { + SetupInstantMessageDelegate(); + InstantMessage message = CreateInstantMessage(); + message.attributions[0].id = msg_id1_; + message.collaboration_event = CollaborationEvent::COLLABORATION_MEMBER_ADDED; + message.attributions[0].affected_user = data_sharing::GroupMember(); + message.attributions[0].affected_user->gaia_id = GaiaId("affected1"); + message.localized_message = u"Random message title"; + + // Save the last invocation of calls to the InstantMessageDelegate. + // Dispatch instant message. + InstantMessage actual_message; + MessagingBackendService::InstantMessageDelegate::SuccessCallback + success_callback; + EXPECT_CALL(mock_instant_message_delegate_, DisplayInstantaneousMessage(_, _)) + .WillRepeatedly( + DoAll(SaveArg<0>(&actual_message), MoveArg<1>(&success_callback))); + processor_->DisplayInstantMessage(message); + task_environment_.FastForwardBy(base::Seconds(10)); + + // Verify instant message. + EXPECT_TRUE(IsSingleMessage(actual_message)); + EXPECT_EQ(message.localized_message, actual_message.localized_message); + EXPECT_EQ(CollaborationEvent::COLLABORATION_MEMBER_ADDED, + actual_message.collaboration_event); + EXPECT_EQ(message.level, actual_message.level); + EXPECT_EQ(message.type, actual_message.type); + EXPECT_EQ(msg_id1_, actual_message.attributions[0].id); + + // Invoke callback and verify that backend clears out the message from DB. + EXPECT_CALL( + messaging_backend_service_, + ClearPersistentMessage(Eq(msg_id1_), + Eq(PersistentNotificationType::INSTANT_MESSAGE))) + .Times(1); + std::move(success_callback).Run(true); +} + +TEST_F(InstantMessageProcessorImplTest, AggregateMemberAddedMessage) { + SetupInstantMessageDelegate(); + + // Create 3 messages of COLLABORATION_MEMBER_ADDED type. + InstantMessage message1 = CreateInstantMessage(); + message1.collaboration_event = CollaborationEvent::COLLABORATION_MEMBER_ADDED; + message1.attributions[0].id = msg_id1_; + + InstantMessage message2 = message1; + message2.attributions[0].affected_user = data_sharing::GroupMember(); + message2.attributions[0].affected_user->gaia_id = GaiaId("affected2"); + message2.attributions[0].id = msg_id2_; + + InstantMessage actual_message; + MessagingBackendService::InstantMessageDelegate::SuccessCallback + success_callback; + EXPECT_CALL(mock_instant_message_delegate_, DisplayInstantaneousMessage(_, _)) + .WillRepeatedly( + DoAll(SaveArg<0>(&actual_message), MoveArg<1>(&success_callback))); + processor_->DisplayInstantMessage(message1); + processor_->DisplayInstantMessage(message2); + task_environment_.FastForwardBy(base::Seconds(10)); + + // Verify the aggregated instant message. + EXPECT_FALSE(IsSingleMessage(actual_message)); + EXPECT_EQ(u"2 members joined \"My Awesome Group\" tab group", + actual_message.localized_message); + EXPECT_EQ(CollaborationEvent::COLLABORATION_MEMBER_ADDED, + actual_message.collaboration_event); + EXPECT_EQ(message1.level, actual_message.level); + EXPECT_EQ(message1.type, actual_message.type); + EXPECT_EQ(msg_id1_, actual_message.attributions[0].id); + EXPECT_EQ(msg_id2_, actual_message.attributions[1].id); + + // Invoke callback and verify that backend clears out the individual messages + // from DB. + testing::InSequence sequence; + EXPECT_CALL( + messaging_backend_service_, + ClearPersistentMessage(Eq(msg_id1_), + Eq(PersistentNotificationType::INSTANT_MESSAGE))) + .Times(1); + EXPECT_CALL( + messaging_backend_service_, + ClearPersistentMessage(Eq(msg_id2_), + Eq(PersistentNotificationType::INSTANT_MESSAGE))) + .Times(1); + std::move(success_callback).Run(true); +} + +TEST_F(InstantMessageProcessorImplTest, AggregateTabGroupRemovedMessage) { + SetupInstantMessageDelegate(); + + // Create 3 messages of TAB_GROUP_REMOVED type. + InstantMessage message1 = CreateInstantMessage(); + message1.collaboration_event = CollaborationEvent::TAB_GROUP_REMOVED; + message1.attributions[0].id = msg_id1_; + InstantMessage message2 = message1; + message2.attributions[0].id = msg_id2_; + InstantMessage message3 = message1; + message3.attributions[0].id = msg_id3_; + + InstantMessage actual_message; + MessagingBackendService::InstantMessageDelegate::SuccessCallback + success_callback; + EXPECT_CALL(mock_instant_message_delegate_, DisplayInstantaneousMessage(_, _)) + .WillRepeatedly( + DoAll(SaveArg<0>(&actual_message), MoveArg<1>(&success_callback))); + processor_->DisplayInstantMessage(message1); + processor_->DisplayInstantMessage(message2); + processor_->DisplayInstantMessage(message3); + task_environment_.FastForwardBy(base::Seconds(10)); + + // Verify the aggregated instant message. + EXPECT_FALSE(IsSingleMessage(actual_message)); + EXPECT_EQ(u"3 tab groups no longer available", + actual_message.localized_message); + EXPECT_EQ(CollaborationEvent::TAB_GROUP_REMOVED, + actual_message.collaboration_event); + EXPECT_EQ(message1.level, actual_message.level); + EXPECT_EQ(message1.type, actual_message.type); + EXPECT_EQ(msg_id1_, actual_message.attributions[0].id); + EXPECT_EQ(msg_id2_, actual_message.attributions[1].id); + EXPECT_EQ(msg_id3_, actual_message.attributions[2].id); + + // Invoke callback and verify that backend clears out the individual messages + // from DB. + testing::InSequence sequence; + EXPECT_CALL( + messaging_backend_service_, + ClearPersistentMessage(Eq(msg_id1_), + Eq(PersistentNotificationType::INSTANT_MESSAGE))) + .Times(1); + EXPECT_CALL( + messaging_backend_service_, + ClearPersistentMessage(Eq(msg_id2_), + Eq(PersistentNotificationType::INSTANT_MESSAGE))) + .Times(1); + EXPECT_CALL( + messaging_backend_service_, + ClearPersistentMessage(Eq(msg_id3_), + Eq(PersistentNotificationType::INSTANT_MESSAGE))) + .Times(1); + std::move(success_callback).Run(true); +} + +TEST_F(InstantMessageProcessorImplTest, ShouldNotAggregateTabRemovedMessage) { + SetupInstantMessageDelegate(); + + // Create 3 messages of TAB_REMOVED type. + InstantMessage message1 = CreateInstantMessage(); + message1.collaboration_event = CollaborationEvent::TAB_REMOVED; + message1.attributions[0].id = msg_id1_; + message1.localized_message = u"Message text 1"; + + InstantMessage message2 = message1; + message2.attributions[0].id = msg_id2_; + message2.localized_message = u"Message text 2"; + + std::vector<InstantMessage> actual_messages; + std::vector<MessagingBackendService::InstantMessageDelegate::SuccessCallback> + success_callbacks; + + EXPECT_CALL(mock_instant_message_delegate_, DisplayInstantaneousMessage(_, _)) + .Times(testing::AtLeast(1)) + .WillRepeatedly( + [&](InstantMessage message, + MessagingBackendService::InstantMessageDelegate::SuccessCallback + success_callback) { + actual_messages.emplace_back(message); + success_callbacks.emplace_back(std::move(success_callback)); + }); + + processor_->DisplayInstantMessage(message1); + processor_->DisplayInstantMessage(message2); + task_environment_.FastForwardBy(base::Seconds(10)); + + // Verify the individual instant messages. + EXPECT_EQ(2u, actual_messages.size()); + EXPECT_TRUE(IsSingleMessage(actual_messages[0])); + EXPECT_EQ(message1.collaboration_event, + actual_messages[0].collaboration_event); + EXPECT_EQ(message1.localized_message, actual_messages[0].localized_message); + EXPECT_EQ(message1.level, actual_messages[0].level); + EXPECT_EQ(message1.type, actual_messages[0].type); + EXPECT_EQ(msg_id1_, actual_messages[0].attributions[0].id); + + EXPECT_TRUE(IsSingleMessage(actual_messages[1])); + EXPECT_EQ(message2.collaboration_event, + actual_messages[1].collaboration_event); + EXPECT_EQ(message2.localized_message, actual_messages[1].localized_message); + EXPECT_EQ(msg_id2_, actual_messages[1].attributions[0].id); + + // Invoke callback and verify that backend clears out the individual messages + // from DB. + testing::InSequence sequence; + EXPECT_CALL( + messaging_backend_service_, + ClearPersistentMessage(Eq(msg_id1_), + Eq(PersistentNotificationType::INSTANT_MESSAGE))) + .Times(1); + EXPECT_CALL( + messaging_backend_service_, + ClearPersistentMessage(Eq(msg_id2_), + Eq(PersistentNotificationType::INSTANT_MESSAGE))) + .Times(1); + std::move(success_callbacks[0]).Run(true); + std::move(success_callbacks[1]).Run(true); +} + +TEST_F(InstantMessageProcessorImplTest, + TwoMessagesOfSimilarTypeWithOneOfDifferentType) { + SetupInstantMessageDelegate(); + + // Create 2 messages of TAB_GROUP_REMOVED type and the third one of + // COLLOABORATION_MEMBER_ADDED type. + InstantMessage message1 = CreateInstantMessage(); + message1.collaboration_event = CollaborationEvent::TAB_GROUP_REMOVED; + message1.attributions[0].id = msg_id1_; + InstantMessage message2 = message1; + message2.attributions[0].id = msg_id2_; + + InstantMessage message3 = message1; + message3.attributions[0].id = msg_id3_; + message3.localized_message = u"Some message"; + message3.collaboration_event = CollaborationEvent::COLLABORATION_MEMBER_ADDED; + + // Save arguments of invocation. + std::vector<InstantMessage> actual_messages; + std::vector<MessagingBackendService::InstantMessageDelegate::SuccessCallback> + success_callbacks; + EXPECT_CALL(mock_instant_message_delegate_, DisplayInstantaneousMessage(_, _)) + .Times(testing::AtLeast(1)) + .WillRepeatedly( + [&](InstantMessage message, + MessagingBackendService::InstantMessageDelegate::SuccessCallback + success_callback) { + actual_messages.emplace_back(message); + success_callbacks.emplace_back(std::move(success_callback)); + }); + + processor_->DisplayInstantMessage(message1); + processor_->DisplayInstantMessage(message2); + processor_->DisplayInstantMessage(message3); + task_environment_.FastForwardBy(base::Seconds(10)); + + // Verify the aggregated instant message. + EXPECT_EQ(2u, actual_messages.size()); + EXPECT_FALSE(IsSingleMessage(actual_messages[0])); + EXPECT_EQ(u"2 tab groups no longer available", + actual_messages[0].localized_message); + EXPECT_EQ(CollaborationEvent::TAB_GROUP_REMOVED, + actual_messages[0].collaboration_event); + EXPECT_EQ(message1.level, actual_messages[0].level); + EXPECT_EQ(message1.type, actual_messages[0].type); + EXPECT_EQ(msg_id1_, actual_messages[0].attributions[0].id); + EXPECT_EQ(msg_id2_, actual_messages[0].attributions[1].id); + + // Verify the single non-aggregated message. + EXPECT_TRUE(IsSingleMessage(actual_messages[1])); + EXPECT_EQ(message3.collaboration_event, + actual_messages[1].collaboration_event); + EXPECT_EQ(message3.localized_message, actual_messages[1].localized_message); + EXPECT_EQ(msg_id3_, actual_messages[1].attributions[0].id); +} + +TEST_F(InstantMessageProcessorImplTest, + DontAggregateMessageswithDifferentInstantNotificationLevel) { + SetupInstantMessageDelegate(); + + // Create 2 messages of TAB_GROUP_REMOVED type, but with different levels. + InstantMessage message1 = CreateInstantMessage(); + message1.collaboration_event = CollaborationEvent::TAB_GROUP_REMOVED; + message1.attributions[0].id = msg_id1_; + message1.level = InstantNotificationLevel::SYSTEM; + + InstantMessage message2 = message1; + message2.attributions[0].id = msg_id2_; + message2.level = InstantNotificationLevel::BROWSER; + + std::vector<InstantMessage> actual_messages; + std::vector<MessagingBackendService::InstantMessageDelegate::SuccessCallback> + success_callbacks; + EXPECT_CALL(mock_instant_message_delegate_, DisplayInstantaneousMessage(_, _)) + .Times(testing::AtLeast(1)) + .WillRepeatedly( + [&](InstantMessage message, + MessagingBackendService::InstantMessageDelegate::SuccessCallback + success_callback) { + actual_messages.emplace_back(message); + success_callbacks.emplace_back(std::move(success_callback)); + }); + + processor_->DisplayInstantMessage(message1); + processor_->DisplayInstantMessage(message2); + task_environment_.FastForwardBy(base::Seconds(10)); + + // Verify that the messages are not aggregated. + EXPECT_EQ(2u, actual_messages.size()); + EXPECT_EQ(msg_id1_, actual_messages[1].attributions[0].id); + EXPECT_EQ(msg_id2_, actual_messages[0].attributions[0].id); + EXPECT_EQ(message1.level, actual_messages[1].level); + EXPECT_EQ(message2.level, actual_messages[0].level); + EXPECT_EQ(CollaborationEvent::TAB_GROUP_REMOVED, + actual_messages[1].collaboration_event); + EXPECT_EQ(CollaborationEvent::TAB_GROUP_REMOVED, + actual_messages[0].collaboration_event); +} + +} // namespace collaboration::messaging
diff --git a/components/collaboration/internal/messaging/messaging_backend_service_impl.cc b/components/collaboration/internal/messaging/messaging_backend_service_impl.cc index caffbd2..72b2ad8 100644 --- a/components/collaboration/internal/messaging/messaging_backend_service_impl.cc +++ b/components/collaboration/internal/messaging/messaging_backend_service_impl.cc
@@ -278,6 +278,68 @@ return std::nullopt; } +std::u16string GetTitleForTabRemovedMessage(const InstantMessage& message) { + const auto& attribution = message.attributions[0]; + std::optional<data_sharing::GroupMember> user = attribution.triggering_user; + std::optional<TabMessageMetadata> tab_metadata = attribution.tab_metadata; + const bool has_title = + tab_metadata.has_value() && tab_metadata->last_known_title.has_value(); + if (!user.has_value() || !has_title) { + return std::u16string(); + } + + return l10n_util::GetStringFUTF16( + IDS_DATA_SHARING_TOAST_TAB_REMOVED, base::UTF8ToUTF16(user->given_name), + base::UTF8ToUTF16(tab_metadata->last_known_title.value())); +} + +std::u16string GetTitleForTabUpdatedMessage(const InstantMessage& message) { + const auto& attribution = message.attributions[0]; + std::optional<data_sharing::GroupMember> user = attribution.triggering_user; + std::optional<TabMessageMetadata> tab_metadata = attribution.tab_metadata; + const bool has_title = + tab_metadata.has_value() && tab_metadata->last_known_title.has_value(); + if (!user.has_value() || !has_title) { + return std::u16string(); + } + + return l10n_util::GetStringFUTF16( + IDS_DATA_SHARING_TOAST_TAB_UPDATED, base::UTF8ToUTF16(user->given_name), + base::UTF8ToUTF16(tab_metadata->last_known_title.value())); +} + +std::u16string GetTitleForMemberAddedMessage(const InstantMessage& message) { + const auto& attribution = message.attributions[0]; + std::optional<data_sharing::GroupMember> user = attribution.affected_user; + std::optional<TabGroupMessageMetadata> tab_group_metadata = + attribution.tab_group_metadata; + const bool has_group_title = tab_group_metadata.has_value() && + tab_group_metadata->last_known_title.has_value(); + if (!user.has_value() || !has_group_title) { + return std::u16string(); + } + + return l10n_util::GetStringFUTF16( + IDS_DATA_SHARING_TOAST_NEW_MEMBER, base::UTF8ToUTF16(user->given_name), + base::UTF8ToUTF16(tab_group_metadata->last_known_title.value())); +} + +std::u16string GetTitleForTabGroupRemovedMessage( + const InstantMessage& message) { + const auto& attribution = message.attributions[0]; + std::optional<TabGroupMessageMetadata> tab_group_metadata = + attribution.tab_group_metadata; + const bool has_group_title = tab_group_metadata.has_value() && + tab_group_metadata->last_known_title.has_value(); + if (!has_group_title) { + return std::u16string(); + } + + return l10n_util::GetStringFUTF16( + IDS_DATA_SHARING_TOAST_BLOCK_LEAVE, + base::UTF8ToUTF16(tab_group_metadata->last_known_title.value())); +} + DirtyType GetDirtyTypeFromPersistentNotificationTypeForQuery( std::optional<PersistentNotificationType> type) { if (!type) { @@ -290,6 +352,8 @@ return DirtyType::kChip; } else if (*type == PersistentNotificationType::TOMBSTONED) { return DirtyType::kTombstoned; + } else if (*type == PersistentNotificationType::INSTANT_MESSAGE) { + return DirtyType::kMessageOnly; } else { // Ask for all dirty messages. return DirtyType::kAll; @@ -365,6 +429,7 @@ std::unique_ptr<TabGroupChangeNotifier> tab_group_change_notifier, std::unique_ptr<DataSharingChangeNotifier> data_sharing_change_notifier, std::unique_ptr<MessagingBackendStore> messaging_backend_store, + std::unique_ptr<InstantMessageProcessor> instant_message_processor, tab_groups::TabGroupSyncService* tab_group_sync_service, data_sharing::DataSharingService* data_sharing_service, signin::IdentityManager* identity_manager) @@ -372,9 +437,11 @@ tab_group_change_notifier_(std::move(tab_group_change_notifier)), data_sharing_change_notifier_(std::move(data_sharing_change_notifier)), store_(std::move(messaging_backend_store)), + instant_message_processor_(std::move(instant_message_processor)), tab_group_sync_service_(tab_group_sync_service), data_sharing_service_(data_sharing_service), identity_manager_(identity_manager) { + instant_message_processor_->SetMessagingBackendService(this); store_->Initialize( base::BindOnce(&MessagingBackendServiceImpl::OnStoreInitialized, weak_ptr_factory_.GetWeakPtr())); @@ -384,13 +451,8 @@ void MessagingBackendServiceImpl::SetInstantMessageDelegate( InstantMessageDelegate* instant_message_delegate) { - // We must be either setting a delegate where there was none before or - // we should be resetting a non-null delegate. - CHECK((instant_message_delegate_ == nullptr && - instant_message_delegate != nullptr) || - (instant_message_delegate_ != nullptr && - instant_message_delegate == nullptr)); - instant_message_delegate_ = instant_message_delegate; + instant_message_processor_->SetInstantMessageDelegate( + instant_message_delegate); } void MessagingBackendServiceImpl::AddPersistentMessageObserver( @@ -667,10 +729,12 @@ NotifyDisplayPersistentMessagesForTypes( persistent_message, {PersistentNotificationType::TOMBSTONED}); - if (instant_message_delegate_) { + if (instant_message_processor_->IsEnabled()) { InstantMessage instant_message = CreateInstantMessage(message, removed_group, /*tab=*/std::nullopt); instant_message.type = InstantNotificationType::UNDEFINED; + instant_message.localized_message = + GetTitleForTabGroupRemovedMessage(instant_message); DisplayInstantMessage(base::Uuid::ParseLowercase(message.uuid()), instant_message, {InstantNotificationLevel::BROWSER}); } @@ -784,10 +848,12 @@ DisplayOrHideTabGroupDirtyDotForTabGroup(*collaboration_group_id, removed_tab.saved_group_guid()); - if (!is_local && is_selected && instant_message_delegate_) { + if (!is_local && is_selected && instant_message_processor_->IsEnabled()) { InstantMessage instant_message = CreateInstantMessage(message, /*tab_group=*/std::nullopt, removed_tab); instant_message.type = InstantNotificationType::CONFLICT_TAB_REMOVED; + instant_message.localized_message = + GetTitleForTabRemovedMessage(instant_message); // TODO(crbug.com/390794240): Remove the id argument to // DisplayInstantMessage as it's now contained inside the @@ -845,14 +911,17 @@ DisplayOrHideTabGroupDirtyDotForTabGroup(*collaboration_group_id, updated_tab.saved_group_guid()); - if (!is_local && is_selected && instant_message_delegate_) { + if (!is_local && is_selected && instant_message_processor_->IsEnabled()) { InstantMessage instant_message_base; - instant_message_base.attribution = CreateMessageAttributionForTabUpdates( - message, std::nullopt, updated_tab); + instant_message_base.attributions.emplace_back( + CreateMessageAttributionForTabUpdates(message, std::nullopt, + updated_tab)); instant_message_base.collaboration_event = CollaborationEvent::TAB_UPDATED; // TODO(crbug.com/391941212): CONFLICT_TAB_REMOVED and UNDEFINED don't seem // to be used. In that case, remove them. instant_message_base.type = InstantNotificationType::UNDEFINED; + instant_message_base.localized_message = + GetTitleForTabUpdatedMessage(instant_message_base); DisplayInstantMessage(base::Uuid::ParseLowercase(message.uuid()), instant_message_base, @@ -1011,9 +1080,11 @@ message.set_affected_user_gaia_id(member_gaia_id.ToString()); store_->AddMessage(message); - if (instant_message_delegate_) { + if (instant_message_processor_->IsEnabled()) { InstantMessage instant_message = CreateInstantMessage(message, tab_group, /*tab=*/std::nullopt); + instant_message.localized_message = + GetTitleForMemberAddedMessage(instant_message); DisplayInstantMessage( base::Uuid::ParseLowercase(message.uuid()), instant_message, {InstantNotificationLevel::SYSTEM, InstantNotificationLevel::BROWSER}); @@ -1449,8 +1520,8 @@ InstantMessage instant_message; instant_message.collaboration_event = ToCollaborationEvent(message.event_type()); - instant_message.attribution = - CreateMessageAttributionForTabUpdates(message, tab_group, tab); + instant_message.attributions.emplace_back( + CreateMessageAttributionForTabUpdates(message, tab_group, tab)); return instant_message; } @@ -1584,14 +1655,10 @@ const base::Uuid& db_message_uuid, const InstantMessage& base_message, const std::vector<InstantNotificationLevel>& levels) { - CHECK(instant_message_delegate_); for (InstantNotificationLevel level : levels) { InstantMessage instant_message = base_message; instant_message.level = level; - instant_message_delegate_->DisplayInstantaneousMessage( - instant_message, - base::BindOnce(&MessagingBackendServiceImpl::ClearMessageDirtyBit, - weak_ptr_factory_.GetWeakPtr(), db_message_uuid)); + instant_message_processor_->DisplayInstantMessage(instant_message); } }
diff --git a/components/collaboration/internal/messaging/messaging_backend_service_impl.h b/components/collaboration/internal/messaging/messaging_backend_service_impl.h index a2735a11..96031be5 100644 --- a/components/collaboration/internal/messaging/messaging_backend_service_impl.h +++ b/components/collaboration/internal/messaging/messaging_backend_service_impl.h
@@ -14,6 +14,7 @@ #include "base/scoped_observation.h" #include "components/collaboration/internal/messaging/configuration.h" #include "components/collaboration/internal/messaging/data_sharing_change_notifier.h" +#include "components/collaboration/internal/messaging/instant_message_processor.h" #include "components/collaboration/internal/messaging/storage/messaging_backend_store.h" #include "components/collaboration/internal/messaging/tab_group_change_notifier.h" #include "components/collaboration/public/messaging/message.h" @@ -47,6 +48,7 @@ std::unique_ptr<TabGroupChangeNotifier> tab_group_change_notifier, std::unique_ptr<DataSharingChangeNotifier> data_sharing_change_notifier, std::unique_ptr<MessagingBackendStore> messaging_backend_store, + std::unique_ptr<InstantMessageProcessor> instant_message_processor, tab_groups::TabGroupSyncService* tab_group_sync_service, data_sharing::DataSharingService* data_sharing_service, signin::IdentityManager* identity_manager); @@ -268,6 +270,10 @@ // data sharing service. DataSharingChangeNotifier::FlushCallback data_sharing_flush_callback_; + // Queues and processes instant messages. Invokes the delegate to ask UI to + // show the instant message. + std::unique_ptr<InstantMessageProcessor> instant_message_processor_; + // Service providing information about tabs and tab groups. raw_ptr<tab_groups::TabGroupSyncService> tab_group_sync_service_; @@ -277,10 +283,6 @@ // Service providing information about sign in. raw_ptr<signin::IdentityManager> identity_manager_; - // The single delegate for when we need to inform the UI about instant - // (one-off) messages. - raw_ptr<InstantMessageDelegate> instant_message_delegate_; - // The list of observers for any changes to persistent messages. base::ObserverList<PersistentMessageObserver> persistent_message_observers_;
diff --git a/components/collaboration/internal/messaging/messaging_backend_service_impl_unittest.cc b/components/collaboration/internal/messaging/messaging_backend_service_impl_unittest.cc index 7bf69197..fc5d61b 100644 --- a/components/collaboration/internal/messaging/messaging_backend_service_impl_unittest.cc +++ b/components/collaboration/internal/messaging/messaging_backend_service_impl_unittest.cc
@@ -14,6 +14,8 @@ #include "base/time/time.h" #include "base/uuid.h" #include "components/collaboration/internal/messaging/data_sharing_change_notifier.h" +#include "components/collaboration/internal/messaging/instant_message_processor.h" +#include "components/collaboration/internal/messaging/instant_message_processor_impl.h" #include "components/collaboration/internal/messaging/storage/collaboration_message_util.h" #include "components/collaboration/internal/messaging/storage/empty_messaging_backend_database.h" #include "components/collaboration/internal/messaging/storage/messaging_backend_store_impl.h" @@ -215,8 +217,9 @@ service_ = std::make_unique<MessagingBackendServiceImpl>( configuration, std::move(tab_group_change_notifier), std::move(data_sharing_change_notifier), - std::move(messaging_backend_store), mock_tab_group_sync_service_.get(), - mock_data_sharing_service_.get(), + std::move(messaging_backend_store), + std::make_unique<InstantMessageProcessorImpl>(), + mock_tab_group_sync_service_.get(), mock_data_sharing_service_.get(), identity_test_env_.identity_manager()); } @@ -274,7 +277,7 @@ } protected: - base::test::SingleThreadTaskEnvironment task_environment{ + base::test::SingleThreadTaskEnvironment task_environment_{ base::test::TaskEnvironment::TimeSource::MOCK_TIME}; signin::IdentityTestEnvironment identity_test_env_; @@ -1649,12 +1652,13 @@ // Updating the currently selected tab should inform the delegate. tg_notifier_observer_->OnTabUpdated(*tab1, tab_groups::TriggerSource::REMOTE, true); + task_environment_.FastForwardBy(base::Seconds(10)); // We should have received a stored message about the updated tab. auto db_message = GetLastMessageFromDB(); EXPECT_NE("", db_message.uuid()); base::Uuid db_message_id = base::Uuid::ParseLowercase(db_message.uuid()); - EXPECT_EQ(db_message_id, message.attribution->id); + EXPECT_EQ(db_message_id, message.attributions[0].id); // Verify that the dirty bit is chip only and no dot. EXPECT_FALSE(static_cast<int>(DirtyType::kDot) & db_message.dirty()); @@ -1705,12 +1709,13 @@ // Removing the currently selected tab should inform the delegate. tg_notifier_observer_->OnTabRemoved(*tab1, tab_groups::TriggerSource::REMOTE, true); + task_environment_.FastForwardBy(base::Seconds(10)); // We should have received a stored message about the removed tab. auto db_message = GetLastMessageFromDB(); EXPECT_NE("", db_message.uuid()); base::Uuid db_message_id = base::Uuid::ParseLowercase(db_message.uuid()); - EXPECT_EQ(db_message_id, message.attribution->id); + EXPECT_EQ(db_message_id, message.attributions[0].id); EXPECT_EQ(CollaborationEvent::TAB_REMOVED, message.collaboration_event); EXPECT_EQ(InstantNotificationType::CONFLICT_TAB_REMOVED, message.type); @@ -1748,6 +1753,7 @@ DoAll(SaveArg<0>(&message), MoveArg<1>(&success_callback))); tg_notifier_observer_->OnTabRemoved(*tab1, tab_groups::TriggerSource::REMOTE, true); + task_environment_.FastForwardBy(base::Seconds(10)); EXPECT_EQ(CollaborationEvent::TAB_REMOVED, message.collaboration_event); EXPECT_EQ(InstantNotificationType::CONFLICT_TAB_REMOVED, message.type); @@ -1781,6 +1787,7 @@ .Times(0); tg_notifier_observer_->OnTabRemoved(*tab2, tab_groups::TriggerSource::REMOTE, false); + task_environment_.FastForwardBy(base::Seconds(10)); } TEST_F(MessagingBackendServiceImplTest, TestTabGroupRemovedInstantMessage) { @@ -1816,6 +1823,7 @@ // Removing the tab group should inform the delegate. tg_notifier_observer_->OnTabGroupRemoved(tab_group, tab_groups::TriggerSource::REMOTE); + task_environment_.FastForwardBy(base::Seconds(10)); // Verify persistent notification. EXPECT_EQ(PersistentNotificationType::TOMBSTONED, @@ -1829,11 +1837,11 @@ auto db_message = GetLastMessageFromDB(); EXPECT_NE("", db_message.uuid()); base::Uuid db_message_id = base::Uuid::ParseLowercase(db_message.uuid()); - EXPECT_EQ(db_message_id, message.attribution->id); + EXPECT_EQ(db_message_id, message.attributions[0].id); EXPECT_EQ(CollaborationEvent::TAB_GROUP_REMOVED, message.collaboration_event); EXPECT_EQ(tab_group.saved_guid(), - message.attribution->tab_group_metadata->sync_tab_group_id); + message.attributions[0].tab_group_metadata->sync_tab_group_id); EXPECT_TRUE(static_cast<int>(DirtyType::kTombstoned) & db_message.dirty()); EXPECT_TRUE(static_cast<int>(DirtyType::kMessageOnly) & db_message.dirty()); @@ -1873,6 +1881,7 @@ EXPECT_FALSE(HasLastMessageFromDB()); tg_notifier_observer_->OnTabGroupRemoved(tab_group, tab_groups::TriggerSource::REMOTE); + task_environment_.FastForwardBy(base::Seconds(10)); } TEST_F(MessagingBackendServiceImplTest, TestInstantMessageCallbackFails) { @@ -1902,6 +1911,7 @@ // Removing the tab group should inform the delegate. tg_notifier_observer_->OnTabGroupRemoved(tab_group, tab_groups::TriggerSource::REMOTE); + task_environment_.FastForwardBy(base::Seconds(10)); EXPECT_TRUE(unowned_messaging_backend_store_->HasAnyDirtyMessages( DirtyType::kMessageOnly)); @@ -1947,13 +1957,15 @@ .WillRepeatedly(Return(group_data)); ds_notifier_observer_->OnGroupMemberAdded(group_data, member2.gaia_id, now); + task_environment_.FastForwardBy(base::Seconds(10)); EXPECT_EQ(CollaborationEvent::COLLABORATION_MEMBER_ADDED, message.collaboration_event); - EXPECT_EQ(member2.gaia_id, message.attribution->affected_user->gaia_id); - ASSERT_TRUE(message.attribution->tab_group_metadata); + const auto& attribution = message.attributions[0]; + EXPECT_EQ(member2.gaia_id, attribution.affected_user->gaia_id); + ASSERT_TRUE(message.attributions[0].tab_group_metadata); EXPECT_EQ(tab_group.saved_guid(), - message.attribution->tab_group_metadata->sync_tab_group_id); + attribution.tab_group_metadata->sync_tab_group_id); } TEST_F(MessagingBackendServiceImplTest, TestMemberAddedOrRemovedIsOwner) { @@ -1984,6 +1996,7 @@ time += base::Seconds(1); ds_notifier_observer_->OnGroupMemberRemoved(group_data, member1.gaia_id, time); + task_environment_.FastForwardBy(base::Seconds(10)); } TEST_F(MessagingBackendServiceImplTest, TestTabSelectionClearsChipByDefault) { @@ -2316,7 +2329,8 @@ // Create a dirty db instant message. base::Time now = base::Time::Now(); collaboration_pb::Message message1 = CreateStoredMessage( - collaboration_group_id, collaboration_pb::EventType::COLLABORATION_ADDED, + collaboration_group_id, + collaboration_pb::EventType::COLLABORATION_MEMBER_ADDED, DirtyType::kMessageOnly, now - base::Minutes(5)); message1.set_triggering_user_gaia_id("gaia_1"); AddMessage(message1); @@ -2327,6 +2341,7 @@ .Times(1); tg_notifier_observer_->OnTabGroupOpened(tab_group); + task_environment_.FastForwardBy(base::Seconds(10)); } } // namespace collaboration::messaging
diff --git a/components/collaboration/public/BUILD.gn b/components/collaboration/public/BUILD.gn index ad5a350..20cd91b 100644 --- a/components/collaboration/public/BUILD.gn +++ b/components/collaboration/public/BUILD.gn
@@ -155,7 +155,6 @@ sources = [ "android/java/src/org/chromium/components/collaboration/messaging/ActivityLogItem.java", "android/java/src/org/chromium/components/collaboration/messaging/ActivityLogQueryParams.java", - "android/java/src/org/chromium/components/collaboration/messaging/AggregatedMessageData.java", "android/java/src/org/chromium/components/collaboration/messaging/InstantMessage.java", "android/java/src/org/chromium/components/collaboration/messaging/MessageAttribution.java", "android/java/src/org/chromium/components/collaboration/messaging/MessageUtils.java",
diff --git a/components/collaboration/public/android/java/src/org/chromium/components/collaboration/messaging/InstantMessage.java b/components/collaboration/public/android/java/src/org/chromium/components/collaboration/messaging/InstantMessage.java index c1b577f9..9745e6e 100644 --- a/components/collaboration/public/android/java/src/org/chromium/components/collaboration/messaging/InstantMessage.java +++ b/components/collaboration/public/android/java/src/org/chromium/components/collaboration/messaging/InstantMessage.java
@@ -5,7 +5,9 @@ package org.chromium.components.collaboration.messaging; import org.chromium.build.annotations.NullMarked; -import org.chromium.build.annotations.Nullable; + +import java.util.ArrayList; +import java.util.List; /** * Represents a message from the Tab Group Sharing system, where something of note requires an @@ -22,6 +24,15 @@ @SuppressWarnings("NullAway.Init") // This is set to a non-null value immediately after init public String localizedMessage; - public @Nullable MessageAttribution attribution; - public @Nullable AggregatedMessageData aggregatedData; + // The list of message attributions for the messages that it represents. + // For single message case, the size is 1. For aggregated message case, it + // will be greater than 1.` + public List<MessageAttribution> attributions = new ArrayList<>(); + + /** + * @return Whether this message is a non-aggregated message. + */ + public boolean isSingleMessage() { + return attributions.size() == 1; + } }
diff --git a/components/collaboration/public/android/java/src/org/chromium/components/collaboration/messaging/MessageUtils.java b/components/collaboration/public/android/java/src/org/chromium/components/collaboration/messaging/MessageUtils.java index f7ba70e..9c2a137c 100644 --- a/components/collaboration/public/android/java/src/org/chromium/components/collaboration/messaging/MessageUtils.java +++ b/components/collaboration/public/android/java/src/org/chromium/components/collaboration/messaging/MessageUtils.java
@@ -31,13 +31,21 @@ } /** Returns the id of the group, or null. */ + public static @Nullable MessageAttribution getFirstAttribution( + @Nullable InstantMessage message) { + return message == null + ? null + : (message.attributions.isEmpty() ? null : message.attributions.get(0)); + } + + /** Returns the id of the group, or null. */ public static @Nullable Token extractTabGroupId(@Nullable InstantMessage message) { - return message == null ? null : extractTabGroupId(message.attribution); + return message == null ? null : extractTabGroupId(getFirstAttribution(message)); } /** Returns the sync id of the group, or null. */ public static @Nullable String extractSyncTabGroupId(@Nullable InstantMessage message) { - return message == null ? null : extractSyncTabGroupId(message.attribution); + return message == null ? null : extractSyncTabGroupId(getFirstAttribution(message)); } /** Returns the sync id of the group, or null. */ @@ -53,16 +61,16 @@ /** Returns the tab title or the empty string. */ public static @Nullable String extractTabTitle(@Nullable InstantMessage message) { - return message == null - || message.attribution == null - || message.attribution.tabMetadata == null + if (message == null) return ""; + MessageAttribution attribution = getFirstAttribution(message); + return attribution == null || attribution.tabMetadata == null ? "" - : message.attribution.tabMetadata.lastKnownTitle; + : attribution.tabMetadata.lastKnownTitle; } /** Returns the tab group title or the empty string. */ public static @Nullable String extractTabGroupTitle(@Nullable InstantMessage message) { - return message == null ? "" : extractTabGroupTitle(message.attribution); + return message == null ? "" : extractTabGroupTitle(getFirstAttribution(message)); } /** Returns the tab group title or the empty string. */ @@ -86,14 +94,14 @@ /** Returns the collaboration id or null. */ public static @Nullable String extractCollaborationId(@Nullable InstantMessage message) { - return message == null || message.attribution == null - ? null - : message.attribution.collaborationId; + if (message == null) return null; + MessageAttribution attribution = getFirstAttribution(message); + return attribution == null ? null : attribution.collaborationId; } /** Returns a GroupMember associated with the message, prioritizing affected over triggering. */ public static @Nullable GroupMember extractMember(@Nullable InstantMessage message) { - return message == null ? null : extractMember(message.attribution); + return message == null ? null : extractMember(getFirstAttribution(message)); } /** Returns a GroupMember associated with the message, prioritizing affected over triggering. */ @@ -113,11 +121,11 @@ /** Returns the url of the tab or null. */ public static @Nullable String extractTabUrl(@Nullable InstantMessage message) { - return message == null - || message.attribution == null - || message.attribution.tabMetadata == null + if (message == null) return null; + MessageAttribution attribution = getFirstAttribution(message); + return attribution == null || attribution.tabMetadata == null ? null - : message.attribution.tabMetadata.lastKnownUrl; + : attribution.tabMetadata.lastKnownUrl; } private static @Nullable String extractSyncTabGroupId( @@ -129,7 +137,9 @@ /** Returns the message id or null. */ public static @Nullable String extractMessageId(@Nullable InstantMessage message) { - return message == null || message.attribution == null ? null : message.attribution.id; + if (message == null) return null; + MessageAttribution attribution = getFirstAttribution(message); + return attribution == null ? null : attribution.id; } /** Returns the message id or null. */
diff --git a/components/collaboration/public/android/java/src/org/chromium/components/collaboration/messaging/MessageUtilsUnitTest.java b/components/collaboration/public/android/java/src/org/chromium/components/collaboration/messaging/MessageUtilsUnitTest.java index e85eddd..01dd7e4 100644 --- a/components/collaboration/public/android/java/src/org/chromium/components/collaboration/messaging/MessageUtilsUnitTest.java +++ b/components/collaboration/public/android/java/src/org/chromium/components/collaboration/messaging/MessageUtilsUnitTest.java
@@ -68,15 +68,16 @@ @Test public void testExtractTabGroupId_Instant() { InstantMessage message = new InstantMessage(); - message.attribution = new MessageAttribution(); - message.attribution.tabGroupMetadata = new TabGroupMessageMetadata(); - message.attribution.tabGroupMetadata.localTabGroupId = new LocalTabGroupId(TAB_GROUP_ID); + MessageAttribution attribution = new MessageAttribution(); + message.attributions.add(attribution); + attribution.tabGroupMetadata = new TabGroupMessageMetadata(); + attribution.tabGroupMetadata.localTabGroupId = new LocalTabGroupId(TAB_GROUP_ID); assertEquals(TAB_GROUP_ID, MessageUtils.extractTabGroupId(message)); - message.attribution.tabGroupMetadata = null; + attribution.tabGroupMetadata = null; assertEquals(null, MessageUtils.extractTabGroupId(message)); - message.attribution = null; + attribution = null; assertEquals(null, MessageUtils.extractTabGroupId(message)); assertEquals(null, MessageUtils.extractTabGroupId((InstantMessage) null)); @@ -85,15 +86,16 @@ @Test public void testExtractGivenName() { InstantMessage message = new InstantMessage(); - message.attribution = new MessageAttribution(); - message.attribution.triggeringUser = + MessageAttribution attribution = new MessageAttribution(); + message.attributions.add(attribution); + attribution.triggeringUser = new GroupMember(null, null, null, MemberRole.OWNER, null, GIVEN_NAME); assertEquals(GIVEN_NAME, MessageUtils.extractGivenName(message)); - message.attribution.triggeringUser = null; + attribution.triggeringUser = null; assertEquals("", MessageUtils.extractGivenName(message)); - message.attribution = null; + attribution = null; assertEquals("", MessageUtils.extractGivenName(message)); assertEquals("", MessageUtils.extractGivenName(null)); @@ -102,15 +104,16 @@ @Test public void testExtractTabTitle() { InstantMessage message = new InstantMessage(); - message.attribution = new MessageAttribution(); - message.attribution.tabMetadata = new TabMessageMetadata(); - message.attribution.tabMetadata.lastKnownTitle = TAB_TITLE; + MessageAttribution attribution = new MessageAttribution(); + message.attributions.add(attribution); + attribution.tabMetadata = new TabMessageMetadata(); + attribution.tabMetadata.lastKnownTitle = TAB_TITLE; assertEquals(TAB_TITLE, MessageUtils.extractTabTitle(message)); - message.attribution.tabMetadata = null; + attribution.tabMetadata = null; assertEquals("", MessageUtils.extractTabTitle(message)); - message.attribution = null; + attribution = null; assertEquals("", MessageUtils.extractTabTitle(message)); assertEquals("", MessageUtils.extractTabTitle(null)); @@ -119,15 +122,16 @@ @Test public void testExtractTabGroupTitle_Instant() { InstantMessage message = new InstantMessage(); - message.attribution = new MessageAttribution(); - message.attribution.tabGroupMetadata = new TabGroupMessageMetadata(); - message.attribution.tabGroupMetadata.lastKnownTitle = TAB_GROUP_TITLE; + MessageAttribution attribution = new MessageAttribution(); + message.attributions.add(attribution); + attribution.tabGroupMetadata = new TabGroupMessageMetadata(); + attribution.tabGroupMetadata.lastKnownTitle = TAB_GROUP_TITLE; assertEquals(TAB_GROUP_TITLE, MessageUtils.extractTabGroupTitle(message)); - message.attribution.tabGroupMetadata = null; + attribution.tabGroupMetadata = null; assertEquals("", MessageUtils.extractTabGroupTitle(message)); - message.attribution = null; + attribution = null; assertEquals("", MessageUtils.extractTabGroupTitle(message)); assertEquals("", MessageUtils.extractTabGroupTitle((InstantMessage) null)); @@ -158,13 +162,14 @@ InstantMessage message = new InstantMessage(); assertEquals(null, MessageUtils.extractMember(message)); - message.attribution = new MessageAttribution(); + MessageAttribution attribution = new MessageAttribution(); + message.attributions.add(attribution); assertEquals(null, MessageUtils.extractMember(message)); - message.attribution.triggeringUser = GROUP_MEMBER1; + attribution.triggeringUser = GROUP_MEMBER1; assertEquals(GROUP_MEMBER1, MessageUtils.extractMember(message)); - message.attribution.affectedUser = GROUP_MEMBER2; + attribution.affectedUser = GROUP_MEMBER2; assertEquals(GROUP_MEMBER2, MessageUtils.extractMember(message)); } @@ -175,13 +180,14 @@ InstantMessage message = new InstantMessage(); assertEquals(null, MessageUtils.extractTabUrl(message)); - message.attribution = new MessageAttribution(); + MessageAttribution attribution = new MessageAttribution(); + message.attributions.add(attribution); assertEquals(null, MessageUtils.extractTabUrl(message)); - message.attribution.tabMetadata = new TabMessageMetadata(); + attribution.tabMetadata = new TabMessageMetadata(); assertEquals(null, MessageUtils.extractTabUrl(message)); - message.attribution.tabMetadata.lastKnownUrl = JUnitTestGURLs.URL_1.getSpec(); + attribution.tabMetadata.lastKnownUrl = JUnitTestGURLs.URL_1.getSpec(); assertEquals(JUnitTestGURLs.URL_1.getSpec(), MessageUtils.extractTabUrl(message)); } @@ -192,13 +198,14 @@ InstantMessage message = new InstantMessage(); assertNull(MessageUtils.extractSyncTabGroupId(message)); - message.attribution = new MessageAttribution(); + MessageAttribution attribution = new MessageAttribution(); + message.attributions.add(attribution); assertNull(MessageUtils.extractSyncTabGroupId(message)); - message.attribution.tabGroupMetadata = new TabGroupMessageMetadata(); + attribution.tabGroupMetadata = new TabGroupMessageMetadata(); assertNull(MessageUtils.extractSyncTabGroupId(message)); - message.attribution.tabGroupMetadata.syncTabGroupId = TAB_GROUP_SYNC_ID; + attribution.tabGroupMetadata.syncTabGroupId = TAB_GROUP_SYNC_ID; assertEquals(TAB_GROUP_SYNC_ID, MessageUtils.extractSyncTabGroupId(message)); } @@ -222,14 +229,15 @@ @Test public void testExtractMessageId_Instant() { InstantMessage message = new InstantMessage(); - message.attribution = new MessageAttribution(); - message.attribution.id = MESSAGE_ID; + MessageAttribution attribution = new MessageAttribution(); + message.attributions.add(attribution); + attribution.id = MESSAGE_ID; assertEquals(MESSAGE_ID, MessageUtils.extractMessageId(message)); - message.attribution.id = null; + attribution.id = null; assertNull(MessageUtils.extractMessageId(message)); - message.attribution = null; + message.attributions.clear(); assertNull(MessageUtils.extractMessageId(message)); assertNull(MessageUtils.extractMessageId((InstantMessage) null));
diff --git a/components/collaboration/public/messaging/message.cc b/components/collaboration/public/messaging/message.cc index 85884b0..abb5d67 100644 --- a/components/collaboration/public/messaging/message.cc +++ b/components/collaboration/public/messaging/message.cc
@@ -11,11 +11,6 @@ default; MessageAttribution::~MessageAttribution() = default; -AggregatedMessageData::AggregatedMessageData() = default; -AggregatedMessageData::AggregatedMessageData( - const AggregatedMessageData& other) = default; -AggregatedMessageData::~AggregatedMessageData() = default; - InstantMessage::InstantMessage() = default; InstantMessage::InstantMessage(const InstantMessage& other) = default; InstantMessage::~InstantMessage() = default; @@ -30,4 +25,8 @@ default; TabMessageMetadata::~TabMessageMetadata() = default; +bool IsSingleMessage(const InstantMessage& message) { + return message.attributions.size() == 1u; +} + } // namespace collaboration::messaging
diff --git a/components/collaboration/public/messaging/message.h b/components/collaboration/public/messaging/message.h index b900794b4..57cd26fc 100644 --- a/components/collaboration/public/messaging/message.h +++ b/components/collaboration/public/messaging/message.h
@@ -84,6 +84,8 @@ // A marker that an entity (tab or tab group) has been deleted and the user // has not seen it yet. TOMBSTONED, + // The message was an instant message. + INSTANT_MESSAGE, }; // Metadata about the tab group a message is attributed to. @@ -170,16 +172,6 @@ bool triggering_user_is_self = false; }; -// Attribution for aggregated messages. -struct AggregatedMessageData { - AggregatedMessageData(); - AggregatedMessageData(const AggregatedMessageData& other); - ~AggregatedMessageData(); - - // Attributions for each related message. - std::vector<MessageAttribution> attributions; -}; - // An instant notification that the UI to show something to the user // immediately. Depending on the type of message, it might represent // a single event or multiple events of similar type aggregated as a single @@ -202,12 +194,10 @@ // The message content to be shown in the UI. std::u16string localized_message; - // Set only if this message represents a single event. - std::optional<MessageAttribution> attribution; - - // Set only if this message represents multiple messages aggregated into a - // single message. - std::optional<AggregatedMessageData> aggregated_data; + // The list of message attributions for the messages that it represents. + // For single message case, the size is 1. For aggregated message case, it + // will be greater than 1. + std::vector<MessageAttribution> attributions; }; // A persistent notification that requires an ongoing UI affordance until @@ -223,6 +213,10 @@ PersistentNotificationType type; }; +// Helper method to query whether the message represents a non-aggregated +// message. +bool IsSingleMessage(const InstantMessage& message); + } // namespace collaboration::messaging #endif // COMPONENTS_COLLABORATION_PUBLIC_MESSAGING_MESSAGE_H_
diff --git a/components/collaboration/public/messaging/messaging_backend_service.h b/components/collaboration/public/messaging/messaging_backend_service.h index 3163dc7..55076c99 100644 --- a/components/collaboration/public/messaging/messaging_backend_service.h +++ b/components/collaboration/public/messaging/messaging_backend_service.h
@@ -15,7 +15,6 @@ #include "components/saved_tab_groups/public/types.h" namespace collaboration::messaging { -class InstantMessageDelegate; class MessagingBackendService : public KeyedService, public base::SupportsUserData {
diff --git a/components/collaboration_strings.grdp b/components/collaboration_strings.grdp index 330783b1..3b12b1d 100644 --- a/components/collaboration_strings.grdp +++ b/components/collaboration_strings.grdp
@@ -34,9 +34,6 @@ <message name="IDS_COLLABORATION_SEVERAL_GROUPS_REMOVED_NOTIFICATION" desc="Format for the notification text appearing when more than 2 tab groups are no longer shared with the user."> <ph name="GROUP_COUNT">$1<ex>5</ex></ph> tab groups no longer available </message> - <message name="IDS_COLLABORATION_LOADING_TEXT" desc="The text message that appears when tab group is loading." formatter_data="android_java"> - Loading tab group - </message> <!-- Error Messages --> <message name ="IDS_COLLABORATION_SOMETHING_WENT_WRONG_HEADER" desc="The header of the error dialog something went wrong."> Something went wrong. @@ -154,4 +151,31 @@ </message> <!-- Recent Activity --> + <!-- Instant Messages --> + <message name="IDS_DATA_SHARING_TOAST_TAB_REMOVED" desc="Toast text describing that someone has removed a tab."> + <ph name="MEMBER_FIRST_NAME">$1<ex>Ali</ex></ph> removed tab “<ph name="WEBSITE_TITLE">$2<ex>chromium.org</ex></ph>” + </message> + <message name="IDS_DATA_SHARING_TOAST_TAB_UPDATED" desc="Toast text describing that someone has updated a tab."> + <ph name="MEMBER_FIRST_NAME">$1<ex>Ali</ex></ph> updated tab “<ph name="WEBSITE_TITLE">$2<ex>chromium.org</ex></ph>” + </message> + <message name="IDS_DATA_SHARING_TOAST_TAB_REMOVED_ACTION" desc="The action button text on the tab removed toast clicking on which will reopen the tab that was removed."> + Reopen + </message> + <message name="IDS_DATA_SHARING_TOAST_NEW_MEMBER" desc="Toast text describing that a new member has joined the group."> + <ph name="MEMBER_FIRST_NAME">$1<ex>Ali</ex></ph> joined "<ph name="GROUP_NAME">$2<ex>Vacation</ex></ph>" tab group + </message> + <message name="IDS_DATA_SHARING_TOAST_NEW_MEMBER_MULTIPLE_MEMBERS" desc="Toast text describing that multiple new members have joined the group."> + <ph name="MEMBER_COUNT">$1<ex>7</ex></ph> members joined "<ph name="GROUP_NAME">$2<ex>Vacation</ex></ph>" tab group + </message> + <message name="IDS_DATA_SHARING_TOAST_NEW_MEMBER_ACTION" desc="The action button text on the new member joined toast clicking on which will open the group members management screen."> + Manage + </message> + <message name="IDS_DATA_SHARING_TOAST_BLOCK_LEAVE" desc="Toast text describing that the user has lost access to a shared group."> + The "<ph name="GROUP_NAME">$1<ex>Vacation</ex></ph>" tab group is no longer available + </message> + <message name="IDS_DATA_SHARING_TOAST_BLOCK_LEAVE_MULTIPLE_GROUPS" desc="Toast text describing that the user has lost access to multiple shared groups."> + <ph name="GROUP_COUNT">$1<ex>7</ex></ph> tab groups no longer available + </message> + <!-- Instant Messages --> + </grit-part>
diff --git a/components/collaboration_strings_grdp/IDS_COLLABORATION_LOADING_TEXT.png.sha1 b/components/collaboration_strings_grdp/IDS_COLLABORATION_LOADING_TEXT.png.sha1 deleted file mode 100644 index e5b964d..0000000 --- a/components/collaboration_strings_grdp/IDS_COLLABORATION_LOADING_TEXT.png.sha1 +++ /dev/null
@@ -1 +0,0 @@ -33ebf7daa273a9439d5f44004b3ae12873c8d8ff \ No newline at end of file
diff --git a/chrome/app/generated_resources_grd/IDS_DATA_SHARING_TOAST_BLOCK_LEAVE.png.sha1 b/components/collaboration_strings_grdp/IDS_DATA_SHARING_TOAST_BLOCK_LEAVE.png.sha1 similarity index 100% rename from chrome/app/generated_resources_grd/IDS_DATA_SHARING_TOAST_BLOCK_LEAVE.png.sha1 rename to components/collaboration_strings_grdp/IDS_DATA_SHARING_TOAST_BLOCK_LEAVE.png.sha1
diff --git a/chrome/app/generated_resources_grd/IDS_DATA_SHARING_TOAST_BLOCK_LEAVE.png.sha1 b/components/collaboration_strings_grdp/IDS_DATA_SHARING_TOAST_BLOCK_LEAVE_MULTIPLE_GROUPS.png.sha1 similarity index 100% copy from chrome/app/generated_resources_grd/IDS_DATA_SHARING_TOAST_BLOCK_LEAVE.png.sha1 copy to components/collaboration_strings_grdp/IDS_DATA_SHARING_TOAST_BLOCK_LEAVE_MULTIPLE_GROUPS.png.sha1
diff --git a/chrome/app/generated_resources_grd/IDS_DATA_SHARING_TOAST_NEW_MEMBER.png.sha1 b/components/collaboration_strings_grdp/IDS_DATA_SHARING_TOAST_NEW_MEMBER.png.sha1 similarity index 100% rename from chrome/app/generated_resources_grd/IDS_DATA_SHARING_TOAST_NEW_MEMBER.png.sha1 rename to components/collaboration_strings_grdp/IDS_DATA_SHARING_TOAST_NEW_MEMBER.png.sha1
diff --git a/chrome/app/generated_resources_grd/IDS_DATA_SHARING_TOAST_NEW_MEMBER_ACTION.png.sha1 b/components/collaboration_strings_grdp/IDS_DATA_SHARING_TOAST_NEW_MEMBER_ACTION.png.sha1 similarity index 100% rename from chrome/app/generated_resources_grd/IDS_DATA_SHARING_TOAST_NEW_MEMBER_ACTION.png.sha1 rename to components/collaboration_strings_grdp/IDS_DATA_SHARING_TOAST_NEW_MEMBER_ACTION.png.sha1
diff --git a/chrome/app/generated_resources_grd/IDS_DATA_SHARING_TOAST_NEW_MEMBER.png.sha1 b/components/collaboration_strings_grdp/IDS_DATA_SHARING_TOAST_NEW_MEMBER_MULTIPLE_MEMBERS.png.sha1 similarity index 100% copy from chrome/app/generated_resources_grd/IDS_DATA_SHARING_TOAST_NEW_MEMBER.png.sha1 copy to components/collaboration_strings_grdp/IDS_DATA_SHARING_TOAST_NEW_MEMBER_MULTIPLE_MEMBERS.png.sha1
diff --git a/chrome/app/generated_resources_grd/IDS_DATA_SHARING_TOAST_TAB_REMOVED.png.sha1 b/components/collaboration_strings_grdp/IDS_DATA_SHARING_TOAST_TAB_REMOVED.png.sha1 similarity index 100% rename from chrome/app/generated_resources_grd/IDS_DATA_SHARING_TOAST_TAB_REMOVED.png.sha1 rename to components/collaboration_strings_grdp/IDS_DATA_SHARING_TOAST_TAB_REMOVED.png.sha1
diff --git a/chrome/app/generated_resources_grd/IDS_DATA_SHARING_TOAST_TAB_REMOVED_ACTION.png.sha1 b/components/collaboration_strings_grdp/IDS_DATA_SHARING_TOAST_TAB_REMOVED_ACTION.png.sha1 similarity index 100% rename from chrome/app/generated_resources_grd/IDS_DATA_SHARING_TOAST_TAB_REMOVED_ACTION.png.sha1 rename to components/collaboration_strings_grdp/IDS_DATA_SHARING_TOAST_TAB_REMOVED_ACTION.png.sha1
diff --git a/chrome/app/generated_resources_grd/IDS_DATA_SHARING_TOAST_TAB_REMOVED.png.sha1 b/components/collaboration_strings_grdp/IDS_DATA_SHARING_TOAST_TAB_UPDATED.png.sha1 similarity index 100% copy from chrome/app/generated_resources_grd/IDS_DATA_SHARING_TOAST_TAB_REMOVED.png.sha1 copy to components/collaboration_strings_grdp/IDS_DATA_SHARING_TOAST_TAB_UPDATED.png.sha1
diff --git a/components/embedder_support/android/java/src/org/chromium/components/embedder_support/contextmenu/ContextMenuParams.java b/components/embedder_support/android/java/src/org/chromium/components/embedder_support/contextmenu/ContextMenuParams.java index dab4ca2..c30c3815 100644 --- a/components/embedder_support/android/java/src/org/chromium/components/embedder_support/contextmenu/ContextMenuParams.java +++ b/components/embedder_support/android/java/src/org/chromium/components/embedder_support/contextmenu/ContextMenuParams.java
@@ -19,7 +19,7 @@ /** * A list of parameters that explain what kind of context menu to show the user. This data is - * generated from content/public/common/context_menu_params.h. + * generated from components/embedder_support/android/contextmenu/context_menu_builder.h. */ @JNINamespace("context_menu") @NullMarked
diff --git a/components/heap_profiling/in_process/heap_profiler_controller.cc b/components/heap_profiling/in_process/heap_profiler_controller.cc index cbf1ca2a..256cd22 100644 --- a/components/heap_profiling/in_process/heap_profiler_controller.cc +++ b/components/heap_profiling/in_process/heap_profiler_controller.cc
@@ -91,9 +91,13 @@ // Returns the full name of a histogram to record by appending the // ProfiledProcess variant name for `process_type` (defined in // tools/metrics/histograms/metadata/memory/histograms.xml) to `base_name`. +// Returns `base_name` unchanged if `process_type` is nullopt. std::string ProcessHistogramName(std::string_view base_name, - ProcessType process_type) { - switch (process_type) { + std::optional<ProcessType> process_type) { + if (!process_type.has_value()) { + return std::string(base_name); + } + switch (process_type.value()) { case ProcessType::kBrowser: return base::StrCat({base_name, ".Browser"}); case ProcessType::kRenderer: @@ -166,6 +170,43 @@ return {false, "Default"}; } +// Logs statistics about the sampling profiler. +void LogProfilerStats(std::optional<ProcessType> process_type, + const base::PoissonAllocationSamplerStats& profiler_stats, + size_t num_samples) { + const double hit_rate = + static_cast<double>(profiler_stats.address_cache_hits) / + (profiler_stats.address_cache_hits + profiler_stats.address_cache_misses); + base::UmaHistogramCounts100000( + ProcessHistogramName("HeapProfiling.InProcess.SamplesPerSnapshot", + process_type), + num_samples); + base::UmaHistogramCounts1M( + ProcessHistogramName( + "HeapProfiling.InProcess.SampledAddressCacheHitCount", process_type), + profiler_stats.address_cache_hits); + base::UmaHistogramCounts10000( + ProcessHistogramName("HeapProfiling.InProcess.SampledAddressCacheHitRate", + process_type), + hit_rate * 10000); + base::UmaHistogramCounts1M( + ProcessHistogramName("HeapProfiling.InProcess.SampledAddressCacheMaxSize", + process_type), + profiler_stats.address_cache_max_size); + base::UmaHistogramPercentage( + ProcessHistogramName( + "HeapProfiling.InProcess.SampledAddressCacheMaxLoadFactor", + process_type), + 100 * profiler_stats.address_cache_max_load_factor); + for (size_t bucket_length : profiler_stats.address_cache_bucket_lengths) { + base::UmaHistogramCounts100( + ProcessHistogramName( + "HeapProfiling.InProcess.SampledAddressCacheBucketLengths", + process_type), + bucket_length); + } +} + } // namespace HeapProfilerController::SnapshotParams::SnapshotParams( @@ -268,6 +309,12 @@ if (sampling_rate_bytes > 0) { base::SamplingHeapProfiler::Get()->SetSamplingInterval(sampling_rate_bytes); } + const float hash_set_load_factor = + GetHashSetLoadFactorForProcess(process_type_); + if (hash_set_load_factor > 0) { + base::PoissonAllocationSampler::Get()->SetTargetHashSetLoadFactor( + hash_set_load_factor); + } base::SamplingHeapProfiler::Get()->Start(); if (process_type_ != ProcessType::kBrowser) { @@ -449,59 +496,11 @@ std::vector<Sample> samples = base::SamplingHeapProfiler::Get()->GetSamples(0); - // Log statistics about the sampling profiler. const base::PoissonAllocationSamplerStats profiler_stats = base::PoissonAllocationSampler::Get()->GetAndResetStats(); - const double hit_rate = - static_cast<double>(profiler_stats.address_cache_hits) / - (profiler_stats.address_cache_hits + profiler_stats.address_cache_misses); - base::UmaHistogramCounts100000( - ProcessHistogramName("HeapProfiling.InProcess.SamplesPerSnapshot", - process_type), - samples.size()); - base::UmaHistogramCounts1M( - ProcessHistogramName( - "HeapProfiling.InProcess.SampledAddressCacheHitCount", process_type), - profiler_stats.address_cache_hits); - base::UmaHistogramCounts10000( - ProcessHistogramName("HeapProfiling.InProcess.SampledAddressCacheHitRate", - process_type), - hit_rate * 10000); - base::UmaHistogramCounts1M( - ProcessHistogramName("HeapProfiling.InProcess.SampledAddressCacheMaxSize", - process_type), - profiler_stats.address_cache_max_size); - base::UmaHistogramPercentage( - ProcessHistogramName( - "HeapProfiling.InProcess.SampledAddressCacheMaxLoadFactor", - process_type), - 100 * profiler_stats.address_cache_max_load_factor); - for (size_t bucket_length : profiler_stats.address_cache_bucket_lengths) { - base::UmaHistogramCounts100( - ProcessHistogramName( - "HeapProfiling.InProcess.SampledAddressCacheBucketLengths", - process_type), - bucket_length); - } + LogProfilerStats(process_type, profiler_stats, samples.size()); // Also summarize over all process types. - base::UmaHistogramCounts100000("HeapProfiling.InProcess.SamplesPerSnapshot", - samples.size()); - base::UmaHistogramCounts1M( - "HeapProfiling.InProcess.SampledAddressCacheHitCount", - profiler_stats.address_cache_hits); - base::UmaHistogramCounts10000( - "HeapProfiling.InProcess.SampledAddressCacheHitRate", hit_rate * 10000); - base::UmaHistogramCounts1M( - "HeapProfiling.InProcess.SampledAddressCacheMaxSize", - profiler_stats.address_cache_max_size); - base::UmaHistogramPercentage( - "HeapProfiling.InProcess.SampledAddressCacheMaxLoadFactor", - 100 * profiler_stats.address_cache_max_load_factor); - for (size_t bucket_length : profiler_stats.address_cache_bucket_lengths) { - base::UmaHistogramCounts100( - "HeapProfiling.InProcess.SampledAddressCacheBucketLengths", - bucket_length); - } + LogProfilerStats(std::nullopt, profiler_stats, samples.size()); base::ModuleCache module_cache; sampling_profiler::CallStackProfileParams params(
diff --git a/components/heap_profiling/in_process/heap_profiler_controller_unittest.cc b/components/heap_profiling/in_process/heap_profiler_controller_unittest.cc index 7163da8..fe6f3bc 100644 --- a/components/heap_profiling/in_process/heap_profiler_controller_unittest.cc +++ b/components/heap_profiling/in_process/heap_profiler_controller_unittest.cc
@@ -163,7 +163,7 @@ using ::testing::Optional; using ::testing::Property; using ::testing::ResultOf; -using ::testing::UnorderedElementsAreArray; +using ::testing::UnorderedElementsAre; using ::testing::Values; using ::testing::ValuesIn; @@ -1487,15 +1487,23 @@ // be profiled - the 5th is invisible to the profiler. EXPECT_THAT( received_profiles, - UnorderedElementsAreArray({ + UnorderedElementsAre( sampled_profile_matches(metrics::Process::BROWSER_PROCESS, 0, 100, 1), sampled_profile_matches(metrics::Process::GPU_PROCESS, 1, 100, 1), sampled_profile_matches(metrics::Process::UTILITY_PROCESS, 2, 50, 1), // The first renderer should be skipped. sampled_profile_matches(metrics::Process::RENDERER_PROCESS, 0, 66, 3), sampled_profile_matches(metrics::Process::RENDERER_PROCESS, 4, 66, 3), - sampled_profile_matches(metrics::Process::RENDERER_PROCESS, 5, 66, 3), - })); + sampled_profile_matches(metrics::Process::RENDERER_PROCESS, 5, 66, + 3))); + + // Make sure both per-process and aggregate profiler stats are logged. + // Subprocess metrics aren't hooked up in this test, so `histogram_tester_` + // only sees the browser process histograms. + histogram_tester_.ExpectTotalCount( + "HeapProfiling.InProcess.SamplesPerSnapshot.Browser", 1); + histogram_tester_.ExpectTotalCount( + "HeapProfiling.InProcess.SamplesPerSnapshot", 1); } #endif // ENABLE_MULTIPROCESS_TESTS
diff --git a/components/heap_profiling/in_process/heap_profiler_parameters.cc b/components/heap_profiling/in_process/heap_profiler_parameters.cc index 4ace1c1..8d09b48 100644 --- a/components/heap_profiling/in_process/heap_profiler_parameters.cc +++ b/components/heap_profiling/in_process/heap_profiler_parameters.cc
@@ -110,6 +110,19 @@ &kHeapProfilerReporting, "utility-sampling-rate-bytes", kDefaultSamplingRateBytes / 10}; +// The load factor that should be used by PoissonAllocationSampler's hash set in +// each process type. +constexpr base::FeatureParam<double> kBrowserHashSetLoadFactor{ + &kHeapProfilerReporting, "browser-hash-set-load-factor", 1.0}; +constexpr base::FeatureParam<double> kGpuHashSetLoadFactor{ + &kHeapProfilerReporting, "gpu-hash-set-load-factor", 1.0}; +constexpr base::FeatureParam<double> kNetworkHashSetLoadFactor{ + &kHeapProfilerReporting, "network-hash-set-load-factor", 1.0}; +constexpr base::FeatureParam<double> kRendererHashSetLoadFactor{ + &kHeapProfilerReporting, "renderer-hash-set-load-factor", 1.0}; +constexpr base::FeatureParam<double> kUtilityHashSetLoadFactor{ + &kHeapProfilerReporting, "utility-hash-set-load-factor", 1.0}; + } // namespace BASE_FEATURE(kHeapProfilerReporting, @@ -182,4 +195,22 @@ return snapshot_probability_pct; } +float GetHashSetLoadFactorForProcess( + sampling_profiler::ProfilerProcessType process_type) { + switch (process_type) { + case sampling_profiler::ProfilerProcessType::kBrowser: + return kBrowserHashSetLoadFactor.Get(); + case sampling_profiler::ProfilerProcessType::kGpu: + return kGpuHashSetLoadFactor.Get(); + case sampling_profiler::ProfilerProcessType::kNetworkService: + return kNetworkHashSetLoadFactor.Get(); + case sampling_profiler::ProfilerProcessType::kRenderer: + return kRendererHashSetLoadFactor.Get(); + case sampling_profiler::ProfilerProcessType::kUtility: + return kUtilityHashSetLoadFactor.Get(); + default: + NOTREACHED(); + } +} + } // namespace heap_profiling
diff --git a/components/heap_profiling/in_process/heap_profiler_parameters.h b/components/heap_profiling/in_process/heap_profiler_parameters.h index b5b81cd0..6d7f9d6 100644 --- a/components/heap_profiling/in_process/heap_profiler_parameters.h +++ b/components/heap_profiling/in_process/heap_profiler_parameters.h
@@ -31,7 +31,8 @@ // Mean time between snapshots. extern const base::FeatureParam<base::TimeDelta> kCollectionInterval; -// Returns the sampling rate in bytes to use for `process_type`. +// Returns the sampling rate in bytes to use for `process_type`. 0 means to use +// PoissonAllocationSampler's default sampling rate. size_t GetSamplingRateForProcess( sampling_profiler::ProfilerProcessType process_type); @@ -40,6 +41,11 @@ int GetSnapshotProbabilityForProcess( sampling_profiler::ProfilerProcessType process_type); +// Returns the load factor that PoissonAllocationSampler's hash set should use +// in a `process_type` process. 0.0 means to use the hash set's default. +float GetHashSetLoadFactorForProcess( + sampling_profiler::ProfilerProcessType process_type); + } // namespace heap_profiling #endif // COMPONENTS_HEAP_PROFILING_IN_PROCESS_HEAP_PROFILER_PARAMETERS_H_
diff --git a/components/history/content/browser/web_contents_top_sites_observer_unittest.cc b/components/history/content/browser/web_contents_top_sites_observer_unittest.cc index 0bb75c09..7570b68 100644 --- a/components/history/content/browser/web_contents_top_sites_observer_unittest.cc +++ b/components/history/content/browser/web_contents_top_sites_observer_unittest.cc
@@ -36,6 +36,7 @@ MOCK_CONST_METHOD0(loaded, bool()); MOCK_METHOD0(GetPrepopulatedPages, history::PrepopulatedPageList()); MOCK_METHOD1(OnNavigationCommitted, void(const GURL& url)); + MOCK_CONST_METHOD0(NumBlockedSites, int()); // Publicly expose notification to observers, since the implementation cannot // be overridden.
diff --git a/components/history/core/browser/history_backend.cc b/components/history/core/browser/history_backend.cc index 71dac72..e110c95e 100644 --- a/components/history/core/browser/history_backend.cc +++ b/components/history/core/browser/history_backend.cc
@@ -2907,7 +2907,10 @@ return result; } -MostVisitedURLList HistoryBackend::QueryMostVisitedURLs(int result_count) { +MostVisitedURLList HistoryBackend::QueryMostVisitedURLs( + int result_count, + const std::optional<std::string>& recency_factor_name, + std::optional<size_t> recency_window_days) { if (!db_) return {}; @@ -2918,8 +2921,8 @@ ? base::BindRepeating(&HistoryBackendClient::IsWebSafe, base::Unretained(backend_client_.get())) : base::NullCallback(); - std::vector<std::unique_ptr<PageUsageData>> data = - db_->QuerySegmentUsage(result_count, url_filter); + std::vector<std::unique_ptr<PageUsageData>> data = db_->QuerySegmentUsage( + result_count, url_filter, recency_factor_name, recency_window_days); MostVisitedURLList result; for (const std::unique_ptr<PageUsageData>& current_data : data) {
diff --git a/components/history/core/browser/history_backend.h b/components/history/core/browser/history_backend.h index 77fc38f..f03b85c 100644 --- a/components/history/core/browser/history_backend.h +++ b/components/history/core/browser/history_backend.h
@@ -323,7 +323,15 @@ // Request the `result_count` most visited URLs and the chain of // redirects leading to each of these URLs. Used by TopSites. - MostVisitedURLList QueryMostVisitedURLs(int result_count); + // `recency_factor_name` is the type of scoring algorithm SegmentScorer + // will use when rankings results. + // `recency_window_days` is the number of days of history to consider + // when scoring segments. A result older than this window will not add to a + // segment's score. + MostVisitedURLList QueryMostVisitedURLs( + int result_count, + const std::optional<std::string>& recency_factor_name = std::nullopt, + std::optional<size_t> recency_window_days = std::nullopt); // Request `result_count` of the most repeated queries for the given keyword. // Used by TopSites.
diff --git a/components/history/core/browser/history_service.cc b/components/history/core/browser/history_service.cc index 3043e8b..ff5ff1b 100644 --- a/components/history/core/browser/history_service.cc +++ b/components/history/core/browser/history_service.cc
@@ -1456,13 +1456,15 @@ base::CancelableTaskTracker::TaskId HistoryService::QueryMostVisitedURLs( int result_count, QueryMostVisitedURLsCallback callback, - base::CancelableTaskTracker* tracker) { + base::CancelableTaskTracker* tracker, + const std::optional<std::string>& recency_factor_name, + std::optional<size_t> recency_window_days) { DCHECK(backend_task_runner_) << "History service being called after cleanup"; DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); return tracker->PostTaskAndReplyWithResult( backend_task_runner_.get(), FROM_HERE, base::BindOnce(&HistoryBackend::QueryMostVisitedURLs, history_backend_, - result_count), + result_count, recency_factor_name, recency_window_days), std::move(callback)); }
diff --git a/components/history/core/browser/history_service.h b/components/history/core/browser/history_service.h index 4c39d701..5988f23 100644 --- a/components/history/core/browser/history_service.h +++ b/components/history/core/browser/history_service.h
@@ -8,6 +8,7 @@ #include <stdint.h> #include <memory> +#include <optional> #include <set> #include <string> #include <utility> @@ -382,7 +383,9 @@ virtual base::CancelableTaskTracker::TaskId QueryMostVisitedURLs( int result_count, QueryMostVisitedURLsCallback callback, - base::CancelableTaskTracker* tracker); + base::CancelableTaskTracker* tracker, + const std::optional<std::string>& recency_factor_name = std::nullopt, + std::optional<size_t> recency_window_days = std::nullopt); // Request `result_count` of the most repeated queries for the given keyword. // Used by TopSites.
diff --git a/components/history/core/browser/segment_scorer.cc b/components/history/core/browser/segment_scorer.cc index 90865a797..7802a27 100644 --- a/components/history/core/browser/segment_scorer.cc +++ b/components/history/core/browser/segment_scorer.cc
@@ -21,13 +21,7 @@ // static std::unique_ptr<SegmentScorer::RecencyFactor> -SegmentScorer::RecencyFactor::CreateFromFeatureFlags() { - std::string recency_factor_name = - base::FeatureParam<std::string>(&history::kMostVisitedTilesNewScoring, - kMvtScoringParamRecencyFactor, - kMvtScoringParamRecencyFactor_Default) - .Get(); - +SegmentScorer::RecencyFactor::Create(const std::string& recency_factor_name) { if (recency_factor_name == kMvtScoringParamRecencyFactor_Decay) { double decay_per_day = std::clamp( base::FeatureParam<double>(&history::kMostVisitedTilesNewScoring, @@ -92,8 +86,14 @@ // static std::unique_ptr<SegmentScorer> SegmentScorer::CreateFromFeatureFlags() { - std::unique_ptr<SegmentScorer::RecencyFactor> recency_factor = - SegmentScorer::RecencyFactor::CreateFromFeatureFlags(); + std::string recency_factor_name = + base::FeatureParam<std::string>(&history::kMostVisitedTilesNewScoring, + kMvtScoringParamRecencyFactor, + kMvtScoringParamRecencyFactor_Default) + .Get(); + + std::unique_ptr<RecencyFactor> recency_factor = + RecencyFactor::Create(recency_factor_name); int daily_visit_count_cap = base::FeatureParam<int>(&history::kMostVisitedTilesNewScoring, @@ -103,9 +103,23 @@ new SegmentScorer(std::move(recency_factor), daily_visit_count_cap)); } -SegmentScorer::SegmentScorer( - std::unique_ptr<SegmentScorer::RecencyFactor> recency_factor, - int daily_visit_count_cap) +// static +std::unique_ptr<SegmentScorer> SegmentScorer::Create( + const std::string& recency_factor_name) { + std::unique_ptr<RecencyFactor> recency_factor = + RecencyFactor::Create(recency_factor_name); + + // TODO(crbug.com/405422202): Explicitly define in the omnibox feature config. + int daily_visit_count_cap = + base::FeatureParam<int>(&history::kMostVisitedTilesNewScoring, + kMvtScoringParamDailyVisitCountCap, INT_MAX) + .Get(); + return base::WrapUnique( + new SegmentScorer(std::move(recency_factor), daily_visit_count_cap)); +} + +SegmentScorer::SegmentScorer(std::unique_ptr<RecencyFactor> recency_factor, + int daily_visit_count_cap) : recency_factor_(std::move(recency_factor)), daily_visit_count_cap_(daily_visit_count_cap) {} @@ -113,7 +127,8 @@ float SegmentScorer::Compute(const std::vector<base::Time>& time_slots, const std::vector<int>& visit_counts, - base::Time now) const { + base::Time now, + std::optional<size_t> recency_window_days) const { size_t n = time_slots.size(); CHECK_EQ(n, visit_counts.size()); float score = 0.0f; @@ -128,6 +143,11 @@ // Recent visits count more than historical ones, so multiply a // recency factor related to how long ago this day was. int days_ago = (now - time_slot).InDays(); + // Ignore entries older than `recency_window_days`. + if (recency_window_days && + days_ago > static_cast<int>(recency_window_days.value())) { + continue; + } score += recency_factor_->Compute(days_ago) * day_visits_score; } return score;
diff --git a/components/history/core/browser/segment_scorer.h b/components/history/core/browser/segment_scorer.h index f8b3b17..ad41266 100644 --- a/components/history/core/browser/segment_scorer.h +++ b/components/history/core/browser/segment_scorer.h
@@ -6,6 +6,7 @@ #define COMPONENTS_HISTORY_CORE_BROWSER_SEGMENT_SCORER_H_ #include <memory> +#include <optional> #include <vector> #include "base/time/time.h" @@ -17,7 +18,8 @@ private: // Formula to add more weight to recent visits, and less to past ones. struct RecencyFactor { - static std::unique_ptr<RecencyFactor> CreateFromFeatureFlags(); + static std::unique_ptr<RecencyFactor> Create( + const std::string& recency_factor_name); virtual ~RecencyFactor(); virtual float Compute(int days_ago) = 0; @@ -45,6 +47,8 @@ public: static std::unique_ptr<SegmentScorer> CreateFromFeatureFlags(); + static std::unique_ptr<SegmentScorer> Create( + const std::string& recency_factor_name); private: SegmentScorer(std::unique_ptr<RecencyFactor> recency_factor, @@ -58,7 +62,8 @@ float Compute(const std::vector<base::Time>& time_slots, const std::vector<int>& visit_counts, - base::Time now) const; + base::Time now, + std::optional<size_t> recency_window_days) const; private: std::unique_ptr<RecencyFactor> recency_factor_;
diff --git a/components/history/core/browser/segment_scorer_unittest.cc b/components/history/core/browser/segment_scorer_unittest.cc index 2408b0b..5b4b508 100644 --- a/components/history/core/browser/segment_scorer_unittest.cc +++ b/components/history/core/browser/segment_scorer_unittest.cc
@@ -9,6 +9,7 @@ #include <algorithm> #include <memory> +#include <optional> #include <string> #include <utility> #include <vector> @@ -77,10 +78,11 @@ std::vector<std::string> GetTestDataRankingUsingScorer( std::vector<SegmentTestItem>&& test_items, - std::unique_ptr<SegmentScorer> scorer) { + std::unique_ptr<SegmentScorer> scorer, + std::optional<size_t> recency_window_days = std::nullopt) { for (auto& item : test_items) { - item.score = - scorer->Compute(item.time_slots, item.visit_counts, fake_now); + item.score = scorer->Compute(item.time_slots, item.visit_counts, fake_now, + recency_window_days); } // Sort to make items with highest score appear first. @@ -184,4 +186,29 @@ ASSERT_EQ("1 today", names_by_rank[cur++]); } +TEST_F(SegmentScorerTest, DesktopRankByDecayDefaultVisitCap10DayCap5Scorer) { + base::FieldTrialParams params; + params[history::kMvtScoringParamDailyVisitCountCap] = "10"; + + base::test::ScopedFeatureList feature_list; + feature_list.InitAndEnableFeatureWithParameters( + history::kMostVisitedTilesNewScoring, params); + + // Consider last 5 days of data using default decay. + std::vector<std::string> names_by_rank = GetTestDataRankingUsingScorer( + MakeTestItems(), + SegmentScorer::Create(history::kMvtScoringParamRecencyFactor_Default), + 4u); + int cur = 0; + ASSERT_EQ("10 last 5 days", names_by_rank[cur++]); + ASSERT_EQ("10 increase last 4 days", names_by_rank[cur++]); + ASSERT_EQ("10 decrease last 4 days", names_by_rank[cur++]); + ASSERT_EQ("10 last 2 days", names_by_rank[cur++]); + ASSERT_EQ("10 last 10 days", names_by_rank[cur++]); + ASSERT_EQ("10 today", names_by_rank[cur++]); + ASSERT_EQ("10 over 2 days week apart", names_by_rank[cur++]); + ASSERT_EQ("10 last 19 days", names_by_rank[cur++]); + ASSERT_EQ("1 today", names_by_rank[cur++]); +} + } // namespace history
diff --git a/components/history/core/browser/top_sites.h b/components/history/core/browser/top_sites.h index 28659be..8aa014ed 100644 --- a/components/history/core/browser/top_sites.h +++ b/components/history/core/browser/top_sites.h
@@ -78,6 +78,9 @@ // Removes all blocked urls. Should be called from the UI thread. virtual void ClearBlockedUrls() = 0; + // Returns the number of blocked URLs. + virtual int NumBlockedSites() const = 0; + // Returns true if the top sites list is full (i.e. we already have the // maximum number of top sites). This function also returns false if TopSites // isn't loaded yet.
diff --git a/components/history/core/browser/top_sites_impl.cc b/components/history/core/browser/top_sites_impl.cc index 813d74d5..be49857e 100644 --- a/components/history/core/browser/top_sites_impl.cc +++ b/components/history/core/browser/top_sites_impl.cc
@@ -230,6 +230,11 @@ NotifyTopSitesChanged(TopSitesObserver::ChangeReason::BLOCKED_URLS); } +int TopSitesImpl::NumBlockedSites() const { + DCHECK(thread_checker_.CalledOnValidThread()); + return pref_service_->GetDict(kBlockedUrlsPrefsKey).size(); +} + bool TopSitesImpl::IsFull() { return loaded_ && top_sites_.size() >= kTopSitesNumber; } @@ -414,7 +419,7 @@ int TopSitesImpl::num_results_to_request_from_history() const { DCHECK(thread_checker_.CalledOnValidThread()); - return kTopSitesNumber + pref_service_->GetDict(kBlockedUrlsPrefsKey).size(); + return kTopSitesNumber + NumBlockedSites(); } void TopSitesImpl::MoveStateToLoaded() {
diff --git a/components/history/core/browser/top_sites_impl.h b/components/history/core/browser/top_sites_impl.h index 622ebc9..7be926a 100644 --- a/components/history/core/browser/top_sites_impl.h +++ b/components/history/core/browser/top_sites_impl.h
@@ -76,6 +76,7 @@ PrepopulatedPageList GetPrepopulatedPages() override; bool loaded() const override; void OnNavigationCommitted(const GURL& url) override; + int NumBlockedSites() const override; // RefcountedKeyedService: void ShutdownOnUIThread() override;
diff --git a/components/history/core/browser/visitsegment_database.cc b/components/history/core/browser/visitsegment_database.cc index 10d6b81..564e262 100644 --- a/components/history/core/browser/visitsegment_database.cc +++ b/components/history/core/browser/visitsegment_database.cc
@@ -261,7 +261,9 @@ std::vector<std::unique_ptr<PageUsageData>> VisitSegmentDatabase::QuerySegmentUsage( int max_result_count, - const base::RepeatingCallback<bool(const GURL&)>& url_filter) { + const base::RepeatingCallback<bool(const GURL&)>& url_filter, + const std::optional<std::string>& recency_factor_name, + std::optional<size_t> recency_window_days) { // Phase 1: Gather all segments and compute scores. std::vector<std::unique_ptr<PageUsageData>> segments; base::Time now = base::Time::Now(); @@ -276,7 +278,8 @@ SegmentVisitor segment_visitor(&statement); SegmentInfo segment_info; std::unique_ptr<SegmentScorer> scorer = - SegmentScorer::CreateFromFeatureFlags(); + recency_factor_name ? SegmentScorer::Create(recency_factor_name.value()) + : SegmentScorer::CreateFromFeatureFlags(); while (segment_visitor.Step(&segment_info)) { DCHECK(!segment_info.time_slots.empty()); DCHECK_EQ(segment_info.time_slots.size(), segment_info.visit_counts.size()); @@ -288,7 +291,8 @@ segment->SetVisitCount(std::accumulate(segment_info.visit_counts.begin(), segment_info.visit_counts.end(), 0)); segment->SetScore(scorer->Compute(segment_info.time_slots, - segment_info.visit_counts, now)); + segment_info.visit_counts, now, + recency_window_days)); segments.push_back(std::move(segment)); }
diff --git a/components/history/core/browser/visitsegment_database.h b/components/history/core/browser/visitsegment_database.h index a6709c7..c631083 100644 --- a/components/history/core/browser/visitsegment_database.h +++ b/components/history/core/browser/visitsegment_database.h
@@ -6,6 +6,7 @@ #define COMPONENTS_HISTORY_CORE_BROWSER_VISITSEGMENT_DATABASE_H_ #include <memory> +#include <optional> #include <string> #include "base/functional/callback_forward.h" @@ -57,7 +58,9 @@ // included. std::vector<std::unique_ptr<PageUsageData>> QuerySegmentUsage( int max_result_count, - const base::RepeatingCallback<bool(const GURL&)>& url_filter); + const base::RepeatingCallback<bool(const GURL&)>& url_filter, + const std::optional<std::string>& recency_factor_name = std::nullopt, + std::optional<size_t> recency_window_days = std::nullopt); // Deletes all segment data older than `older_than`. bool DeleteSegmentDataOlderThan(base::Time older_than);
diff --git a/components/input/render_input_router.cc b/components/input/render_input_router.cc index c2a1f4c..faf1323 100644 --- a/components/input/render_input_router.cc +++ b/components/input/render_input_router.cc
@@ -149,13 +149,18 @@ in_flight_event_count_ = 0; StopInputEventAckTimeout(); + bool was_active = input_router_ && input_router_->IsActive(); + input_router_ = std::make_unique<InputRouterImpl>( this, this, fling_scheduler_.get(), GetInputRouterConfigForPlatform(task_runner_)); - // input_router_ recreated, need to update the force_enable_zoom_ state. + // Restore states in the newly recreated `input_router_`. input_router_->SetForceEnableZoom(force_enable_zoom_); input_router_->SetDeviceScaleFactor(device_scale_factor); + if (was_active) { + input_router_->MakeActive(); + } } void RenderInputRouter::SetFlingScheduler(
diff --git a/components/messages/android/java/src/org/chromium/components/messages/MessagesMetrics.java b/components/messages/android/java/src/org/chromium/components/messages/MessagesMetrics.java index dad5657..b5dd7be 100644 --- a/components/messages/android/java/src/org/chromium/components/messages/MessagesMetrics.java +++ b/components/messages/android/java/src/org/chromium/components/messages/MessagesMetrics.java
@@ -373,6 +373,8 @@ return "CctAccountMismatchNotice"; case MessageIdentifier.PROMPT_HATS_CLEAR_BROWSING_DATA: return "PromptHatsClearBrowsingData"; + case MessageIdentifier.OS_ADVANCED_PROTECTION_SETTING_CHANGED_MESSAGE: + return "OsAdvancedProtectionSettingChangedMessage"; default: return "Unknown"; }
diff --git a/components/messages/android/message_enums.h b/components/messages/android/message_enums.h index 776fe74..af88289 100644 --- a/components/messages/android/message_enums.h +++ b/components/messages/android/message_enums.h
@@ -142,6 +142,7 @@ COLLABORATION_REMOVED = 57, CCT_ACCOUNT_MISMATCH_NOTICE = 58, PROMPT_HATS_CLEAR_BROWSING_DATA = 59, + OS_ADVANCED_PROTECTION_SETTING_CHANGED_MESSAGE = 60, // Insert new values before this line. COUNT };
diff --git a/components/ntp_tiles/most_visited_sites_unittest.cc b/components/ntp_tiles/most_visited_sites_unittest.cc index adbec2de..95c68aa 100644 --- a/components/ntp_tiles/most_visited_sites_unittest.cc +++ b/components/ntp_tiles/most_visited_sites_unittest.cc
@@ -164,6 +164,7 @@ MOCK_CONST_METHOD0(loaded, bool()); MOCK_METHOD0(GetPrepopulatedPages, history::PrepopulatedPageList()); MOCK_METHOD1(OnNavigationCommitted, void(const GURL& url)); + MOCK_CONST_METHOD0(NumBlockedSites, int()); // Publicly expose notification to observers, since the implementation cannot // be overriden.
diff --git a/components/omnibox/browser/BUILD.gn b/components/omnibox/browser/BUILD.gn index c25f966..82519f0 100644 --- a/components/omnibox/browser/BUILD.gn +++ b/components/omnibox/browser/BUILD.gn
@@ -724,6 +724,8 @@ "test_omnibox_client.h", "test_omnibox_edit_model.cc", "test_omnibox_edit_model.h", + "test_omnibox_popup_view.cc", + "test_omnibox_popup_view.h", "test_omnibox_view.cc", "test_omnibox_view.h", "test_scheme_classifier.cc",
diff --git a/components/omnibox/browser/autocomplete_controller.h b/components/omnibox/browser/autocomplete_controller.h index f1da5bd..b5a6855 100644 --- a/components/omnibox/browser/autocomplete_controller.h +++ b/components/omnibox/browser/autocomplete_controller.h
@@ -385,6 +385,7 @@ FRIEND_TEST_ALL_PREFIXES(OmniboxEditModelPopupTest, GetIconForExtensionWithImageURL); FRIEND_TEST_ALL_PREFIXES(RealboxHandlerTest, RealboxUpdatesEditModelInput); + FRIEND_TEST_ALL_PREFIXES(OmniboxViewPopupTest, GetIcon_IconUrl); // A minimal representation of the previous `AutocompleteResult`. Used by // `UpdateResult()`'s helper methods.
diff --git a/components/omnibox/browser/most_visited_sites_provider.cc b/components/omnibox/browser/most_visited_sites_provider.cc index 452241f4..397f903 100644 --- a/components/omnibox/browser/most_visited_sites_provider.cc +++ b/components/omnibox/browser/most_visited_sites_provider.cc
@@ -11,6 +11,7 @@ #include "base/functional/bind.h" #include "base/metrics/histogram_functions.h" #include "base/strings/escape.h" +#include "components/history/core/browser/history_service.h" #include "components/history/core/browser/top_sites.h" #include "components/omnibox/browser/autocomplete_input.h" #include "components/omnibox/browser/autocomplete_match.h" @@ -99,12 +100,17 @@ if (urls.empty()) { return false; } + scoped_refptr<history::TopSites> top_sites = client->GetTopSites(); + if (!top_sites) { + return false; + } TemplateURLService* const url_service = client->GetTemplateURLService(); int relevance = kMostVisitedTilesIndividualHighRelevance; for (const auto& url : urls) { // Skip SRP results from DSP on Desktop. On-focus ZPS suggestions should - // be sites. - if (url_service->IsSearchResultsPageFromDefaultSearchProvider(url.url)) { + // be sites. Also skip blocked sites. + if (url_service->IsSearchResultsPageFromDefaultSearchProvider(url.url) || + top_sites->IsBlocked(url.url)) { continue; } auto match = BuildMatch(provider, client, url.title, url.url, relevance, @@ -248,18 +254,34 @@ // TODO(ender): Relocate this to StartPrefetch() when additional prefetch // contexts are available. - // TopSites updates itself after a delay. To ensure up-to-date results, - // force an update now. - top_sites->SyncWithHistory(); - top_sites->GetMostVisitedURLs( - base::BindRepeating(&MostVisitedSitesProvider::OnMostVisitedUrlsAvailable, - request_weak_ptr_factory_.GetWeakPtr())); + auto url_suggestions_on_focus_config = + omnibox_feature_configs::OmniboxUrlSuggestionsOnFocus::Get(); + if (url_suggestions_on_focus_config.enabled && + url_suggestions_on_focus_config.directly_query_history_service) { + client_->GetHistoryService()->QueryMostVisitedURLs( + top_sites->NumBlockedSites() + + url_suggestions_on_focus_config.max_suggestions, + base::BindOnce( + &MostVisitedSitesProvider::OnMostVisitedUrlsFromHistoryAvailable, + request_weak_ptr_factory_.GetWeakPtr()), + &cancelable_task_tracker_, + url_suggestions_on_focus_config.most_visited_recency_factor, + url_suggestions_on_focus_config.most_visited_recency_window); + } else { + // TopSites updates itself after a delay. To ensure up-to-date results, + // force an update now. + top_sites->SyncWithHistory(); + top_sites->GetMostVisitedURLs(base::BindRepeating( + &MostVisitedSitesProvider::OnMostVisitedUrlsAvailable, + request_weak_ptr_factory_.GetWeakPtr())); + } } void MostVisitedSitesProvider::Stop(bool clear_cached_results, bool due_to_user_inactivity) { AutocompleteProvider::Stop(clear_cached_results, due_to_user_inactivity); request_weak_ptr_factory_.InvalidateWeakPtrs(); + cancelable_task_tracker_.TryCancelAll(); } MostVisitedSitesProvider::MostVisitedSitesProvider( @@ -293,6 +315,14 @@ } } +void MostVisitedSitesProvider::OnMostVisitedUrlsFromHistoryAvailable( + history::MostVisitedURLList sites) { + done_ = true; + if (BuildAutocompleteMatches(this, client_, sites, matches_)) { + NotifyListeners(true); + } +} + bool MostVisitedSitesProvider::AllowMostVisitedSitesSuggestions( const AutocompleteInput& input) const { const auto& page_url = input.current_url();
diff --git a/components/omnibox/browser/most_visited_sites_provider.h b/components/omnibox/browser/most_visited_sites_provider.h index 3e33e38a9..64ab4cf 100644 --- a/components/omnibox/browser/most_visited_sites_provider.h +++ b/components/omnibox/browser/most_visited_sites_provider.h
@@ -8,6 +8,7 @@ #include "base/gtest_prod_util.h" #include "base/memory/raw_ptr.h" #include "base/memory/weak_ptr.h" +#include "base/task/cancelable_task_tracker.h" #include "components/omnibox/browser/autocomplete_input.h" #include "components/omnibox/browser/autocomplete_provider.h" #include "components/omnibox/browser/autocomplete_provider_client.h" @@ -41,6 +42,13 @@ // converts those urls to AutocompleteMatches and adds them to |matches_|. void OnMostVisitedUrlsAvailable(const history::MostVisitedURLList& urls); + // When the HistoryService serves the most visited URLs, this function + // converts those urls to AutocompleteMatches and adds them to |matches_|. + // Unlike `OnMostVisitedUrlsAvailable` which gets called through a request + // to TopSites, this callback is invoked when HistoryService is queried + // directly in the provider. + void OnMostVisitedUrlsFromHistoryAvailable(history::MostVisitedURLList sites); + // Whether zero suggest suggestions are allowed in the given context. // Invoked early, confirms all the external conditions for ZeroSuggest are // met. @@ -48,6 +56,9 @@ void BlockURL(const GURL& site_url); + // Task tracker for querying the most visited URLs from HistoryService. + base::CancelableTaskTracker cancelable_task_tracker_; + const ui::DeviceFormFactor device_form_factor_; const raw_ptr<AutocompleteProviderClient, DanglingUntriaged> client_; // Note: used to cancel requests - not a general purpose WeakPtr factory.
diff --git a/components/omnibox/browser/most_visited_sites_provider_unittest.cc b/components/omnibox/browser/most_visited_sites_provider_unittest.cc index 1921765..ef86c33 100644 --- a/components/omnibox/browser/most_visited_sites_provider_unittest.cc +++ b/components/omnibox/browser/most_visited_sites_provider_unittest.cc
@@ -11,7 +11,9 @@ #include "base/test/metrics/histogram_tester.h" #include "base/test/scoped_feature_list.h" #include "base/test/task_environment.h" +#include "components/history/core/browser/features.h" #include "components/history/core/browser/top_sites.h" +#include "components/history/core/browser/top_sites_impl.h" #include "components/omnibox/browser/autocomplete_provider_listener.h" #include "components/omnibox/browser/fake_autocomplete_provider_client.h" #include "components/omnibox/browser/test_scheme_classifier.h" @@ -30,6 +32,7 @@ using OEP = metrics::OmniboxEventProto; using OFT = metrics::OmniboxFocusType; +using testing::_; class FakeTopSites : public history::TopSites { public: @@ -58,6 +61,7 @@ return history::PrepopulatedPageList(); } void OnNavigationCommitted(const GURL& url) override {} + int NumBlockedSites() const override { return blocked_urls_.size(); } // RefcountedKeyedService: void ShutdownOnUIThread() override {} @@ -106,6 +110,21 @@ {true, {GURL("http://www.google.com/search?q=abc"), u"abc"}}}; } +class MockHistoryService : public history::HistoryService { + public: + MockHistoryService() = default; + ~MockHistoryService() override = default; + + MOCK_METHOD(base::CancelableTaskTracker::TaskId, + QueryMostVisitedURLs, + (int result_count, + history::HistoryService::QueryMostVisitedURLsCallback callback, + base::CancelableTaskTracker* tracker, + const std::optional<std::string>& recency_factor_name, + std::optional<size_t> recency_window_days), + (override)); +}; + } // namespace class MostVisitedSitesProviderTest : public testing::Test, @@ -525,11 +544,12 @@ #endif // BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_IOS) #if !(BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_IOS)) -TEST_F(MostVisitedSitesProviderTest, TestCreateMostVisitedSitesDesktopMatches) { +TEST_F(MostVisitedSitesProviderTest, TestCreateMostVisitedTopSitesMatches) { omnibox_feature_configs::ScopedConfigForTesting< omnibox_feature_configs::OmniboxUrlSuggestionsOnFocus> scoped_config; scoped_config.Get().enabled = true; + scoped_config.Get().directly_query_history_service = false; provider_->Start(BuildAutocompleteInputForWebOnFocus(), true); @@ -559,4 +579,50 @@ chrome_url, chrome_url, OEP::OTHER, OFT::INTERACTION_FOCUS))); } +TEST_F(MostVisitedSitesProviderTest, TestDesktopQueryingHistoryService) { + // Set a MockHistoryService. + auto history_service = std::make_unique<MockHistoryService>(); + auto& history_service_ref = *history_service; + client_.set_history_service(std::move(history_service)); + omnibox_feature_configs::ScopedConfigForTesting< + omnibox_feature_configs::OmniboxUrlSuggestionsOnFocus> + scoped_config; + scoped_config.Get().enabled = true; + scoped_config.Get().most_visited_recency_window = 4; + scoped_config.Get().most_visited_recency_factor = + history::kMvtScoringParamRecencyFactor_Default; + scoped_config.Get().max_suggestions = 8; + + history::HistoryService::QueryMostVisitedURLsCallback callback; + EXPECT_CALL(history_service_ref, QueryMostVisitedURLs(_, _, _, _, _)) + .WillOnce([&](int result_count, + history::HistoryService::QueryMostVisitedURLsCallback cb, + base::CancelableTaskTracker* tracker, + std::optional<std::string> recency_factor_name, + std::optional<size_t> recency_window_days) + -> base::CancelableTaskTracker::TaskId { + EXPECT_EQ(static_cast<int>(scoped_config.Get().max_suggestions) + + top_sites_->NumBlockedSites(), + result_count); + EXPECT_TRUE(recency_factor_name.has_value()); + EXPECT_EQ(history::kMvtScoringParamRecencyFactor_Default, + recency_factor_name.value()); + EXPECT_TRUE(recency_window_days.has_value()); + EXPECT_EQ(4u, recency_window_days.value()); + callback = std::move(cb); + return {}; + }); + AutocompleteInput input(BuildAutocompleteInputForWebOnFocus()); + provider_->Start(input, false); + EXPECT_FALSE(provider_->done()); + history::MostVisitedURLList result; + for (const auto& test_element : DefaultTestData()) { + result.push_back(test_element.entry); + } + std::move(callback).Run(std::move(result)); + // Shouldn't include the match from the SRP. + EXPECT_TRUE(provider_->done()); + ASSERT_EQ(4u, provider_->matches().size()); +} + #endif // !(BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_IOS))
diff --git a/components/omnibox/browser/omnibox_edit_model_unittest.cc b/components/omnibox/browser/omnibox_edit_model_unittest.cc index 37bbd78..ba9295cb 100644 --- a/components/omnibox/browser/omnibox_edit_model_unittest.cc +++ b/components/omnibox/browser/omnibox_edit_model_unittest.cc
@@ -30,6 +30,7 @@ #include "components/omnibox/browser/test_location_bar_model.h" #include "components/omnibox/browser/test_omnibox_client.h" #include "components/omnibox/browser/test_omnibox_edit_model.h" +#include "components/omnibox/browser/test_omnibox_popup_view.h" #include "components/omnibox/browser/test_omnibox_view.h" #include "components/omnibox/browser/test_scheme_classifier.h" #include "components/omnibox/browser/unscoped_extension_provider.h" @@ -64,19 +65,6 @@ namespace { -class TestOmniboxPopupView : public OmniboxPopupView { - public: - TestOmniboxPopupView() : OmniboxPopupView(/*controller=*/nullptr) {} - ~TestOmniboxPopupView() override = default; - bool IsOpen() const override { return false; } - void InvalidateLine(size_t line) override {} - void UpdatePopupAppearance() override {} - void ProvideButtonFocusHint(size_t line) override {} - void OnMatchIconUpdated(size_t match_index) override {} - void OnDragCanceled() override {} - void GetPopupAccessibleNodeData(ui::AXNodeData* node_data) const override {} -}; - void OpenUrlFromEditBox(OmniboxController* controller, TestOmniboxEditModel* model, const std::u16string url_text,
diff --git a/components/omnibox/browser/omnibox_view.cc b/components/omnibox/browser/omnibox_view.cc index 465f15d..3427e4c 100644 --- a/components/omnibox/browser/omnibox_view.cc +++ b/components/omnibox/browser/omnibox_view.cc
@@ -209,6 +209,14 @@ gfx::Image favicon; AutocompleteMatch match = model()->CurrentMatch(nullptr); + if (!match.icon_url.is_empty()) { + const SkBitmap* bitmap = + model()->GetPopupRichSuggestionBitmap(match.icon_url); + if (bitmap) { + return ui::ImageModel::FromImage( + controller_->client()->GetSizedIcon(bitmap)); + } + } if (AutocompleteMatch::IsSearchType(match.type)) { // For search queries, display default search engine's favicon. If the // default search engine is google return the icon instead of favicon for
diff --git a/components/omnibox/browser/omnibox_view_unittest.cc b/components/omnibox/browser/omnibox_view_unittest.cc index ce6224a..8c3f7dd 100644 --- a/components/omnibox/browser/omnibox_view_unittest.cc +++ b/components/omnibox/browser/omnibox_view_unittest.cc
@@ -23,13 +23,16 @@ #include "components/omnibox/browser/omnibox_controller.h" #include "components/omnibox/browser/test_omnibox_client.h" #include "components/omnibox/browser/test_omnibox_edit_model.h" +#include "components/omnibox/browser/test_omnibox_popup_view.h" #include "components/omnibox/browser/test_omnibox_view.h" #include "components/omnibox/common/omnibox_features.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/skia/include/core/SkBitmap.h" #include "ui/base/ui_base_features.h" #include "ui/gfx/color_palette.h" #include "ui/gfx/favicon_size.h" +#include "ui/gfx/image/image_unittest_util.h" #include "ui/gfx/paint_vector_icon.h" #if !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_IOS) @@ -72,11 +75,41 @@ private: base::test::TaskEnvironment task_environment_; - raw_ptr<TestOmniboxClient, DanglingUntriaged> omnibox_client_; std::unique_ptr<TestOmniboxView> view_; std::unique_ptr<bookmarks::BookmarkModel> bookmark_model_; + raw_ptr<TestOmniboxClient> omnibox_client_; }; +class OmniboxViewPopupTest : public testing::Test { + public: + OmniboxViewPopupTest() { + auto omnibox_client = std::make_unique<TestOmniboxClient>(); + omnibox_client_ = omnibox_client.get(); + + view_ = std::make_unique<TestOmniboxView>(std::move(omnibox_client)); + view_->controller()->SetEditModelForTesting( + std::make_unique<TestOmniboxEditModel>(view_->controller(), view_.get(), + /*pref_service=*/nullptr)); + model()->set_popup_view(&popup_view_); + model()->SetPopupIsOpen(true); + } + + TestOmniboxView* view() { return view_.get(); } + + TestOmniboxEditModel* model() { + return static_cast<TestOmniboxEditModel*>(view_->model()); + } + + TestOmniboxClient* client() { return omnibox_client_; } + + private: + base::test::TaskEnvironment task_environment_; + std::unique_ptr<TestOmniboxView> view_; + raw_ptr<TestOmniboxClient> omnibox_client_; + TestOmniboxPopupView popup_view_; +}; +} // namespace + TEST_F(OmniboxViewTest, TestStripSchemasUnsafeForPaste) { constexpr const auto urls = std::to_array<const char*>({ " \x01 ", // Safe query. @@ -229,6 +262,35 @@ EXPECT_EQ(page_url, kUrl); } + +// Tests GetIcon returns the website's favicon when the match is a website. +TEST_F(OmniboxViewPopupTest, GetIcon_IconUrl) { + SkBitmap bitmap; + bitmap.allocN32Pixels(16, 16); + bitmap.eraseColor(SK_ColorRED); + + EXPECT_CALL(*client(), GetFaviconForPageUrl(_, _)).Times(0); + + // Creates a set of matches. + ACMatches matches; + AutocompleteMatch match(nullptr, 1000, false, + AutocompleteMatchType::NAVSUGGEST); + match.icon_url = GURL("https://example.com/icon.png"); + matches.push_back(match); + AutocompleteResult* result = + &view()->controller()->autocomplete_controller()->published_result_; + result->AppendMatches(matches); + model()->SetCurrentMatchForTest(match); + + // Sets the popup rich suggestion bitmap for search aggregator match. + model()->SetPopupRichSuggestionBitmap(0, bitmap); + + ui::ImageModel image = view()->GetIcon( + gfx::kFaviconSize, gfx::kPlaceholderColor, gfx::kPlaceholderColor, + gfx::kPlaceholderColor, gfx::kPlaceholderColor, base::DoNothing(), false); + gfx::test::CheckColors(bitmap.getColor(0, 0), + image.GetImage().ToSkBitmap()->getColor(0, 0)); +} #endif // !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_IOS) // Tests GetStateChanges correctly determines if text was deleted. @@ -375,5 +437,3 @@ EXPECT_TRUE(state_changes.just_deleted_text); } } - -} // namespace
diff --git a/components/omnibox/browser/test_omnibox_popup_view.cc b/components/omnibox/browser/test_omnibox_popup_view.cc new file mode 100644 index 0000000..bf98022 --- /dev/null +++ b/components/omnibox/browser/test_omnibox_popup_view.cc
@@ -0,0 +1,9 @@ +// Copyright 2025 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/omnibox/browser/test_omnibox_popup_view.h" + +bool TestOmniboxPopupView::IsOpen() const { + return false; +}
diff --git a/components/omnibox/browser/test_omnibox_popup_view.h b/components/omnibox/browser/test_omnibox_popup_view.h new file mode 100644 index 0000000..27a567dba --- /dev/null +++ b/components/omnibox/browser/test_omnibox_popup_view.h
@@ -0,0 +1,24 @@ +// Copyright 2025 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_OMNIBOX_BROWSER_TEST_OMNIBOX_POPUP_VIEW_H_ +#define COMPONENTS_OMNIBOX_BROWSER_TEST_OMNIBOX_POPUP_VIEW_H_ + +#include "components/omnibox/browser/omnibox_popup_view.h" + +// Fake implementation of OmniboxPopupView for use in tests. +class TestOmniboxPopupView : public OmniboxPopupView { + public: + TestOmniboxPopupView() : OmniboxPopupView(/*controller=*/nullptr) {} + ~TestOmniboxPopupView() override = default; + bool IsOpen() const override; + void InvalidateLine(size_t line) override {} + void UpdatePopupAppearance() override {} + void ProvideButtonFocusHint(size_t line) override {} + void OnMatchIconUpdated(size_t match_index) override {} + void OnDragCanceled() override {} + void GetPopupAccessibleNodeData(ui::AXNodeData* node_data) const override {} +}; + +#endif // COMPONENTS_OMNIBOX_BROWSER_TEST_OMNIBOX_POPUP_VIEW_H_
diff --git a/components/omnibox/common/omnibox_feature_configs.cc b/components/omnibox/common/omnibox_feature_configs.cc index dc1cb801..fea0248b 100644 --- a/components/omnibox/common/omnibox_feature_configs.cc +++ b/components/omnibox/common/omnibox_feature_configs.cc
@@ -253,6 +253,7 @@ "OmniboxUrlSuggestionsOnFocus", base::FEATURE_DISABLED_BY_DEFAULT); OmniboxUrlSuggestionsOnFocus::OmniboxUrlSuggestionsOnFocus() { + const char kMvtScoringParamRecencyFactor_Default[] = "default"; enabled = base::FeatureList::IsEnabled(kOmniboxUrlSuggestionsOnFocus); show_recently_closed_tabs = base::FeatureParam<bool>(&kOmniboxUrlSuggestionsOnFocus, @@ -269,5 +270,27 @@ base::FeatureParam<size_t>(&kOmniboxUrlSuggestionsOnFocus, "OnFocusMaxUrlSuggestions", 4) .Get(); + most_visited_recency_window = + base::FeatureParam<size_t>(&kOmniboxUrlSuggestionsOnFocus, + "OnFocusMostVisitedRecencyWindow", 13) + .Get(); + most_visited_recency_factor = + base::FeatureParam<std::string>(&kOmniboxUrlSuggestionsOnFocus, + "OnFocusMostVisitedRecencyFactor", + kMvtScoringParamRecencyFactor_Default) + .Get(); + directly_query_history_service = + base::FeatureParam<bool>(&kOmniboxUrlSuggestionsOnFocus, + "OnFocusMostVisitedDirectlyQueryHistoryService", + true) + .Get(); } + +OmniboxUrlSuggestionsOnFocus::OmniboxUrlSuggestionsOnFocus( + const OmniboxUrlSuggestionsOnFocus&) = default; + +OmniboxUrlSuggestionsOnFocus& OmniboxUrlSuggestionsOnFocus::operator=( + const OmniboxUrlSuggestionsOnFocus&) = default; + +OmniboxUrlSuggestionsOnFocus::~OmniboxUrlSuggestionsOnFocus() = default; } // namespace omnibox_feature_configs
diff --git a/components/omnibox/common/omnibox_feature_configs.h b/components/omnibox/common/omnibox_feature_configs.h index 59b1e9b6..3c9abe2 100644 --- a/components/omnibox/common/omnibox_feature_configs.h +++ b/components/omnibox/common/omnibox_feature_configs.h
@@ -250,6 +250,9 @@ struct OmniboxUrlSuggestionsOnFocus : Config<OmniboxUrlSuggestionsOnFocus> { DECLARE_FEATURE(kOmniboxUrlSuggestionsOnFocus); OmniboxUrlSuggestionsOnFocus(); + OmniboxUrlSuggestionsOnFocus(const OmniboxUrlSuggestionsOnFocus&); + OmniboxUrlSuggestionsOnFocus& operator=(const OmniboxUrlSuggestionsOnFocus&); + ~OmniboxUrlSuggestionsOnFocus(); bool enabled; bool show_recently_closed_tabs; // Max number of zps suggestions to show. @@ -258,6 +261,15 @@ size_t max_search_suggestions; // Max number of url zps suggestions to show. size_t max_url_suggestions; + // Number of days to consider for most visited sites (0-indexed). + size_t most_visited_recency_window; + // Recency factor heuristic used to calculate most visited sites. Must be + // one of `kMvtScoringParamRecencyFactor` feature param values listed in + // //components/history/core/browser/features.h. + std::string most_visited_recency_factor; + // Whether MostVisitedProvider should directly query HistoryService for its + // most visited sites list. False if the provider should query TopSites. + bool directly_query_history_service; }; // Do not add new configs here at the bottom by default. They should be ordered
diff --git a/components/optimization_guide/core/optimization_guide_proto_util.cc b/components/optimization_guide/core/optimization_guide_proto_util.cc index 5f56173..8a6dfad 100644 --- a/components/optimization_guide/core/optimization_guide_proto_util.cc +++ b/components/optimization_guide/core/optimization_guide_proto_util.cc
@@ -912,9 +912,9 @@ case ax::mojom::StringListAttribute::kAriaNotificationAnnouncements: return optimization_guide::proto::AXStringListAttribute:: AX_SLA_ARIANOTIFICATIONANNOUNCEMENTS; - case ax::mojom::StringListAttribute::kAriaNotificationIds: + case ax::mojom::StringListAttribute::kAriaNotificationTypes: return optimization_guide::proto::AXStringListAttribute:: - AX_SLA_ARIANOTIFICATIONIDS; + AX_SLA_ARIANOTIFICATIONTYPES; case ax::mojom::StringListAttribute::kCustomActionDescriptions: return optimization_guide::proto::AXStringListAttribute:: AX_SLA_CUSTOMACTIONDESCRIPTIONS;
diff --git a/components/optimization_guide/proto/features/common_quality_data.proto b/components/optimization_guide/proto/features/common_quality_data.proto index 52523c8..cbb87bfe 100644 --- a/components/optimization_guide/proto/features/common_quality_data.proto +++ b/components/optimization_guide/proto/features/common_quality_data.proto
@@ -1533,7 +1533,7 @@ AX_SLA_ARIANOTIFICATIONANNOUNCEMENTS = 2; - AX_SLA_ARIANOTIFICATIONIDS = 3; + AX_SLA_ARIANOTIFICATIONTYPES = 3; } // This will be updated when there is a significant change in the parsing logic.
diff --git a/components/page_info/android/java/src/org/chromium/components/page_info/PageInfoCookiesSettings.java b/components/page_info/android/java/src/org/chromium/components/page_info/PageInfoCookiesSettings.java index e6de3fb..3e40594 100644 --- a/components/page_info/android/java/src/org/chromium/components/page_info/PageInfoCookiesSettings.java +++ b/components/page_info/android/java/src/org/chromium/components/page_info/PageInfoCookiesSettings.java
@@ -18,6 +18,7 @@ import org.chromium.base.Callback; import org.chromium.base.TimeUtils; +import org.chromium.base.metrics.RecordUserAction; import org.chromium.build.annotations.Initializer; import org.chromium.build.annotations.NullMarked; import org.chromium.build.annotations.Nullable; @@ -368,6 +369,8 @@ Website currentWebsite = rwsInfo.findWebsiteForOrigin(currentOrigin); if (currentWebsite != null) { mPageInfoControllerDelegate.showSiteSettings(currentWebsite); + RecordUserAction.record( + "PageInfo.CookiesSubpage.RwsSiteSettingsOpened"); } return false; });
diff --git a/components/password_manager/content/browser/content_password_manager_driver.cc b/components/password_manager/content/browser/content_password_manager_driver.cc index 79267e1..1eab7ea 100644 --- a/components/password_manager/content/browser/content_password_manager_driver.cc +++ b/components/password_manager/content/browser/content_password_manager_driver.cc
@@ -578,35 +578,24 @@ "form.fields.size()!"); } - last_triggering_field_id_ = request.element_id; + last_triggering_field_id_ = request.field.element_id; - base::OnceClosure show_with_autofill_manager_cb = base::BindOnce( - &PasswordAutofillManager::OnShowPasswordSuggestions, - GetPasswordAutofillManager()->GetWeakPtr(), request.element_id, - request.trigger_source, request.text_direction, request.typed_username, - ShowWebAuthnCredentials(request.show_webauthn_credentials), - TransformToRootCoordinates(render_frame_host_, request.bounds)); #if !BUILDFLAG(IS_ANDROID) - std::move(show_with_autofill_manager_cb).Run(); + ShowPasswordSuggestionsForField(request.field); #else - client_->ShowKeyboardReplacingSurface( - this, - PasswordFillingParams(request.form_data, request.username_field_index, - request.password_field_index, request.element_id), - request.show_webauthn_credentials, - base::BindOnce( - [](base::OnceClosure cb, bool shown) { - if (shown) { - // UI shown by `client_`, all done. - return; - } - // Otherwise, show with PasswordAutofillManager. - std::move(cb).Run(); - }, - std::move(show_with_autofill_manager_cb))); + client_->ShowKeyboardReplacingSurface(this, request); #endif // !BUILDFLAG(IS_ANDROID) } +void ContentPasswordManagerDriver::ShowPasswordSuggestionsForField( + const autofill::TriggeringField& triggering_field) { + GetPasswordAutofillManager()->OnShowPasswordSuggestions( + triggering_field.element_id, triggering_field.trigger_source, + triggering_field.text_direction, triggering_field.typed_username, + ShowWebAuthnCredentials(triggering_field.show_webauthn_credentials), + TransformToRootCoordinates(render_frame_host_, triggering_field.bounds)); +} + void ContentPasswordManagerDriver::CheckSafeBrowsingReputation( const GURL& form_action, const GURL& frame_url) {
diff --git a/components/password_manager/content/browser/content_password_manager_driver.h b/components/password_manager/content/browser/content_password_manager_driver.h index b2f7877..1eecedc0 100644 --- a/components/password_manager/content/browser/content_password_manager_driver.h +++ b/components/password_manager/content/browser/content_password_manager_driver.h
@@ -128,6 +128,11 @@ void GeneratePassword(autofill::mojom::PasswordGenerationAgent:: TriggeredGeneratePasswordCallback callback); + // Notify the associated `PasswordAutofillManager` that password suggestions + // for the triggering field can be shown. + void ShowPasswordSuggestionsForField( + const autofill::TriggeringField& triggering_field); + // Returns true if the field is any of the following cases: // 1) The field has type="password". // 2) The field was type="password" field at some point of time.
diff --git a/components/password_manager/core/browser/password_credential_filler_impl.cc b/components/password_manager/core/browser/password_credential_filler_impl.cc index ae35b11..59b2e6d 100644 --- a/components/password_manager/core/browser/password_credential_filler_impl.cc +++ b/components/password_manager/core/browser/password_credential_filler_impl.cc
@@ -45,10 +45,10 @@ // password_autofill_agent.cc. Remove the logic in the agent when // PasswordSuggestionBottomSheetV2 is launched. SubmissionReadinessState CalculateSubmissionReadiness( - const password_manager::PasswordFillingParams& params) { - const autofill::FormData& form_data = params.form; - uint64_t username_index = params.username_field_index; - uint64_t password_index = params.password_field_index; + const autofill::PasswordSuggestionRequest& request) { + const autofill::FormData& form_data = request.form_data; + uint64_t username_index = request.username_field_index; + uint64_t password_index = request.password_field_index; size_t number_of_elements = form_data.fields().size(); CHECK(username_index <= number_of_elements && password_index <= number_of_elements); @@ -121,10 +121,9 @@ PasswordCredentialFillerImpl::PasswordCredentialFillerImpl( base::WeakPtr<PasswordManagerDriver> driver, - const PasswordFillingParams& password_filling_params) + const autofill::PasswordSuggestionRequest& request) : driver_(driver), - submission_readiness_( - CalculateSubmissionReadiness(password_filling_params)), + submission_readiness_(CalculateSubmissionReadiness(request)), trigger_submission_(CalculateTriggerSubmission(submission_readiness_)) {} PasswordCredentialFillerImpl::~PasswordCredentialFillerImpl() = default;
diff --git a/components/password_manager/core/browser/password_credential_filler_impl.h b/components/password_manager/core/browser/password_credential_filler_impl.h index 32ba4fbe..3f6806e 100644 --- a/components/password_manager/core/browser/password_credential_filler_impl.h +++ b/components/password_manager/core/browser/password_credential_filler_impl.h
@@ -8,18 +8,17 @@ #include <string> #include "base/memory/weak_ptr.h" +#include "components/autofill/core/common/password_form_fill_data.h" #include "components/password_manager/core/browser/password_credential_filler.h" #include "components/password_manager/core/browser/password_manager_driver.h" namespace password_manager { -struct PasswordFillingParams; - class PasswordCredentialFillerImpl final : public PasswordCredentialFiller { public: PasswordCredentialFillerImpl( base::WeakPtr<PasswordManagerDriver> driver, - const PasswordFillingParams& password_filling_params); + const autofill::PasswordSuggestionRequest& request); PasswordCredentialFillerImpl(const PasswordCredentialFillerImpl&) = delete; PasswordCredentialFillerImpl& operator=(const PasswordCredentialFillerImpl&) = delete;
diff --git a/components/password_manager/core/browser/password_credential_filler_impl_unittest.cc b/components/password_manager/core/browser/password_credential_filler_impl_unittest.cc index e94dc08f..37ccf78 100644 --- a/components/password_manager/core/browser/password_credential_filler_impl_unittest.cc +++ b/components/password_manager/core/browser/password_credential_filler_impl_unittest.cc
@@ -12,6 +12,7 @@ #include "base/test/mock_callback.h" #include "components/autofill/core/common/form_data.h" #include "components/autofill/core/common/mojom/autofill_types.mojom.h" +#include "components/autofill/core/common/password_form_fill_data.h" #include "components/autofill/core/common/signatures.h" #include "components/autofill/core/common/unique_ids.h" #include "components/password_manager/core/browser/password_manager_client.h" @@ -26,7 +27,6 @@ using autofill::FormFieldData; using autofill::mojom::SubmissionReadinessState; using password_manager::PasswordCredentialFillerImpl; -using password_manager::PasswordFillingParams; using testing ::_; using testing::ReturnRefOfCopy; @@ -79,103 +79,104 @@ return form; } -const std::vector<std::tuple<PasswordFillingParams, SubmissionReadinessState>> +const std::vector< + std::tuple<autofill::PasswordSuggestionRequest, SubmissionReadinessState>> kPasswordCredentialFillerV2TestCases = { // empty form data. field indices should not matter. - {PasswordFillingParams( + {autofill::PasswordSuggestionRequest( + autofill::TriggeringField(), PrepareFormData({}, /*has_captcha=*/false), /*username_field_index=*/0, - /*password_field_index=*/0, - /*focused_field_renderer_id_=*/autofill::FieldRendererId()), + /*password_field_index=*/0), SubmissionReadinessState::kError}, - {PasswordFillingParams( + {autofill::PasswordSuggestionRequest( + autofill::TriggeringField(), PrepareFormData({FormFieldFocusabilityType::kNonFocusableInput, FormFieldFocusabilityType::kNonFocusableInput}, /*has_captcha=*/false), /*username_field_index=*/2, - /*password_field_index=*/2, - /*focused_field_renderer_id_=*/autofill::FieldRendererId()), + /*password_field_index=*/2), SubmissionReadinessState::kError}, // There's no password field in this case, so expected // SubmissionReadiness is `kNoPasswordField`. - {PasswordFillingParams( + {autofill::PasswordSuggestionRequest( + autofill::TriggeringField(), PrepareFormData({FormFieldFocusabilityType::kFocusableInput, FormFieldFocusabilityType::kFocusableInput}, /*has_captcha=*/false), /*username_field_index=*/0, - /*password_field_index=*/2, - /*focused_field_renderer_id_=*/autofill::FieldRendererId()), + /*password_field_index=*/2), SubmissionReadinessState::kNoPasswordField}, // There's no username field in this case, so expected // SubmissionReadiness is `kNoUsernameField`. - {PasswordFillingParams( + {autofill::PasswordSuggestionRequest( + autofill::TriggeringField(), PrepareFormData({FormFieldFocusabilityType::kFocusableInput, FormFieldFocusabilityType::kFocusableInput}, /*has_captcha=*/false), /*username_field_index=*/2, - /*password_field_index=*/0, - /*focused_field_renderer_id_=*/autofill::FieldRendererId()), + /*password_field_index=*/0), SubmissionReadinessState::kNoUsernameField}, // There's a focusable field between username and password fields - {PasswordFillingParams( + {autofill::PasswordSuggestionRequest( + autofill::TriggeringField(), PrepareFormData({FormFieldFocusabilityType::kFocusableInput, FormFieldFocusabilityType::kFocusableInput, FormFieldFocusabilityType::kFocusableInput}, /*has_captcha=*/false), /*username_field_index=*/0, - /*password_field_index=*/2, - /*focused_field_renderer_id_=*/autofill::FieldRendererId()), + /*password_field_index=*/2), SubmissionReadinessState::kFieldBetweenUsernameAndPassword}, // There's an ignorable field between username and password fields. It's // doesn't matter if it's empty. - {PasswordFillingParams( + {autofill::PasswordSuggestionRequest( + autofill::TriggeringField(), PrepareFormData({FormFieldFocusabilityType::kFocusableInput, FormFieldFocusabilityType::kNonFocusableInput, FormFieldFocusabilityType::kFocusableInput}, /*has_captcha=*/false), /*username_field_index=*/0, - /*password_field_index=*/2, - /*focused_field_renderer_id_=*/autofill::FieldRendererId()), + /*password_field_index=*/2), SubmissionReadinessState::kTwoFields}, // There's a focusable field after password field. - {PasswordFillingParams( + {autofill::PasswordSuggestionRequest( + autofill::TriggeringField(), PrepareFormData({FormFieldFocusabilityType::kFocusableInput, FormFieldFocusabilityType::kFocusableInput, FormFieldFocusabilityType::kFocusableInput}, /*has_captcha=*/false), /*username_field_index=*/0, - /*password_field_index=*/1, - /*focused_field_renderer_id_=*/autofill::FieldRendererId()), + /*password_field_index=*/1), SubmissionReadinessState::kFieldAfterPasswordField}, // There are unfocusable fields other than username and password fields. - {PasswordFillingParams( + {autofill::PasswordSuggestionRequest( + autofill::TriggeringField(), PrepareFormData({FormFieldFocusabilityType::kFocusableInput, FormFieldFocusabilityType::kNonFocusableInput, FormFieldFocusabilityType::kFocusableInput, FormFieldFocusabilityType::kNonFocusableInput}, /*has_captcha=*/false), /*username_field_index=*/0, - /*password_field_index=*/2, - /*focused_field_renderer_id_=*/autofill::FieldRendererId()), + /*password_field_index=*/2), SubmissionReadinessState::kTwoFields}, // There is a checkbox field after the password field. - {PasswordFillingParams( + {autofill::PasswordSuggestionRequest( + autofill::TriggeringField(), PrepareFormData({FormFieldFocusabilityType::kFocusableInput, FormFieldFocusabilityType::kFocusableInput, FormFieldFocusabilityType::kFocusableCheckbox}, /*has_captcha=*/false), /*username_field_index=*/0, - /*password_field_index=*/1, - /*focused_field_renderer_id_=*/autofill::FieldRendererId()), + /*password_field_index=*/1), SubmissionReadinessState::kTwoFields}, // There is a CAPTCHA within the form - {PasswordFillingParams( + {autofill::PasswordSuggestionRequest( + autofill::TriggeringField(), PrepareFormData({FormFieldFocusabilityType::kFocusableInput, FormFieldFocusabilityType::kFocusableInput}, /*has_captcha=*/true), /*username_field_index=*/0, - /*password_field_index=*/1, - /*focused_field_renderer_id_=*/autofill::FieldRendererId()), + /*password_field_index=*/1), SubmissionReadinessState::kLikelyHasCaptcha}, }; @@ -197,13 +198,13 @@ TEST_F(PasswordCredentialFillerBaseTest, FillingFailed) { PasswordCredentialFillerImpl filler( driver().AsWeakPtr(), - PasswordFillingParams( + autofill::PasswordSuggestionRequest( + autofill::TriggeringField(), PrepareFormData({FormFieldFocusabilityType::kFocusableInput, FormFieldFocusabilityType::kFocusableInput}, /*has_captcha=*/false), /*username_field_index=*/0, - /*password_field_index=*/1, - /*focused_field_renderer_id_=*/autofill::FieldRendererId())); + /*password_field_index=*/1)); ASSERT_EQ(filler.GetSubmissionReadinessState(), autofill::mojom::SubmissionReadinessState::kTwoFields); @@ -219,8 +220,8 @@ TEST_F(PasswordCredentialFillerBaseTest, FillWithNullDriver) { PasswordCredentialFillerImpl filler( - nullptr, - PasswordFillingParams(FormData(), 0, 0, autofill::FieldRendererId())); + nullptr, autofill::PasswordSuggestionRequest(autofill::TriggeringField(), + FormData(), 0, 0)); // Should not crash. filler.FillUsernameAndPassword(kUsername, kPassword, base::DoNothing()); } @@ -228,11 +229,12 @@ class PasswordCredentialFillerV2ParameterTest : public PasswordCredentialFillerBaseTest, public testing::WithParamInterface< - std::tuple<PasswordFillingParams, SubmissionReadinessState>> { + std::tuple<autofill::PasswordSuggestionRequest, + SubmissionReadinessState>> { public: PasswordCredentialFillerImpl PrepareFiller() { - PasswordFillingParams params = std::get<0>(GetParam()); - return PasswordCredentialFillerImpl(driver().AsWeakPtr(), params); + autofill::PasswordSuggestionRequest request = std::get<0>(GetParam()); + return PasswordCredentialFillerImpl(driver().AsWeakPtr(), request); } private:
diff --git a/components/password_manager/core/browser/password_manager.cc b/components/password_manager/core/browser/password_manager.cc index 32830c5..54246c8685 100644 --- a/components/password_manager/core/browser/password_manager.cc +++ b/components/password_manager/core/browser/password_manager.cc
@@ -695,7 +695,6 @@ void PasswordManager::DropFormManagers() { ResetFormsAndPredictionsCache(); owned_submitted_form_manager_.reset(); - visible_forms_data_.clear(); } base::span<const PasswordForm> PasswordManager::GetBestMatches( @@ -1342,10 +1341,6 @@ visible_forms_data.size()); } - // Record all visible forms from the frame. - visible_forms_data_.insert(visible_forms_data_.end(), - visible_forms_data.begin(), - visible_forms_data.end()); if ( #if BUILDFLAG(IS_IOS) // On iOS, drivers are bound to WebFrames, but some pages (e.g. files) @@ -1364,7 +1359,7 @@ // If we see the login form again, then the login failed. if (submitted_manager->GetPendingCredentials().scheme == PasswordForm::Scheme::kHtml) { - for (const FormData& form_data : visible_forms_data_) { + for (const FormData& form_data : visible_forms_data) { if (submitted_manager->IsEqualToSubmittedForm(form_data)) { if (submitted_manager->HasLikelyChangeOrResetFormSubmitted() && AreChangePasswordFieldsEmpty( @@ -1376,8 +1371,6 @@ form_data); } OnLoginFailed(logger.get()); - // Clear visible_forms_data_ once we found the match. - visible_forms_data_.clear(); return; } } @@ -1386,8 +1379,6 @@ logger->LogMessage(Logger::STRING_PROVISIONALLY_SAVED_FORM_IS_NOT_HTML); } } - // Clear visible_forms_data_ after checking all the visible forms. - visible_forms_data_.clear(); // Looks like a successful login attempt. Either show an infobar or // automatically save the login data. We prompt when the user hasn't
diff --git a/components/password_manager/core/browser/password_manager.h b/components/password_manager/core/browser/password_manager.h index 8965197..2e71ba2 100644 --- a/components/password_manager/core/browser/password_manager.h +++ b/components/password_manager/core/browser/password_manager.h
@@ -460,12 +460,6 @@ const base::CallbackListSubscription account_store_cb_list_subscription_; - // Records all visible forms seen during a page load, in all frames of the - // page. When the page stops loading, the password manager checks if one of - // the recorded forms matches the login form from the previous page - // (to see if the login was a failure), and clears the vector. - std::vector<autofill::FormData> visible_forms_data_; - // Server predictions for the forms on the page. std::map<autofill::FormSignature, FormPredictions> server_predictions_;
diff --git a/components/password_manager/core/browser/password_manager_client.cc b/components/password_manager/core/browser/password_manager_client.cc index e7a92d7e..da1a90cb3 100644 --- a/components/password_manager/core/browser/password_manager_client.cc +++ b/components/password_manager/core/browser/password_manager_client.cc
@@ -38,11 +38,7 @@ void PasswordManagerClient::ShowKeyboardReplacingSurface( PasswordManagerDriver* driver, - const PasswordFillingParams& password_filling_params, - bool is_webauthn_form, - base::OnceCallback<void(bool)> shown_cb) { - std::move(shown_cb).Run(false); -} + const autofill::PasswordSuggestionRequest& request) {} #endif bool PasswordManagerClient::IsReauthBeforeFillingRequired(
diff --git a/components/password_manager/core/browser/password_manager_client.h b/components/password_manager/core/browser/password_manager_client.h index 4747fc94..0d3d5cb8 100644 --- a/components/password_manager/core/browser/password_manager_client.h +++ b/components/password_manager/core/browser/password_manager_client.h
@@ -116,15 +116,6 @@ enum class ErrorMessageFlowType { kSaveFlow, kFillFlow }; -#if BUILDFLAG(IS_ANDROID) -struct PasswordFillingParams { - autofill::FormData form; - uint64_t username_field_index; - uint64_t password_field_index; - autofill::FieldRendererId focused_field_renderer_id_; -}; -#endif // BUILDFLAG(IS_ANDROID) - // An abstraction of operations that depend on the embedders (e.g. Chrome) // environment. PasswordManagerClient is instantiated once per WebContents. // Main frame w.r.t WebContents refers to the primary main frame so usages of @@ -225,9 +216,7 @@ // storage notice is gone. virtual void ShowKeyboardReplacingSurface( PasswordManagerDriver* driver, - const PasswordFillingParams& password_filling_params, - bool is_webauthn_form, - base::OnceCallback<void(bool)> shown_cb); + const autofill::PasswordSuggestionRequest& request); #endif // Checks whether user re-authentication should be triggered before password
diff --git a/components/permissions/BUILD.gn b/components/permissions/BUILD.gn index 98d26a9..7eea9cf 100644 --- a/components/permissions/BUILD.gn +++ b/components/permissions/BUILD.gn
@@ -45,6 +45,8 @@ "contexts/keyboard_lock_permission_context.h", "contexts/local_fonts_permission_context.cc", "contexts/local_fonts_permission_context.h", + "contexts/local_network_access_permission_context.cc", + "contexts/local_network_access_permission_context.h", "contexts/midi_permission_context.cc", "contexts/midi_permission_context.h", "contexts/midi_sysex_permission_context.cc",
diff --git a/components/permissions/android/java/src/org/chromium/components/permissions/OsAdditionalSecurityPermissionProvider.java b/components/permissions/android/java/src/org/chromium/components/permissions/OsAdditionalSecurityPermissionProvider.java index ae08713..c89a5ce2 100644 --- a/components/permissions/android/java/src/org/chromium/components/permissions/OsAdditionalSecurityPermissionProvider.java +++ b/components/permissions/android/java/src/org/chromium/components/permissions/OsAdditionalSecurityPermissionProvider.java
@@ -6,7 +6,10 @@ import android.content.Context; +import androidx.annotation.Nullable; + import org.chromium.build.annotations.NullMarked; +import org.chromium.ui.modelutil.PropertyModel; /** * Placeholder provider class to query whether the operating system has granted various security @@ -14,11 +17,30 @@ */ @NullMarked public abstract class OsAdditionalSecurityPermissionProvider { + public interface Observer { + /** Called when the Android-OS advanced-protection-mode setting changes. */ + void onAdvancedProtectionOsSettingChanged(); + } + + public void addObserver(Observer observer) {} + + public void removeObserver(Observer observer) {} + + /** + * Returns whether the Android OS requests advanced-protection-mode. Implementations must allow + * querying from any thread. + */ + public boolean isAdvancedProtectionRequestedByOs() { + return !hasJavascriptOptimizerPermission(); + } + /** * Returns whether the operating system has granted permission to enable javascript optimizers. * Implementations must allow querying from any thread. */ - public abstract boolean hasJavascriptOptimizerPermission(); + public boolean hasJavascriptOptimizerPermission() { + return false; + } /** * Returns message to display in site settings explaining why the operating system has denied @@ -27,4 +49,15 @@ public String getJavascriptOptimizerMessage(Context context) { return ""; } + + /** + * Returns {@link PropertyModel} for message-UI to notify user about new + * advanced-protection-mode state. + * + * @param primaryButtonAction The action to run when the message-UI primary-button is clicked. + */ + public @Nullable PropertyModel buildAdvancedProtectionMessagePropertyModel( + Context context, Runnable primaryButtonAction) { + return null; + } }
diff --git a/components/permissions/contexts/local_network_access_permission_context.cc b/components/permissions/contexts/local_network_access_permission_context.cc new file mode 100644 index 0000000..36bc287 --- /dev/null +++ b/components/permissions/contexts/local_network_access_permission_context.cc
@@ -0,0 +1,19 @@ +// Copyright 2025 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/permissions/contexts/local_network_access_permission_context.h" + +#include "components/content_settings/core/common/content_settings_types.h" +#include "services/network/public/mojom/permissions_policy/permissions_policy_feature.mojom.h" + +LocalNetworkAccessPermissionContext::LocalNetworkAccessPermissionContext( + content::BrowserContext* browser_context) + : PermissionContextBase( + browser_context, + ContentSettingsType::LOCAL_NETWORK_ACCESS, + // TODO(crbug.com/400455013): Add permission policy for LNA. + network::mojom::PermissionsPolicyFeature::kNotFound) {} + +LocalNetworkAccessPermissionContext::~LocalNetworkAccessPermissionContext() = + default;
diff --git a/components/permissions/contexts/local_network_access_permission_context.h b/components/permissions/contexts/local_network_access_permission_context.h new file mode 100644 index 0000000..6c5bc73 --- /dev/null +++ b/components/permissions/contexts/local_network_access_permission_context.h
@@ -0,0 +1,23 @@ +// Copyright 2025 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_PERMISSIONS_CONTEXTS_LOCAL_NETWORK_ACCESS_PERMISSION_CONTEXT_H_ +#define COMPONENTS_PERMISSIONS_CONTEXTS_LOCAL_NETWORK_ACCESS_PERMISSION_CONTEXT_H_ + +#include "components/permissions/permission_context_base.h" + +class LocalNetworkAccessPermissionContext + : public permissions::PermissionContextBase { + public: + explicit LocalNetworkAccessPermissionContext( + content::BrowserContext* browser_context); + ~LocalNetworkAccessPermissionContext() override; + + LocalNetworkAccessPermissionContext( + const LocalNetworkAccessPermissionContext&) = delete; + LocalNetworkAccessPermissionContext& operator=( + const LocalNetworkAccessPermissionContext&) = delete; +}; + +#endif // COMPONENTS_PERMISSIONS_CONTEXTS_LOCAL_NETWORK_ACCESS_PERMISSION_CONTEXT_H_
diff --git a/components/permissions/permission_request.cc b/components/permissions/permission_request.cc index d6c9fa6..28591a8 100644 --- a/components/permissions/permission_request.cc +++ b/components/permissions/permission_request.cc
@@ -353,6 +353,9 @@ case RequestType::kLocalFonts: message_id = IDS_FONT_ACCESS_PERMISSION_FRAGMENT; break; + case RequestType::kLocalNetworkAccess: + message_id = IDS_LOCAL_NETWORK_ACCESS_PERMISSION_FRAGMENT; + break; case RequestType::kMicStream: message_id = IDS_MEDIA_CAPTURE_AUDIO_ONLY_PERMISSION_FRAGMENT; break;
diff --git a/components/permissions/permission_uma_util.cc b/components/permissions/permission_uma_util.cc index 912aa7f7..f6444b3 100644 --- a/components/permissions/permission_uma_util.cc +++ b/components/permissions/permission_uma_util.cc
@@ -88,6 +88,9 @@ // TODO(crbug.com/40214907): Enable on Android case RequestType::kLocalFonts: return RequestTypeForUma::PERMISSION_LOCAL_FONTS; + // TODO(crbug.com/400455013): Enable on Android. + case RequestType::kLocalNetworkAccess: + return RequestTypeForUma::PERMISSION_LOCAL_NETWORK_ACCESS; #endif case RequestType::kGeolocation: return RequestTypeForUma::PERMISSION_GEOLOCATION; @@ -245,6 +248,8 @@ return "KeyboardAndPointerLock"; case RequestTypeForUma::PERMISSION_WEB_APP_INSTALLATION: return "WebAppInstallation"; + case RequestTypeForUma::PERMISSION_LOCAL_NETWORK_ACCESS: + return "LocalNetworkAccess"; case RequestTypeForUma::UNKNOWN: case RequestTypeForUma::PERMISSION_FLASH: @@ -1464,6 +1469,10 @@ base::UmaHistogramEnumeration("Permissions.Action.WebAppInstallation", action, PermissionAction::NUM); break; + case ContentSettingsType::LOCAL_NETWORK_ACCESS: + base::UmaHistogramEnumeration("Permissions.Action.LocalNetworkAccess", + action, PermissionAction::NUM); + break; // The user is not prompted for these permissions, thus there is no // permission action recorded for them. default:
diff --git a/components/permissions/permission_uma_util.h b/components/permissions/permission_uma_util.h index 8d7a001a..ab0a7d1 100644 --- a/components/permissions/permission_uma_util.h +++ b/components/permissions/permission_uma_util.h
@@ -115,6 +115,7 @@ MULTIPLE_KEYBOARD_AND_POINTER_LOCK = 39, PERMISSION_HAND_TRACKING = 40, PERMISSION_WEB_APP_INSTALLATION = 41, + PERMISSION_LOCAL_NETWORK_ACCESS = 42, // NUM must be the last value in the enum. NUM, };
diff --git a/components/permissions/request_type.cc b/components/permissions/request_type.cc index e5ddbe3f..20df13a 100644 --- a/components/permissions/request_type.cc +++ b/components/permissions/request_type.cc
@@ -98,6 +98,9 @@ return vector_icons::kKeyboardLockIcon; case RequestType::kLocalFonts: return vector_icons::kFontDownloadChromeRefreshIcon; + case RequestType::kLocalNetworkAccess: + // TODO(crbug.com/400455013): Replace with final icon. + return vector_icons::kDevicesIcon; case RequestType::kMicStream: return vector_icons::kMicChromeRefreshIcon; case RequestType::kMidiSysex: @@ -158,6 +161,9 @@ return vector_icons::kHandGestureOffIcon; case RequestType::kIdleDetection: return vector_icons::kDevicesOffIcon; + case RequestType::kLocalNetworkAccess: + // TODO(crbug.com/400455013): Replace with final icon. + return vector_icons::kDevicesOffIcon; case RequestType::kMicStream: return vector_icons::kMicOffChromeRefreshIcon; case RequestType::kMidiSysex: @@ -239,6 +245,9 @@ #if !BUILDFLAG(IS_ANDROID) case ContentSettingsType::WINDOW_MANAGEMENT: return RequestType::kWindowManagement; + // TODO(crbug.com/400455013): Enable on Android. + case ContentSettingsType::LOCAL_NETWORK_ACCESS: + return RequestType::kLocalNetworkAccess; #endif case ContentSettingsType::TOP_LEVEL_STORAGE_ACCESS: return RequestType::kTopLevelStorageAccess; @@ -291,6 +300,8 @@ #if !BUILDFLAG(IS_ANDROID) case RequestType::kLocalFonts: return ContentSettingsType::LOCAL_FONTS; + case RequestType::kLocalNetworkAccess: + return ContentSettingsType::LOCAL_NETWORK_ACCESS; #endif case RequestType::kGeolocation: return ContentSettingsType::GEOLOCATION; @@ -412,6 +423,8 @@ return "keyboard_lock"; case permissions::RequestType::kLocalFonts: return "local_fonts"; + case permissions::RequestType::kLocalNetworkAccess: + return "local_network_access"; #endif case permissions::RequestType::kMicStream: return "mic_stream";
diff --git a/components/permissions/request_type.h b/components/permissions/request_type.h index fe38545f..f92d640 100644 --- a/components/permissions/request_type.h +++ b/components/permissions/request_type.h
@@ -38,6 +38,8 @@ kIdleDetection, #if !BUILDFLAG(IS_ANDROID) kLocalFonts, + // TODO(crbug.com/400455013): Add Android support. + kLocalNetworkAccess, #endif kMicStream, kMidiSysex,
diff --git a/components/permissions/test/permission_test_util.cc b/components/permissions/test/permission_test_util.cc index 89bda2b..97c48bb1 100644 --- a/components/permissions/test/permission_test_util.cc +++ b/components/permissions/test/permission_test_util.cc
@@ -90,6 +90,10 @@ std::make_unique<FakePermissionContext>( browser_context, ContentSettingsType::AUTOMATIC_FULLSCREEN, network::mojom::PermissionsPolicyFeature::kFullscreen); + permission_contexts[ContentSettingsType::LOCAL_NETWORK_ACCESS] = + std::make_unique<FakePermissionContext>( + browser_context, ContentSettingsType::LOCAL_NETWORK_ACCESS, + network::mojom::PermissionsPolicyFeature::kNotFound); return permission_contexts; }
diff --git a/components/permissions_strings.grdp b/components/permissions_strings.grdp index 1e3b5fe1..a0f93c9 100644 --- a/components/permissions_strings.grdp +++ b/components/permissions_strings.grdp
@@ -189,6 +189,9 @@ <message name="IDS_WEB_APP_INSTALLATION_PERMISSION_FRAGMENT" desc="Permission fragment shown in the permissions bubble when a web page requests to install a web app."> Be able to install web apps </message> + <message name="IDS_LOCAL_NETWORK_ACCESS_PERMISSION_FRAGMENT" desc="Permission fragment shown in the permissions bubble when a web page requests to access the user's local network."> + Look for and connect to any device on your local network + </message> <message name="IDS_PERMISSION_ALLOW" desc="Label on button to allow a permissions request."> Allow </message> @@ -369,6 +372,7 @@ Hand tracking not allowed </message> + <message name="IDS_GEOLOCATION_PERMISSION_BLOCKED_CHIP" desc="Button text representing a blocked or expired request for the user's physical location from a website. When clicked, shows a permission prompt bubble with more information."> Location blocked </message>
diff --git a/components/permissions_strings_grdp/IDS_LOCAL_NETWORK_ACCESS_PERMISSION_FRAGMENT.png.sha1 b/components/permissions_strings_grdp/IDS_LOCAL_NETWORK_ACCESS_PERMISSION_FRAGMENT.png.sha1 new file mode 100644 index 0000000..5feb969 --- /dev/null +++ b/components/permissions_strings_grdp/IDS_LOCAL_NETWORK_ACCESS_PERMISSION_FRAGMENT.png.sha1
@@ -0,0 +1 @@ +7ce9f81a96298ef15365193d3e531f7950884b9c \ No newline at end of file
diff --git a/components/policy/resources/templates/policy_definitions/Miscellaneous/ReduceAcceptLanguageEnabled.yaml b/components/policy/resources/templates/policy_definitions/Miscellaneous/ReduceAcceptLanguageEnabled.yaml index 347ea75..72d36e2d 100644 --- a/components/policy/resources/templates/policy_definitions/Miscellaneous/ReduceAcceptLanguageEnabled.yaml +++ b/components/policy/resources/templates/policy_definitions/Miscellaneous/ReduceAcceptLanguageEnabled.yaml
@@ -1,11 +1,11 @@ -caption: Control rollout of <ph name="AL_HEADER_NAME">Accept-Language</ph> reduction +caption: Control <ph name="ALR_FEATURE_NAME">Accept-Language Reduction</ph> desc: |- The <ph name="AL_HEADER_NAME">Accept-Language</ph> HTTP request header and the JavaScript <ph name="JS_GETTER_NAME">navigator.languages</ph> getter are planned for reduction for privacy reasons. - To facilitate testing and ensure compatibility, this policy allows you to enable or disable this reduction rollout. + To facilitate testing and ensure compatibility, this policy allows you to enable or disable the <ph name="ALR_FEATURE_NAME">Accept-Language Reduction</ph> feature. - If this policy is set to enabled or left unset, <ph name="AL_HEADER_NAME">Accept-Language</ph> reduction rollout will be applied through field trials. - If this policy is set to disabled, field trials will not be able to activate the reduction rollout. + If this policy is set to enabled or left unset, <ph name="ALR_FEATURE_NAME">Accept-Language Reduction</ph> will be applied through field trials. + If this policy is set to disabled, field trials will not be able to activate <ph name="ALR_FEATURE_NAME">Accept-Language Reduction</ph>. For more information about this feature, please visit: https://github.com/explainers-by-googlers/reduce-accept-language. @@ -28,9 +28,9 @@ schema: type: boolean items: -- caption: Enable <ph name="AL_HEADER_NAME">Accept-Language</ph> reduction rollout to be controlled via field trials +- caption: Enable <ph name="ALR_FEATURE_NAME">Accept-Language Reduction</ph> value: true -- caption: Disable <ph name="AL_HEADER_NAME">Accept-Language</ph> reduction rollout to be controlled via field trials +- caption: Disable <ph name="ALR_FEATURE_NAME">Accept-Language Reduction</ph> value: false default: true
diff --git a/components/safe_browsing/content/browser/web_ui/resources/safe_browsing.html b/components/safe_browsing/content/browser/web_ui/resources/safe_browsing.html index dc96cf2..1352171 100644 --- a/components/safe_browsing/content/browser/web_ui/resources/safe_browsing.html +++ b/components/safe_browsing/content/browser/web_ui/resources/safe_browsing.html
@@ -18,8 +18,8 @@ <div slot="tab" id="urt-lookup">URT Lookup</div> <div slot="tab" id="referrer-chain">Referrer Chain</div> <div slot="tab" id="log">Log Messages</div> -<if expr="not is_android"> <div slot="tab" id="reporting">Reporting Events</div> +<if expr="not is_android"> <div slot="tab" id="db-manager">Database Manager</div> <div slot="tab" id="hash-cache">Hash Cache</div> </if> @@ -106,13 +106,13 @@ <p id="log-messages"></p> </div> </div> -<if expr="not is_android"> <div slot="panel"> <h2>Reporting Events</h2> <div class="content"> <p id="reporting-events"></p> </div> </div> +<if expr="not is_android"> <div slot="panel"> <h2>Database Manager</h2> <div class="content">
diff --git a/components/search_engines/BUILD.gn b/components/search_engines/BUILD.gn index 2b67c6a..1ae183e 100644 --- a/components/search_engines/BUILD.gn +++ b/components/search_engines/BUILD.gn
@@ -324,5 +324,8 @@ source = "regional_settings.json" schema_file = "regional_settings_schema.json" namespace = "TemplateURLPrepopulateData" - deps = [ "//base" ] + deps = [ + "//base", + "//third_party/search_engines_data:prepopulated_engines", + ] }
diff --git a/components/signin/internal/identity_manager/token_binding_helper.cc b/components/signin/internal/identity_manager/token_binding_helper.cc index 85e4f951..52fd757 100644 --- a/components/signin/internal/identity_manager/token_binding_helper.cc +++ b/components/signin/internal/identity_manager/token_binding_helper.cc
@@ -30,8 +30,9 @@ constexpr std::string_view kTokenBindingNamespace = "TokenBinding"; -unexportable_keys::BackgroundTaskPriority kTokenBindingPriority = +constexpr unexportable_keys::BackgroundTaskPriority kTokenBindingPriority = unexportable_keys::BackgroundTaskPriority::kBestEffort; +constexpr size_t kMaxRetriesToSignAssertionToken = 3; base::expected<std::string, TokenBindingHelper::Error> CreateAssertionToken( const std::string& header_and_payload, @@ -183,7 +184,7 @@ unexportable_key_service_->SignSlowlyAsync( *binding_key, base::as_byte_span(*header_and_payload), - kTokenBindingPriority, + kTokenBindingPriority, kMaxRetriesToSignAssertionToken, base::BindOnce(&CreateAssertionToken, *header_and_payload, algorithm) .Then(base::BindOnce(&RunCallbackAndRecordMetrics, std::move(callback))));
diff --git a/components/spellcheck/browser/windows_spell_checker.cc b/components/spellcheck/browser/windows_spell_checker.cc index f5a7411..7b78720 100644 --- a/components/spellcheck/browser/windows_spell_checker.cc +++ b/components/spellcheck/browser/windows_spell_checker.cc
@@ -15,6 +15,7 @@ #include <locale> #include <string> +#include "base/compiler_specific.h" #include "base/functional/bind.h" #include "base/functional/callback.h" #include "base/functional/callback_helpers.h" @@ -301,7 +302,7 @@ hr = suggestions->Next(1, &suggestion, nullptr); if (hr == S_OK) { std::u16string utf16_suggestion; - if (base::WideToUTF16(suggestion.get(), wcslen(suggestion), + if (base::WideToUTF16(suggestion.get(), UNSAFE_TODO(wcslen(suggestion)), &utf16_suggestion)) { optional_suggestions->push_back(utf16_suggestion); }
diff --git a/components/storage_monitor/storage_monitor_win_unittest.cc b/components/storage_monitor/storage_monitor_win_unittest.cc index 9de17f7..f3cf37a 100644 --- a/components/storage_monitor/storage_monitor_win_unittest.cc +++ b/components/storage_monitor/storage_monitor_win_unittest.cc
@@ -14,6 +14,7 @@ #include <utility> #include <vector> +#include "base/compiler_specific.h" #include "base/memory/free_deleter.h" #include "base/memory/raw_ptr.h" #include "base/memory/ref_counted.h" @@ -213,12 +214,12 @@ dev_interface_broadcast( static_cast<DEV_BROADCAST_DEVICEINTERFACE*>(malloc(size))); DCHECK(dev_interface_broadcast); - ZeroMemory(dev_interface_broadcast.get(), size); + UNSAFE_TODO(ZeroMemory(dev_interface_broadcast.get(), size)); dev_interface_broadcast->dbcc_size = size; dev_interface_broadcast->dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE; dev_interface_broadcast->dbcc_classguid = guidDevInterface; - memcpy(dev_interface_broadcast->dbcc_name, pnp_device_id.data(), - device_id_size); + UNSAFE_TODO(memcpy(dev_interface_broadcast->dbcc_name, pnp_device_id.data(), + device_id_size)); int expect_attach_calls = observer_.attach_calls(); int expect_detach_calls = observer_.detach_calls();
diff --git a/components/storage_monitor/volume_mount_watcher_win.cc b/components/storage_monitor/volume_mount_watcher_win.cc index 3a6234d..e31bc59 100644 --- a/components/storage_monitor/volume_mount_watcher_win.cc +++ b/components/storage_monitor/volume_mount_watcher_win.cc
@@ -16,6 +16,7 @@ #include <algorithm> #include <string> +#include "base/compiler_specific.h" #include "base/containers/contains.h" #include "base/functional/bind.h" #include "base/functional/callback_helpers.h" @@ -126,7 +127,7 @@ kMaxPathBufLen)) { return false; } - mount_point.resize(wcslen(mount_point.c_str())); + mount_point.resize(UNSAFE_TODO(wcslen(mount_point.c_str()))); // Note: experimentally this code does not spin a floppy drive. It // returns a GUID associated with the device, not the volume.
diff --git a/components/unexportable_keys/BUILD.gn b/components/unexportable_keys/BUILD.gn index ccb0f84..e80cdb9 100644 --- a/components/unexportable_keys/BUILD.gn +++ b/components/unexportable_keys/BUILD.gn
@@ -50,6 +50,8 @@ "mock_unexportable_key.h", "mock_unexportable_key_service.cc", "mock_unexportable_key_service.h", + "scoped_mock_unexportable_key_provider.cc", + "scoped_mock_unexportable_key_provider.h", ] public_deps = [
diff --git a/components/unexportable_keys/fake_unexportable_key_service.cc b/components/unexportable_keys/fake_unexportable_key_service.cc index a32863f..65525b6 100644 --- a/components/unexportable_keys/fake_unexportable_key_service.cc +++ b/components/unexportable_keys/fake_unexportable_key_service.cc
@@ -31,6 +31,7 @@ const UnexportableKeyId& key_id, base::span<const uint8_t> data, BackgroundTaskPriority priority, + size_t max_retries, base::OnceCallback<void(ServiceErrorOr<std::vector<uint8_t>>)> callback) { std::move(callback).Run(base::unexpected(ServiceError::kKeyNotFound)); }
diff --git a/components/unexportable_keys/fake_unexportable_key_service.h b/components/unexportable_keys/fake_unexportable_key_service.h index 8e3c568..e51c8b59 100644 --- a/components/unexportable_keys/fake_unexportable_key_service.h +++ b/components/unexportable_keys/fake_unexportable_key_service.h
@@ -29,6 +29,7 @@ const UnexportableKeyId& key_id, base::span<const uint8_t> data, BackgroundTaskPriority priority, + size_t max_retries, base::OnceCallback<void(ServiceErrorOr<std::vector<uint8_t>>)> callback) override; ServiceErrorOr<std::vector<uint8_t>> GetSubjectPublicKeyInfo(
diff --git a/components/unexportable_keys/mock_unexportable_key_service.h b/components/unexportable_keys/mock_unexportable_key_service.h index 6e81aac..759333c 100644 --- a/components/unexportable_keys/mock_unexportable_key_service.h +++ b/components/unexportable_keys/mock_unexportable_key_service.h
@@ -43,6 +43,7 @@ (const UnexportableKeyId& key_id, base::span<const uint8_t> data, BackgroundTaskPriority priority, + size_t max_retries, base::OnceCallback<void(ServiceErrorOr<std::vector<uint8_t>>)> callback), (override)); MOCK_METHOD(ServiceErrorOr<std::vector<uint8_t>>,
diff --git a/components/unexportable_keys/scoped_mock_unexportable_key_provider.cc b/components/unexportable_keys/scoped_mock_unexportable_key_provider.cc new file mode 100644 index 0000000..d1d9a41 --- /dev/null +++ b/components/unexportable_keys/scoped_mock_unexportable_key_provider.cc
@@ -0,0 +1,103 @@ +// Copyright 2025 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/unexportable_keys/scoped_mock_unexportable_key_provider.h" + +#include <memory> +#include <optional> + +#include "base/containers/span.h" +#include "components/unexportable_keys/mock_unexportable_key.h" +#include "crypto/unexportable_key.h" +#include "testing/gmock/include/gmock/gmock.h" + +namespace unexportable_keys { + +namespace { + +ScopedMockUnexportableKeyProvider* g_mock_provider = nullptr; + +class MockUnexportableKeyProvider : public crypto::UnexportableKeyProvider { + public: + MockUnexportableKeyProvider(); + ~MockUnexportableKeyProvider() override; + + // crypto::UnexportableKeyProvider: + std::optional<crypto::SignatureVerifier::SignatureAlgorithm> SelectAlgorithm( + base::span<const crypto::SignatureVerifier::SignatureAlgorithm> + acceptable_algorithms) override; + std::unique_ptr<crypto::UnexportableSigningKey> GenerateSigningKeySlowly( + base::span<const crypto::SignatureVerifier::SignatureAlgorithm> + acceptable_algorithms) override; + std::unique_ptr<crypto::UnexportableSigningKey> FromWrappedSigningKeySlowly( + base::span<const uint8_t> wrapped_key) override; + bool DeleteSigningKeySlowly(base::span<const uint8_t> wrapped_key) override; +}; + +MockUnexportableKeyProvider::MockUnexportableKeyProvider() = default; +MockUnexportableKeyProvider::~MockUnexportableKeyProvider() = default; + +std::optional<crypto::SignatureVerifier::SignatureAlgorithm> +MockUnexportableKeyProvider::SelectAlgorithm( + base::span<const crypto::SignatureVerifier::SignatureAlgorithm> + acceptable_algorithms) { + if (acceptable_algorithms.empty()) { + return std::nullopt; + } + return acceptable_algorithms.front(); +} + +std::unique_ptr<crypto::UnexportableSigningKey> +MockUnexportableKeyProvider::GenerateSigningKeySlowly( + base::span<const crypto::SignatureVerifier::SignatureAlgorithm> + acceptable_algorithms) { + return g_mock_provider->GetNextGeneratedKey(); +} + +std::unique_ptr<crypto::UnexportableSigningKey> +MockUnexportableKeyProvider::FromWrappedSigningKeySlowly( + base::span<const uint8_t> wrapped_key) { + return g_mock_provider->GetNextGeneratedKey(); +} + +bool MockUnexportableKeyProvider::DeleteSigningKeySlowly( + base::span<const uint8_t> wrapped_key) { + return true; +} + +std::unique_ptr<crypto::UnexportableKeyProvider> GetMockKeyProvider() { + return std::make_unique<MockUnexportableKeyProvider>(); +} + +} // namespace + +ScopedMockUnexportableKeyProvider::ScopedMockUnexportableKeyProvider() { + CHECK(!g_mock_provider) << "Nested providers are not allowed"; + // Store `this` in a global pointer so that all mock key providers can access + // the `next_generated_keys_` queue. + g_mock_provider = this; + crypto::internal::SetUnexportableKeyProviderForTesting(&GetMockKeyProvider); +} + +ScopedMockUnexportableKeyProvider::~ScopedMockUnexportableKeyProvider() { + crypto::internal::SetUnexportableKeyProviderForTesting(nullptr); + g_mock_provider = nullptr; +} + +void ScopedMockUnexportableKeyProvider::AddNextGeneratedKey( + std::unique_ptr<crypto::UnexportableSigningKey> key) { + next_generated_keys_.push(std::move(key)); +} + +std::unique_ptr<crypto::UnexportableSigningKey> +ScopedMockUnexportableKeyProvider::GetNextGeneratedKey() { + std::unique_ptr<crypto::UnexportableSigningKey> next_generated_key; + if (!next_generated_keys_.empty()) { + next_generated_key = std::move(next_generated_keys_.front()); + next_generated_keys_.pop(); + } + return next_generated_key; +} + +} // namespace unexportable_keys
diff --git a/components/unexportable_keys/scoped_mock_unexportable_key_provider.h b/components/unexportable_keys/scoped_mock_unexportable_key_provider.h new file mode 100644 index 0000000..0877a0b --- /dev/null +++ b/components/unexportable_keys/scoped_mock_unexportable_key_provider.h
@@ -0,0 +1,37 @@ +// Copyright 2025 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_UNEXPORTABLE_KEYS_SCOPED_MOCK_UNEXPORTABLE_KEY_PROVIDER_H_ +#define COMPONENTS_UNEXPORTABLE_KEYS_SCOPED_MOCK_UNEXPORTABLE_KEY_PROVIDER_H_ + +#include "base/containers/queue.h" +#include "crypto/unexportable_key.h" + +namespace unexportable_keys { + +// Causes `GetUnexportableKeyProvider()` to return fully mockable +// `MockUnexportableKey`s while it is in scope. +// The mock provider will return mock keys previously added via +// `AddNextGeneratedKey()` in the queue order. +class ScopedMockUnexportableKeyProvider { + public: + ScopedMockUnexportableKeyProvider(); + ScopedMockUnexportableKeyProvider(const ScopedMockUnexportableKeyProvider&) = + delete; + ScopedMockUnexportableKeyProvider& operator=( + const ScopedMockUnexportableKeyProvider&) = delete; + ~ScopedMockUnexportableKeyProvider(); + + void AddNextGeneratedKey(std::unique_ptr<crypto::UnexportableSigningKey> key); + + std::unique_ptr<crypto::UnexportableSigningKey> GetNextGeneratedKey(); + + private: + base::queue<std::unique_ptr<crypto::UnexportableSigningKey>> + next_generated_keys_; +}; + +} // namespace unexportable_keys + +#endif // COMPONENTS_UNEXPORTABLE_KEYS_SCOPED_MOCK_UNEXPORTABLE_KEY_PROVIDER_H_
diff --git a/components/unexportable_keys/unexportable_key_loader_unittest.cc b/components/unexportable_keys/unexportable_key_loader_unittest.cc index 96e47f4..3224131 100644 --- a/components/unexportable_keys/unexportable_key_loader_unittest.cc +++ b/components/unexportable_keys/unexportable_key_loader_unittest.cc
@@ -187,9 +187,9 @@ key_loader->InvokeCallbackAfterKeyLoaded(base::BindLambdaForTesting( [&](ServiceErrorOr<UnexportableKeyId> key_id_or_error) { ASSERT_TRUE(key_id_or_error.has_value()); - service().SignSlowlyAsync(*key_id_or_error, - std::vector<uint8_t>({1, 2, 3}), - kTaskPriority, sign_future.GetCallback()); + service().SignSlowlyAsync( + *key_id_or_error, std::vector<uint8_t>({1, 2, 3}), kTaskPriority, + /*max_retries=*/0, sign_future.GetCallback()); })); EXPECT_FALSE(sign_future.IsReady()); RunBackgroundTasks();
diff --git a/components/unexportable_keys/unexportable_key_service.h b/components/unexportable_keys/unexportable_key_service.h index 756cd855..bd490cc 100644 --- a/components/unexportable_keys/unexportable_key_service.h +++ b/components/unexportable_keys/unexportable_key_service.h
@@ -86,15 +86,19 @@ // Schedules a new asynchronous signing task. // Might return a cached result if a task with the same combination of - // `signing_key` and `data` has been completed recently. + // `signing_key` and `data` has been completed recently. In case of a failure, + // the task might be retried up to `max_retries` times. // Invokes `callback` with a signature of `data`, or a `ServiceError` if // `key_id` is/ not found or an error occurs during signing. // `key_id` must have resulted from calling `GenerateSigningKeySlowlyAsync()` // or `FromWrappedSigningKeySlowlyAsync()` + // TODO(crbug.com/405408610): remove `max_retries` parameter once all callers + // adopt the retry logic. virtual void SignSlowlyAsync( const UnexportableKeyId& key_id, base::span<const uint8_t> data, BackgroundTaskPriority priority, + size_t max_retries, base::OnceCallback<void(ServiceErrorOr<std::vector<uint8_t>>)> callback) = 0;
diff --git a/components/unexportable_keys/unexportable_key_service_impl.cc b/components/unexportable_keys/unexportable_key_service_impl.cc index 14056eaf..3ff93bb 100644 --- a/components/unexportable_keys/unexportable_key_service_impl.cc +++ b/components/unexportable_keys/unexportable_key_service_impl.cc
@@ -164,15 +164,15 @@ const UnexportableKeyId& key_id, base::span<const uint8_t> data, BackgroundTaskPriority priority, + size_t max_retries, base::OnceCallback<void(ServiceErrorOr<std::vector<uint8_t>>)> callback) { auto it = key_by_key_id_.find(key_id); if (it == key_by_key_id_.end()) { std::move(callback).Run(base::unexpected(ServiceError::kKeyNotFound)); return; } - // TODO(crbug.com/400903525): expose `max_retries` as a parameter. - task_manager_->SignSlowlyAsync(it->second, data, priority, - /*max_retries=*/0, std::move(callback)); + task_manager_->SignSlowlyAsync(it->second, data, priority, max_retries, + std::move(callback)); } ServiceErrorOr<std::vector<uint8_t>>
diff --git a/components/unexportable_keys/unexportable_key_service_impl.h b/components/unexportable_keys/unexportable_key_service_impl.h index 49ceb4da..0d73b52 100644 --- a/components/unexportable_keys/unexportable_key_service_impl.h +++ b/components/unexportable_keys/unexportable_key_service_impl.h
@@ -59,6 +59,7 @@ const UnexportableKeyId& key_id, base::span<const uint8_t> data, BackgroundTaskPriority priority, + size_t max_retries, base::OnceCallback<void(ServiceErrorOr<std::vector<uint8_t>>)> callback) override; ServiceErrorOr<std::vector<uint8_t>> GetSubjectPublicKeyInfo(
diff --git a/components/unexportable_keys/unexportable_key_service_impl_unittest.cc b/components/unexportable_keys/unexportable_key_service_impl_unittest.cc index 0a035a8..a53858b 100644 --- a/components/unexportable_keys/unexportable_key_service_impl_unittest.cc +++ b/components/unexportable_keys/unexportable_key_service_impl_unittest.cc
@@ -4,6 +4,7 @@ #include "components/unexportable_keys/unexportable_key_service_impl.h" +#include <optional> #include <variant> #include "base/containers/span.h" @@ -15,7 +16,9 @@ #include "base/test/task_environment.h" #include "base/test/test_future.h" #include "components/unexportable_keys/background_task_priority.h" +#include "components/unexportable_keys/mock_unexportable_key.h" #include "components/unexportable_keys/ref_counted_unexportable_signing_key.h" +#include "components/unexportable_keys/scoped_mock_unexportable_key_provider.h" #include "components/unexportable_keys/service_error.h" #include "components/unexportable_keys/unexportable_key_task_manager.h" #include "crypto/scoped_mock_unexportable_key_provider.h" @@ -26,6 +29,10 @@ namespace unexportable_keys { +using testing::ElementsAreArray; +using testing::NiceMock; +using testing::Return; + namespace { constexpr crypto::SignatureVerifier::SignatureAlgorithm @@ -59,14 +66,25 @@ scoped_key_provider_.emplace<crypto::ScopedNullUnexportableKeyProvider>(); } + unexportable_keys::ScopedMockUnexportableKeyProvider& + SwitchToMockKeyProvider() { + // Using `emplace()` to destroy the existing scoped object before + // constructing a new one. + scoped_key_provider_ + .emplace<unexportable_keys::ScopedMockUnexportableKeyProvider>(); + return std::get<unexportable_keys::ScopedMockUnexportableKeyProvider>( + scoped_key_provider_); + } + private: base::test::TaskEnvironment task_environment_{ base::test::TaskEnvironment::ThreadPoolExecutionMode:: QUEUED}; // QUEUED - tasks don't run until `RunUntilIdle()` is // called. - // Provides a mock key provider by default. + // Provides a software-based key provider by default. std::variant<crypto::ScopedMockUnexportableKeyProvider, - crypto::ScopedNullUnexportableKeyProvider> + crypto::ScopedNullUnexportableKeyProvider, + unexportable_keys::ScopedMockUnexportableKeyProvider> scoped_key_provider_; std::unique_ptr<UnexportableKeyTaskManager> task_manager_; std::unique_ptr<UnexportableKeyServiceImpl> service_; @@ -270,7 +288,7 @@ base::test::TestFuture<ServiceErrorOr<std::vector<uint8_t>>> sign_future; std::vector<uint8_t> data = {1, 2, 3}; - service().SignSlowlyAsync(key_id, data, kTaskPriority, + service().SignSlowlyAsync(key_id, data, kTaskPriority, /*max_retries=*/0, sign_future.GetCallback()); EXPECT_FALSE(sign_future.IsReady()); RunBackgroundTasks(); @@ -290,10 +308,61 @@ // `SignSlowlyAsync()` should fail. base::test::TestFuture<ServiceErrorOr<std::vector<uint8_t>>> sign_future; std::vector<uint8_t> data = {1, 2, 3}; - service().SignSlowlyAsync(fake_key_id, data, kTaskPriority, + service().SignSlowlyAsync(fake_key_id, data, kTaskPriority, /*max_retries=*/0, sign_future.GetCallback()); EXPECT_TRUE(sign_future.IsReady()); EXPECT_EQ(sign_future.Get(), base::unexpected(ServiceError::kKeyNotFound)); } +TEST_F(UnexportableKeyServiceImplTest, SignFailed) { + auto key_to_generate = std::make_unique<NiceMock<MockUnexportableKey>>(); + ON_CALL(*key_to_generate, Algorithm) + .WillByDefault(Return(crypto::SignatureVerifier::ECDSA_SHA256)); + ON_CALL(*key_to_generate, GetWrappedKey) + .WillByDefault(Return(std::vector<uint8_t>{0, 0, 1})); + std::vector<uint8_t> data = {1, 2, 3}; + EXPECT_CALL(*key_to_generate, SignSlowly(ElementsAreArray(data))) + .WillOnce(Return(std::nullopt)); + SwitchToMockKeyProvider().AddNextGeneratedKey(std::move(key_to_generate)); + + base::test::TestFuture<ServiceErrorOr<UnexportableKeyId>> generate_future; + service().GenerateSigningKeySlowlyAsync(kAcceptableAlgorithms, kTaskPriority, + generate_future.GetCallback()); + RunBackgroundTasks(); + ASSERT_OK_AND_ASSIGN(UnexportableKeyId key_id, generate_future.Get()); + + base::test::TestFuture<ServiceErrorOr<std::vector<uint8_t>>> sign_future; + service().SignSlowlyAsync(key_id, data, kTaskPriority, /*max_retries=*/0, + sign_future.GetCallback()); + RunBackgroundTasks(); + EXPECT_EQ(sign_future.Get(), + base::unexpected(ServiceError::kCryptoApiFailed)); +} + +TEST_F(UnexportableKeyServiceImplTest, SignWithRetry) { + auto key_to_generate = std::make_unique<NiceMock<MockUnexportableKey>>(); + ON_CALL(*key_to_generate, Algorithm) + .WillByDefault(Return(crypto::SignatureVerifier::ECDSA_SHA256)); + ON_CALL(*key_to_generate, GetWrappedKey) + .WillByDefault(Return(std::vector<uint8_t>{0, 0, 1})); + std::vector<uint8_t> data = {1, 2, 3}; + std::vector<uint8_t> signed_data = {3, 2, 1}; + EXPECT_CALL(*key_to_generate, SignSlowly(ElementsAreArray(data))) + .WillOnce(Return(std::nullopt)) + .WillOnce(Return(signed_data)); + SwitchToMockKeyProvider().AddNextGeneratedKey(std::move(key_to_generate)); + + base::test::TestFuture<ServiceErrorOr<UnexportableKeyId>> generate_future; + service().GenerateSigningKeySlowlyAsync(kAcceptableAlgorithms, kTaskPriority, + generate_future.GetCallback()); + RunBackgroundTasks(); + ASSERT_OK_AND_ASSIGN(UnexportableKeyId key_id, generate_future.Get()); + + base::test::TestFuture<ServiceErrorOr<std::vector<uint8_t>>> sign_future; + service().SignSlowlyAsync(key_id, data, kTaskPriority, /*max_retries=*/3, + sign_future.GetCallback()); + RunBackgroundTasks(); + EXPECT_EQ(sign_future.Get(), signed_data); +} + } // namespace unexportable_keys
diff --git a/components/viz/common/display/renderer_settings.h b/components/viz/common/display/renderer_settings.h index b18f488..60c6f96 100644 --- a/components/viz/common/display/renderer_settings.h +++ b/components/viz/common/display/renderer_settings.h
@@ -35,6 +35,9 @@ bool auto_resize_output_surface = true; bool requires_alpha_channel = false; bool disable_render_pass_bypassing = false; + // Force render pass backings to allocate shared images without the scanout + // usage. The render pass backing will still claim the backing is scanout. + bool force_non_scanout_backing_for_pixel_tests = false; int slow_down_compositing_scale_factor = 1;
diff --git a/components/viz/service/display/renderer_pixeltest.cc b/components/viz/service/display/renderer_pixeltest.cc index 3e23e873..9de588f 100644 --- a/components/viz/service/display/renderer_pixeltest.cc +++ b/components/viz/service/display/renderer_pixeltest.cc
@@ -5958,6 +5958,8 @@ this->display_color_spaces_ = gfx::DisplayColorSpaces(gfx::ColorSpace::CreateSCRGBLinear80Nits()); this->display_color_spaces_.SetSDRMaxLuminanceNits(80.f); + this->display_color_spaces_.SetOutputBufferFormats( + gfx::BufferFormat::RGBA_F16, gfx::BufferFormat::RGBA_F16); if (std::get<1>(GetParam())) { features_.InitAndEnableFeature(features::kColorConversionInRenderer); @@ -6014,6 +6016,140 @@ // GetGpuRendererTypes() can return an empty list, e.g. on Fuchsia ARM64. GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(RendererPixelTestColorConversion); +#if BUILDFLAG(IS_WIN) +class VideoPixelRendererPixelTestColorConversion + : public VideoRendererPixelTestBase, + public testing::WithParamInterface<std::tuple<RendererType, bool>> { + public: + VideoPixelRendererPixelTestColorConversion() + : VideoRendererPixelTestBase(std::get<0>(GetParam())) {} + + void SetUp() override { + // Set a color space that is not suitable for blending to ensure we go + // through the color conversion code paths. + this->display_color_spaces_ = + gfx::DisplayColorSpaces(gfx::ColorSpace::CreateSCRGBLinear80Nits()); + this->display_color_spaces_.SetSDRMaxLuminanceNits(80.f); + this->display_color_spaces_.SetOutputBufferFormats( + gfx::BufferFormat::RGBA_F16, gfx::BufferFormat::RGBA_F16); + + // Allow non-root render passes to have the above non-suitable-for-blending + // color space by being scanout. + renderer_settings_.force_non_scanout_backing_for_pixel_tests = true; + + if (std::get<1>(GetParam())) { + features_.InitWithFeatures({features::kDelegatedCompositing, + features::kColorConversionInRenderer}, + {}); + } else { + features_.InitWithFeatures({features::kDelegatedCompositing}, + {features::kColorConversionInRenderer}); + } + + VideoRendererPixelTestBase::SetUp(); + } + + private: + base::test::ScopedFeatureList features_; +}; + +// This checks the correct color conversion is happening in the following case: +// a non-root render pass has a texture quad that requires a color conversion +// filter, but no quads in the render pass require blending. +// +// In this case, the color conversion layer is elided, but we choose the wrong +// "destination" color space for the color conversion filter when we draw the +// texture quad. +// See: crbug.com/397995970 +TEST_P(VideoPixelRendererPixelTestColorConversion, + RenderPassWithHdrVideoDoesntNeedBlending) { + // Create a test frame that embeds a pass which: + // - contains a texture quad that requires a color conversion filter and + // - needs blending, iff `child_pass_needs_blending`. + auto CreateFrame = + [&](bool child_pass_needs_blending) -> AggregatedRenderPassList { + const gfx::Rect rect(this->device_viewport_size_); + + CompositorRenderPassId id{1}; + auto child_pass = CreateTestRootRenderPass(id, rect); + + auto color_space = gfx::ColorSpace::CreateHDR10(); + + CreateTestMultiplanarVideoDrawQuad( + TestVideoFrameBuilder(media::PIXEL_FORMAT_I420, color_space, + kUnitSquare, rect.size(), rect.size()) + .DrawSolid(144, 54, 34), + /*alpha_value=*/255, gfx::Transform(), gfx::MaskFilterInfo(), + /*sorting_context_id=*/0, child_pass.get(), + this->video_resource_updater_.get(), rect, rect, + this->resource_provider_.get(), this->child_resource_provider_.get(), + this->child_context_provider_.get()); + + AggregatedRenderPassList pass_list; + + AggregatedRenderPassId hdr_child_id{2}; + { + auto child_pass_copy = cc::CopyToAggregatedRenderPass( + child_pass.get(), hdr_child_id, gfx::ContentColorUsage::kHDR); + + // Make `is_scanout == true` on Windows for non-root pass. + // See: `DirectRenderer::CalculateRenderPassRequirements` + { + EXPECT_TRUE( + base::FeatureList::IsEnabled(features::kDelegatedCompositing)); + child_pass_copy->is_from_surface_root_pass = true; + child_pass_copy->will_backing_be_read_by_viz = false; + } + + // When `ColorConversionInRenderer` is enabled, make the HDR child render + // pass not use the color conversion layer since it won't contain quads + // that require blending. + // When `ColorConversionInRenderer` is disabled, color conversion will + // happen unconditionally as a render pass. + for (auto* quad : child_pass_copy->quad_list) { + quad->needs_blending = child_pass_needs_blending; + } + + pass_list.push_back(std::move(child_pass_copy)); + } + + // Add a root pass that embeds the problematic pass. The root render pass + // color space is handled specially and we are testing the non-root case. + { + AggregatedRenderPassId root_id{1}; + auto root_pass = CreateTestRootRenderPass(root_id, rect); + root_pass->content_color_usage = gfx::ContentColorUsage::kSRGB; + + SharedQuadState* shared_state = CreateTestSharedQuadState( + gfx::Transform(), rect, root_pass.get(), gfx::MaskFilterInfo()); + CreateTestRenderPassDrawQuad(shared_state, rect, hdr_child_id, + root_pass.get()); + + pass_list.push_back(std::move(root_pass)); + } + + return pass_list; + }; + + // Render the child pass with blending to use as a baseline, since we expect + // the output to be the same in both cases. + AggregatedRenderPassList pass_list_with_blending = + CreateFrame(/*child_pass_needs_blending=*/true); + + AggregatedRenderPassList pass_list_without_blending = + CreateFrame(/*child_pass_needs_blending=*/false); + EXPECT_TRUE(this->RunPixelTest(&pass_list_without_blending, + &pass_list_with_blending, + cc::AlphaDiscardingExactPixelComparator())); +} + +INSTANTIATE_TEST_SUITE_P( + , + VideoPixelRendererPixelTestColorConversion, + testing::Combine(testing::ValuesIn(GetGpuRendererTypes()), + testing::Bool())); +#endif + using PrimaryID = gfx::ColorSpace::PrimaryID; using TransferID = gfx::ColorSpace::TransferID; @@ -6042,6 +6178,10 @@ } this->display_color_spaces_ = gfx::DisplayColorSpaces(this->dst_color_space_); + if (this->dst_color_space_.IsWide()) { + this->display_color_spaces_.SetOutputBufferFormats( + gfx::BufferFormat::RGBA_F16, gfx::BufferFormat::RGBA_F16); + } this->premultiplied_alpha_ = std::get<3>(GetParam()); if (std::get<4>(GetParam())) { features_.InitAndEnableFeature(features::kColorConversionInRenderer);
diff --git a/components/viz/service/display/skia_renderer.cc b/components/viz/service/display/skia_renderer.cc index cef4d9b..ec2d1f2 100644 --- a/components/viz/service/display/skia_renderer.cc +++ b/components/viz/service/display/skia_renderer.cc
@@ -1440,9 +1440,25 @@ } gfx::ColorSpace SkiaRenderer::CurrentDrawLayerColorSpace() const { - return hdr_color_conversion_layer_reset_ - ? gfx::ColorSpace::CreateExtendedSRGB() - : RenderPassColorSpace(current_frame()->current_render_pass); + if (hdr_color_conversion_layer_reset_) { + // A color conversion layer allows us to draw everything in extended sRGB. + return gfx::ColorSpace::CreateExtendedSRGB(); + } + + // `NeedsLayerForColorConversion` can return false when no quads in a render + // pass require blending. To correctly handle color conversion, the + // destination color space (the result of this function) must match the actual + // render pass backing. We thus cannot unconditionally use the compositing + // color space because it may not be what SCANOUT render pass backings use. + const auto it = + render_pass_backings_.find(current_frame()->current_render_pass->id); + if (it != render_pass_backings_.end()) { + return it->second.color_space; + } + + // If there is no render pass backing, we must be drawing the root pass. + CHECK(!output_surface_->capabilities().renderer_allocates_images); + return RenderPassColorSpace(current_frame()->root_render_pass); } void SkiaRenderer::BeginDrawingRenderPass( @@ -3643,7 +3659,8 @@ DCHECK(!requirements.is_scanout); usage |= gpu::SHARED_IMAGE_USAGE_MIPMAP; } - if (requirements.is_scanout) { + if (requirements.is_scanout && + !settings_->force_non_scanout_backing_for_pixel_tests) { usage |= gpu::SHARED_IMAGE_USAGE_SCANOUT; #if BUILDFLAG(IS_WIN)
diff --git a/components/viz/service/display_embedder/skia_output_device_offscreen.cc b/components/viz/service/display_embedder/skia_output_device_offscreen.cc index d915817..f2780ba4 100644 --- a/components/viz/service/display_embedder/skia_output_device_offscreen.cc +++ b/components/viz/service/display_embedder/skia_output_device_offscreen.cc
@@ -55,6 +55,8 @@ kBGRA_8888_SkColorType; capabilities_.sk_color_type_map[SinglePlaneFormat::kBGRX_8888] = kBGRA_8888_SkColorType; + capabilities_.sk_color_type_map[SinglePlaneFormat::kRGBA_F16] = + kRGBA_F16_SkColorType; } SkiaOutputDeviceOffscreen::~SkiaOutputDeviceOffscreen() {
diff --git a/components/viz/service/layers/layer_context_impl.cc b/components/viz/service/layers/layer_context_impl.cc index 5abebc5..426bb34 100644 --- a/components/viz/service/layers/layer_context_impl.cc +++ b/components/viz/service/layers/layer_context_impl.cc
@@ -103,6 +103,8 @@ } node.local = wire.local; node.origin = wire.origin; + node.post_translation = wire.post_translation; + node.set_to_parent(wire.to_parent); node.SetScrollOffset(wire.scroll_offset, cc::DamageReason::kUntracked); node.snap_amount = wire.snap_amount;
diff --git a/content/browser/accessibility/browser_accessibility_android.cc b/content/browser/accessibility/browser_accessibility_android.cc index d3f1ff4..7a3fa84c 100644 --- a/content/browser/accessibility/browser_accessibility_android.cc +++ b/content/browser/accessibility/browser_accessibility_android.cc
@@ -619,6 +619,11 @@ return false; } + // Listboxes with children should never be a leaf node. + if (GetRole() == ax::mojom::Role::kListBox && InternalChildCount() > 0) { + return false; + } + // For Android only, tab-panels and tab-lists are never leaves. We do this to // temporarily get around the gap for aria-labelledby in the Android API. // See b/241526393.
diff --git a/content/browser/accessibility/browser_accessibility_manager_android.cc b/content/browser/accessibility/browser_accessibility_manager_android.cc index c3a34c8..a073b692 100644 --- a/content/browser/accessibility/browser_accessibility_manager_android.cc +++ b/content/browser/accessibility/browser_accessibility_manager_android.cc
@@ -420,8 +420,8 @@ ui::BrowserAccessibility* node, const std::string& announcement, ax::mojom::AriaNotificationPriority priority_property, - const std::string& notification_id, - ax::mojom::AriaNotificationInterrupt interrupt_property) { + ax::mojom::AriaNotificationInterrupt interrupt_property, + const std::string& type) { DCHECK(node); auto* wcax = GetWebContentsAXFromRootManager();
diff --git a/content/browser/accessibility/browser_accessibility_manager_android.h b/content/browser/accessibility/browser_accessibility_manager_android.h index 27fdf60..f1095bb 100644 --- a/content/browser/accessibility/browser_accessibility_manager_android.h +++ b/content/browser/accessibility/browser_accessibility_manager_android.h
@@ -116,8 +116,8 @@ ui::BrowserAccessibility* node, const std::string& announcement, ax::mojom::AriaNotificationPriority priority_property, - const std::string& notification_id, - ax::mojom::AriaNotificationInterrupt interrupt_property) override; + ax::mojom::AriaNotificationInterrupt interrupt_property, + const std::string& type) override; void FireLocationChanged(ui::BrowserAccessibility* node);
diff --git a/content/browser/accessibility/cross_platform_accessibility_browsertest.cc b/content/browser/accessibility/cross_platform_accessibility_browsertest.cc index 5d9ca5c..170a9706 100644 --- a/content/browser/accessibility/cross_platform_accessibility_browsertest.cc +++ b/content/browser/accessibility/cross_platform_accessibility_browsertest.cc
@@ -3134,7 +3134,7 @@ } function otherNotify(clickedElement) { clickedElement.ariaNotify("world", {"interrupt": "pending", - "notificationId": "test", + "type": "test", "priority": "high"}); } </script>)HTML"); @@ -3161,7 +3161,7 @@ EXPECT_EQ(std::vector<std::string>{""}, button->GetStringListAttribute( - ax::mojom::StringListAttribute::kAriaNotificationIds)); + ax::mojom::StringListAttribute::kAriaNotificationTypes)); EXPECT_EQ( std::vector<int32_t>{ @@ -3192,11 +3192,11 @@ button->GetStringListAttribute( ax::mojom::StringListAttribute::kAriaNotificationAnnouncements)); - // For v1 of the feature, notificationId should have a default value of + // For v1 of the feature, type should have a default value of // empty string. EXPECT_EQ(std::vector<std::string>{""}, button->GetStringListAttribute( - ax::mojom::StringListAttribute::kAriaNotificationIds)); + ax::mojom::StringListAttribute::kAriaNotificationTypes)); // For v1 of the feature, interrupt should have a default value of none. EXPECT_EQ( @@ -3248,7 +3248,7 @@ EXPECT_EQ(std::vector<std::string>{""}, button->GetStringListAttribute( - ax::mojom::StringListAttribute::kAriaNotificationIds)); + ax::mojom::StringListAttribute::kAriaNotificationTypes)); EXPECT_EQ( std::vector<int32_t>{ @@ -3268,7 +3268,7 @@ } } -// For v1 of the feature, notificationId should have a default value of empty +// For v1 of the feature, type should have a default value of empty // string and interrupt should have the default value of none. IN_PROC_BROWSER_TEST_F(AriaNotifyCrossPlatformAccessibilityBrowserTest, TestConsecutiveAriaNotifications) { @@ -3279,10 +3279,10 @@ </div> <script> function notify(clickedElement) { - clickedElement.ariaNotify("one", {"notificationId": "kOne", + clickedElement.ariaNotify("one", {"type": "kOne", "interrupt": "all"}); clickedElement.ariaNotify("two", {"priority": "high"}); - clickedElement.ariaNotify("three", {"notificationId": "kThree", + clickedElement.ariaNotify("three", {"type": "kThree", "interrupt": "pending"}); } </script>)HTML"); @@ -3318,7 +3318,7 @@ EXPECT_EQ(std::vector<std::string>({"", "", ""}), button->GetStringListAttribute( - ax::mojom::StringListAttribute::kAriaNotificationIds)); + ax::mojom::StringListAttribute::kAriaNotificationTypes)); EXPECT_EQ( std::vector<int32_t>( @@ -3367,7 +3367,7 @@ } function otherNotify(clickedElement) { clickedElement.ariaNotify("world", {"interrupt": "pending", - "notificationId": "test", + "type": "test", "priority": "high"}); } </script>)HTML"); @@ -3394,7 +3394,7 @@ EXPECT_EQ(std::vector<std::string>{""}, button->GetStringListAttribute( - ax::mojom::StringListAttribute::kAriaNotificationIds)); + ax::mojom::StringListAttribute::kAriaNotificationTypes)); EXPECT_EQ( std::vector<int32_t>{ @@ -3427,7 +3427,7 @@ EXPECT_EQ(std::vector<std::string>{"test"}, button->GetStringListAttribute( - ax::mojom::StringListAttribute::kAriaNotificationIds)); + ax::mojom::StringListAttribute::kAriaNotificationTypes)); EXPECT_EQ( std::vector<int32_t>{ @@ -3443,7 +3443,7 @@ } } -// For v2 of the feature, notificationId and interrupt should have their given +// For v2 of the feature, type and interrupt should have their given // values. IN_PROC_BROWSER_TEST_F(AriaNotifyV2CrossPlatformAccessibilityBrowserTest, TestConsecutiveAriaNotificationsV2) { @@ -3459,10 +3459,10 @@ </div> <script> function notify(clickedElement) { - clickedElement.ariaNotify("one", {"notificationId": "kOne", + clickedElement.ariaNotify("one", {"type": "kOne", "interrupt": "all"}); clickedElement.ariaNotify("two", {"priority": "high"}); - clickedElement.ariaNotify("three", {"notificationId": "kThree", + clickedElement.ariaNotify("three", {"type": "kThree", "interrupt": "pending"}); } </script>)HTML"); @@ -3489,7 +3489,7 @@ EXPECT_EQ(std::vector<std::string>({"kOne", "", "kThree"}), button->GetStringListAttribute( - ax::mojom::StringListAttribute::kAriaNotificationIds)); + ax::mojom::StringListAttribute::kAriaNotificationTypes)); EXPECT_EQ( std::vector<int32_t>(
diff --git a/content/browser/attribution_reporting/attributions_browsertest.cc b/content/browser/attribution_reporting/attributions_browsertest.cc index 19e5dd1..20c8b7b 100644 --- a/content/browser/attribution_reporting/attributions_browsertest.cc +++ b/content/browser/attribution_reporting/attributions_browsertest.cc
@@ -215,8 +215,6 @@ GURL expected_url; base::Value::Dict expected_body; - std::string source_debug_key; - std::string trigger_debug_key; std::unique_ptr<net::test_server::ControllableHttpResponse> response; bool HasRequest() { return !!response->http_request(); } @@ -249,17 +247,9 @@ EXPECT_TRUE(body.FindDouble("randomized_trigger_rate")); - if (source_debug_key.empty()) { - EXPECT_FALSE(body.FindString("source_debug_key")); - } else { - base::ExpectDictStringValue(source_debug_key, body, "source_debug_key"); - } + EXPECT_FALSE(body.FindString("source_debug_key")); - if (trigger_debug_key.empty()) { - EXPECT_FALSE(body.FindString("trigger_debug_key")); - } else { - base::ExpectDictStringValue(trigger_debug_key, body, "trigger_debug_key"); - } + EXPECT_FALSE(body.FindString("trigger_debug_key")); // Clear the port as it is assigned by the EmbeddedTestServer at runtime. replace_host.SetPortStr("");
diff --git a/content/browser/back_forward_cache_basics_browsertest.cc b/content/browser/back_forward_cache_basics_browsertest.cc index ed967f5e..7e6affd4 100644 --- a/content/browser/back_forward_cache_basics_browsertest.cc +++ b/content/browser/back_forward_cache_basics_browsertest.cc
@@ -243,6 +243,43 @@ ExpectRestored(FROM_HERE); } +IN_PROC_BROWSER_TEST_F(BackForwardCacheBrowserTest, DidFinishLoadNotCalled) { + ASSERT_TRUE(embedded_test_server()->Start()); + GURL url_a(embedded_test_server()->GetURL("a.com", "/title1.html")); + GURL url_b(embedded_test_server()->GetURL("b.com", "/page_with_iframe.html")); + + int did_finish_load_count = 0; + + // Set up a LoadFinishObserver to observe the DidFinishLoad event. + LoadFinishObserver load_finish_observer( + shell()->web_contents(), + base::BindLambdaForTesting( + [&](RenderFrameHost* render_frame_host, const GURL& validated_url) { + did_finish_load_count++; + })); + + // 1) Navigate to A. DidFinishLoad will be called once. + EXPECT_TRUE(NavigateToURL(shell(), url_a)); + EXPECT_EQ(did_finish_load_count, 1); + + // 2) Navigate to B. DidFinishLoad will be called once for the main frame and + // once for iframe. + EXPECT_TRUE(NavigateToURL(shell(), url_b)); + EXPECT_EQ(did_finish_load_count, 3); + + // 3) Go back to A. DidFinishLoad should not be called in the back forward + // cache navigation. + ASSERT_TRUE(HistoryGoBack(web_contents())); + EXPECT_EQ(did_finish_load_count, 3); + ExpectRestored(FROM_HERE); + + // 4) Go forward to B. DidFinishLoad should not be called in the back forward + // cache navigation. + ASSERT_TRUE(HistoryGoForward(web_contents())); + EXPECT_EQ(did_finish_load_count, 3); + ExpectRestored(FROM_HERE); +} + // The current page can't enter the BackForwardCache if another page can script // it. This can happen when one document opens a popup using window.open() for // instance. It prevents the BackForwardCache from being used.
diff --git a/content/browser/back_forward_cache_features_browsertest.cc b/content/browser/back_forward_cache_features_browsertest.cc index f5a6b3d..6e6dcf4 100644 --- a/content/browser/back_forward_cache_features_browsertest.cc +++ b/content/browser/back_forward_cache_features_browsertest.cc
@@ -92,10 +92,8 @@ ExpectRestored(FROM_HERE); } -// The bool parameter is used for switching PlzDedicatedWorker. class BackForwardCacheWithDedicatedWorkerBrowserTest - : public BackForwardCacheBrowserTest, - public testing::WithParamInterface<bool> { + : public BackForwardCacheBrowserTest { public: const int kMaxBufferedBytesPerProcess = 10000; const base::TimeDelta kGracePeriodToFinishLoading = base::Seconds(5); @@ -103,11 +101,6 @@ BackForwardCacheWithDedicatedWorkerBrowserTest() { server_.Start(); } void SetUpCommandLine(base::CommandLine* command_line) override { - if (IsPlzDedicatedWorkerEnabled()) { - EnableFeatureAndSetParams(blink::features::kPlzDedicatedWorker, "", ""); - } else { - DisableFeature(blink::features::kPlzDedicatedWorker); - } // Disable the feature to test eviction for dedicated worker. DisableFeature( blink::features::kAllowDatapipeDrainedAsBytesConsumerInBFCache); @@ -123,8 +116,6 @@ server_.SetUpCommandLine(command_line); } - bool IsPlzDedicatedWorkerEnabled() { return GetParam(); } - int port() const { return server_.server_address().port(); } int CountWorkerClients(RenderFrameHostImpl* rfh) { @@ -142,12 +133,8 @@ WebTransportSimpleTestServer server_; }; -INSTANTIATE_TEST_SUITE_P(All, - BackForwardCacheWithDedicatedWorkerBrowserTest, - testing::Bool()); - // Confirms that a page using a dedicated worker is cached. -IN_PROC_BROWSER_TEST_P(BackForwardCacheWithDedicatedWorkerBrowserTest, +IN_PROC_BROWSER_TEST_F(BackForwardCacheWithDedicatedWorkerBrowserTest, CacheWithDedicatedWorker) { CreateHttpsServer(); ASSERT_TRUE(https_server()->Start()); @@ -170,7 +157,7 @@ // Confirms that an active page using a dedicated worker that calls // importScripts won't trigger an eviction IPC, causing the page to reload. // Regression test for https://crbug.com/1305041. -IN_PROC_BROWSER_TEST_P( +IN_PROC_BROWSER_TEST_F( BackForwardCacheWithDedicatedWorkerBrowserTest, PageWithDedicatedWorkerAndImportScriptsWontTriggerReload) { CreateHttpsServer(); @@ -193,7 +180,7 @@ // Confirms that a page using a dedicated worker with WebTransport is not // cached. -IN_PROC_BROWSER_TEST_P(BackForwardCacheWithDedicatedWorkerBrowserTest, +IN_PROC_BROWSER_TEST_F(BackForwardCacheWithDedicatedWorkerBrowserTest, DoNotCacheWithDedicatedWorkerWithWebTransport) { CreateHttpsServer(); ASSERT_TRUE(https_server()->Start()); @@ -225,7 +212,7 @@ // Confirms that a page using a dedicated worker with a closed WebTransport is // cached as WebTransport is not a sticky feature. -IN_PROC_BROWSER_TEST_P(BackForwardCacheWithDedicatedWorkerBrowserTest, +IN_PROC_BROWSER_TEST_F(BackForwardCacheWithDedicatedWorkerBrowserTest, CacheWithDedicatedWorkerWithWebTransportClosed) { CreateHttpsServer(); ASSERT_TRUE(https_server()->Start()); @@ -261,7 +248,7 @@ #define MAYBE_DoNotCacheWithDedicatedWorkerWithWebTransportAndDocumentWithBlockingFeature \ DoNotCacheWithDedicatedWorkerWithWebTransportAndDocumentWithBlockingFeature #endif -IN_PROC_BROWSER_TEST_P( +IN_PROC_BROWSER_TEST_F( BackForwardCacheWithDedicatedWorkerBrowserTest, MAYBE_DoNotCacheWithDedicatedWorkerWithWebTransportAndDocumentWithBlockingFeature) { CreateHttpsServer(); @@ -309,7 +296,7 @@ } // TODO(crbug.com/40821593): Disabled due to being flaky. -IN_PROC_BROWSER_TEST_P( +IN_PROC_BROWSER_TEST_F( BackForwardCacheWithDedicatedWorkerBrowserTest, DISABLED_DoNotCacheWithDedicatedWorkerWithClosedWebTransportAndDocumentWithBroadcastChannel) { CreateHttpsServer(); @@ -371,7 +358,7 @@ // Tests the case when the page starts fetching in a dedicated worker, goes to // BFcache, and then a redirection happens. The cached page should evicted in // this case. -IN_PROC_BROWSER_TEST_P(BackForwardCacheWithDedicatedWorkerBrowserTest, +IN_PROC_BROWSER_TEST_F(BackForwardCacheWithDedicatedWorkerBrowserTest, FetchRedirectedWhileStoring) { CreateHttpsServer(); @@ -439,7 +426,7 @@ // Tests the case when the page starts fetching in a nested dedicated worker, // goes to BFcache, and then a redirection happens. The cached page should // evicted in this case. -IN_PROC_BROWSER_TEST_P(BackForwardCacheWithDedicatedWorkerBrowserTest, +IN_PROC_BROWSER_TEST_F(BackForwardCacheWithDedicatedWorkerBrowserTest, FetchRedirectedWhileStoring_Nested) { CreateHttpsServer(); @@ -515,7 +502,7 @@ // Tests the case when the page starts fetching in a dedicated worker, goes to // BFcache, and then the response amount reaches the threshold. The cached page // should evicted in this case. -IN_PROC_BROWSER_TEST_P( +IN_PROC_BROWSER_TEST_F( BackForwardCacheWithDedicatedWorkerBrowserTest, FetchStillLoading_ResponseStartedWhileFrozen_ExceedsPerProcessBytesLimit) { CreateHttpsServer(); @@ -574,7 +561,7 @@ // Tests the case when the page starts fetching in a nested dedicated worker, // goes to BFcache, and then the response amount reaches the threshold. The // cached page should evicted in this case. -IN_PROC_BROWSER_TEST_P( +IN_PROC_BROWSER_TEST_F( BackForwardCacheWithDedicatedWorkerBrowserTest, FetchStillLoading_ResponseStartedWhileFrozen_ExceedsPerProcessBytesLimit_Nested) { CreateHttpsServer(); @@ -638,7 +625,7 @@ // Tests the case when fetching started in a dedicated worker and the header was // received before the page is frozen, but parts of the response body is // received when the page is frozen. -IN_PROC_BROWSER_TEST_P(BackForwardCacheWithDedicatedWorkerBrowserTest, +IN_PROC_BROWSER_TEST_F(BackForwardCacheWithDedicatedWorkerBrowserTest, PageWithDrainedDatapipeRequestsForFetchShouldBeEvicted) { CreateHttpsServer(); @@ -687,7 +674,7 @@ // Tests the case when fetching started in a nested dedicated worker and the // header was received before the page is frozen, but parts of the response body // is received when the page is frozen. -IN_PROC_BROWSER_TEST_P( +IN_PROC_BROWSER_TEST_F( BackForwardCacheWithDedicatedWorkerBrowserTest, PageWithDrainedDatapipeRequestsForFetchShouldBeEvicted_Nested) { CreateHttpsServer(); @@ -743,7 +730,7 @@ // Tests the case when fetch started in a dedicated worker, but the response // never ends after the page is frozen. This should result in an eviction due to // timeout. -IN_PROC_BROWSER_TEST_P(BackForwardCacheWithDedicatedWorkerBrowserTest, +IN_PROC_BROWSER_TEST_F(BackForwardCacheWithDedicatedWorkerBrowserTest, ImageStillLoading_ResponseStartedWhileFrozen_Timeout) { CreateHttpsServer(); @@ -799,7 +786,7 @@ // Tests the case when fetch started in a nested dedicated worker, but the // response never ends after the page is frozen. This should result in an // eviction due to timeout. -IN_PROC_BROWSER_TEST_P( +IN_PROC_BROWSER_TEST_F( BackForwardCacheWithDedicatedWorkerBrowserTest, ImageStillLoading_ResponseStartedWhileFrozen_Timeout_Nested) { CreateHttpsServer(); @@ -861,7 +848,7 @@ // Tests that dedicated workers in back/forward cache are not visible to a // service worker. -IN_PROC_BROWSER_TEST_P(BackForwardCacheWithDedicatedWorkerBrowserTest, +IN_PROC_BROWSER_TEST_F(BackForwardCacheWithDedicatedWorkerBrowserTest, ServiceWorkerClientMatchAll) { CreateHttpsServer(); ASSERT_TRUE(https_server()->Start()); @@ -885,10 +872,9 @@ // Confirm there is no worker client. EXPECT_EQ(0, CountWorkerClients(rfh_a.get())); - // Call fetch in a dedicated worker. If the PlzDedicatedWorker is enabled, the - // number of worker clients should be 1. If PlzDedicatedWorker is disabled, - // worker clients are not supported, so the number should be 0. - int expected_number = IsPlzDedicatedWorkerEnabled() ? 1 : 0; + // Call fetch in a dedicated worker and verify that we see the expected number + // of worker clients. + const int kExpectedWorkerClientCount = 1; std::string dedicated_worker_script = JsReplace( R"( (async() => { @@ -897,7 +883,7 @@ })(); )", https_server()->GetURL("a.test", "/service_worker/count_worker_clients")); - EXPECT_EQ(base::NumberToString(expected_number), + EXPECT_EQ(base::NumberToString(kExpectedWorkerClientCount), EvalJs(rfh_a.get(), JsReplace(R"( new Promise(async (resolve) => { const blobURL = URL.createObjectURL(new Blob([$1])); @@ -919,12 +905,13 @@ // Restore from the back/forward cache. ASSERT_TRUE(HistoryGoBack(web_contents())); - EXPECT_EQ(expected_number, CountWorkerClients(current_frame_host())); + EXPECT_EQ(kExpectedWorkerClientCount, + CountWorkerClients(current_frame_host())); } // Tests that dedicated workers, including a nested dedicated workers, in // back/forward cache are not visible to a service worker. -IN_PROC_BROWSER_TEST_P(BackForwardCacheWithDedicatedWorkerBrowserTest, +IN_PROC_BROWSER_TEST_F(BackForwardCacheWithDedicatedWorkerBrowserTest, ServiceWorkerClientMatchAll_Nested) { CreateHttpsServer(); ASSERT_TRUE(https_server()->Start()); @@ -948,10 +935,9 @@ // Confirm there is no worker client. EXPECT_EQ(0, CountWorkerClients(rfh_a.get())); - // Call fetch in a dedicated worker. If the PlzDedicatedWorker is enabled, the - // number of worker clients should be 2. If PlzDedicatedWorker is disabled, - // worker clients are not supported, so the number should be 0. - int expected_number = IsPlzDedicatedWorkerEnabled() ? 2 : 0; + // Call fetch in a dedicated worker and verify that we see the expected number + // of worker clients. + const int kExpectedWorkerClientCount = 2; std::string child_worker_script = JsReplace( R"( (async() => { @@ -969,7 +955,7 @@ }); )", child_worker_script); - EXPECT_EQ(base::NumberToString(expected_number), + EXPECT_EQ(base::NumberToString(kExpectedWorkerClientCount), EvalJs(rfh_a.get(), JsReplace(R"( new Promise(async (resolve) => { const blobURL = URL.createObjectURL(new Blob([$1])); @@ -991,13 +977,14 @@ // Restore from the back/forward cache. ASSERT_TRUE(HistoryGoBack(web_contents())); - EXPECT_EQ(expected_number, CountWorkerClients(current_frame_host())); + EXPECT_EQ(kExpectedWorkerClientCount, + CountWorkerClients(current_frame_host())); } // Tests that dedicated workers in back/forward cache are not visible to a // service worker. This works correctly even if a dedicated worker is not loaded // completely when the page is put into back/forward cache, -IN_PROC_BROWSER_TEST_P(BackForwardCacheWithDedicatedWorkerBrowserTest, +IN_PROC_BROWSER_TEST_F(BackForwardCacheWithDedicatedWorkerBrowserTest, ServiceWorkerClientMatchAll_LoadWorkerAfterRestoring) { CreateHttpsServer(); @@ -1067,11 +1054,7 @@ }); )"))); - // If the PlzDedicatedWorker is enabled, the number of worker clients should - // be 1. If PlzDedicatedWorker is disabled, worker clients are not supported, - // so the number should be 0. - EXPECT_EQ(IsPlzDedicatedWorkerEnabled() ? 1 : 0, - CountWorkerClients(current_frame_host())); + EXPECT_EQ(1, CountWorkerClients(current_frame_host())); } // TODO(crbug.com/40290702): Shared workers are not available on Android.
diff --git a/content/browser/blob_storage/blob_url_browsertest.cc b/content/browser/blob_storage/blob_url_browsertest.cc index 5350d715..7b2146b 100644 --- a/content/browser/blob_storage/blob_url_browsertest.cc +++ b/content/browser/blob_storage/blob_url_browsertest.cc
@@ -9,6 +9,7 @@ #include "base/test/with_feature_override.h" #include "build/build_config.h" #include "content/browser/devtools/render_frame_devtools_agent_host.h" +#include "content/browser/permissions/permission_controller_impl.h" #include "content/browser/renderer_host/render_frame_host_impl.h" #include "content/browser/web_contents/web_contents_impl.h" #include "content/public/common/content_switches.h" @@ -43,6 +44,14 @@ LogWebFeatureForCurrentPage, (content::RenderFrameHost*, blink::mojom::WebFeature), (override)); + + bool IsFullCookieAccessAllowed( + content::BrowserContext* browser_context, + content::WebContents* web_contents, + const GURL& url, + const blink::StorageKey& storage_key) override { + return false; + } }; } // namespace @@ -251,8 +260,10 @@ class BlobUrlDevToolsIssueTest : public ContentBrowserTest { protected: BlobUrlDevToolsIssueTest() { - feature_list_.InitAndEnableFeature( - features::kBlockCrossPartitionBlobUrlFetching); + feature_list_.InitWithFeatures( + {features::kBlockCrossPartitionBlobUrlFetching, + blink::features::kEnforceNoopenerOnBlobURLNavigation}, + {}); } void SetUpOnMainThread() override { @@ -260,8 +271,11 @@ host_resolver()->AddRule("*", "127.0.0.1"); SetupCrossSiteRedirector(embedded_test_server()); ASSERT_TRUE(embedded_test_server()->Start()); + client_ = std::make_unique<MockContentBrowserClient>(); } + void TearDownOnMainThread() override { client_.reset(); } + void WaitForIssueAndCheckUrl(const std::string& url, TestDevToolsProtocolClient* client, const std::string& expected_info_enum) { @@ -300,7 +314,11 @@ client->ClearNotifications(); } + private: base::test::ScopedFeatureList feature_list_; + + private: + std::unique_ptr<MockContentBrowserClient> client_; }; IN_PROC_BROWSER_TEST_F(BlobUrlDevToolsIssueTest, PartitioningBlobUrlIssue) { @@ -324,6 +342,12 @@ RenderFrameHost* rfh_b = ChildFrameAt(rfh_c, 0); RenderFrameHost* rfh_c_2 = ChildFrameAt(rfh_b, 0); + static_cast<PermissionControllerImpl*>( + rfh_c_2->GetBrowserContext()->GetPermissionController()) + ->SetPermissionOverride(/*origin=*/std::nullopt, + blink::PermissionType::STORAGE_ACCESS_GRANT, + blink::mojom::PermissionStatus::DENIED); + std::unique_ptr<content::TestDevToolsProtocolClient> client = std::make_unique<content::TestDevToolsProtocolClient>(); client->AttachToFrameTreeHost(rfh_c_2);
diff --git a/content/browser/btm/btm_page_visit_observer.cc b/content/browser/btm/btm_page_visit_observer.cc index 65f00f5..fbd5e01 100644 --- a/content/browser/btm/btm_page_visit_observer.cc +++ b/content/browser/btm/btm_page_visit_observer.cc
@@ -212,6 +212,17 @@ return; } + // Attribute accesses by iframes and other subresources to the first-party + // page they're embedded in. + const GURL& first_party_url = GetFirstPartyURL(*render_frame_host); + + // BTM is only turned on when non-CHIPS 3PCs are blocked, so mirror that + // behavior by ignoring non-CHIPS 3PC accesses. + if (!HasCHIPS(details.cookie_access_result_list) && + !IsSameSiteForBtm(first_party_url, details.url)) { + return; + } + // Check to see if this is a late report for a redirect. Only Navigation // cookie accesses should be attributed to redirects. // @@ -237,10 +248,8 @@ // If the cookie was accessed by a subresource request in a now-bfcached // page, try to find that page's visit. - const GURL& page_url = - render_frame_host->GetMainFrame()->GetLastCommittedURL(); for (VisitTuple& visit : pending_visits_) { - if (page_url == visit.prev_page.url) { + if (first_party_url == visit.prev_page.url) { visit.prev_page.had_qualifying_storage_access = true; return; } @@ -257,8 +266,17 @@ return; } - if (!navigation_handle->IsInMainFrame()) { - // Subframe navigation + bool is_subframe_navigation = !navigation_handle->IsInMainFrame(); + if (is_subframe_navigation) { + const GURL& first_party_url = GetFirstPartyURL(*navigation_handle); + // BTM is only turned on when non-CHIPS 3PCs are blocked, so mirror that + // behavior by ignoring non-CHIPS 3PC accesses. + if (!HasCHIPS(details.cookie_access_result_list) && + !IsSameSiteForBtm(first_party_url, details.url)) { + return; + } + + // Attribute subframe storage accesses to the top-level page. current_page_.had_qualifying_storage_access = true; return; }
diff --git a/content/browser/btm/btm_page_visit_observer_browsertest.cc b/content/browser/btm/btm_page_visit_observer_browsertest.cc index 77970294..bea18d8 100644 --- a/content/browser/btm/btm_page_visit_observer_browsertest.cc +++ b/content/browser/btm/btm_page_visit_observer_browsertest.cc
@@ -7,6 +7,7 @@ #include "base/feature_list.h" #include "base/test/simple_test_clock.h" #include "components/ukm/content/source_url_recorder.h" +#include "content/browser/btm/btm_browsertest_utils.h" #include "content/browser/btm/btm_page_visit_observer_test_utils.h" #include "content/browser/btm/btm_test_utils.h" #include "content/browser/btm/btm_utils.h" @@ -590,20 +591,40 @@ IframeNavigationCookie) { const GURL url1 = embedded_https_test_server().GetURL( "a.test", "/page_with_blank_iframe.html"); - const GURL url2 = - embedded_https_test_server().GetURL("b.test", "/empty.html"); - const GURL url3 = - embedded_https_test_server().GetURL("c.test", "/empty.html"); + const GURL url2 = embedded_https_test_server().GetURL( + "b.test", "/page_with_blank_iframe.html"); + const GURL url3 = embedded_https_test_server().GetURL( + "c.test", "/page_with_blank_iframe.html"); + const GURL url4 = + embedded_https_test_server().GetURL("d.test", "/empty.html"); WebContents* web_contents = shell()->web_contents(); BtmPageVisitRecorder recorder(web_contents); + // End index-0 page visit; start index-1 page visit. ASSERT_TRUE(NavigateToURL(web_contents, url1)); - ASSERT_TRUE(NavigateIframeToURL( - web_contents, "test_iframe", - embedded_https_test_server().GetURL("a.test", "/set-cookie?foo=bar"))); + const GURL iframe_1p_cookie_url = embedded_https_test_server().GetURL( + url1.host_piece(), "/set-cookie?foo=bar"); + ASSERT_TRUE( + NavigateIframeToURL(web_contents, "test_iframe", iframe_1p_cookie_url)); + // End index-1 page visit; start index-2 page visit. ASSERT_TRUE(NavigateToURL(web_contents, url2)); + const GURL iframe_3p_unpartitioned_cookie_url = + embedded_https_test_server().GetURL( + "a.test", "/set-cookie?bar=baz;SameSite=None;Secure;"); + ASSERT_TRUE(NavigateIframeToURL(web_contents, "test_iframe", + iframe_3p_unpartitioned_cookie_url)); + // End index-2 page visit; start index-3 page visit. ASSERT_TRUE(NavigateToURL(web_contents, url3)); - ASSERT_TRUE(recorder.WaitForSize(3)); + const GURL iframe_3p_partitioned_cookie_url = + embedded_https_test_server().GetURL( + "a.test", + "/set-cookie?__Host-baz=quux;SameSite=None;Secure;Path=/" + ";Partitioned;"); + ASSERT_TRUE(NavigateIframeToURL(web_contents, "test_iframe", + iframe_3p_partitioned_cookie_url)); + // End index-3 page visit. + ASSERT_TRUE(NavigateToURL(web_contents, url4)); + ASSERT_TRUE(recorder.WaitForSize(4)); const BtmPageVisitObserver::VisitTuple& first_visit = recorder.visits()[0]; EXPECT_THAT(first_visit.prev_page, HasUrlAndSourceIdForBlankPage()); @@ -613,43 +634,88 @@ const BtmPageVisitObserver::VisitTuple& second_visit = recorder.visits()[1]; EXPECT_THAT(second_visit.prev_page, HasUrlAndMatchingSourceId(url1, &ukm_recorder())); + // 1P cookie accesses in iframes should be reported. EXPECT_TRUE(second_visit.prev_page.had_qualifying_storage_access); EXPECT_EQ(second_visit.url, url2); const BtmPageVisitObserver::VisitTuple& third_visit = recorder.visits()[2]; EXPECT_THAT(third_visit.prev_page, HasUrlAndMatchingSourceId(url2, &ukm_recorder())); + // Non-CHIPS 3P cookie accesses in iframes should be ignored. EXPECT_FALSE(third_visit.prev_page.had_qualifying_storage_access); EXPECT_EQ(third_visit.url, url3); - EXPECT_EQ(recorder.visits().size(), 3u); + const BtmPageVisitObserver::VisitTuple& fourth_visit = recorder.visits()[3]; + EXPECT_THAT(fourth_visit.prev_page, + HasUrlAndMatchingSourceId(url3, &ukm_recorder())); + // CHIPS 3P cookie accesses in iframes should be reported. + EXPECT_TRUE(fourth_visit.prev_page.had_qualifying_storage_access); + EXPECT_EQ(fourth_visit.url, url4); + + EXPECT_EQ(recorder.visits().size(), 4u); } IN_PROC_BROWSER_TEST_F(BtmPageVisitObserverBrowserTest, IframeDocumentCookie) { const GURL url1 = embedded_https_test_server().GetURL("a.test", "/page_with_iframe.html"); - const GURL url2 = - embedded_https_test_server().GetURL("b.test", "/empty.html"); - const GURL url3 = - embedded_https_test_server().GetURL("c.test", "/empty.html"); + const GURL url2 = embedded_https_test_server().GetURL( + "b.test", "/page_with_blank_iframe.html"); + const GURL url3 = embedded_https_test_server().GetURL( + "c.test", "/page_with_blank_iframe.html"); + const GURL url4 = + embedded_https_test_server().GetURL("d.test", "/empty.html"); WebContents* web_contents = shell()->web_contents(); BtmPageVisitRecorder recorder(web_contents); + // If the bfcache is disabled, we often don't receive cookie access + // notifications unless we wait for them before navigating away. If the + // bfcache *is* enabled, we *don't* want to wait — part of the point of this + // test is to make sure we properly handle late notifications. + bool should_await_cookie_access_notifications = + !base::FeatureList::IsEnabled(features::kBackForwardCache); + // End index-0 page visit; start index-1 page visit. ASSERT_TRUE(NavigateToURL(web_contents, url1)); - RenderFrameHost* iframe = ChildFrameAt(web_contents, 0); - FrameCookieAccessObserver cookie_observer(web_contents, iframe, - CookieOperation::kChange); - ASSERT_TRUE(ExecJs(iframe, "document.cookie = 'foo=bar';")); - if (!base::FeatureList::IsEnabled(features::kBackForwardCache)) { - // If the bfcache is disabled, we often don't receive the cookie - // notification unless we wait for it before navigating away. (If the - // bfcache *is* enabled, we *don't* want to wait -- that's part of the point - // of this test.) - cookie_observer.Wait(); + RenderFrameHost* iframe1 = ChildFrameAt(web_contents, 0); + FrameCookieAccessObserver cookie_observer1(web_contents, iframe1, + CookieOperation::kChange); + ASSERT_TRUE(ExecJs(iframe1, "document.cookie = '1PC=1';")); + if (should_await_cookie_access_notifications) { + cookie_observer1.Wait(); } + // End index-1 page visit; start index-2 page visit. ASSERT_TRUE(NavigateToURL(web_contents, url2)); + RenderFrameHost* iframe2 = ChildFrameAt(web_contents, 0); + ASSERT_TRUE(NavigateIframeToURL( + web_contents, "test_iframe", + embedded_https_test_server().GetURL("d.test", "/title1.html"))); + iframe2 = ChildFrameAt(web_contents, 0); + FrameCookieAccessObserver cookie_observer2(web_contents, iframe2, + CookieOperation::kChange); + ASSERT_TRUE( + ExecJs(iframe2, + "document.cookie = " + "'__Host-CHIPS_3PC=1;SameSite=None;Secure;Path=/;Partitioned;';")); + if (should_await_cookie_access_notifications) { + cookie_observer2.Wait(); + } + // End index-2 page visit; start index-3 page visit. ASSERT_TRUE(NavigateToURL(web_contents, url3)); - ASSERT_TRUE(recorder.WaitForSize(3)); + RenderFrameHost* iframe3 = ChildFrameAt(web_contents, 0); + ASSERT_TRUE(NavigateIframeToURL( + web_contents, "test_iframe", + embedded_https_test_server().GetURL("d.test", "/title1.html"))); + iframe3 = ChildFrameAt(web_contents, 0); + FrameCookieAccessObserver cookie_observer3(web_contents, iframe3, + CookieOperation::kChange); + ASSERT_TRUE(ExecJs( + iframe3, + "document.cookie = 'unpartitioned_3PC=1;SameSite=None;Secure;Path=/;';")); + if (should_await_cookie_access_notifications) { + cookie_observer3.Wait(); + } + // End index-3 page visit. + ASSERT_TRUE(NavigateToURL(web_contents, url4)); + ASSERT_TRUE(recorder.WaitForSize(4)); const BtmPageVisitObserver::VisitTuple& first_visit = recorder.visits()[0]; EXPECT_THAT(first_visit.prev_page, HasUrlAndSourceIdForBlankPage()); @@ -659,16 +725,25 @@ const BtmPageVisitObserver::VisitTuple& second_visit = recorder.visits()[1]; EXPECT_THAT(second_visit.prev_page, HasUrlAndMatchingSourceId(url1, &ukm_recorder())); + // Iframe 1P cookie accesses should be reported. EXPECT_TRUE(second_visit.prev_page.had_qualifying_storage_access); EXPECT_EQ(second_visit.url, url2); const BtmPageVisitObserver::VisitTuple& third_visit = recorder.visits()[2]; EXPECT_THAT(third_visit.prev_page, HasUrlAndMatchingSourceId(url2, &ukm_recorder())); - EXPECT_FALSE(third_visit.prev_page.had_qualifying_storage_access); + // CHIPS 3PC accesses should be reported. + EXPECT_TRUE(third_visit.prev_page.had_qualifying_storage_access); EXPECT_EQ(third_visit.url, url3); - EXPECT_EQ(recorder.visits().size(), 3u); + const BtmPageVisitObserver::VisitTuple& fourth_visit = recorder.visits()[3]; + EXPECT_THAT(fourth_visit.prev_page, + HasUrlAndMatchingSourceId(url3, &ukm_recorder())); + // Non-CHIPS 3PC accesses should be ignored. + EXPECT_FALSE(fourth_visit.prev_page.had_qualifying_storage_access); + EXPECT_EQ(fourth_visit.url, url4); + + EXPECT_EQ(recorder.visits().size(), 4u); } IN_PROC_BROWSER_TEST_F(BtmPageVisitObserverBrowserTest,
diff --git a/content/browser/gpu/gpu_data_manager_impl_private.cc b/content/browser/gpu/gpu_data_manager_impl_private.cc index 0b61969..6706651 100644 --- a/content/browser/gpu/gpu_data_manager_impl_private.cc +++ b/content/browser/gpu/gpu_data_manager_impl_private.cc
@@ -1315,7 +1315,10 @@ use_gl = browser_command_line->GetSwitchValueASCII(switches::kUseGL); break; case gpu::GpuMode::SOFTWARE_GL: - gl::SetSoftwareWebGLCommandLineSwitches(command_line); + if (!gl::HasRequestedSoftwareGLImplementationFromCommandLine( + command_line)) { + gl::SetSoftwareWebGLCommandLineSwitches(command_line); + } break; default: use_gl = gl::kGLImplementationDisabledName;
diff --git a/content/browser/interest_group/auction_runner_unittest.cc b/content/browser/interest_group/auction_runner_unittest.cc index 91db5269..ff497dd 100644 --- a/content/browser/interest_group/auction_runner_unittest.cc +++ b/content/browser/interest_group/auction_runner_unittest.cc
@@ -24943,6 +24943,66 @@ EXPECT_THAT(result_.errors, testing::ElementsAre()); } +// No non-k-anon winner is sometimes possible with targetNumAdComponents +// See https://crbug.com/367302752 +TEST_P(AuctionRunnerKAnonTest, NoNonKAnonWinner2) { + if (kanon_mode() != KAnonMode::kEnforce) { + return; + } + + std::vector<StorageInterestGroup> bidders; + bidders.emplace_back(MakeInterestGroup( + kBidder1, kBidder1Name, kBidder1Url, + /*trusted_bidding_signals_url=*/std::nullopt, + /*trusted_bidding_signals_keys=*/{}, GURL("https://ad1.com"), + std::make_optional(std::vector<GURL>( + {GURL("https://ad1.com/1"), GURL("https://ad1.com/2")})))); + + const char kGenerateBidScript[] = R"( + function generateBid(interestGroup, auctionSignals, perBuyerSignals, + trustedBiddingSignals, browserSignals) { + return { + bid: 5, + render: {url: "https://ad1.com/"}, + adComponents: [ + "https://ad1.com/1", + "https://ad1.com/2", + ], + targetNumAdComponents: 1 + }; + } + )"; + + const char kScoreAdScript[] = R"( + function scoreAd(adMetadata, bid, auctionConfig, trustedScoringSignals, + browserSignals) { + if (browserSignals.adComponents[0] === 'https://ad1.com/1') { + return -1; + } + return {desirability: bid, + allowComponentAuction: true, + ad: adMetadata}; + } + )"; + + auction_worklet::AddJavascriptResponse( + &url_loader_factory_, kBidder1Url, + std::string(kGenerateBidScript) + kSimpleReportWin); + auction_worklet::AddJavascriptResponse( + &url_loader_factory_, kSellerUrl, + std::string(kScoreAdScript) + kBasicReportResult); + + // Don't authorize the first ad component, but do authorize others. + AuthorizeKAnonAd(bidders[0].interest_group.ads.value()[0], "https://ad1.com/", + bidders[0]); + AuthorizeKAnonAdComponent(bidders[0].interest_group.ad_components.value()[1], + "https://ad1.com/2", bidders[0]); + + StartAuction(kSellerUrl, bidders); + auction_run_loop_->Run(); + EXPECT_THAT(result_.errors, testing::ElementsAre()); +} + // Test where the k-anon ad has a higher bid. TEST_P(AuctionRunnerKAnonTest, KAnonHigher) { auction_worklet::AddJavascriptResponse(
diff --git a/content/browser/interest_group/interest_group_auction.cc b/content/browser/interest_group/interest_group_auction.cc index b4bb498..22ffe43 100644 --- a/content/browser/interest_group/interest_group_auction.cc +++ b/content/browser/interest_group/interest_group_auction.cc
@@ -3534,7 +3534,6 @@ DCHECK(!load_interest_groups_phase_callback_); DCHECK(!bidding_and_scoring_phase_callback_); DCHECK_EQ(*final_auction_result_, AuctionResult::kSuccess); - DCHECK(non_kanon_enforced_auction_leader_.top_bid); // This should only be called on top-level auctions. DCHECK(!parent_);
diff --git a/content/browser/network/split_cache_browsertest.cc b/content/browser/network/split_cache_browsertest.cc index 2a55af0..c1b78bf 100644 --- a/content/browser/network/split_cache_browsertest.cc +++ b/content/browser/network/split_cache_browsertest.cc
@@ -473,30 +473,6 @@ } }); -class SplitCacheContentBrowserTestPlzDedicatedWorker - : public SplitCacheContentBrowserTest, - public ::testing::WithParamInterface<bool> { - public: - SplitCacheContentBrowserTestPlzDedicatedWorker() { - std::vector<base::test::FeatureRef> enabled_features; - std::vector<base::test::FeatureRef> disabled_features; - enabled_features.push_back(net::features::kSplitCacheByNetworkIsolationKey); - - // When the test parameter is true, we test the split cache with - // PlzDedicatedWorker enabled. - if (GetParam()) { - enabled_features.push_back(blink::features::kPlzDedicatedWorker); - } else { - disabled_features.push_back(blink::features::kPlzDedicatedWorker); - } - - feature_list_.InitWithFeatures(enabled_features, disabled_features); - } - - private: - base::test::ScopedFeatureList feature_list_; -}; - class SplitCacheContentBrowserTestDisabled : public SplitCacheContentBrowserTest { public: @@ -989,7 +965,7 @@ EXPECT_EQ(size1, size2); } -IN_PROC_BROWSER_TEST_P(SplitCacheContentBrowserTestPlzDedicatedWorker, +IN_PROC_BROWSER_TEST_P(SplitCacheContentBrowserTestEnabled, DedicatedWorkers) { // Load 3p.com/script from a.com's worker. The first time it's loaded from the // network and the second it's cached. @@ -1035,7 +1011,7 @@ // https://crbug.com/1218723 started flaking after Field Trial Testing Config // was enabled for content_browsertests. -IN_PROC_BROWSER_TEST_P(SplitCacheContentBrowserTestPlzDedicatedWorker, +IN_PROC_BROWSER_TEST_P(SplitCacheContentBrowserTestEnabled, DISABLED_DedicatedWorkersScripts) { // Load a.com's worker. The first time the worker script is loaded from the // network and the second it's cached. @@ -1105,10 +1081,6 @@ GenURL("e.com", "/worker.js"))); } -INSTANTIATE_TEST_SUITE_P(All, - SplitCacheContentBrowserTestPlzDedicatedWorker, - ::testing::Values(true, false)); - class SplitCacheByIncludeCredentialsTest : public ContentBrowserTest { public: SplitCacheByIncludeCredentialsTest()
diff --git a/content/browser/network_service_client.cc b/content/browser/network_service_client.cc index 495d198..a4bf27df 100644 --- a/content/browser/network_service_client.cc +++ b/content/browser/network_service_client.cc
@@ -308,6 +308,11 @@ std::move(callback).Run(false); } +void NetworkServiceClient::OnLocalNetworkAccessPermissionRequired( + OnLocalNetworkAccessPermissionRequiredCallback callback) { + std::move(callback).Run(false); +} + void NetworkServiceClient::OnClearSiteData( const GURL& url, const std::string& header_value,
diff --git a/content/browser/network_service_client.h b/content/browser/network_service_client.h index 687a327a..403c45c 100644 --- a/content/browser/network_service_client.h +++ b/content/browser/network_service_client.h
@@ -114,6 +114,8 @@ const std::optional<std::string>& private_network_device_id, const std::optional<std::string>& private_network_device_name, OnPrivateNetworkAccessPermissionRequiredCallback callback) override; + void OnLocalNetworkAccessPermissionRequired( + OnLocalNetworkAccessPermissionRequiredCallback callback) override; void OnClearSiteData( const GURL& url, const std::string& header_value,
diff --git a/content/browser/network_service_restart_browsertest.cc b/content/browser/network_service_restart_browsertest.cc index 005e283..860f636 100644 --- a/content/browser/network_service_restart_browsertest.cc +++ b/content/browser/network_service_restart_browsertest.cc
@@ -651,34 +651,8 @@ EXPECT_EQ(last_request_relative_url(), "/title2.html"); } -// Run tests with PlzDedicatedWorker. -// TODO(crbug.com/40093136): Merge this test fixture into -// NetworkServiceRestartBrowserTest once PlzDedicatedWorker is enabled by -// default. -class NetworkServiceRestartForWorkerBrowserTest - : public NetworkServiceRestartBrowserTest, - public ::testing::WithParamInterface<bool> { - public: - NetworkServiceRestartForWorkerBrowserTest() { - if (GetParam()) { - scoped_feature_list_.InitAndEnableFeature( - blink::features::kPlzDedicatedWorker); - } else { - scoped_feature_list_.InitAndDisableFeature( - blink::features::kPlzDedicatedWorker); - } - } - - private: - base::test::ScopedFeatureList scoped_feature_list_; -}; - -INSTANTIATE_TEST_SUITE_P(All, - NetworkServiceRestartForWorkerBrowserTest, - ::testing::Values(false, true)); - // Make sure worker fetch works after crash. -IN_PROC_BROWSER_TEST_P(NetworkServiceRestartForWorkerBrowserTest, WorkerFetch) { +IN_PROC_BROWSER_TEST_F(NetworkServiceRestartBrowserTest, WorkerFetch) { if (IsInProcessNetworkService()) return; StoragePartitionImpl* partition = static_cast<StoragePartitionImpl*>( @@ -704,7 +678,7 @@ } // Make sure multiple workers are tracked correctly and work after crash. -IN_PROC_BROWSER_TEST_P(NetworkServiceRestartForWorkerBrowserTest, +IN_PROC_BROWSER_TEST_F(NetworkServiceRestartBrowserTest, MultipleWorkerFetch) { if (IsInProcessNetworkService()) return;
diff --git a/content/browser/renderer_host/cookie_browsertest.cc b/content/browser/renderer_host/cookie_browsertest.cc index f8311643..464daa4 100644 --- a/content/browser/renderer_host/cookie_browsertest.cc +++ b/content/browser/renderer_host/cookie_browsertest.cc
@@ -416,12 +416,13 @@ const url::Origin& top_frame_origin, net::StorageAccessApiStatus storage_access_api_status, bool get_version_shared_memory, + bool is_ad_tagged, bool apply_devtools_overrides, const std::string& cookie, SetCookieFromStringCallback callback) override { GetForwardingInterface()->SetCookieFromString( URLToUse(url), site_for_cookies, top_frame_origin, - storage_access_api_status, get_version_shared_memory, + storage_access_api_status, get_version_shared_memory, is_ad_tagged, apply_devtools_overrides, std::move(cookie), std::move(callback)); }
diff --git a/content/browser/renderer_host/render_frame_host_impl.cc b/content/browser/renderer_host/render_frame_host_impl.cc index bcc57e2..7b63583 100644 --- a/content/browser/renderer_host/render_frame_host_impl.cc +++ b/content/browser/renderer_host/render_frame_host_impl.cc
@@ -156,6 +156,7 @@ #include "content/browser/site_info.h" #include "content/browser/sms/webotp_service.h" #include "content/browser/speech/speech_synthesis_impl.h" +#include "content/browser/storage_access/storage_access_handle.h" #include "content/browser/storage_partition_impl.h" #include "content/browser/url_loader_factory_params_helper.h" #include "content/browser/usb/web_usb_service_impl.h" @@ -12666,6 +12667,12 @@ std::move(details))); } +void RenderFrameHostImpl::DoesDocumentHaveStorageAccess( + base::OnceCallback<void(bool)> callback) { + std::move(callback).Run( + StorageAccessHandle::DoesFrameHaveStorageAccess(this)); +} + void RenderFrameHostImpl::BindBlobUrlStoreAssociatedReceiver( mojo::PendingAssociatedReceiver<blink::mojom::BlobURLStore> receiver) { DCHECK_CURRENTLY_ON(BrowserThread::UI); @@ -12677,6 +12684,8 @@ base::BindRepeating( &RenderFrameHostImpl::ReportBlockingCrossPartitionBlobURL, weak_ptr_factory_.GetWeakPtr()), + base::BindRepeating(&RenderFrameHostImpl::DoesDocumentHaveStorageAccess, + weak_ptr_factory_.GetWeakPtr()), !(GetContentClient()->browser()->IsBlobUrlPartitioningEnabled( GetBrowserContext()))); }
diff --git a/content/browser/renderer_host/render_frame_host_impl.h b/content/browser/renderer_host/render_frame_host_impl.h index 3f427c85..34213d9 100644 --- a/content/browser/renderer_host/render_frame_host_impl.h +++ b/content/browser/renderer_host/render_frame_host_impl.h
@@ -4277,6 +4277,10 @@ const GURL& blocked_url, std::optional<blink::mojom::PartitioningBlobURLInfo> info); + // This runs when fetches to cross-partition, same-origin Blob URL checks for + // storage access + void DoesDocumentHaveStorageAccess(base::OnceCallback<void(bool)> callback); + // For frames and main thread worklets we use a navigation-associated // interface and bind `receiver` to a `BlobURLStore` instance, which // implements the Blob URL API in the browser process.
diff --git a/content/browser/storage_access/storage_access_handle.cc b/content/browser/storage_access/storage_access_handle.cc index 44179b2..aaccfe8 100644 --- a/content/browser/storage_access/storage_access_handle.cc +++ b/content/browser/storage_access/storage_access_handle.cc
@@ -173,12 +173,23 @@ static_cast<RenderFrameHostImpl&>(render_frame_host()) .GetStoragePartition() ->GetBlobUrlRegistry() - ->AddReceiver(blink::StorageKey::CreateFirstParty( - render_frame_host().GetStorageKey().origin()), - render_frame_host().GetLastCommittedOrigin(), - render_frame_host().GetProcess()->GetDeprecatedID(), - std::move(receiver), base::DoNothing(), - /*partitioning_disabled_by_policy=*/false); + ->AddReceiver( + blink::StorageKey::CreateFirstParty( + render_frame_host().GetStorageKey().origin()), + render_frame_host().GetLastCommittedOrigin(), + render_frame_host().GetProcess()->GetDeprecatedID(), + std::move(receiver), + /*partitioning_blob_url_closure=*/base::DoNothing(), + // In the case that a context is granted storage access, the + // StorageAccessHandle context still shouldn't bypass partitioning + // check. (eg. using a Blob URL created with URL.createObjectURL in + // the third-party context with the StorageAccessHandle's SharedWorker + // constructor.) + /*storage_access_check_callback= */ + base::BindRepeating([](base::OnceCallback<void(bool)> callback) { + std::move(callback).Run(false); + }), + /*partitioning_disabled_by_policy=*/false); } void StorageAccessHandle::BindBroadcastChannel(
diff --git a/content/browser/storage_partition_impl.cc b/content/browser/storage_partition_impl.cc index 214fbcc..861d6c3 100644 --- a/content/browser/storage_partition_impl.cc +++ b/content/browser/storage_partition_impl.cc
@@ -2208,6 +2208,71 @@ std::move(callback)); } +void StoragePartitionImpl::OnLocalNetworkAccessPermissionRequired( + OnLocalNetworkAccessPermissionRequiredCallback callback) { + if (!base::FeatureList::IsEnabled( + network::features::kLocalNetworkAccessChecks) && + !network::features::kLocalNetworkAccessChecksWarn.Get()) { + // If LNA checks are not enabled, just allow the request by default. + std::move(callback).Run(true); + return; + } + + if (url_loader_network_observers_.empty()) { + std::move(callback).Run(false); + return; + } + const URLLoaderNetworkContext& context = + url_loader_network_observers_.current_context(); + + // Currently requesting the Local Network Access permission is restricted to + // document contexts (subresource requests). + // TODO(crbug.com/404887282): Add support for allowing requests from workers + // if the user has previously granted the permission. + // TODO(crbug.com/404887285): Add support for having subframe navigation + // requests query and trigger the permission prompt. + if (context.type() != ContextType::kRenderFrameHostContext || + !context.navigation_or_document()) { + std::move(callback).Run(false); + return; + } + RenderFrameHost* rfh = context.navigation_or_document()->GetDocument(); + if (!rfh) { + std::move(callback).Run(false); + return; + } + + PermissionController* permission_controller = + browser_context_->GetPermissionController(); + DCHECK(permission_controller); + + auto status = permission_controller->GetPermissionStatusForCurrentDocument( + blink::PermissionType::LOCAL_NETWORK_ACCESS, rfh); + if (status == blink::mojom::PermissionStatus::GRANTED) { + std::move(callback).Run(true); + return; + } else if (status == blink::mojom::PermissionStatus::DENIED) { + std::move(callback).Run(false); + return; + } else { + // PermissionStatus is ASK, so request the permission. Converts the result + // into a boolean to pass back to `callback`, capturing whether the + // permission is granted or not. + permission_controller->RequestPermissionFromCurrentDocument( + rfh, + PermissionRequestDescription( + blink::PermissionType::LOCAL_NETWORK_ACCESS), + base::BindOnce( + [](OnLocalNetworkAccessPermissionRequiredCallback cb, + PermissionStatus status) { + std::move(cb).Run(status == + blink::mojom::PermissionStatus::GRANTED); + }, + std::move(callback))); + return; + } +} + void StoragePartitionImpl::OnCertificateRequested( const std::optional<base::UnguessableToken>& window_id, const scoped_refptr<net::SSLCertRequestInfo>& cert_info,
diff --git a/content/browser/storage_partition_impl.h b/content/browser/storage_partition_impl.h index c6d539d..72fc2482 100644 --- a/content/browser/storage_partition_impl.h +++ b/content/browser/storage_partition_impl.h
@@ -380,6 +380,8 @@ const std::optional<std::string>& private_network_device_id, const std::optional<std::string>& private_network_device_name, OnPrivateNetworkAccessPermissionRequiredCallback callback) override; + void OnLocalNetworkAccessPermissionRequired( + OnLocalNetworkAccessPermissionRequiredCallback callback) override; void OnClearSiteData( const GURL& url, const std::string& header_value,
diff --git a/content/browser/storage_partition_impl_unittest.cc b/content/browser/storage_partition_impl_unittest.cc index d282f64..63931e9 100644 --- a/content/browser/storage_partition_impl_unittest.cc +++ b/content/browser/storage_partition_impl_unittest.cc
@@ -2463,6 +2463,23 @@ EXPECT_FALSE(grant_permission.Get()); } +TEST_F(StoragePartitionImplTest, LocalNetworkAccessPermission) { + base::test::ScopedFeatureList features( + network::features::kLocalNetworkAccessChecks); + + StoragePartitionImpl* partition = static_cast<StoragePartitionImpl*>( + browser_context()->GetDefaultStoragePartition()); + + mojo::Remote<network::mojom::URLLoaderNetworkServiceObserver> observer( + partition->CreateAuthCertObserverForServiceWorker( + network::mojom::kBrowserProcessId)); + + base::test::TestFuture<bool> grant_permission; + observer->OnLocalNetworkAccessPermissionRequired( + base::BindOnce(grant_permission.GetCallback())); + EXPECT_FALSE(grant_permission.Get()); +} + TEST_F(StoragePartitionImplTest, ClearDataStorageKeyDeletesPartitionedCookies) { StoragePartitionImpl* partition = static_cast<StoragePartitionImpl*>( browser_context()->GetDefaultStoragePartition());
diff --git a/content/browser/tracing/background_tracing_manager_impl.cc b/content/browser/tracing/background_tracing_manager_impl.cc index b0f19d2..c36eda4 100644 --- a/content/browser/tracing/background_tracing_manager_impl.cc +++ b/content/browser/tracing/background_tracing_manager_impl.cc
@@ -564,6 +564,7 @@ (data_filtering == ANONYMIZE_DATA_AND_FILTER_PACKAGE_NAME); std::vector<std::string> added_scenarios; + std::set<raw_ptr<TracingScenario>> conflicting_scenarios; for (const auto& scenario_config : config.scenarios()) { auto scenario = TracingScenario::Create( scenario_config, enable_privacy_filter, /*is_local_scenario=*/true, @@ -576,14 +577,23 @@ it != preset_scenarios_.end()) { if (active_scenario_ == it->second.get()) { active_scenario_->Abort(); - } else { + conflicting_scenarios.insert(it->second.get()); + } else if (it->second->current_state() != + TracingScenario::State::kDisabled) { it->second->Disable(); + conflicting_scenarios.insert(it->second.get()); } } added_scenarios.push_back(scenario->scenario_name()); preset_scenarios_[scenario->scenario_name()] = std::move(scenario); } + if (!conflicting_scenarios.empty()) { + std::erase_if(enabled_scenarios_, [&](raw_ptr<TracingScenario> scenario) { + return conflicting_scenarios.contains(scenario); + }); + } + return added_scenarios; }
diff --git a/content/browser/webui/web_ui_browsertest.cc b/content/browser/webui/web_ui_browsertest.cc index ae38291..d0c3fcf 100644 --- a/content/browser/webui/web_ui_browsertest.cc +++ b/content/browser/webui/web_ui_browsertest.cc
@@ -16,7 +16,6 @@ #include "base/strings/strcat.h" #include "base/strings/utf_string_conversions.h" #include "base/test/bind.h" -#include "base/test/scoped_feature_list.h" #include "base/test/simple_test_tick_clock.h" #include "base/time/time.h" #include "build/build_config.h" @@ -52,7 +51,6 @@ #include "content/shell/browser/shell.h" #include "content/test/content_browser_test_utils_internal.h" #include "testing/gmock/include/gmock/gmock-matchers.h" -#include "third_party/blink/public/common/features.h" #include "third_party/blink/public/common/input/web_mouse_event.h" #include "third_party/blink/public/common/input/web_mouse_wheel_event.h" #include "ui/events/base_event_utils.h" @@ -1101,23 +1099,6 @@ &factory_}; }; -class WebUIDedicatedWorkerTest : public WebUIWorkerTest, - public testing::WithParamInterface<bool> { - public: - WebUIDedicatedWorkerTest() { - if (GetParam()) { - feature_list_.InitAndEnableFeature(blink::features::kPlzDedicatedWorker); - } else { - feature_list_.InitAndDisableFeature(blink::features::kPlzDedicatedWorker); - } - } - - private: - base::test::ScopedFeatureList feature_list_; -}; - -INSTANTIATE_TEST_SUITE_P(All, WebUIDedicatedWorkerTest, testing::Bool()); - // TODO(crbug.com/40290702): Shared workers are not available on Android. #if !BUILDFLAG(IS_ANDROID) // Verify that we can create SharedWorker with scheme "chrome://" under @@ -1262,7 +1243,7 @@ #endif // !BUILDFLAG(IS_ANDROID) // Verify that we can create a Worker with scheme "chrome://" under WebUI page. -IN_PROC_BROWSER_TEST_P(WebUIDedicatedWorkerTest, +IN_PROC_BROWSER_TEST_F(WebUIWorkerTest, CanCreateWebUIDedicatedWorkerForWebUI) { ASSERT_TRUE(embedded_test_server()->Start()); EXPECT_EQ(true, @@ -1274,7 +1255,7 @@ // Verify that pages with scheme other than "chrome://" cannot create a Worker // with scheme "chrome://". -IN_PROC_BROWSER_TEST_P(WebUIDedicatedWorkerTest, +IN_PROC_BROWSER_TEST_F(WebUIWorkerTest, CannotCreateWebUIDedicatedWorkerForNonWebUI) { ASSERT_TRUE(embedded_test_server()->Start()); EvalJsResult result = RunWorkerTest( @@ -1288,7 +1269,7 @@ } // Test that we can start a Worker from a chrome-untrusted:// iframe. -IN_PROC_BROWSER_TEST_P(WebUIDedicatedWorkerTest, +IN_PROC_BROWSER_TEST_F(WebUIWorkerTest, CanCreateDedicatedWorkerFromUntrustedIframe) { ASSERT_TRUE(embedded_test_server()->Start()); auto* web_contents = shell()->web_contents(); @@ -1330,8 +1311,8 @@ } // Test that we can create a Worker from a chrome-untrusted:// main frame. -IN_PROC_BROWSER_TEST_P( - WebUIDedicatedWorkerTest, +IN_PROC_BROWSER_TEST_F( + WebUIWorkerTest, CanCreateUntrustedWebUIDedicatedWorkerForUntrustedWebUI) { ASSERT_TRUE(embedded_test_server()->Start()); SetUntrustedWorkerSrcToWebUIConfig(/*allow_embedded_frame=*/false); @@ -1345,8 +1326,8 @@ // Verify that chrome:// pages cannot create a Worker with scheme // "chrome-untrusted://". -IN_PROC_BROWSER_TEST_P( - WebUIDedicatedWorkerTest, +IN_PROC_BROWSER_TEST_F( + WebUIWorkerTest, CannotCreateUntrustedWebUIDedicatedWorkerFromTrustedWebUI) { ASSERT_TRUE(embedded_test_server()->Start()); EvalJsResult result = RunWorkerTest( @@ -1363,7 +1344,7 @@ // Verify that pages with scheme other than "chrome-untrusted://" cannot create // a Worker with scheme "chrome-untrusted://". -IN_PROC_BROWSER_TEST_P(WebUIDedicatedWorkerTest, +IN_PROC_BROWSER_TEST_F(WebUIWorkerTest, CannotCreateUntrustedWebUIDedicatedWorkerForWebURL) { ASSERT_TRUE(embedded_test_server()->Start()); EvalJsResult result = RunWorkerTest( @@ -1381,7 +1362,7 @@ // Verify that pages with scheme "chrome-untrusted://" cannot create a Worker // with scheme "chrome://". -IN_PROC_BROWSER_TEST_P(WebUIDedicatedWorkerTest, +IN_PROC_BROWSER_TEST_F(WebUIWorkerTest, CannotCreateWebUIDedicatedWorkerForUntrustedPage) { ASSERT_TRUE(embedded_test_server()->Start()); SetUntrustedWorkerSrcToWebUIConfig(/*allow_embedded_frame=*/false);
diff --git a/content/browser/worker_host/dedicated_worker_host_factory_impl.cc b/content/browser/worker_host/dedicated_worker_host_factory_impl.cc index 2ec1c9d8..c6de23d 100644 --- a/content/browser/worker_host/dedicated_worker_host_factory_impl.cc +++ b/content/browser/worker_host/dedicated_worker_host_factory_impl.cc
@@ -66,97 +66,6 @@ DedicatedWorkerHostFactoryImpl::~DedicatedWorkerHostFactoryImpl() = default; -void DedicatedWorkerHostFactoryImpl::CreateWorkerHost( - const blink::DedicatedWorkerToken& token, - const GURL& script_url, - const url::Origin& renderer_origin, - mojo::PendingReceiver<blink::mojom::BrowserInterfaceBroker> broker_receiver, - mojo::PendingReceiver<blink::mojom::DedicatedWorkerHost> host_receiver, - CreateWorkerHostCallback callback) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - // Always invoke the callback. If we don't, even if we exit with a - // mojo::ReportBadMessage, the callback will explode as it is torn down. - // Ideally we'd have a handle to our binding and we'd manually close it - // before returning, letting the callback die without being run. - DCHECK(callback); - - if (base::FeatureList::IsEnabled(blink::features::kPlzDedicatedWorker)) { - std::move(callback).Run( - creator_client_security_state_->cross_origin_embedder_policy, - /*back_forward_cache_controller_host=*/mojo::NullRemote()); - mojo::ReportBadMessage("DWH_INVALID_WORKER_CREATION"); - return; - } - - auto* policy = ChildProcessSecurityPolicyImpl::GetInstance(); - if (!policy->HostsOrigin(worker_process_id_, renderer_origin)) { - std::move(callback).Run( - creator_client_security_state_->cross_origin_embedder_policy, - /*back_forward_cache_controller_host=*/mojo::NullRemote()); - RenderFrameHostImpl* ancestor_render_frame_host = - RenderFrameHostImpl::FromID(ancestor_render_frame_host_id_); - SCOPED_CRASH_KEY_STRING32( - "", "is_primary_main_frame", - (ancestor_render_frame_host && - ancestor_render_frame_host->IsInPrimaryMainFrame()) - ? "true" - : "false"); - SCOPED_CRASH_KEY_STRING256( - "", "lifecycle_state", - ancestor_render_frame_host - ? RenderFrameHostImpl::LifecycleStateImplToString( - ancestor_render_frame_host->lifecycle_state()) - : "no_rfh"); - SCOPED_CRASH_KEY_STRING256( - "", "browser_origin", - ancestor_render_frame_host - ? ancestor_render_frame_host->GetLastCommittedOrigin() - .GetDebugString() - : ""); - SCOPED_CRASH_KEY_STRING256("", "renderer_origin", - renderer_origin.GetDebugString()); - mojo::ReportBadMessage("DWH_INVALID_ORIGIN"); - return; - } - - // Get the dedicated worker service. - auto* worker_process_host = RenderProcessHost::FromID(worker_process_id_); - auto* service = - GetDedicatedWorkerServiceImplForRenderProcessHost(worker_process_host); - if (!service) { - std::move(callback).Run( - creator_client_security_state_->cross_origin_embedder_policy, - /*back_forward_cache_controller_host=*/mojo::NullRemote()); - return; - } - - if (service->HasToken(token)) { - std::move(callback).Run( - creator_client_security_state_->cross_origin_embedder_policy, - /*back_forward_cache_controller_host=*/mojo::NullRemote()); - mojo::ReportBadMessage("DWH_INVALID_WORKER_TOKEN"); - return; - } - - network::CrossOriginEmbedderPolicy cross_origin_embedder_policy = - creator_client_security_state_->cross_origin_embedder_policy; - - auto* host = new DedicatedWorkerHost( - service, token, worker_process_host, creator_, - ancestor_render_frame_host_id_, creator_storage_key_, renderer_origin, - isolation_info_, std::move(creator_client_security_state_), - std::move(creator_coep_reporter_), std::move(ancestor_coep_reporter_), - std::move(host_receiver)); - host->BindBrowserInterfaceBrokerReceiver(std::move(broker_receiver)); - host->MaybeCountWebFeature(script_url); - - std::move(callback).Run( - cross_origin_embedder_policy, - host->BindAndPassRemoteForBackForwardCacheControllerHost()); -} - -// PlzDedicatedWorker: void DedicatedWorkerHostFactoryImpl::CreateWorkerHostAndStartScriptLoad( const blink::DedicatedWorkerToken& token, const GURL& script_url,
diff --git a/content/browser/worker_host/dedicated_worker_host_factory_impl.h b/content/browser/worker_host/dedicated_worker_host_factory_impl.h index 7da5b01..1d6f5bb 100644 --- a/content/browser/worker_host/dedicated_worker_host_factory_impl.h +++ b/content/browser/worker_host/dedicated_worker_host_factory_impl.h
@@ -52,16 +52,6 @@ ~DedicatedWorkerHostFactoryImpl() override; // blink::mojom::DedicatedWorkerHostFactory: - void CreateWorkerHost( - const blink::DedicatedWorkerToken& token, - const GURL& script_url, - const url::Origin& renderer_origin, - mojo::PendingReceiver<blink::mojom::BrowserInterfaceBroker> - broker_receiver, - mojo::PendingReceiver<blink::mojom::DedicatedWorkerHost> host_receiver, - CreateWorkerHostCallback callback) override; - - // PlzDedicatedWorker: void CreateWorkerHostAndStartScriptLoad( const blink::DedicatedWorkerToken& token, const GURL& script_url,
diff --git a/content/browser/worker_host/dedicated_worker_service_impl_unittest.cc b/content/browser/worker_host/dedicated_worker_service_impl_unittest.cc index 008fc97..6b36c859 100644 --- a/content/browser/worker_host/dedicated_worker_service_impl_unittest.cc +++ b/content/browser/worker_host/dedicated_worker_service_impl_unittest.cc
@@ -10,7 +10,6 @@ #include "base/functional/callback_helpers.h" #include "base/run_loop.h" #include "base/scoped_observation.h" -#include "base/test/scoped_feature_list.h" #include "content/browser/site_instance_impl.h" #include "content/browser/worker_host/dedicated_worker_host.h" #include "content/browser/worker_host/dedicated_worker_host_factory_impl.h" @@ -23,7 +22,6 @@ #include "net/base/isolation_info.h" #include "net/storage_access_api/status.h" #include "services/network/public/mojom/client_security_state.mojom.h" -#include "third_party/blink/public/common/features.h" #include "third_party/blink/public/common/storage_key/storage_key.h" #include "third_party/blink/public/common/tokens/tokens.h" #include "third_party/blink/public/common/tokens/tokens_mojom_traits.h" @@ -61,20 +59,13 @@ coep_reporter->GetWeakPtr(), coep_reporter->GetWeakPtr()), factory_.BindNewPipeAndPassReceiver()); - if (base::FeatureList::IsEnabled(blink::features::kPlzDedicatedWorker)) { - factory_->CreateWorkerHostAndStartScriptLoad( - blink::DedicatedWorkerToken(), - /*script_url=*/GURL(), network::mojom::CredentialsMode::kSameOrigin, - blink::mojom::FetchClientSettingsObject::New(), - mojo::PendingRemote<blink::mojom::BlobURLToken>(), - receiver_.BindNewPipeAndPassRemote(), - net::StorageAccessApiStatus::kNone); - } else { - factory_->CreateWorkerHost( - blink::DedicatedWorkerToken(), /*script_url=*/GURL(), origin, - browser_interface_broker_.BindNewPipeAndPassReceiver(), - remote_host_.BindNewPipeAndPassReceiver(), base::DoNothing()); - } + factory_->CreateWorkerHostAndStartScriptLoad( + blink::DedicatedWorkerToken(), + /*script_url=*/GURL(), network::mojom::CredentialsMode::kSameOrigin, + blink::mojom::FetchClientSettingsObject::New(), + mojo::PendingRemote<blink::mojom::BlobURLToken>(), + receiver_.BindNewPipeAndPassRemote(), + net::StorageAccessApiStatus::kNone); } ~MockDedicatedWorker() override = default; @@ -121,8 +112,7 @@ }; class DedicatedWorkerServiceImplTest - : public RenderViewHostImplTestHarness, - public testing::WithParamInterface<bool> { + : public RenderViewHostImplTestHarness { public: DedicatedWorkerServiceImplTest() = default; ~DedicatedWorkerServiceImplTest() override = default; @@ -134,8 +124,6 @@ const DedicatedWorkerServiceImplTest& other) = delete; void SetUp() override { - scoped_feature_list_.InitWithFeatureState( - blink::features::kPlzDedicatedWorker, GetParam()); RenderViewHostImplTestHarness::SetUp(); browser_context_ = std::make_unique<TestBrowserContext>(); } @@ -159,9 +147,6 @@ } private: - // Controls the state of the blink::features::kPlzDedicatedWorker feature. - base::test::ScopedFeatureList scoped_feature_list_; - std::unique_ptr<TestBrowserContext> browser_context_; }; @@ -232,7 +217,7 @@ dedicated_worker_infos_; }; -TEST_P(DedicatedWorkerServiceImplTest, DedicatedWorkerServiceObserver) { +TEST_F(DedicatedWorkerServiceImplTest, DedicatedWorkerServiceObserver) { // Set up the observer. TestDedicatedWorkerServiceObserver observer; base::ScopedObservation<DedicatedWorkerService, @@ -291,8 +276,4 @@ EXPECT_TRUE(observer.dedicated_worker_infos().empty()); } -// Runs DedicatedWorkerServiceImplTest with both the enabled and disabled state -// of the kPlzDedicatedWorker feature. -INSTANTIATE_TEST_SUITE_P(, DedicatedWorkerServiceImplTest, testing::Bool()); - } // namespace content
diff --git a/content/browser/worker_host/worker_browsertest.cc b/content/browser/worker_host/worker_browsertest.cc index 51c9195..a4d25d2d 100644 --- a/content/browser/worker_host/worker_browsertest.cc +++ b/content/browser/worker_host/worker_browsertest.cc
@@ -55,7 +55,6 @@ #include "net/traffic_annotation/network_traffic_annotation_test_helper.h" #include "services/network/public/mojom/cookie_manager.mojom.h" #include "services/network/public/mojom/network_context.mojom.h" -#include "third_party/blink/public/common/features.h" #include "third_party/blink/public/common/storage_key/storage_key.h" #include "url/gurl.h" @@ -82,43 +81,22 @@ #endif } +std::string ParamToTestSuffix(const testing::TestParamInfo<bool>& info) { + if (info.param) { + return "PrivateNetworkAccessForWorkersEnabled"; + } else { + return "PrivateNetworkAccessForWorkersDisabled"; + } +} + } // namespace -// These tests are parameterized on following options: -// 0 => Base -// 1 => kPlzDedicatedWorker enabled -// 2 => kPrivateNetworkAccessForWorkers enabled class WorkerTest : public ContentBrowserTest, - public testing::WithParamInterface<int> { + public testing::WithParamInterface<bool> { public: WorkerTest() : select_certificate_count_(0) { - switch (GetParam()) { - case 0: // Base case. - feature_list_.InitWithFeatures({}, - { - blink::features::kPlzDedicatedWorker, - }); - break; - case 1: // PlzDedicatedWorker - feature_list_.InitWithFeatures( - { - blink::features::kPlzDedicatedWorker, - }, - { - features::kPrivateNetworkAccessForWorkers, - }); - break; - case 2: // PrivateNetworkAccessForWorkers - feature_list_.InitWithFeatures( - { - blink::features::kPlzDedicatedWorker, - features::kPrivateNetworkAccessForWorkers, - }, - {}); - break; - default: - NOTREACHED(); - } + feature_list_.InitWithFeatureState( + features::kPrivateNetworkAccessForWorkers, GetParam()); } void SetUpOnMainThread() override { @@ -322,7 +300,7 @@ base::test::ScopedFeatureList feature_list_; }; -INSTANTIATE_TEST_SUITE_P(All, WorkerTest, testing::Range(0, 3)); +INSTANTIATE_TEST_SUITE_P(All, WorkerTest, testing::Bool(), ParamToTestSuffix); IN_PROC_BROWSER_TEST_P(WorkerTest, SingleWorker) { RunTest(GetTestURL("single_worker.html", std::string())); @@ -342,7 +320,8 @@ INSTANTIATE_TEST_SUITE_P(All, WorkerTestWithAllowFileAccessFromFiles, - testing::Range(0, 3)); + testing::Bool(), + ParamToTestSuffix); IN_PROC_BROWSER_TEST_P(WorkerTestWithAllowFileAccessFromFiles, SingleWorkerFromFile) { @@ -922,7 +901,7 @@ INSTANTIATE_TEST_SUITE_P(All, WorkerFromCredentiallessIframeNikBrowserTest, - testing::Range(0, 3)); + testing::Bool(), ParamToTestSuffix); IN_PROC_BROWSER_TEST_P(WorkerFromCredentiallessIframeNikBrowserTest, SharedWorkerRequestIsDoneWithPartitionedNetworkState) {
diff --git a/content/child/font_warmup_win_unittest.cc b/content/child/font_warmup_win_unittest.cc index e0b42e7..79dc4c63d 100644 --- a/content/child/font_warmup_win_unittest.cc +++ b/content/child/font_warmup_win_unittest.cc
@@ -15,6 +15,7 @@ #include <memory> #include <vector> +#include "base/compiler_specific.h" #include "base/files/file_path.h" #include "base/logging.h" #include "base/path_service.h" @@ -100,9 +101,10 @@ const wchar_t* kTestFontFamilyInvalid = L"InvalidFont"; void InitLogFont(LOGFONTW* logfont, const wchar_t* fontname) { - size_t length = std::min(sizeof(logfont->lfFaceName), - (wcslen(fontname) + 1) * sizeof(wchar_t)); - memcpy(logfont->lfFaceName, fontname, length); + size_t length = + std::min(sizeof(logfont->lfFaceName), + (UNSAFE_TODO(wcslen(fontname)) + 1) * sizeof(wchar_t)); + UNSAFE_TODO(memcpy(logfont->lfFaceName, fontname, length)); } content::GdiFontPatchData* SetupTest() { @@ -275,7 +277,7 @@ std::vector<char> data(data_size); DWORD size = GetFontData(hdc, kTestFontTableTag, 0, &data[0], data.size()); EXPECT_EQ(size, data_size); - EXPECT_EQ(memcmp(&data[0], kTestFontTableData, data.size()), 0); + EXPECT_EQ(UNSAFE_TODO(memcmp(&data[0], kTestFontTableData, data.size())), 0); EXPECT_TRUE(DeleteObject(font)); EXPECT_TRUE(DeleteDC(hdc)); }
diff --git a/content/public/common/content_features.cc b/content/public/common/content_features.cc index a62a14c7..94e6f280 100644 --- a/content/public/common/content_features.cc +++ b/content/public/common/content_features.cc
@@ -351,6 +351,9 @@ const base::FeatureParam<base::TimeDelta> kBtmClientBounceDetectionTimeout{ &kBtm, "client_bounce_detection_timeout", base::Seconds(10)}; +// Enables Bounce Tracking Mitigations for Dual Use sites. +BASE_FEATURE(kBtmDualUse, "BtmDualUse", base::FEATURE_DISABLED_BY_DEFAULT); + // Enables HW decode acceleration for WebRTC. BASE_FEATURE(kWebRtcHWDecoding, "webrtc-hw-decoding",
diff --git a/content/public/common/content_features.h b/content/public/common/content_features.h index 0d31bb0..339935e 100644 --- a/content/public/common/content_features.h +++ b/content/public/common/content_features.h
@@ -85,8 +85,6 @@ kDeviceBoundSessionTerminationEvictBackForwardCache); CONTENT_EXPORT BASE_DECLARE_FEATURE(kDevToolsPrivacyUI); CONTENT_EXPORT BASE_DECLARE_FEATURE(kDigitalGoodsApi); -// TODO(crbug.com/364900088): Refactor BTM feature flags and parameters into -// their own features file. CONTENT_EXPORT BASE_DECLARE_FEATURE(kBtm); CONTENT_EXPORT BASE_DECLARE_FEATURE(kBtmTtl); CONTENT_EXPORT extern const base::FeatureParam<bool> @@ -100,6 +98,7 @@ kBtmTriggeringAction; CONTENT_EXPORT extern const base::FeatureParam<base::TimeDelta> kBtmClientBounceDetectionTimeout; +CONTENT_EXPORT BASE_DECLARE_FEATURE(kBtmDualUse); CONTENT_EXPORT BASE_DECLARE_FEATURE(kWebContentsDiscard); CONTENT_EXPORT BASE_DECLARE_FEATURE(kDocumentIsolationPolicyOriginTrial); CONTENT_EXPORT BASE_DECLARE_FEATURE(kDrawCutoutEdgeToEdge);
diff --git a/content/renderer/worker/dedicated_worker_host_factory_client.cc b/content/renderer/worker/dedicated_worker_host_factory_client.cc index be0a5b9..244f973db 100644 --- a/content/renderer/worker/dedicated_worker_host_factory_client.cc +++ b/content/renderer/worker/dedicated_worker_host_factory_client.cc
@@ -43,42 +43,6 @@ DedicatedWorkerHostFactoryClient::~DedicatedWorkerHostFactoryClient() = default; -void DedicatedWorkerHostFactoryClient::CreateWorkerHostDeprecated( - const blink::DedicatedWorkerToken& dedicated_worker_token, - const blink::WebURL& script_url, - const blink::WebSecurityOrigin& origin, - CreateWorkerHostCallback callback) { - // The callback of mojom::CreateWorkerHost() requires mojo::PendingRemote as - // the second param, but the passed callback requires - // blink::CrossVariantMojoRemote. To bridge them, wrap the passed callback. - using MojoCreateWorkerHostCallback = base::OnceCallback<void( - const network::CrossOriginEmbedderPolicy&, - mojo::PendingRemote<blink::mojom::BackForwardCacheControllerHost>)>; - MojoCreateWorkerHostCallback adapter_callback = base::BindOnce( - [](CreateWorkerHostCallback callback, - const network::CrossOriginEmbedderPolicy& policy, - mojo::PendingRemote<blink::mojom::BackForwardCacheControllerHost> - back_forward_cache_controller_host) { - blink::CrossVariantMojoRemote< - blink::mojom::BackForwardCacheControllerHostInterfaceBase> - pending_remote = std::move(back_forward_cache_controller_host); - std::move(callback).Run(policy, std::move(pending_remote)); - }, - std::move(callback)); - - DCHECK(!base::FeatureList::IsEnabled(blink::features::kPlzDedicatedWorker)); - mojo::PendingRemote<blink::mojom::BrowserInterfaceBroker> - browser_interface_broker; - mojo::PendingRemote<blink::mojom::DedicatedWorkerHost> dedicated_worker_host; - factory_->CreateWorkerHost( - dedicated_worker_token, script_url, origin, - browser_interface_broker.InitWithNewPipeAndPassReceiver(), - dedicated_worker_host.InitWithNewPipeAndPassReceiver(), - std::move(adapter_callback)); - OnWorkerHostCreated(std::move(browser_interface_broker), - std::move(dedicated_worker_host), origin); -} - void DedicatedWorkerHostFactoryClient::CreateWorkerHost( const blink::DedicatedWorkerToken& dedicated_worker_token, const blink::WebURL& script_url,
diff --git a/content/renderer/worker/dedicated_worker_host_factory_client.h b/content/renderer/worker/dedicated_worker_host_factory_client.h index dbbb021f..15c9345 100644 --- a/content/renderer/worker/dedicated_worker_host_factory_client.h +++ b/content/renderer/worker/dedicated_worker_host_factory_client.h
@@ -49,11 +49,6 @@ ~DedicatedWorkerHostFactoryClient() override; // Implements blink::WebDedicatedWorkerHostFactoryClient. - void CreateWorkerHostDeprecated( - const blink::DedicatedWorkerToken& dedicated_worker_token, - const blink::WebURL& script_url, - const blink::WebSecurityOrigin& origin, - CreateWorkerHostCallback callback) override; void CreateWorkerHost( const blink::DedicatedWorkerToken& dedicated_worker_token, const blink::WebURL& script_url,
diff --git a/content/shell/browser/shell_download_manager_delegate.cc b/content/shell/browser/shell_download_manager_delegate.cc index efeb0ae..2476f25 100644 --- a/content/shell/browser/shell_download_manager_delegate.cc +++ b/content/shell/browser/shell_download_manager_delegate.cc
@@ -19,6 +19,7 @@ #include "base/check_op.h" #include "base/command_line.h" +#include "base/compiler_specific.h" #include "base/files/file_util.h" #include "base/functional/bind.h" #include "base/notreached.h" @@ -170,9 +171,10 @@ #if BUILDFLAG(IS_WIN) std::wstring file_part = base::FilePath(suggested_path).BaseName().value(); wchar_t file_name[MAX_PATH]; - base::wcslcpy(file_name, file_part.c_str(), std::size(file_name)); + UNSAFE_TODO( + base::wcslcpy(file_name, file_part.c_str(), std::size(file_name))); OPENFILENAME save_as; - ZeroMemory(&save_as, sizeof(save_as)); + UNSAFE_TODO(ZeroMemory(&save_as, sizeof(save_as))); save_as.lStructSize = sizeof(OPENFILENAME); WebContents* web_contents = DownloadItemUtils::GetWebContents(item); // |web_contents| could be null if the tab was quickly closed.
diff --git a/content/test/content_browser_test_utils_internal.cc b/content/test/content_browser_test_utils_internal.cc index 6f4278d5..4a38011 100644 --- a/content/test/content_browser_test_utils_internal.cc +++ b/content/test/content_browser_test_utils_internal.cc
@@ -1197,10 +1197,22 @@ LoadingStopObserver::LoadingStopObserver(WebContents* web_contents, Callback callback) : WebContentsObserver(web_contents), callback_(std::move(callback)) {} + LoadingStopObserver::~LoadingStopObserver() = default; void LoadingStopObserver::DidStopLoading() { callback_.Run(); } +LoadFinishObserver::LoadFinishObserver(WebContents* web_contents, + Callback callback) + : WebContentsObserver(web_contents), callback_(std::move(callback)) {} + +LoadFinishObserver::~LoadFinishObserver() = default; + +void LoadFinishObserver::DidFinishLoad(RenderFrameHost* render_frame_host, + const GURL& validated_url) { + callback_.Run(render_frame_host, validated_url); +} + } // namespace content
diff --git a/content/test/content_browser_test_utils_internal.h b/content/test/content_browser_test_utils_internal.h index 1d5f17e..3ad97f6 100644 --- a/content/test/content_browser_test_utils_internal.h +++ b/content/test/content_browser_test_utils_internal.h
@@ -860,6 +860,21 @@ Callback callback_; }; +// Forwards DidFinishLoad calls to the provided callback. +class LoadFinishObserver : public WebContentsObserver { + public: + using Callback = base::RepeatingCallback<void(RenderFrameHost*, const GURL&)>; + + LoadFinishObserver(WebContents* web_contents, Callback callback); + ~LoadFinishObserver() override; + + private: + void DidFinishLoad(RenderFrameHost* render_frame_host, + const GURL& validated_url) override; + + Callback callback_; +}; + } // namespace content #endif // CONTENT_TEST_CONTENT_BROWSER_TEST_UTILS_INTERNAL_H_
diff --git a/content/test/data/accessibility/aria/aria-multiselectable-aria-labelledby-expected-android-external.txt b/content/test/data/accessibility/aria/aria-multiselectable-aria-labelledby-expected-android-external.txt index 7f7671e8..592a47d 100644 --- a/content/test/data/accessibility/aria/aria-multiselectable-aria-labelledby-expected-android-external.txt +++ b/content/test/data/accessibility/aria/aria-multiselectable-aria-labelledby-expected-android-external.txt
@@ -1,5 +1,13 @@ WebView focusable focused actions:[CLEAR_FOCUS, AX_FOCUS] bundle:[chromeRole="rootWebArea"] ++TextView text:"None selected listbox" viewIdResName:"none-selected-listbox" actions:[AX_FOCUS, NEXT, PREVIOUS] bundle:[chromeRole="genericContainer"] ++ListView text:"None selected listbox" stateDescription:"multiselectable, none selected." clickable focusable CollectionInfo:[rows=4, cols=1] actions:[FOCUS, CLICK, AX_FOCUS, NEXT, PREVIOUS] bundle:[chromeRole="listBox", roleDescription="list box"] +++++View text:"Example 1" CollectionItemInfo:[rowIndex=0, colIndex=0] actions:[AX_FOCUS, NEXT, PREVIOUS] bundle:[chromeRole="listBoxOption"] +++++View text:"Example 2" CollectionItemInfo:[rowIndex=1, colIndex=0] actions:[AX_FOCUS, NEXT, PREVIOUS] bundle:[chromeRole="listBoxOption"] +++++View text:"Example 3" CollectionItemInfo:[rowIndex=2, colIndex=0] actions:[AX_FOCUS, NEXT, PREVIOUS] bundle:[chromeRole="listBoxOption"] +++++View text:"Example 4" CollectionItemInfo:[rowIndex=3, colIndex=0] actions:[AX_FOCUS, NEXT, PREVIOUS] bundle:[chromeRole="listBoxOption"] ++TextView text:"Some selected listbox" viewIdResName:"some-selected-listbox" actions:[AX_FOCUS, NEXT, PREVIOUS] bundle:[chromeRole="genericContainer"] -++ListView text:"Some selected listbox" stateDescription:"multiselectable, none selected." clickable focusable CollectionInfo:[rows=4, cols=1] actions:[FOCUS, CLICK, AX_FOCUS, NEXT, PREVIOUS] bundle:[chromeRole="listBox", roleDescription="list box"] +++ListView text:"Some selected listbox" stateDescription:"multiselectable, 2 of 4 selected." clickable focusable CollectionInfo:[rows=4, cols=1] actions:[FOCUS, CLICK, AX_FOCUS, NEXT, PREVIOUS] bundle:[chromeRole="listBox", roleDescription="list box"] +++++View text:"Example 1" CollectionItemInfo:[rowIndex=0, colIndex=0] actions:[AX_FOCUS, NEXT, PREVIOUS] bundle:[chromeRole="listBoxOption"] +++++View text:"Example 2" selected CollectionItemInfo:[rowIndex=1, colIndex=0] actions:[AX_FOCUS, NEXT, PREVIOUS] bundle:[chromeRole="listBoxOption"] +++++View text:"Example 3" CollectionItemInfo:[rowIndex=2, colIndex=0] actions:[AX_FOCUS, NEXT, PREVIOUS] bundle:[chromeRole="listBoxOption"] +++++View text:"Example 4" selected CollectionItemInfo:[rowIndex=3, colIndex=0] actions:[AX_FOCUS, NEXT, PREVIOUS] bundle:[chromeRole="listBoxOption"]
diff --git a/content/test/data/accessibility/aria/aria-multiselectable-aria-labelledby-expected-android.txt b/content/test/data/accessibility/aria/aria-multiselectable-aria-labelledby-expected-android.txt index 0245e58a..3fc6357 100644 --- a/content/test/data/accessibility/aria/aria-multiselectable-aria-labelledby-expected-android.txt +++ b/content/test/data/accessibility/aria/aria-multiselectable-aria-labelledby-expected-android.txt
@@ -1,5 +1,13 @@ android.webkit.WebView focusable focused ++android.widget.TextView interesting name='None selected listbox' ++android.widget.ListView role_description='list box' clickable collection focusable multiselectable interesting name='None selected listbox' state_description='multiselectable, none selected.' item_count=4 row_count=4 column_count=1 +++++android.view.View collection_item name='Example 1' row_span=1 column_span=1 +++++android.view.View collection_item name='Example 2' item_index=1 row_index=1 row_span=1 column_span=1 +++++android.view.View collection_item name='Example 3' item_index=2 row_index=2 row_span=1 column_span=1 +++++android.view.View collection_item name='Example 4' item_index=3 row_index=3 row_span=1 column_span=1 ++android.widget.TextView interesting name='Some selected listbox' -++android.widget.ListView role_description='list box' clickable collection focusable multiselectable interesting name='Some selected listbox' state_description='multiselectable, none selected.' item_count=4 row_count=4 column_count=1 +++android.widget.ListView role_description='list box' clickable collection focusable multiselectable interesting name='Some selected listbox' state_description='multiselectable, 2 of 4 selected.' item_count=4 row_count=4 column_count=1 +++++android.view.View collection_item name='Example 1' row_span=1 column_span=1 +++++android.view.View collection_item selected name='Example 2' item_index=1 row_index=1 row_span=1 column_span=1 +++++android.view.View collection_item name='Example 3' item_index=2 row_index=2 row_span=1 column_span=1 +++++android.view.View collection_item selected name='Example 4' item_index=3 row_index=3 row_span=1 column_span=1
diff --git a/content/test/data/accessibility/html/button-with-listbox-popup-expected-android-external.txt b/content/test/data/accessibility/html/button-with-listbox-popup-expected-android-external.txt index 927ad82a..5efe433 100644 --- a/content/test/data/accessibility/html/button-with-listbox-popup-expected-android-external.txt +++ b/content/test/data/accessibility/html/button-with-listbox-popup-expected-android-external.txt
@@ -3,3 +3,6 @@ ++++TextView text:"Choose one:" viewIdResName:"span" actions:[AX_FOCUS, NEXT, PREVIOUS] bundle:[chromeRole="genericContainer"] ++++Button text:"Choose one: Foo" viewIdResName:"test" canOpenPopUp clickable focusable actions:[FOCUS, CLICK, AX_FOCUS, NEXT, PREVIOUS] bundle:[chromeRole="popUpButton", clickableScore="300", roleDescription="pop up button"] ++++ListView text:"Choose one:" viewIdResName:"options" clickable focusable CollectionInfo:[rows=3, cols=1] actions:[FOCUS, CLICK, AX_FOCUS, NEXT, PREVIOUS] bundle:[chromeRole="listBox", clickableScore="300", roleDescription="list box"] +++++++View text:"Baz" viewIdResName:"option1" clickable CollectionItemInfo:[rowIndex=0, colIndex=0] actions:[CLICK, AX_FOCUS, NEXT, PREVIOUS] bundle:[chromeRole="listBoxOption", clickableScore="200"] +++++++View text:"Bar" viewIdResName:"option2" clickable CollectionItemInfo:[rowIndex=1, colIndex=0] actions:[CLICK, AX_FOCUS, NEXT, PREVIOUS] bundle:[chromeRole="listBoxOption", clickableScore="200"] +++++++View text:"Foo" viewIdResName:"option3" clickable CollectionItemInfo:[rowIndex=2, colIndex=0] actions:[CLICK, AX_FOCUS, NEXT, PREVIOUS] bundle:[chromeRole="listBoxOption", clickableScore="200"]
diff --git a/content/test/data/accessibility/html/button-with-listbox-popup-expected-android.txt b/content/test/data/accessibility/html/button-with-listbox-popup-expected-android.txt index 40d1ada4..7e42679d 100644 --- a/content/test/data/accessibility/html/button-with-listbox-popup-expected-android.txt +++ b/content/test/data/accessibility/html/button-with-listbox-popup-expected-android.txt
@@ -3,3 +3,6 @@ ++++android.widget.TextView interesting name='Choose one:' ++++android.widget.Button role_description='pop up button' clickable focusable interesting name='Choose one: Foo' ++++android.widget.ListView role_description='list box' clickable collection focusable interesting name='Choose one:' item_count=3 row_count=3 column_count=1 +++++++android.view.View clickable collection_item name='Baz' row_span=1 column_span=1 +++++++android.view.View clickable collection_item name='Bar' item_index=1 row_index=1 row_span=1 column_span=1 +++++++android.view.View clickable collection_item name='Foo' item_index=2 row_index=2 row_span=1 column_span=1
diff --git a/device/bluetooth/bluetooth_classic_win_fake.cc b/device/bluetooth/bluetooth_classic_win_fake.cc index 7863c3fc..98483bd 100644 --- a/device/bluetooth/bluetooth_classic_win_fake.cc +++ b/device/bluetooth/bluetooth_classic_win_fake.cc
@@ -5,6 +5,7 @@ #include "device/bluetooth/bluetooth_classic_win_fake.h" #include "base/check_op.h" +#include "base/compiler_specific.h" #include "base/notreached.h" #include "base/strings/string_util.h" @@ -93,7 +94,7 @@ size_t length = ((name.size() > BLUETOOTH_MAX_NAME_SIZE) ? BLUETOOTH_MAX_NAME_SIZE : name.size()); - wcsncpy(radio->radio_info.szName, base::as_wcstr(name), length); + UNSAFE_TODO(wcsncpy(radio->radio_info.szName, base::as_wcstr(name), length)); radio->radio_info.address = address; simulated_radios_.reset(radio); return radio;
diff --git a/device/fido/win/webauthn_api.cc b/device/fido/win/webauthn_api.cc index ce89d98..41e6587c 100644 --- a/device/fido/win/webauthn_api.cc +++ b/device/fido/win/webauthn_api.cc
@@ -10,6 +10,7 @@ #include <string_view> #include <vector> +#include "base/compiler_specific.h" #include "base/feature_list.h" #include "base/functional/bind.h" #include "base/logging.h" @@ -70,7 +71,7 @@ return nullptr; } - memset(values_storage, 0, sizeof(*values_storage)); + UNSAFE_TODO(memset(values_storage, 0, sizeof(*values_storage))); // These vectors must not reallocate because the Windows structures will have // pointers into their elements. salts_storage->reserve(inputs.size());
diff --git a/device/vr/openxr/openxr_controller.cc b/device/vr/openxr/openxr_controller.cc index 7d647e0..a26416e3 100644 --- a/device/vr/openxr/openxr_controller.cc +++ b/device/vr/openxr/openxr_controller.cc
@@ -7,6 +7,7 @@ #include <stdint.h> #include "base/check.h" +#include "base/compiler_specific.h" #include "base/notreached.h" #include "base/strings/string_util.h" #include "device/gamepad/public/cpp/gamepad.h" @@ -163,13 +164,15 @@ XR_TYPE_ACTION_SET_CREATE_INFO}; size_t dest_size = std::size(action_set_create_info.actionSetName); - size_t src_size = base::strlcpy(action_set_create_info.actionSetName, - action_set_name.c_str(), dest_size); + size_t src_size = + UNSAFE_TODO(base::strlcpy(action_set_create_info.actionSetName, + action_set_name.c_str(), dest_size)); DCHECK_LT(src_size, dest_size); dest_size = std::size(action_set_create_info.localizedActionSetName); - src_size = base::strlcpy(action_set_create_info.localizedActionSetName, - action_set_name.c_str(), dest_size); + src_size = + UNSAFE_TODO(base::strlcpy(action_set_create_info.localizedActionSetName, + action_set_name.c_str(), dest_size)); DCHECK_LT(src_size, dest_size); RETURN_IF_XR_FAILED( @@ -627,13 +630,13 @@ action_create_info.actionType = type; size_t dest_size = std::size(action_create_info.actionName); - size_t src_size = base::strlcpy(action_create_info.actionName, - action_name.data(), dest_size); + size_t src_size = UNSAFE_TODO(base::strlcpy(action_create_info.actionName, + action_name.data(), dest_size)); DCHECK_LT(src_size, dest_size); dest_size = std::size(action_create_info.localizedActionName); - src_size = base::strlcpy(action_create_info.localizedActionName, - action_name.data(), dest_size); + src_size = UNSAFE_TODO(base::strlcpy(action_create_info.localizedActionName, + action_name.data(), dest_size)); DCHECK_LT(src_size, dest_size); return xrCreateAction(action_set_, &action_create_info, action); }
diff --git a/device/vr/openxr/openxr_hand_tracker.cc b/device/vr/openxr/openxr_hand_tracker.cc index 26530963..955cf4bc 100644 --- a/device/vr/openxr/openxr_hand_tracker.cc +++ b/device/vr/openxr/openxr_hand_tracker.cc
@@ -8,6 +8,7 @@ #include <vector> #include "base/command_line.h" +#include "base/compiler_specific.h" #include "base/containers/flat_set.h" #include "base/no_destructor.h" #include "base/strings/string_util.h" @@ -230,8 +231,9 @@ std::ranges::any_of( GetRequestedExtensions(), [&extension_enum](std::string_view extension) { - return strcmp(extension.data(), - XR_EXT_HAND_TRACKING_EXTENSION_NAME) != 0 && + return UNSAFE_TODO( + strcmp(extension.data(), + XR_EXT_HAND_TRACKING_EXTENSION_NAME)) != 0 && extension_enum->ExtensionSupported(extension.data()); }); }
diff --git a/device/vr/openxr/openxr_platform_helper.cc b/device/vr/openxr/openxr_platform_helper.cc index 2b54cf4..66b7fb8 100644 --- a/device/vr/openxr/openxr_platform_helper.cc +++ b/device/vr/openxr/openxr_platform_helper.cc
@@ -7,6 +7,7 @@ #include <set> #include <utility> +#include "base/compiler_specific.h" #include "base/containers/contains.h" #include "base/metrics/histogram_macros.h" #include "base/strings/strcat.h" @@ -98,9 +99,9 @@ version_info::GetMajorVersionNumber()}); size_t dest_size = std::size(instance_create_info.applicationInfo.applicationName); - size_t src_size = + size_t src_size = UNSAFE_TODO( base::strlcpy(instance_create_info.applicationInfo.applicationName, - application_name.c_str(), dest_size); + application_name.c_str(), dest_size)); DCHECK_LT(src_size, dest_size); base::Version version = version_info::GetVersion(); @@ -111,8 +112,8 @@ instance_create_info.applicationInfo.applicationVersion = build; dest_size = std::size(instance_create_info.applicationInfo.engineName); - src_size = base::strlcpy(instance_create_info.applicationInfo.engineName, - "Chromium", dest_size); + src_size = UNSAFE_TODO(base::strlcpy( + instance_create_info.applicationInfo.engineName, "Chromium", dest_size)); DCHECK_LT(src_size, dest_size); // engine version should be the build number of chromium
diff --git a/docs/rust-ffi.md b/docs/rust-ffi.md new file mode 100644 index 0000000..8cae381 --- /dev/null +++ b/docs/rust-ffi.md
@@ -0,0 +1,38 @@ +# Rust FFI + +This document tries to provide guidance for C++/Rust FFI. +CLs to improve this guidance are welcomed. + +## General guidance + +Chromium recommends using [the `cxx` crate](https://cxx.rs/) for C++/Rust FFI. +For introductory guidance, please see +[the `cxx` chapter](https://google.github.io/comprehensive-rust/chromium/interoperability-with-cpp.html) +in the Chromium day of the Comprehensive Rust course. + +Chromium also supports the following tools: + +* [`bindgen`](https://rust-lang.github.io/rust-bindgen/) - see + `//build/rust/rust_bindgen.gni` for usage instructions. + +At this point Chromium's `//build/rust/*.gni` templates do not support other FFI +tools like: + +* [`cbindgen`](https://github.com/mozilla/cbindgen) +* [`crubit`](https://github.com/google/crubit) + +### `cxx` guidance + +#### Best practices + +* Generate C++ side of bindings into a project-specific or crate-specific + `namespace`. For example: `#[cxx::bridge(namespace = "some_cpp_namespace")]`. +* Maintain binding declarations in a **single** `#[cxx::bridge]` declaration. + `cxx` supports reusing types across multiple `bridge`s, but there are some + rough edges. + +#### Suggestions + +TODO: Provide some examples or suggestions on how to structure FFI bindings +(even if these suggestions wouldn't necessarily rise to the level of "best +practices").
diff --git a/docs/rust.md b/docs/rust.md index 67e3682..b4a4d5ba 100644 --- a/docs/rust.md +++ b/docs/rust.md
@@ -237,15 +237,7 @@ mixed-language Chromium build and get the correct compiler options applied to them. -The [CXX](https://cxx.rs) tool is used for generating C++ bindings to Rust -code. Since it requires explicit declarations in Rust, an wrapper shim around a -pure Rust library is needed. Add these Rust shims that contain the CXX -`bridge` macro to the `cxx_bindings` GN variable in the `rust_static_library` -to have CXX generate a C++ header for that file. To include the C++ header -file, rooted in the `gen` output directory, use -``` -#include "the/path/to/the/rust/file.rs.h" -``` +See `rust-ffi.md` for information on C++/Rust FFI. # Logging
diff --git a/docs/testing/batching_instrumentation_tests.md b/docs/testing/batching_instrumentation_tests.md index 048e52d..d07fb81 100644 --- a/docs/testing/batching_instrumentation_tests.md +++ b/docs/testing/batching_instrumentation_tests.md
@@ -52,7 +52,7 @@ `@Before` are run for each test case (same for `@AfterClass` / `@After`). Activity-reused Public Transit tests use the `ReusedCtaTransitRule` or the -`BlankCTATabInitialStatePublicTransitRule`. +`AutoResetCtaTransitRule`. ### Performance
diff --git a/fuchsia_web/av_testing/av_sync_tests.py b/fuchsia_web/av_testing/av_sync_tests.py index 5e77a5b..8b1ee8d 100755 --- a/fuchsia_web/av_testing/av_sync_tests.py +++ b/fuchsia_web/av_testing/av_sync_tests.py
@@ -107,6 +107,12 @@ result.fps = 120 # All the videos now being used are 30s long. result.duration_sec = 30 + # Expect the camera serial number to be set, but now the hosts running in + # media lab have only one camera per host and need no serial number. + # TODO(crbug.com/391663618): Remove the condition once all the hosts are + # migrated into chrome lab. + if os.environ.get('CAMERA_SERIAL_NUMBER'): + result.serial_number = os.environ['CAMERA_SERIAL_NUMBER'] return result
diff --git a/gin/gin_features.cc b/gin/gin_features.cc index e6f9e49..28cf8b15 100644 --- a/gin/gin_features.cc +++ b/gin/gin_features.cc
@@ -132,6 +132,13 @@ const base::FeatureParam<int> kV8MemoryReducerGCCount{ &kV8MemoryReducer, "V8MemoryReducerGCCount", 3}; +BASE_FEATURE(kV8PreconfigureOldGen, + "V8PreconfigureOldGen", + kFeatureDefaultStateControlledByV8); + +const base::FeatureParam<int> kV8PreconfigureOldGenSize{ + &kV8PreconfigureOldGen, "V8PreconfigureOldGenSize", 32}; + // Enables MinorMC young generation garbage collector. BASE_FEATURE(kV8MinorMS, ("V8MinorMS"), kFeatureDefaultStateControlledByV8);
diff --git a/gin/gin_features.h b/gin/gin_features.h index f4d7567..1a54e51 100644 --- a/gin/gin_features.h +++ b/gin/gin_features.h
@@ -50,6 +50,8 @@ GIN_EXPORT BASE_DECLARE_FEATURE(kV8ConcurrentMaglevHighPriorityThreads); GIN_EXPORT BASE_DECLARE_FEATURE(kV8MemoryReducer); GIN_EXPORT extern const base::FeatureParam<int> kV8MemoryReducerGCCount; +GIN_EXPORT BASE_DECLARE_FEATURE(kV8PreconfigureOldGen); +GIN_EXPORT extern const base::FeatureParam<int> kV8PreconfigureOldGenSize; GIN_EXPORT BASE_DECLARE_FEATURE(kV8MinorMS); GIN_EXPORT BASE_DECLARE_FEATURE(kV8MegaDomIC); GIN_EXPORT BASE_DECLARE_FEATURE(kV8NoReclaimUnmodifiedWrappers);
diff --git a/gin/public/v8_platform.h b/gin/public/v8_platform.h index c34f3414..9dac402 100644 --- a/gin/public/v8_platform.h +++ b/gin/public/v8_platform.h
@@ -63,6 +63,7 @@ double CurrentClockTimeMillisecondsHighResolution() override; StackTracePrinter GetStackTracePrinter() override; v8::TracingController* GetTracingController() override; + void DumpWithoutCrashing() override; private: friend struct base::LazyInstanceTraitsBase<V8Platform>;
diff --git a/gin/v8_initializer.cc b/gin/v8_initializer.cc index 974bb08..4c9a30f 100644 --- a/gin/v8_initializer.cc +++ b/gin/v8_initializer.cc
@@ -389,6 +389,10 @@ SetV8FlagsFormatted("--memory-reducer-gc-count=%i", features::kV8MemoryReducerGCCount.Get()); } + if (base::FeatureList::IsEnabled(features::kV8PreconfigureOldGen)) { + SetV8FlagsFormatted("--initial-old-space-size=%i", + features::kV8PreconfigureOldGenSize.Get()); + } SetV8FlagsIfOverridden(features::kV8IncrementalMarkingStartUserVisible, "--incremental-marking-start-user-visible", "--no-incremental-marking-start-user-visible");
diff --git a/gin/v8_platform.cc b/gin/v8_platform.cc index fa799a4c..698b29e 100644 --- a/gin/v8_platform.cc +++ b/gin/v8_platform.cc
@@ -8,6 +8,7 @@ #include "base/bit_cast.h" #include "base/check_op.h" +#include "base/debug/dump_without_crashing.h" #include "base/debug/stack_trace.h" #include "base/functional/bind.h" #include "base/location.h" @@ -332,4 +333,8 @@ return PrintStackTrace; } +void V8Platform::DumpWithoutCrashing() { + base::debug::DumpWithoutCrashing(); +} + } // namespace gin
diff --git a/gpu/config/gpu_info_collector_win.cc b/gpu/config/gpu_info_collector_win.cc index 7052381..73781ef6 100644 --- a/gpu/config/gpu_info_collector_win.cc +++ b/gpu/config/gpu_info_collector_win.cc
@@ -15,6 +15,7 @@ #include <vulkan/vulkan.h> #include <wrl/client.h> +#include "base/compiler_specific.h" #include "base/file_version_info_win.h" #include "base/files/file_enumerator.h" #include "base/files/file_path.h" @@ -330,7 +331,7 @@ CHROME_LUID{desc.AdapterLuid.LowPart, desc.AdapterLuid.HighPart}; device.device_string = base::WideToUTF8(std::wstring_view( desc.Description, - wcsnlen_s(desc.Description, std::size(desc.Description)))); + UNSAFE_TODO(wcsnlen_s(desc.Description, std::size(desc.Description))))); LARGE_INTEGER umd_version; hr = dxgi_adapter->CheckInterfaceSupport(__uuidof(IDXGIDevice),
diff --git a/gpu/config/gpu_util.cc b/gpu/config/gpu_util.cc index 4bb70fe7..ea0b73d6 100644 --- a/gpu/config/gpu_util.cc +++ b/gpu/config/gpu_util.cc
@@ -777,8 +777,10 @@ if (disable_software_rasterizer || blocklist_needs_more_info) return false; // Don't overwrite user preference. - if (command_line->HasSwitch(switches::kUseGL)) + if (gl::GetRequestedGLImplementationFromCommandLine(command_line) + .has_value()) { return false; + } if (gpu_feature_info.status_values[GPU_FEATURE_TYPE_ACCELERATED_WEBGL] != kGpuFeatureStatusEnabled || gpu_feature_info.status_values[GPU_FEATURE_TYPE_ACCELERATED_GL] !=
diff --git a/headless/test/headless_test_launcher.cc b/headless/test/headless_test_launcher.cc index 16ab0d0..fc35eb6 100644 --- a/headless/test/headless_test_launcher.cc +++ b/headless/test/headless_test_launcher.cc
@@ -7,6 +7,7 @@ #include "base/command_line.h" #include "base/functional/bind.h" #include "base/functional/callback_helpers.h" +#include "base/test/allow_check_is_test_for_testing.h" #include "base/test/launcher/test_launcher.h" #include "build/build_config.h" #include "content/public/test/content_test_suite_base.h" @@ -52,10 +53,12 @@ } // namespace headless int main(int argc, char** argv) { + base::test::AllowCheckIsTestForTesting(); base::CommandLine::Init(argc, argv); size_t parallel_jobs = base::NumParallelJobs(/*cores_per_job=*/2); - if (parallel_jobs == 0U) + if (parallel_jobs == 0U) { return 1; + } #if BUILDFLAG(IS_WIN) // Load and pin user32.dll to avoid having to load it once tests start while
diff --git a/internal b/internal index b9a65e1..41278638 160000 --- a/internal +++ b/internal
@@ -1 +1 @@ -Subproject commit b9a65e19474a3e02829e57463335f99df7b6939a +Subproject commit 41278638c9719c44d0c524460a0ed2d6ba96be4c
diff --git a/ios/chrome/app/strings/ios_strings.grd b/ios/chrome/app/strings/ios_strings.grd index ceaa2ea1..d3874d8c 100644 --- a/ios/chrome/app/strings/ios_strings.grd +++ b/ios/chrome/app/strings/ios_strings.grd
@@ -1420,6 +1420,9 @@ <message name="IDS_IOS_CONTENT_SUGGESTIONS_SETTING_TITLE" desc="The title of the settings to toggle the articles suggestions on the NTP on/off"> Article suggestions </message> + <message name="IDS_IOS_CONTENT_SUGGESTIONS_SHOPCARD_PRICE_DROP_CONTEXT_MENU_TITLE" desc="Customize cards title for Price Drops on Tab Resumption"> + This card shows a price drop on your tracked product from one of your synced devices + </message> <message name="IDS_IOS_CONTENT_SUGGESTIONS_SHOPCARD_PRICE_DROP_OPEN_TABS_ACCESSIBILITY_LABEL" desc="Accessibility label for Price Drop on Open Tabs"> Price drop on your open tab, from <ph name="PREVIOUS_PRICE">$1<ex>$799</ex></ph> to <ph name="PRICE">$2<ex>$699</ex></ph>, <ph name="PRODUCT_NAME">$3<ex>Pixel phone</ex></ph>, <ph name="DOMAIN">$4<ex>store.google.com</ex></ph> </message> @@ -2545,6 +2548,12 @@ <message name="IDS_IOS_HISTORY_SYNC_FOOTER_WITH_EMAIL" desc="Small text above the main button on a page that asks users to start syncing their tabs and browsing history. The first sentence reminds the user that they're signed in with a certain account. The second sentence is meant to reassure users that they can always change their mind and opt out again. The third sentence explains how history data may be used to personalise the user's experience in other services. The tone should be friendly and reassuring."> You are signed in as <ph name="USER_EMAIL">$1<ex>janedoe@google.com</ex></ph>. You can stop syncing anytime in settings. Google may personalize Search and other services based on your history. </message> + <message name="IDS_IOS_HISTORY_SYNC_GROUP_COLLABORATION_SUBTITLE" desc="Title displayed to the user when they attempt to access or interact with a shared group."> + To share, join, and collaborate in tab groups, sync your history and tabs + </message> + <message name="IDS_IOS_HISTORY_SYNC_GROUP_COLLABORATION_TITLE" desc="Subtitle displayed to the user when they attempt to access or interact with a shared group."> + Sync tabs and history to continue + </message> <message name="IDS_IOS_HISTORY_SYNC_PRIMARY_ACTION" desc="Title of the button to validate the user consent to sync their history and tabs data."> Yes, I'm in </message> @@ -7225,4 +7234,4 @@ </message> </messages> </release> -</grit> +</grit> \ No newline at end of file
diff --git a/ios/chrome/app/strings/ios_strings_grd/IDS_IOS_CONTENT_SUGGESTIONS_SHOPCARD_PRICE_DROP_CONTEXT_MENU_TITLE.png.sha1 b/ios/chrome/app/strings/ios_strings_grd/IDS_IOS_CONTENT_SUGGESTIONS_SHOPCARD_PRICE_DROP_CONTEXT_MENU_TITLE.png.sha1 new file mode 100644 index 0000000..97ef93a --- /dev/null +++ b/ios/chrome/app/strings/ios_strings_grd/IDS_IOS_CONTENT_SUGGESTIONS_SHOPCARD_PRICE_DROP_CONTEXT_MENU_TITLE.png.sha1
@@ -0,0 +1 @@ +7c535d4b91a85fb44cb0f5e3b18f7325f237d276 \ No newline at end of file
diff --git a/ios/chrome/app/strings/ios_strings_grd/IDS_IOS_HISTORY_SYNC_GROUP_COLLABORATION_SUBTITLE.png.sha1 b/ios/chrome/app/strings/ios_strings_grd/IDS_IOS_HISTORY_SYNC_GROUP_COLLABORATION_SUBTITLE.png.sha1 new file mode 100644 index 0000000..aec8e53d --- /dev/null +++ b/ios/chrome/app/strings/ios_strings_grd/IDS_IOS_HISTORY_SYNC_GROUP_COLLABORATION_SUBTITLE.png.sha1
@@ -0,0 +1 @@ +bec51d9b9fcde2d759bf566abdfc2fc56b88500b \ No newline at end of file
diff --git a/ios/chrome/app/strings/ios_strings_grd/IDS_IOS_HISTORY_SYNC_GROUP_COLLABORATION_TITLE.png.sha1 b/ios/chrome/app/strings/ios_strings_grd/IDS_IOS_HISTORY_SYNC_GROUP_COLLABORATION_TITLE.png.sha1 new file mode 100644 index 0000000..aec8e53d --- /dev/null +++ b/ios/chrome/app/strings/ios_strings_grd/IDS_IOS_HISTORY_SYNC_GROUP_COLLABORATION_TITLE.png.sha1
@@ -0,0 +1 @@ +bec51d9b9fcde2d759bf566abdfc2fc56b88500b \ No newline at end of file
diff --git a/ios/chrome/browser/authentication/ui_bundled/history_sync/history_sync_coordinator.mm b/ios/chrome/browser/authentication/ui_bundled/history_sync/history_sync_coordinator.mm index 00daea7f..73f259b9 100644 --- a/ios/chrome/browser/authentication/ui_bundled/history_sync/history_sync_coordinator.mm +++ b/ios/chrome/browser/authentication/ui_bundled/history_sync/history_sync_coordinator.mm
@@ -120,7 +120,8 @@ return; } - _viewController = [[HistorySyncViewController alloc] init]; + _viewController = + [[HistorySyncViewController alloc] initWithAccessPoint:_accessPoint]; _viewController.delegate = self; ChromeAccountManagerService* chromeAccountManagerService =
diff --git a/ios/chrome/browser/authentication/ui_bundled/history_sync/history_sync_view_controller.h b/ios/chrome/browser/authentication/ui_bundled/history_sync/history_sync_view_controller.h index 5c537a4..59cff4700 100644 --- a/ios/chrome/browser/authentication/ui_bundled/history_sync/history_sync_view_controller.h +++ b/ios/chrome/browser/authentication/ui_bundled/history_sync/history_sync_view_controller.h
@@ -8,10 +8,21 @@ #import "ios/chrome/browser/authentication/ui_bundled/history_sync/history_sync_consumer.h" #import "ios/chrome/common/ui/promo_style/promo_style_view_controller.h" +namespace signin_metrics { +enum class AccessPoint : int; +} + // View controller for history sync. @interface HistorySyncViewController : PromoStyleViewController <HistorySyncConsumer> +// Designated initializer. +// `accessPoint` associated with the history opt-in screen. +- (instancetype)initWithAccessPoint:(signin_metrics::AccessPoint)accessPoint + NS_DESIGNATED_INITIALIZER; + +- (instancetype)init NS_UNAVAILABLE; + @end #endif // IOS_CHROME_BROWSER_AUTHENTICATION_UI_BUNDLED_HISTORY_SYNC_HISTORY_SYNC_VIEW_CONTROLLER_H_
diff --git a/ios/chrome/browser/authentication/ui_bundled/history_sync/history_sync_view_controller.mm b/ios/chrome/browser/authentication/ui_bundled/history_sync/history_sync_view_controller.mm index 220b625..3e08bce 100644 --- a/ios/chrome/browser/authentication/ui_bundled/history_sync/history_sync_view_controller.mm +++ b/ios/chrome/browser/authentication/ui_bundled/history_sync/history_sync_view_controller.mm
@@ -18,7 +18,20 @@ #import "ios/chrome/grit/ios_strings.h" #import "ui/base/l10n/l10n_util.h" -@implementation HistorySyncViewController +using signin_metrics::AccessPoint; + +@implementation HistorySyncViewController { + // Access point associated with the history opt-in screen. + AccessPoint _accessPoint; +} + +- (instancetype)initWithAccessPoint:(AccessPoint)accessPoint { + self = [super init]; + if (self) { + _accessPoint = accessPoint; + } + return self; +} @dynamic delegate; @@ -35,8 +48,22 @@ self.headerBackgroundImage = [UIImage imageNamed:@"history_sync_opt_in_background"]; } - self.titleText = l10n_util::GetNSString(IDS_IOS_HISTORY_SYNC_TITLE); - self.subtitleText = l10n_util::GetNSString(IDS_IOS_HISTORY_SYNC_SUBTITLE); + + switch (_accessPoint) { + case AccessPoint::kCollaborationTabGroup: { + self.titleText = l10n_util::GetNSString( + IDS_IOS_HISTORY_SYNC_GROUP_COLLABORATION_TITLE); + self.subtitleText = l10n_util::GetNSString( + IDS_IOS_HISTORY_SYNC_GROUP_COLLABORATION_SUBTITLE); + break; + } + default: { + self.titleText = l10n_util::GetNSString(IDS_IOS_HISTORY_SYNC_TITLE); + self.subtitleText = l10n_util::GetNSString(IDS_IOS_HISTORY_SYNC_SUBTITLE); + break; + } + } + self.primaryActionString = l10n_util::GetNSString(IDS_IOS_HISTORY_SYNC_PRIMARY_ACTION); self.secondaryActionString =
diff --git a/ios/chrome/browser/bookmarks/ui_bundled/home/bookmarks_home_view_controller.mm b/ios/chrome/browser/bookmarks/ui_bundled/home/bookmarks_home_view_controller.mm index 1a99080..9b3f664 100644 --- a/ios/chrome/browser/bookmarks/ui_bundled/home/bookmarks_home_view_controller.mm +++ b/ios/chrome/browser/bookmarks/ui_bundled/home/bookmarks_home_view_controller.mm
@@ -1615,14 +1615,30 @@ return 0; } + UITableView* tableView = self.tableView; + // If no rows in table, return 0. - NSArray* visibleIndexPaths = [self.tableView indexPathsForVisibleRows]; + NSArray* visibleIndexPaths = [tableView indexPathsForVisibleRows]; if (!visibleIndexPaths.count) { return 0; } - // Return the first visible row. - NSIndexPath* topMostIndexPath = [visibleIndexPaths objectAtIndex:0]; + NSIndexPath* topMostIndexPath; + UIView* navigationBar = self.navigationController.navigationBar; + CGRect navigationBarFrame = [navigationBar.superview + convertRect:self.navigationController.navigationBar.frame + toView:nil]; + // Take the first row that has its center visible below the navigation bar. + for (NSIndexPath* indexPath in visibleIndexPaths) { + CGRect rowFrame = + [tableView convertRect:[tableView rectForRowAtIndexPath:indexPath] + toView:nil]; + if (CGRectGetMidY(rowFrame) > CGRectGetMaxY(navigationBarFrame)) { + topMostIndexPath = indexPath; + break; + } + } + return topMostIndexPath.row; }
diff --git a/ios/chrome/browser/collaboration/model/messaging/messaging_backend_service_factory.mm b/ios/chrome/browser/collaboration/model/messaging/messaging_backend_service_factory.mm index 7773398..94c942ef 100644 --- a/ios/chrome/browser/collaboration/model/messaging/messaging_backend_service_factory.mm +++ b/ios/chrome/browser/collaboration/model/messaging/messaging_backend_service_factory.mm
@@ -9,6 +9,7 @@ #import "components/collaboration/internal/messaging/configuration.h" #import "components/collaboration/internal/messaging/data_sharing_change_notifier_impl.h" #import "components/collaboration/internal/messaging/empty_messaging_backend_service.h" +#import "components/collaboration/internal/messaging/instant_message_processor_impl.h" #import "components/collaboration/internal/messaging/messaging_backend_service_impl.h" #import "components/collaboration/internal/messaging/storage/empty_messaging_backend_database.h" #import "components/collaboration/internal/messaging/storage/messaging_backend_database_impl.h" @@ -85,6 +86,8 @@ auto messaging_backend_store = std::make_unique<MessagingBackendStoreImpl>( std::move(messaging_backend_database)); + auto instant_message_processor = + std::make_unique<InstantMessageProcessorImpl>(); // iOS does not need any specialized configuration. MessagingBackendConfiguration configuration; @@ -93,7 +96,8 @@ std::make_unique<MessagingBackendServiceImpl>( configuration, std::move(tab_group_change_notifier), std::move(data_sharing_change_notifier), - std::move(messaging_backend_store), tab_group_sync_service, + std::move(messaging_backend_store), + std::move(instant_message_processor), tab_group_sync_service, data_sharing_service, identity_manager); auto* instant_messaging_service =
diff --git a/ios/chrome/browser/ntp/model/set_up_list_unittest.mm b/ios/chrome/browser/ntp/model/set_up_list_unittest.mm index a166bf5a..421eed7 100644 --- a/ios/chrome/browser/ntp/model/set_up_list_unittest.mm +++ b/ios/chrome/browser/ntp/model/set_up_list_unittest.mm
@@ -42,6 +42,7 @@ #import "ios/web/public/test/web_task_environment.h" #import "testing/platform_test.h" #import "third_party/ocmock/OCMock/OCMock.h" +#import "third_party/ocmock/gtest_support.h" using set_up_list_prefs::SetUpListItemState; @@ -338,6 +339,7 @@ // Tests that SetUpList observes local state changes, updates the item, and // calls the delegate. TEST_F(SetUpListTest, ObservesPrefs) { + SetFalseChromeLikelyDefaultBrowser(); BuildSetUpList(); id delegate = [OCMockObject mockForProtocol:@protocol(SetUpListDelegate)]; set_up_list_.delegate = delegate; @@ -347,7 +349,7 @@ set_up_list_prefs::MarkItemComplete(GetLocalState(), SetUpListItemType::kDefaultBrowser); EXPECT_TRUE(item.complete); - [delegate verify]; + EXPECT_OCMOCK_VERIFY(delegate); } // Tests that `allItemsComplete` correctly returns whether all items are
diff --git a/ios/chrome/browser/settings/ui_bundled/google_services/google_services_settings_coordinator.h b/ios/chrome/browser/settings/ui_bundled/google_services/google_services_settings_coordinator.h index 76256e24..8606608 100644 --- a/ios/chrome/browser/settings/ui_bundled/google_services/google_services_settings_coordinator.h +++ b/ios/chrome/browser/settings/ui_bundled/google_services/google_services_settings_coordinator.h
@@ -30,11 +30,6 @@ // Delegate. @property(nonatomic, weak) id<GoogleServicesSettingsCoordinatorDelegate> delegate; -// Whether the Google services settings view is at the top of the navigation -// stack. This does not necessarily mean the view is displayed to the user since -// it can be obstructed by views that are not owned by the navigation stack -// (e.g. MyGoogle UI). -@property(nonatomic, assign, readonly) BOOL googleServicesSettingsViewIsShown; - (instancetype)initWithBaseViewController:(UIViewController*)viewController browser:(Browser*)browser NS_UNAVAILABLE;
diff --git a/ios/chrome/browser/settings/ui_bundled/google_services/google_services_settings_coordinator.mm b/ios/chrome/browser/settings/ui_bundled/google_services/google_services_settings_coordinator.mm index 4baa137..7e8c9c3 100644 --- a/ios/chrome/browser/settings/ui_bundled/google_services/google_services_settings_coordinator.mm +++ b/ios/chrome/browser/settings/ui_bundled/google_services/google_services_settings_coordinator.mm
@@ -10,7 +10,6 @@ #import "components/strings/grit/components_strings.h" #import "components/sync/service/sync_service.h" #import "components/sync/service/sync_user_settings.h" -#import "ios/chrome/browser/authentication/ui_bundled/authentication_flow/authentication_flow.h" #import "ios/chrome/browser/authentication/ui_bundled/authentication_ui_util.h" #import "ios/chrome/browser/authentication/ui_bundled/signin/signin_utils.h" #import "ios/chrome/browser/authentication/ui_bundled/signout_action_sheet/signout_action_sheet_coordinator.h" @@ -50,17 +49,11 @@ @property(nonatomic, strong) GoogleServicesSettingsMediator* mediator; // Returns the authentication service. @property(nonatomic, assign, readonly) AuthenticationService* authService; -// Manages the authentication flow for a given identity. -@property(nonatomic, strong) AuthenticationFlow* authenticationFlow; -// Manages user's Google identities. -@property(nonatomic, assign, readonly) signin::IdentityManager* identityManager; // View controller presented by this coordinator. @property(nonatomic, strong, readonly) GoogleServicesSettingsViewController* googleServicesSettingsViewController; // Action sheets that provides options for sign out. @property(nonatomic, strong) ActionSheetCoordinator* signOutCoordinator; -@property(nonatomic, strong) - SignoutActionSheetCoordinator* signoutActionSheetCoordinator; @end @implementation GoogleServicesSettingsCoordinator @@ -136,12 +129,6 @@ self.signOutCoordinator = nil; } -- (void)authenticationFlowDidComplete { - DCHECK(self.authenticationFlow); - self.authenticationFlow = nil; - [self.googleServicesSettingsViewController allowUserInteraction]; -} - #pragma mark - Properties - (AuthenticationService*)authService { @@ -153,10 +140,6 @@ self.viewController); } -- (signin::IdentityManager*)identityManager { - return IdentityManagerFactory::GetForProfile(self.profile); -} - #pragma mark - GoogleServicesSettingsCommandHandler - (void)showSignOutFromTargetRect:(CGRect)targetRect
diff --git a/ios/chrome/browser/shared/ui/table_view/table_view_navigation_controller.mm b/ios/chrome/browser/shared/ui/table_view/table_view_navigation_controller.mm index e361cbdc..cbd341c 100644 --- a/ios/chrome/browser/shared/ui/table_view/table_view_navigation_controller.mm +++ b/ios/chrome/browser/shared/ui/table_view/table_view_navigation_controller.mm
@@ -19,9 +19,7 @@ - (void)viewDidLoad { [super viewDidLoad]; - self.navigationBar.translucent = NO; self.navigationBar.prefersLargeTitles = YES; - self.toolbar.translucent = NO; self.navigationBar.barTintColor = [UIColor colorNamed:kGroupedPrimaryBackgroundColor];
diff --git a/ios/chrome/browser/ui/content_suggestions/magic_stack/magic_stack_context_menu_interaction_handler.h b/ios/chrome/browser/ui/content_suggestions/magic_stack/magic_stack_context_menu_interaction_handler.h index 2d705c4..8c61541 100644 --- a/ios/chrome/browser/ui/content_suggestions/magic_stack/magic_stack_context_menu_interaction_handler.h +++ b/ios/chrome/browser/ui/content_suggestions/magic_stack/magic_stack_context_menu_interaction_handler.h
@@ -8,6 +8,7 @@ #import <UIKit/UIKit.h> enum class ContentSuggestionsModuleType; +@class MagicStackModule; @protocol MagicStackModuleContainerDelegate; /// Object that handles context menu interactions on the magic stack module.. @@ -15,7 +16,8 @@ : NSObject <UIContextMenuInteractionDelegate> /// Configure the interaction handler with type. -- (void)configureWithType:(ContentSuggestionsModuleType)type; +- (void)configureWithType:(ContentSuggestionsModuleType)type + config:(MagicStackModule*)config; /// Menu elements being shown on interaction. - (NSArray<UIMenuElement*>*)menuElements;
diff --git a/ios/chrome/browser/ui/content_suggestions/magic_stack/magic_stack_context_menu_interaction_handler.mm b/ios/chrome/browser/ui/content_suggestions/magic_stack/magic_stack_context_menu_interaction_handler.mm index a24453d..2a7c0531b 100644 --- a/ios/chrome/browser/ui/content_suggestions/magic_stack/magic_stack_context_menu_interaction_handler.mm +++ b/ios/chrome/browser/ui/content_suggestions/magic_stack/magic_stack_context_menu_interaction_handler.mm
@@ -14,7 +14,10 @@ #import "ios/chrome/browser/shared/ui/symbols/symbols.h" #import "ios/chrome/browser/ui/content_suggestions/content_suggestions_collection_utils.h" #import "ios/chrome/browser/ui/content_suggestions/content_suggestions_constants.h" +#import "ios/chrome/browser/ui/content_suggestions/magic_stack/magic_stack_module.h" #import "ios/chrome/browser/ui/content_suggestions/magic_stack/magic_stack_module_container_delegate.h" +#import "ios/chrome/browser/ui/content_suggestions/shop_card/shop_card_data.h" +#import "ios/chrome/browser/ui/content_suggestions/tab_resumption/tab_resumption_item.h" #import "ios/chrome/grit/ios_branded_strings.h" #import "ios/chrome/grit/ios_strings.h" #import "ui/base/l10n/l10n_util.h" @@ -50,9 +53,21 @@ } /// Title string for the context menu of this container. -NSString* GetContextMenuTitleForType(ContentSuggestionsModuleType type) { +NSString* GetContextMenuTitleForType(ContentSuggestionsModuleType type, + MagicStackModule* config) { switch (type) { case ContentSuggestionsModuleType::kTabResumption: + if (commerce::kShopCardVariation.Get() == commerce::kShopCardArm3) { + TabResumptionItem* tabResumptionItemConfig = + static_cast<TabResumptionItem*>(config); + if (tabResumptionItemConfig.shopCardData && + tabResumptionItemConfig.shopCardData.shopCardItemType == + ShopCardItemType::kPriceDropOnTab && + tabResumptionItemConfig.shopCardData.priceDrop.has_value()) { + return l10n_util::GetNSString( + IDS_IOS_CONTENT_SUGGESTIONS_SHOPCARD_PRICE_DROP_CONTEXT_MENU_TITLE); + } + } return l10n_util::GetNSString(IDS_IOS_TAB_RESUMPTION_CONTEXT_MENU_TITLE); case ContentSuggestionsModuleType::kSafetyCheck: return l10n_util::GetNSString(IDS_IOS_SAFETY_CHECK_CONTEXT_MENU_TITLE); @@ -149,6 +164,9 @@ /// Type of magic stack module being handled. @property(nonatomic, assign) ContentSuggestionsModuleType type; +// Configuration for the Magic Stack Module. +@property(nonatomic, assign) MagicStackModule* config; + /// Whether the magic stack module should be hidden when the context menu /// finishes presentation. @property(nonatomic, assign) BOOL shouldHide; @@ -165,8 +183,10 @@ return self; } -- (void)configureWithType:(ContentSuggestionsModuleType)type { +- (void)configureWithType:(ContentSuggestionsModuleType)type + config:(MagicStackModule*)config { self.type = type; + self.config = config; } - (void)reset { @@ -217,7 +237,8 @@ __weak __typeof(self) weakSelf = self; UIContextMenuActionProvider actionProvider = ^(NSArray<UIMenuElement*>* suggestedActions) { - return [UIMenu menuWithTitle:GetContextMenuTitleForType(weakSelf.type) + return [UIMenu menuWithTitle:GetContextMenuTitleForType(weakSelf.type, + weakSelf.config) children:[weakSelf menuElements]]; }; return
diff --git a/ios/chrome/browser/ui/content_suggestions/magic_stack/magic_stack_module_container.mm b/ios/chrome/browser/ui/content_suggestions/magic_stack/magic_stack_module_container.mm index 7524c03..5a3bd41 100644 --- a/ios/chrome/browser/ui/content_suggestions/magic_stack/magic_stack_module_container.mm +++ b/ios/chrome/browser/ui/content_suggestions/magic_stack/magic_stack_module_container.mm
@@ -304,7 +304,7 @@ return; } _type = config.type; - [[self contextMenuInteractionHandler] configureWithType:_type]; + [[self contextMenuInteractionHandler] configureWithType:_type config:config]; _title.text = [MagicStackModuleContainer titleStringForModule:_type inMagicStack:inMagicStack
diff --git a/ios_internal b/ios_internal index 41d60aa..f1cb064 160000 --- a/ios_internal +++ b/ios_internal
@@ -1 +1 @@ -Subproject commit 41d60aadfdbde1077d2704420cd0c9ac52bbeec9 +Subproject commit f1cb064c6da4d2ef42d1f268c13d2ac07f5ae740
diff --git a/media/audio/win/audio_low_latency_input_win_unittest.cc b/media/audio/win/audio_low_latency_input_win_unittest.cc index 74711df4..63a6084 100644 --- a/media/audio/win/audio_low_latency_input_win_unittest.cc +++ b/media/audio/win/audio_low_latency_input_win_unittest.cc
@@ -12,6 +12,7 @@ #include <memory> +#include "base/compiler_specific.h" #include "base/containers/span.h" #include "base/environment.h" #include "base/files/file_util.h" @@ -132,7 +133,7 @@ } // Write recorded data chunk to the file and prepare for next chunk. - fwrite(chunk.data(), 1, chunk.size(), binary_file_); + UNSAFE_TODO(fwrite(chunk.data(), 1, chunk.size(), binary_file_)); buffer_.Seek(chunk.size()); bytes_written += chunk.size(); }
diff --git a/media/audio/win/core_audio_util_win.cc b/media/audio/win/core_audio_util_win.cc index 5958d966..1a35c7f 100644 --- a/media/audio/win/core_audio_util_win.cc +++ b/media/audio/win/core_audio_util_win.cc
@@ -256,7 +256,8 @@ ScopedCoMem<WCHAR> device_id_com; std::string device_id; if (SUCCEEDED(device->GetId(&device_id_com))) - base::WideToUTF8(device_id_com, wcslen(device_id_com), &device_id); + base::WideToUTF8(device_id_com, UNSAFE_TODO(wcslen(device_id_com)), + &device_id); return device_id; } @@ -283,7 +284,8 @@ if (friendly_name_pv.get().vt == VT_LPWSTR && friendly_name_pv.get().pwszVal) { base::WideToUTF8(friendly_name_pv.get().pwszVal, - wcslen(friendly_name_pv.get().pwszVal), friendly_name); + UNSAFE_TODO(wcslen(friendly_name_pv.get().pwszVal)), + friendly_name); } return hr; @@ -809,7 +811,7 @@ std::string controller_id; base::WideToUTF8(instance_id.get().pwszVal, - wcslen(instance_id.get().pwszVal), + UNSAFE_TODO(wcslen(instance_id.get().pwszVal)), &controller_id); return controller_id; @@ -957,7 +959,7 @@ // the returned structure is correctly extended or not. CHECK_LE(wrapped_format.size(), sizeof(WAVEFORMATEXTENSIBLE)) << "Format tag: 0x" << std::hex << wrapped_format->wFormatTag; - memcpy(format, wrapped_format.get(), wrapped_format.size()); + UNSAFE_TODO(memcpy(format, wrapped_format.get(), wrapped_format.size())); DVLOG(2) << CoreAudioUtil::WaveFormatToString(format); return hr;
diff --git a/media/capture/video/win/sink_input_pin_win.cc b/media/capture/video/win/sink_input_pin_win.cc index 70c05d9d..9d73bdf0 100644 --- a/media/capture/video/win/sink_input_pin_win.cc +++ b/media/capture/video/win/sink_input_pin_win.cc
@@ -11,6 +11,7 @@ #include <dshow.h> #include <stdint.h> +#include "base/compiler_specific.h" #include "base/logging.h" #include "base/time/time.h" #include "base/win/win_util.h" @@ -128,7 +129,7 @@ VIDEOINFOHEADER* const pvi = reinterpret_cast<VIDEOINFOHEADER*>(media_type->pbFormat); - ZeroMemory(pvi, sizeof(VIDEOINFOHEADER)); + UNSAFE_TODO(ZeroMemory(pvi, sizeof(VIDEOINFOHEADER))); pvi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER); pvi->bmiHeader.biPlanes = 1; pvi->bmiHeader.biClrImportant = 0;
diff --git a/media/cdm/aes_cbc_crypto.cc b/media/cdm/aes_cbc_crypto.cc index 8e98bb53..32bfac82 100644 --- a/media/cdm/aes_cbc_crypto.cc +++ b/media/cdm/aes_cbc_crypto.cc
@@ -68,15 +68,12 @@ return true; } -bool AesCbcCrypto::Initialize(const crypto::SymmetricKey& key, - base::span<const uint8_t> iv) { - return Initialize(base::as_byte_span(key.key()), iv); -} - bool AesCbcCrypto::Decrypt(base::span<const uint8_t> encrypted_data, - uint8_t* decrypted_data) { + base::span<uint8_t> decrypted_data) { crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE); + CHECK_GE(decrypted_data.size(), encrypted_data.size()); + if (encrypted_data.size_bytes() % EVP_CIPHER_CTX_block_size(ctx_.get()) != 0) { DVLOG(1) << "Encrypted bytes not a multiple of block size."; @@ -84,7 +81,7 @@ } int out_length; - if (!EVP_DecryptUpdate(ctx_.get(), decrypted_data, &out_length, + if (!EVP_DecryptUpdate(ctx_.get(), decrypted_data.data(), &out_length, encrypted_data.data(), encrypted_data.size_bytes())) { DVLOG(1) << "EVP_DecryptUpdate() failed."; return false;
diff --git a/media/cdm/aes_cbc_crypto.h b/media/cdm/aes_cbc_crypto.h index df5cea1..f8c00b96 100644 --- a/media/cdm/aes_cbc_crypto.h +++ b/media/cdm/aes_cbc_crypto.h
@@ -11,16 +11,16 @@ #include "media/base/media_export.h" #include "third_party/boringssl/src/include/openssl/evp.h" -namespace crypto { -class SymmetricKey; -} - namespace media { // This class implements AES-CBC-128 decryption as described in the Advanced // Encryption Standard specified by AES [FIPS-197, https://www.nist.gov] // using 128-bit keys in Cipher Block Chaining mode, as specified in Block // Cipher Modes [NIST 800-38A, https://www.nist.gov]. +// +// This class uses BoringSSL directly rather than using the abstraction in +// //crypto/aes_cbc because it needs to do streaming decryption with a +// persistent IV rather than one-shot decryption. class MEDIA_EXPORT AesCbcCrypto { public: @@ -35,17 +35,12 @@ // the key or the initialization vector cannot be used. bool Initialize(base::span<const uint8_t> key, base::span<const uint8_t> iv); - // Deprecated initializer that takes a crypto::SymmetricKey. Do not add new - // uses of this - pass the key as a byte span instead. - bool Initialize(const crypto::SymmetricKey& key, - base::span<const uint8_t> iv); - // Decrypts |encrypted_data| into |decrypted_data|. |encrypted_data| must be // a multiple of the blocksize (128 bits), and |decrypted_data| must have // enough space for |encrypted_data|.size(). Returns false if the decryption // fails. bool Decrypt(base::span<const uint8_t> encrypted_data, - uint8_t* decrypted_data); + base::span<uint8_t> decrypted_data); private: bssl::ScopedEVP_CIPHER_CTX ctx_;
diff --git a/media/cdm/aes_cbc_crypto_unittest.cc b/media/cdm/aes_cbc_crypto_unittest.cc index 87de083..087952a 100644 --- a/media/cdm/aes_cbc_crypto_unittest.cc +++ b/media/cdm/aes_cbc_crypto_unittest.cc
@@ -75,9 +75,9 @@ AesCbcCrypto crypto; EXPECT_TRUE(crypto.Initialize(kKey1, kIv)); - std::vector<uint8_t> output(encrypted_block.size()); - EXPECT_TRUE(crypto.Decrypt(encrypted_block, output.data())); - EXPECT_EQ(base::as_byte_span(output), kOneBlock); + std::array<uint8_t, kBlockSize> output; + EXPECT_TRUE(crypto.Decrypt(encrypted_block, output)); + EXPECT_EQ(output, kOneBlock); } TEST(AesCbcCryptoTest, WrongKey) { @@ -88,9 +88,9 @@ AesCbcCrypto crypto; EXPECT_TRUE(crypto.Initialize(kKey2, kIv)); - std::vector<uint8_t> output(encrypted_block.size()); - EXPECT_TRUE(crypto.Decrypt(encrypted_block, output.data())); - EXPECT_NE(base::as_byte_span(output), kOneBlock); + std::array<uint8_t, kBlockSize> output; + EXPECT_TRUE(crypto.Decrypt(encrypted_block, output)); + EXPECT_NE(output, kOneBlock); } TEST(AesCbcCryptoTest, WrongIV) { @@ -99,12 +99,17 @@ // Use a different IV when trying to decrypt. AesCbcCrypto crypto; - std::vector<uint8_t> alternate_iv(kIv.size(), 'a'); - EXPECT_TRUE(crypto.Initialize(kKey1, alternate_iv)); + // clang-format off + constexpr auto kWrongIv = std::to_array<uint8_t>({ + 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', + 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', + }); + // clang-format on + EXPECT_TRUE(crypto.Initialize(kKey1, kWrongIv)); - std::vector<uint8_t> output(encrypted_block.size()); - EXPECT_TRUE(crypto.Decrypt(encrypted_block, output.data())); - EXPECT_NE(base::as_byte_span(output), kOneBlock); + std::array<uint8_t, kBlockSize> output; + EXPECT_TRUE(crypto.Decrypt(encrypted_block, output)); + EXPECT_NE(output, kOneBlock); } TEST(AesCbcCryptoTest, PartialBlock) { @@ -115,10 +120,9 @@ EXPECT_TRUE(crypto.Initialize(kKey2, kIv)); // Try to decrypt less than a full block. - std::vector<uint8_t> output(encrypted_block.size()); + std::array<uint8_t, kBlockSize> output; EXPECT_FALSE(crypto.Decrypt( - base::span(encrypted_block).first(encrypted_block.size() - 5), - output.data())); + base::span(encrypted_block).first(encrypted_block.size() - 5), output)); } TEST(AesCbcCryptoTest, MultipleBlocks) { @@ -131,9 +135,9 @@ AesCbcCrypto crypto; EXPECT_TRUE(crypto.Initialize(kKey2, kIv)); - std::vector<uint8_t> output(encrypted_block.size()); - EXPECT_TRUE(crypto.Decrypt(encrypted_block, output.data())); - EXPECT_EQ(output, Repeat(kOneBlock, kNumBlocksInData)); + std::array<uint8_t, kNumBlocksInData * kBlockSize> output; + EXPECT_TRUE(crypto.Decrypt(encrypted_block, output)); + EXPECT_EQ(output, base::as_byte_span(Repeat(kOneBlock, kNumBlocksInData))); } // As the code in aes_cbc_crypto.cc relies on decrypting the data block by @@ -141,22 +145,23 @@ // decrypts one block at a time or all the blocks in one call. TEST(AesCbcCryptoTest, BlockDecryptionWorks) { constexpr size_t kNumBlocksInData = 5; - std::vector<uint8_t> data = {1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, - 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, - 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, - 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, - 9, 9, 9, 9, 9, 9, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0}; - ASSERT_EQ(data.size(), kNumBlocksInData * kBlockSize); - auto encrypted_data = Encrypt(data, kKey1, kIv); + constexpr auto kData = std::to_array<uint8_t>( + {1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, + 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, + 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, + 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0}); + ASSERT_EQ(kData.size(), kNumBlocksInData * kBlockSize); + auto encrypted_data = Encrypt(kData, kKey1, kIv); // Decrypt |encrypted_data| in one pass. { AesCbcCrypto crypto; EXPECT_TRUE(crypto.Initialize(kKey1, kIv)); - std::vector<uint8_t> output(kNumBlocksInData * kBlockSize); - EXPECT_TRUE(crypto.Decrypt(encrypted_data, output.data())); - EXPECT_EQ(output, data); + std::array<uint8_t, kNumBlocksInData * kBlockSize> output; + ; + EXPECT_TRUE(crypto.Decrypt(encrypted_data, output)); + EXPECT_EQ(output, kData); } // Repeat but call Decrypt() once for each block. @@ -164,13 +169,13 @@ AesCbcCrypto crypto; EXPECT_TRUE(crypto.Initialize(kKey1, kIv)); - std::vector<uint8_t> output(kNumBlocksInData * kBlockSize); - base::span input(encrypted_data); + std::array<uint8_t, kNumBlocksInData * kBlockSize> output; for (size_t offset = 0; offset < output.size(); offset += kBlockSize) { EXPECT_TRUE( - crypto.Decrypt(input.subspan(offset, kBlockSize), &output[offset])); + crypto.Decrypt(base::span(encrypted_data).subspan(offset, kBlockSize), + base::span(output).subspan(offset, kBlockSize))); } - EXPECT_EQ(output, data); + EXPECT_EQ(output, kData); } }
diff --git a/media/cdm/aes_decryptor.cc b/media/cdm/aes_decryptor.cc index c937c8d5..b83b4b4 100644 --- a/media/cdm/aes_decryptor.cc +++ b/media/cdm/aes_decryptor.cc
@@ -15,7 +15,6 @@ #include "base/not_fatal_until.h" #include "base/strings/string_number_conversions.h" #include "base/time/time.h" -#include "crypto/symmetric_key.h" #include "media/base/audio_decoder_config.h" #include "media/base/cdm_promise.h" #include "media/base/decoder_buffer.h" @@ -67,15 +66,16 @@ } // namespace -// Keeps track of the session IDs and DecryptionKeys. The keys are ordered by -// insertion time (last insertion is first). It takes ownership of the -// DecryptionKeys. +// Keeps track of the session IDs and decryption keys. The keys are ordered by +// insertion time (last insertion is first). It creates its own copies of the +// inserted keys. class AesDecryptor::SessionIdDecryptionKeyMap { // Use a std::list to actually hold the data. Insertion is always done // at the front, so the "latest" decryption key is always the first one // in the list. - using KeyList = - std::list<std::pair<std::string, std::unique_ptr<DecryptionKey>>>; + using KeyList = std::list< + std::pair<std::string, + std::array<uint8_t, DecryptConfig::kDecryptionKeySize>>>; public: SessionIdDecryptionKeyMap() = default; @@ -90,7 +90,7 @@ // This |decryption_key| becomes the latest until another insertion or // |session_id| is erased. void Insert(const std::string& session_id, - std::unique_ptr<DecryptionKey> decryption_key); + base::span<const uint8_t> decryption_key); // Deletes the entry for |session_id| if present. void Erase(const std::string& session_id); @@ -98,10 +98,14 @@ // Returns whether the list is empty bool Empty() const { return key_list_.empty(); } - // Returns the last inserted DecryptionKey. - DecryptionKey* LatestDecryptionKey() { - DCHECK(!key_list_.empty()); - return key_list_.begin()->second.get(); + // Returns the last inserted DecryptionKey; returns an empty span if there is + // no such key. + base::span<const uint8_t> LatestDecryptionKey() { + if (!key_list_.empty()) { + return key_list_.begin()->second; + } else { + return {}; + } } bool Contains(const std::string& session_id) { @@ -120,11 +124,13 @@ void AesDecryptor::SessionIdDecryptionKeyMap::Insert( const std::string& session_id, - std::unique_ptr<DecryptionKey> decryption_key) { + base::span<const uint8_t> key) { auto it = Find(session_id); if (it != key_list_.end()) Erase(it); - key_list_.push_front(std::make_pair(session_id, std::move(decryption_key))); + std::array<uint8_t, DecryptConfig::kDecryptionKeySize> local_key; + base::span(local_key).copy_from(key); + key_list_.emplace_front(session_id, local_key); } void AesDecryptor::SessionIdDecryptionKeyMap::Erase( @@ -146,23 +152,22 @@ void AesDecryptor::SessionIdDecryptionKeyMap::Erase( KeyList::iterator position) { - DCHECK(position->second); + DCHECK(!position->second.empty()); key_list_.erase(position); } // Decrypts |input| using |key|. Returns a DecoderBuffer with the decrypted // data if decryption succeeded or NULL if decryption failed. -static scoped_refptr<DecoderBuffer> DecryptData( - const DecoderBuffer& input, - const crypto::SymmetricKey& key) { +static scoped_refptr<DecoderBuffer> DecryptData(const DecoderBuffer& input, + base::span<const uint8_t> key) { CHECK(!input.empty()); CHECK(input.decrypt_config()); if (input.decrypt_config()->encryption_scheme() == EncryptionScheme::kCenc) - return DecryptCencBuffer(input, base::as_byte_span(key.key())); + return DecryptCencBuffer(input, key); if (input.decrypt_config()->encryption_scheme() == EncryptionScheme::kCbcs) - return DecryptCbcsBuffer(input, base::as_byte_span(key.key())); + return DecryptCbcsBuffer(input, key); DVLOG(1) << "Only 'cenc' and 'cbcs' modes supported."; return nullptr; @@ -467,15 +472,14 @@ const std::string& key_id = encrypted->decrypt_config()->key_id(); base::AutoLock auto_lock(key_map_lock_); - DecryptionKey* key = GetKey_Locked(key_id); - if (!key) { + base::span<const uint8_t> key = GetKey_Locked(key_id); + if (key.empty()) { DVLOG(1) << "Could not find a matching key for the given key ID."; std::move(decrypt_cb).Run(kNoKey, nullptr); return; } - scoped_refptr<DecoderBuffer> decrypted = - DecryptData(*encrypted.get(), *key->decryption_key()); + scoped_refptr<DecoderBuffer> decrypted = DecryptData(*encrypted.get(), key); if (!decrypted) { DVLOG(1) << "Decryption failed."; std::move(decrypt_cb).Run(kError, nullptr); @@ -545,8 +549,9 @@ for (const auto& [key_id, session_id_map] : key_map_) { if (session_id_map->Contains(session_id)) { // |key| is the value used to create the decryption key. - std::string key = session_id_map->LatestDecryptionKey()->secret(); - keys.push_back(std::make_pair(key_id, key)); + std::string key( + base::as_string_view(session_id_map->LatestDecryptionKey())); + keys.emplace_back(key_id, key); } } } @@ -556,33 +561,28 @@ bool AesDecryptor::AddDecryptionKey(const std::string& session_id, const std::string& key_id, const std::string& key_string) { - std::unique_ptr<DecryptionKey> decryption_key(new DecryptionKey(key_string)); - if (!decryption_key->Init()) { - DVLOG(1) << "Could not initialize decryption key."; - return false; - } - + auto key = base::as_byte_span(key_string); base::AutoLock auto_lock(key_map_lock_); auto key_id_entry = key_map_.find(key_id); if (key_id_entry != key_map_.end()) { - key_id_entry->second->Insert(session_id, std::move(decryption_key)); + key_id_entry->second->Insert(session_id, key); return true; } // |key_id| not found, so need to create new entry. std::unique_ptr<SessionIdDecryptionKeyMap> inner_map( new SessionIdDecryptionKeyMap()); - inner_map->Insert(session_id, std::move(decryption_key)); + inner_map->Insert(session_id, key); key_map_[key_id] = std::move(inner_map); return true; } -AesDecryptor::DecryptionKey* AesDecryptor::GetKey_Locked( +base::span<const uint8_t> AesDecryptor::GetKey_Locked( const std::string& key_id) const { key_map_lock_.AssertAcquired(); auto key_id_found = key_map_.find(key_id); if (key_id_found == key_map_.end()) - return NULL; + return {}; // Return the key from the "latest" session_id entry. return key_id_found->second->LatestDecryptionKey(); @@ -636,18 +636,4 @@ return keys_info; } -AesDecryptor::DecryptionKey::DecryptionKey(const std::string& secret) - : secret_(secret) {} - -AesDecryptor::DecryptionKey::~DecryptionKey() = default; - -bool AesDecryptor::DecryptionKey::Init() { - CHECK(!secret_.empty()); - decryption_key_ = - crypto::SymmetricKey::Import(crypto::SymmetricKey::AES, secret_); - if (!decryption_key_) - return false; - return true; -} - } // namespace media
diff --git a/media/cdm/aes_decryptor.h b/media/cdm/aes_decryptor.h index 5eb6b9c..f0bbd80 100644 --- a/media/cdm/aes_decryptor.h +++ b/media/cdm/aes_decryptor.h
@@ -25,10 +25,6 @@ #include "media/base/media_export.h" #include "media/cdm/json_web_key.h" -namespace crypto { -class SymmetricKey; -} - namespace media { // Decrypts an AES encrypted buffer into an unencrypted buffer. The AES @@ -121,32 +117,6 @@ bool key_added, std::unique_ptr<SimpleCdmPromise> promise); - // TODO(fgalligan): Remove this and change KeyMap to use crypto::SymmetricKey - // as there are no decryptors that are performing an integrity check. - // Helper class that manages the decryption key. - class DecryptionKey { - public: - explicit DecryptionKey(const std::string& secret); - - DecryptionKey(const DecryptionKey&) = delete; - DecryptionKey& operator=(const DecryptionKey&) = delete; - - ~DecryptionKey(); - - // Creates the encryption key. - bool Init(); - - const std::string& secret() { return secret_; } - crypto::SymmetricKey* decryption_key() { return decryption_key_.get(); } - - private: - // The base secret that is used to create the decryption key. - const std::string secret_; - - // The key used to decrypt the data. - std::unique_ptr<crypto::SymmetricKey> decryption_key_; - }; - // Keep track of the keys for a key ID. If multiple sessions specify keys // for the same key ID, then the last key inserted is used. The structure is // optimized so that Decrypt() has fast access, at the cost of slow deletion @@ -166,9 +136,9 @@ const std::string& key_id, const std::string& key_string); - // Gets a DecryptionKey associated with |key_id|. The AesDecryptor still owns - // the key. Returns NULL if no key is associated with |key_id|. - DecryptionKey* GetKey_Locked(const std::string& key_id) const + // Gets a decryption key associated with |key_id|. The AesDecryptor still owns + // the key. Returns an empty span if no corresponding key exists. + base::span<const uint8_t> GetKey_Locked(const std::string& key_id) const EXCLUSIVE_LOCKS_REQUIRED(key_map_lock_); // Determines if |key_id| is already specified for |session_id|.
diff --git a/media/cdm/cbcs_decryptor.cc b/media/cdm/cbcs_decryptor.cc index 69236c4..d1605dcd 100644 --- a/media/cdm/cbcs_decryptor.cc +++ b/media/cdm/cbcs_decryptor.cc
@@ -39,7 +39,7 @@ base::span<const uint8_t> iv, const EncryptionPattern& pattern, base::span<const uint8_t> input_data, - uint8_t* output_data) { + base::span<uint8_t> output_data) { // The AES_CBC decryption is reset for each subsample. AesCbcCrypto aes_cbc_crypto; if (!aes_cbc_crypto.Initialize(key, iv)) { @@ -77,8 +77,7 @@ // repeat until the end. Note that the input does not have to contain // a full pattern or even |crypt_byte_block| blocks at the end. size_t blocks_processed = 0; - const uint8_t* src = input_data.data(); - uint8_t* dest = output_data; + size_t offset = 0; bool is_encrypted_blocks = false; while (blocks_processed < total_blocks) { is_encrypted_blocks = !is_encrypted_blocks; @@ -90,6 +89,8 @@ continue; size_t bytes_to_process = blocks_to_process * kAesBlockSizeInBytes; + auto src = input_data.subspan(offset, bytes_to_process); + auto dest = output_data.subspan(offset, bytes_to_process); // From ISO/IEC 23001-7:2016(E), section 10.4.2: // For a typical pattern length of 10 (e.g. 1:9) "the pattern is repeated @@ -100,22 +101,24 @@ // remain where the pattern is terminated by the byte length of the range // BytesOfProtectedData, is left unencrypted." if (is_encrypted_blocks) { - if (!aes_cbc_crypto.Decrypt(base::span(src, bytes_to_process), dest)) { + if (!aes_cbc_crypto.Decrypt(src, dest)) { return false; } } else { - memcpy(dest, src, bytes_to_process); + dest.copy_from(src); } blocks_processed += blocks_to_process; - src += bytes_to_process; - dest += bytes_to_process; + offset += bytes_to_process; } // Any partial block data remaining in this subsample is considered // unencrypted so simply copy it into |dest|. - if (remaining_bytes > 0) - memcpy(dest, src, remaining_bytes); + if (remaining_bytes > 0) { + auto src = input_data.subspan(offset, remaining_bytes); + auto dest = output_data.subspan(offset, remaining_bytes); + dest.copy_from(src); + } return true; } @@ -149,7 +152,7 @@ if (subsamples.empty()) { // Assume the whole buffer is encrypted. return DecryptWithPattern(key, base::as_byte_span(decrypt_config->iv()), - pattern, base::span(input), output_data.data()) + pattern, base::span(input), output_data) ? buffer : nullptr; } @@ -181,7 +184,7 @@ dest = dest_rem; if (!DecryptWithPattern(key, base::as_bytes(base::span(decrypt_config->iv())), - pattern, src_cypher, dest_cypher.data())) { + pattern, src_cypher, dest_cypher)) { return nullptr; } }
diff --git a/media/cdm/win/test/media_foundation_clear_key_cdm_factory.h b/media/cdm/win/test/media_foundation_clear_key_cdm_factory.h index 0247f63..8f9653b 100644 --- a/media/cdm/win/test/media_foundation_clear_key_cdm_factory.h +++ b/media/cdm/win/test/media_foundation_clear_key_cdm_factory.h
@@ -2,6 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#ifdef UNSAFE_BUFFERS_BUILD +// TODO(crbug.com/390223051): Remove C-library calls to fix the errors. +#pragma allow_unsafe_libc_calls +#endif + #ifndef MEDIA_CDM_WIN_TEST_MEDIA_FOUNDATION_CLEAR_KEY_CDM_FACTORY_H_ #define MEDIA_CDM_WIN_TEST_MEDIA_FOUNDATION_CLEAR_KEY_CDM_FACTORY_H_
diff --git a/media/gpu/windows/supported_profile_helpers_unittest.cc b/media/gpu/windows/supported_profile_helpers_unittest.cc index 286e4177..7206877 100644 --- a/media/gpu/windows/supported_profile_helpers_unittest.cc +++ b/media/gpu/windows/supported_profile_helpers_unittest.cc
@@ -4,13 +4,16 @@ #include "media/gpu/windows/supported_profile_helpers.h" +#include <initguid.h> + #include <d3d11.h> #include <d3d11_1.h> -#include <initguid.h> + #include <map> #include <utility> #include <vector> +#include "base/compiler_specific.h" #include "base/test/scoped_feature_list.h" #include "media/base/media_switches.h" #include "media/base/test_helpers.h" @@ -158,7 +161,7 @@ struct GUIDComparison { bool operator()(const GUID& a, const GUID& b) const { - return memcmp(&a, &b, sizeof(GUID)) < 0; + return UNSAFE_TODO(memcmp(&a, &b, sizeof(GUID))) < 0; } }; base::flat_map<GUID, gfx::Size, GUIDComparison> max_size_for_guids_;
diff --git a/media/gpu/windows/video_rate_control_wrapper.cc b/media/gpu/windows/video_rate_control_wrapper.cc index 62fcf8d..bb33b1c0e 100644 --- a/media/gpu/windows/video_rate_control_wrapper.cc +++ b/media/gpu/windows/video_rate_control_wrapper.cc
@@ -2,6 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#ifdef UNSAFE_BUFFERS_BUILD +// TODO(tsepez): work around what appears to be a compiler issue. +#pragma allow_unsafe_libc_calls +#endif + #include "media/gpu/windows/video_rate_control_wrapper.h" namespace media {
diff --git a/media/renderers/win/media_foundation_texture_pool_unittest.cc b/media/renderers/win/media_foundation_texture_pool_unittest.cc index fb0ca91..6487fab 100644 --- a/media/renderers/win/media_foundation_texture_pool_unittest.cc +++ b/media/renderers/win/media_foundation_texture_pool_unittest.cc
@@ -4,6 +4,11 @@ #include "media/renderers/win/media_foundation_texture_pool.h" +#include <d3d11.h> +#include <dxgi1_2.h> +#include <wrl/client.h> + +#include "base/compiler_specific.h" #include "base/memory/raw_ptr.h" #include "base/test/mock_callback.h" #include "base/test/task_environment.h" @@ -11,10 +16,6 @@ #include "media/base/test_helpers.h" #include "media/base/win/test_utils.h" -#include <d3d11.h> -#include <dxgi1_2.h> -#include <wrl/client.h> - using Microsoft::WRL::ComPtr; namespace media { @@ -92,8 +93,8 @@ private: MockD3D11Texture2D(const D3D11_TEXTURE2D_DESC* texture_description) : resource_(new MockD3D11Resource()) { - memcpy(&texture_description_, texture_description, - sizeof(D3D11_TEXTURE2D_DESC)); + UNSAFE_TODO(memcpy(&texture_description_, texture_description, + sizeof(D3D11_TEXTURE2D_DESC))); } public: @@ -151,7 +152,7 @@ // ID3D11Texture2D void STDMETHODCALLTYPE GetDesc(D3D11_TEXTURE2D_DESC* description) override { - memset(description, 0, sizeof(D3D11_TEXTURE2D_DESC)); + UNSAFE_TODO(memset(description, 0, sizeof(D3D11_TEXTURE2D_DESC))); } // ID3D11Resource @@ -540,4 +541,4 @@ wait_event.Wait(); } -} // namespace media \ No newline at end of file +} // namespace media
diff --git a/net/BUILD.gn b/net/BUILD.gn index 8a5f55b..77c8845c 100644 --- a/net/BUILD.gn +++ b/net/BUILD.gn
@@ -1078,6 +1078,7 @@ "url_request/referrer_policy.h", "url_request/static_http_user_agent_settings.cc", "url_request/static_http_user_agent_settings.h", + "url_request/storage_access_status_cache.h", "url_request/url_request.cc", "url_request/url_request.h", "url_request/url_request_context.cc", @@ -2966,6 +2967,7 @@ "tools/tld_cleanup/tld_cleanup_util_unittest.cc", "url_request/redirect_info_unittest.cc", "url_request/redirect_util_unittest.cc", + "url_request/storage_access_status_cache_unittest.cc", "url_request/url_request_context_builder_unittest.cc", "url_request/url_request_filter_unittest.cc", "url_request/url_request_http_job_unittest.cc",
diff --git a/net/cert/internal/path_builder_trust_store_win_unittest.cc b/net/cert/internal/path_builder_trust_store_win_unittest.cc index a611eb5..8a590c5 100644 --- a/net/cert/internal/path_builder_trust_store_win_unittest.cc +++ b/net/cert/internal/path_builder_trust_store_win_unittest.cc
@@ -2,11 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "third_party/boringssl/src/pki/path_builder.h" - #include <algorithm> #include "base/base_paths.h" +#include "base/compiler_specific.h" #include "base/files/file_util.h" #include "base/functional/callback_forward.h" #include "base/path_service.h" @@ -26,6 +25,7 @@ #include "third_party/boringssl/src/pki/common_cert_errors.h" #include "third_party/boringssl/src/pki/input.h" #include "third_party/boringssl/src/pki/parsed_certificate.h" +#include "third_party/boringssl/src/pki/path_builder.h" #include "third_party/boringssl/src/pki/pem.h" #include "third_party/boringssl/src/pki/simple_path_builder_delegate.h" #include "third_party/boringssl/src/pki/trust_store_collection.h" @@ -192,7 +192,7 @@ X509_ASN_ENCODING, cert->der_cert().data(), cert->der_cert().size())); CERT_ENHKEY_USAGE usage; - memset(&usage, 0, sizeof(usage)); + UNSAFE_TODO(memset(&usage, 0, sizeof(usage))); CertSetEnhancedKeyUsage(os_cert.get(), &usage); if (usage_identifier) { CertAddEnhancedKeyUsageIdentifier(os_cert.get(), usage_identifier);
diff --git a/net/cert/internal/trust_store_win_unittest.cc b/net/cert/internal/trust_store_win_unittest.cc index 1044b24..a9fa2d15 100644 --- a/net/cert/internal/trust_store_win_unittest.cc +++ b/net/cert/internal/trust_store_win_unittest.cc
@@ -8,6 +8,7 @@ #include <memory> #include <string_view> +#include "base/compiler_specific.h" #include "base/containers/to_vector.h" #include "base/logging.h" #include "base/memory/ptr_util.h" @@ -101,7 +102,7 @@ CRYPTO_BUFFER_len(cert->cert_buffer()))); CERT_ENHKEY_USAGE usage; - memset(&usage, 0, sizeof(usage)); + UNSAFE_TODO(memset(&usage, 0, sizeof(usage))); if (!CertSetEnhancedKeyUsage(os_cert.get(), &usage)) { return false; }
diff --git a/net/device_bound_sessions/registration_fetcher.cc b/net/device_bound_sessions/registration_fetcher.cc index 0203f584..9081fa5 100644 --- a/net/device_bound_sessions/registration_fetcher.cc +++ b/net/device_bound_sessions/registration_fetcher.cc
@@ -125,6 +125,7 @@ std::move(optional_header_and_payload.value()); unexportable_key_service.SignSlowlyAsync( key_id, base::as_byte_span(header_and_payload), kTaskPriority, + /*max_retries=*/0, base::BindOnce(&OnDataSigned, expected_algorithm.value(), std::ref(unexportable_key_service), header_and_payload, key_id, std::move(callback)));
diff --git a/net/device_bound_sessions/registration_fetcher_unittest.cc b/net/device_bound_sessions/registration_fetcher_unittest.cc index 0b8d55d9..3597a54 100644 --- a/net/device_bound_sessions/registration_fetcher_unittest.cc +++ b/net/device_bound_sessions/registration_fetcher_unittest.cc
@@ -1186,8 +1186,8 @@ .WillRepeatedly(Invoke( &unexportable_key_service(), &unexportable_keys::UnexportableKeyService::GetSubjectPublicKeyInfo)); - EXPECT_CALL(mock_service, SignSlowlyAsync(_, _, _, _)) - .WillOnce(base::test::RunOnceCallback<3>( + EXPECT_CALL(mock_service, SignSlowlyAsync(_, _, _, _, _)) + .WillOnce(base::test::RunOnceCallback<4>( base::unexpected(unexportable_keys::ServiceError::kCryptoApiFailed))) .WillOnce( Invoke(&unexportable_key_service(), @@ -1224,8 +1224,8 @@ .WillRepeatedly(Invoke( &unexportable_key_service(), &unexportable_keys::UnexportableKeyService::GetSubjectPublicKeyInfo)); - EXPECT_CALL(mock_service, SignSlowlyAsync(_, _, _, _)) - .WillRepeatedly(base::test::RunOnceCallbackRepeatedly<3>( + EXPECT_CALL(mock_service, SignSlowlyAsync(_, _, _, _, _)) + .WillRepeatedly(base::test::RunOnceCallbackRepeatedly<4>( base::unexpected(unexportable_keys::ServiceError::kCryptoApiFailed))); TestRegistrationCallback callback; @@ -1261,8 +1261,8 @@ .WillRepeatedly(Invoke( &unexportable_key_service(), &unexportable_keys::UnexportableKeyService::GetSubjectPublicKeyInfo)); - EXPECT_CALL(mock_service, SignSlowlyAsync(_, _, _, _)) - .WillRepeatedly(base::test::RunOnceCallbackRepeatedly<3>( + EXPECT_CALL(mock_service, SignSlowlyAsync(_, _, _, _, _)) + .WillRepeatedly(base::test::RunOnceCallbackRepeatedly<4>( base::unexpected(unexportable_keys::ServiceError::kCryptoApiFailed))); TestRegistrationCallback callback;
diff --git a/net/http/http_auth_handler_negotiate_unittest.cc b/net/http/http_auth_handler_negotiate_unittest.cc index 900b586..7007ef13 100644 --- a/net/http/http_auth_handler_negotiate_unittest.cc +++ b/net/http/http_auth_handler_negotiate_unittest.cc
@@ -7,6 +7,7 @@ #include <memory> #include <string> +#include "base/compiler_specific.h" #include "base/functional/bind.h" #include "base/memory/ptr_util.h" #include "base/memory/raw_ptr.h" @@ -95,7 +96,7 @@ void SetupMocks(MockAuthLibrary* mock_library) { #if BUILDFLAG(IS_WIN) security_package_ = std::make_unique<SecPkgInfoW>(); - memset(security_package_.get(), 0x0, sizeof(SecPkgInfoW)); + UNSAFE_TODO(memset(security_package_.get(), 0x0, sizeof(SecPkgInfoW))); security_package_->cbMaxToken = 1337; mock_library->ExpectQuerySecurityPackageInfo(SEC_E_OK, security_package_.get());
diff --git a/net/http/http_auth_sspi_win_unittest.cc b/net/http/http_auth_sspi_win_unittest.cc index 7a8bb25..44d8de9 100644 --- a/net/http/http_auth_sspi_win_unittest.cc +++ b/net/http/http_auth_sspi_win_unittest.cc
@@ -8,6 +8,7 @@ #include <vector> #include "base/base64.h" +#include "base/compiler_specific.h" #include "base/functional/bind.h" #include "base/json/json_reader.h" #include "net/base/net_errors.h" @@ -56,7 +57,7 @@ TEST(HttpAuthSSPITest, DetermineMaxTokenLength_Normal) { SecPkgInfoW package_info; - memset(&package_info, 0x0, sizeof(package_info)); + UNSAFE_TODO(memset(&package_info, 0x0, sizeof(package_info))); package_info.cbMaxToken = 1337; MockSSPILibrary mock_library{L"NTLM"};
diff --git a/net/http/http_cache_transaction.cc b/net/http/http_cache_transaction.cc index e3dd46c..52169e7a 100644 --- a/net/http/http_cache_transaction.cc +++ b/net/http/http_cache_transaction.cc
@@ -2,15 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifdef UNSAFE_BUFFERS_BUILD -// TODO(crbug.com/40284755): Remove this and spanify to fix the errors. -#pragma allow_unsafe_buffers -#endif - #include "net/http/http_cache_transaction.h" -#include <array> - #include "base/time/time.h" #include "build/build_config.h" // For IS_POSIX @@ -19,8 +12,10 @@ #endif #include <algorithm> +#include <array> #include <memory> #include <string> +#include <string_view> #include <type_traits> #include <utility> @@ -112,57 +107,56 @@ written_at_run_id.value() < clear_at_run_id.value()); } +// If the request includes one of these request headers, then avoid caching +// to avoid getting confused. struct HeaderNameAndValue { - const char* name; - const char* value; + std::string_view name; + std::optional<std::string_view> value; }; // If the request includes one of these request headers, then avoid caching // to avoid getting confused. -constexpr HeaderNameAndValue kPassThroughHeaders[] = { - {"if-unmodified-since", nullptr}, // causes unexpected 412s - {"if-match", nullptr}, // causes unexpected 412s - {"if-range", nullptr}, - {nullptr, nullptr}}; +constexpr auto kPassThroughHeaders = std::to_array( + {HeaderNameAndValue{"if-unmodified-since", + std::nullopt}, // causes unexpected 412s + HeaderNameAndValue{"if-match", std::nullopt}, // causes unexpected 412s + HeaderNameAndValue{"if-range", std::nullopt}}); struct ValidationHeaderInfo { - const char* request_header_name; - const char* related_response_header_name; + std::string_view request_header_name; + std::string_view related_response_header_name; }; -constexpr auto kValidationHeaders = std::to_array<ValidationHeaderInfo>({ - {"if-modified-since", "last-modified"}, - {"if-none-match", "etag"}, -}); +constexpr auto kValidationHeaders = std::to_array<ValidationHeaderInfo>( + {{"if-modified-since", "last-modified"}, {"if-none-match", "etag"}}); // If the request includes one of these request headers, then avoid reusing // our cached copy if any. -constexpr HeaderNameAndValue kForceFetchHeaders[] = { - {"cache-control", "no-cache"}, - {"pragma", "no-cache"}, - {nullptr, nullptr}}; +constexpr auto kForceFetchHeaders = + std::to_array({HeaderNameAndValue{"cache-control", "no-cache"}, + HeaderNameAndValue{"pragma", "no-cache"}}); // If the request includes one of these request headers, then force our // cached copy (if any) to be revalidated before reusing it. -constexpr HeaderNameAndValue kForceValidateHeaders[] = { - {"cache-control", "max-age=0"}, - {nullptr, nullptr}}; +constexpr auto kForceValidateHeaders = + std::to_array({HeaderNameAndValue{"cache-control", "max-age=0"}}); bool HeaderMatches(const HttpRequestHeaders& headers, - const HeaderNameAndValue* search) { - for (; search->name; ++search) { - std::optional<std::string> header_value = headers.GetHeader(search->name); + base::span<const HeaderNameAndValue> search_headers) { + for (const auto& search_header : search_headers) { + std::optional<std::string> header_value = + headers.GetHeader(search_header.name); if (!header_value) { continue; } - if (!search->value) { + if (!search_header.value) { return true; } HttpUtil::ValuesIterator v(*header_value, ','); while (v.GetNext()) { - if (base::EqualsCaseInsensitiveASCII(v.value(), search->value)) { + if (base::EqualsCaseInsensitiveASCII(v.value(), *search_header.value)) { return true; } } @@ -2649,7 +2643,7 @@ static const struct { // RAW_PTR_EXCLUSION: Never allocated by PartitionAlloc (always points to // constexpr tables), so there is no benefit to using a raw_ptr, only cost. - RAW_PTR_EXCLUSION const HeaderNameAndValue* search; + RAW_PTR_EXCLUSION const base::span<const HeaderNameAndValue> search; int load_flag; } kSpecialHeaders[] = { {kPassThroughHeaders, LOAD_DISABLE_CACHE}, @@ -4037,6 +4031,9 @@ entry_->writers()->HasTransaction(this); } +HttpCache::Transaction::ValidationHeaders::ValidationHeaders() = default; +HttpCache::Transaction::ValidationHeaders::~ValidationHeaders() = default; + HttpCache::Transaction::NetworkTransactionInfo::NetworkTransactionInfo() = default; HttpCache::Transaction::NetworkTransactionInfo::~NetworkTransactionInfo() =
diff --git a/net/http/http_cache_transaction.h b/net/http/http_cache_transaction.h index 56d2fdb0..9d422c6c 100644 --- a/net/http/http_cache_transaction.h +++ b/net/http/http_cache_transaction.h
@@ -11,6 +11,7 @@ #include <stddef.h> #include <stdint.h> +#include <array> #include <memory> #include <string> @@ -200,9 +201,14 @@ // Helper struct to pair a header name with its value, for // headers used to validate cache entries. struct ValidationHeaders { - ValidationHeaders() = default; + ValidationHeaders(); - std::string values[kNumValidationHeaders]; + ValidationHeaders(const ValidationHeaders&) = delete; + ValidationHeaders& operator=(const ValidationHeaders&) = delete; + + ~ValidationHeaders(); + + std::array<std::string, kNumValidationHeaders> values; void Reset() { initialized = false; for (auto& value : values) {
diff --git a/net/http/mock_sspi_library_win.cc b/net/http/mock_sspi_library_win.cc index b2c9438..dcf1975 100644 --- a/net/http/mock_sspi_library_win.cc +++ b/net/http/mock_sspi_library_win.cc
@@ -10,6 +10,7 @@ #include <string> #include "base/check_op.h" +#include "base/compiler_specific.h" #include "base/memory/raw_ptr.h" #include "base/strings/string_util_win.h" #include "base/strings/stringprintf.h" @@ -173,7 +174,8 @@ auto token = new_context->ToString(); PSecBuffer out_buffer = pOutput->pBuffers; out_buffer->cbBuffer = std::min<ULONG>(out_buffer->cbBuffer, token.size()); - std::memcpy(out_buffer->pvBuffer, token.data(), out_buffer->cbBuffer); + UNSAFE_TODO( + std::memcpy(out_buffer->pvBuffer, token.data(), out_buffer->cbBuffer)); if (ptsExpiry) { ptsExpiry->LowPart = 0xBAA5B780;
diff --git a/net/url_request/storage_access_status_cache.h b/net/url_request/storage_access_status_cache.h new file mode 100644 index 0000000..6b81b2d --- /dev/null +++ b/net/url_request/storage_access_status_cache.h
@@ -0,0 +1,56 @@ +// Copyright 2025 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NET_URL_REQUEST_STORAGE_ACCESS_STATUS_CACHE_H_ +#define NET_URL_REQUEST_STORAGE_ACCESS_STATUS_CACHE_H_ + +#include <optional> +#include <variant> + +#include "base/types/optional_util.h" +#include "net/cookies/cookie_util.h" + +namespace net { + +// Holds the StorageAccessStatus of the request. +// TODO(https://crbug.com/366284840): move this out of //net together with the +// `URLRequest::storage_access_status_`. +class StorageAccessStatusCache { + public: + StorageAccessStatusCache() = default; + + explicit StorageAccessStatusCache( + std::optional<net::cookie_util::StorageAccessStatus> + storage_access_status) { + if (storage_access_status.has_value()) { + state_ = storage_access_status.value(); + } else { + state_ = FirstParty{}; + } + } + + friend bool operator==(const StorageAccessStatusCache& status, + cookie_util::StorageAccessStatus status_enum) { + return status.GetStatusForThirdPartyContext() == status_enum; + } + + // Returns the cached storage access status as an optional. Nullopt if the + // state is `FirstParty`. + std::optional<net::cookie_util::StorageAccessStatus> + GetStatusForThirdPartyContext() const { + return base::OptionalFromPtr( + std::get_if<net::cookie_util::StorageAccessStatus>(&state_)); + } + + private: + // `state_` variant used when the storage access status is not applicable + // because the request is first-party. + struct FirstParty {}; + + std::variant<FirstParty, net::cookie_util::StorageAccessStatus> state_; +}; + +} // namespace net + +#endif // NET_URL_REQUEST_STORAGE_ACCESS_STATUS_CACHE_H_
diff --git a/net/url_request/storage_access_status_cache_unittest.cc b/net/url_request/storage_access_status_cache_unittest.cc new file mode 100644 index 0000000..8b170d9c --- /dev/null +++ b/net/url_request/storage_access_status_cache_unittest.cc
@@ -0,0 +1,44 @@ +// Copyright 2025 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/url_request/storage_access_status_cache.h" + +#include "net/cookies/cookie_util.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace net { + +namespace { + +TEST(StorageAccessStatusTest, DefaultConstructor) { + StorageAccessStatusCache status; + EXPECT_EQ(status.GetStatusForThirdPartyContext(), std::nullopt); +} + +TEST(StorageAccessStatusTest, ConstructorWithValue) { + StorageAccessStatusCache status( + net::cookie_util::StorageAccessStatus::kActive); + EXPECT_EQ(status.GetStatusForThirdPartyContext(), + std::make_optional(net::cookie_util::StorageAccessStatus::kActive)); +} + +TEST(StorageAccessStatusTest, ConstructorWithNullopt) { + StorageAccessStatusCache status(std::nullopt); + EXPECT_EQ(status.GetStatusForThirdPartyContext(), std::nullopt); +} + +TEST(StorageAccessStatusTest, EqualityOperatorWithValue) { + StorageAccessStatusCache status(cookie_util::StorageAccessStatus::kActive); + EXPECT_EQ(status, cookie_util::StorageAccessStatus::kActive); + EXPECT_NE(status, cookie_util::StorageAccessStatus::kNone); +} + +TEST(StorageAccessStatusTest, EqualityOperatorWithoutValue) { + StorageAccessStatusCache status; + EXPECT_NE(status, cookie_util::StorageAccessStatus::kNone); +} + +} // namespace + +} // namespace net
diff --git a/net/url_request/url_request.cc b/net/url_request/url_request.cc index b47bb683..4c48b8f 100644 --- a/net/url_request/url_request.cc +++ b/net/url_request/url_request.cc
@@ -46,6 +46,7 @@ #include "net/storage_access_api/status.h" #include "net/url_request/redirect_info.h" #include "net/url_request/redirect_util.h" +#include "net/url_request/storage_access_status_cache.h" #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_error_job.h" #include "net/url_request/url_request_job.h" @@ -1099,8 +1100,9 @@ // implies that the URL is "potentially trustworthy" and that adding the // `kStorageAccessGrantEligibleViaHeader` override is sufficient to make the // status "active". - CHECK(storage_access_status()); - CHECK_EQ(static_cast<int>(storage_access_status().value()), + CHECK(storage_access_status().GetStatusForThirdPartyContext()); + CHECK_EQ(static_cast<int>( + storage_access_status().GetStatusForThirdPartyContext().value()), static_cast<int>(cookie_util::StorageAccessStatus::kActive)); extra_request_headers_.SetHeader("Sec-Fetch-Storage-Access", "active"); base::UmaHistogramEnumeration( @@ -1384,8 +1386,8 @@ DCHECK(url().SchemeIsHTTPOrHTTPS()); socket_tag_ = socket_tag; } -std::optional<net::cookie_util::StorageAccessStatus> -URLRequest::CalculateStorageAccessStatus() const { + +StorageAccessStatusCache URLRequest::CalculateStorageAccessStatus() const { CHECK_EQ(is_redirecting(), deferred_redirect_info_.has_value()); // `Delegate::OnReceivedRedirect` may set `defer_redirect` inside of @@ -1423,7 +1425,7 @@ "API.StorageAccessHeader.StorageAccessStatusOutcome", storage_access_value_outcome.value()); - return storage_access_status; + return StorageAccessStatusCache(storage_access_status); } void URLRequest::SetSharedDictionaryGetter(
diff --git a/net/url_request/url_request.h b/net/url_request/url_request.h index 80697d59b..4b58b6b 100644 --- a/net/url_request/url_request.h +++ b/net/url_request/url_request.h
@@ -59,6 +59,7 @@ #include "net/traffic_annotation/network_traffic_annotation.h" #include "net/url_request/redirect_info.h" #include "net/url_request/referrer_policy.h" +#include "net/url_request/storage_access_status_cache.h" #include "url/gurl.h" #include "url/origin.h" @@ -884,16 +885,14 @@ void SetSharedDictionaryGetter( SharedDictionaryGetter shared_dictionary_getter); - void set_storage_access_status( - std::optional<cookie_util::StorageAccessStatus> status) { + void set_storage_access_status(StorageAccessStatusCache status) { storage_access_status_ = status; } // Returns the StorageAccessStatus for this request. // TODO(https://crbug.com/366284840): move this state out of //net (into // network::URLLoader) to respect layering rules. - std::optional<cookie_util::StorageAccessStatus> storage_access_status() - const { + StorageAccessStatusCache storage_access_status() const { return storage_access_status_; } @@ -907,8 +906,7 @@ // `Delegate::OnReceivedRedirect`. // TODO(https://crbug.com/366284840): Move this to URLLoader once the // "Activate-Storage-Access: retry" header is handled in URLLoader. - std::optional<net::cookie_util::StorageAccessStatus> - CalculateStorageAccessStatus() const; + StorageAccessStatusCache CalculateStorageAccessStatus() const; base::WeakPtr<URLRequest> GetWeakPtr(); @@ -1200,9 +1198,8 @@ SharedDictionaryGetter shared_dictionary_getter_; - // The storage access status for this request. If this is nullopt, this - // request will not include the Sec-Fetch-Storage-Access header. - std::optional<net::cookie_util::StorageAccessStatus> storage_access_status_; + // The storage access status for this request. + StorageAccessStatusCache storage_access_status_; base::RepeatingCallback<void(const device_bound_sessions::SessionAccess&)> device_bound_session_access_callback_;
diff --git a/net/url_request/url_request_unittest.cc b/net/url_request/url_request_unittest.cc index 50df4bb..6c02f18 100644 --- a/net/url_request/url_request_unittest.cc +++ b/net/url_request/url_request_unittest.cc
@@ -147,6 +147,7 @@ #include "net/url_request/redirect_util.h" #include "net/url_request/referrer_policy.h" #include "net/url_request/static_http_user_agent_settings.h" +#include "net/url_request/storage_access_status_cache.h" #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_context_builder.h" #include "net/url_request/url_request_filter.h" @@ -13749,7 +13750,8 @@ test.origin_header->Serialize(), /*overwrite=*/true); } - req->set_storage_access_status(cookie_util::StorageAccessStatus::kInactive); + req->set_storage_access_status( + StorageAccessStatusCache(cookie_util::StorageAccessStatus::kInactive)); req->Start(); d.RunUntilComplete(); @@ -13880,13 +13882,15 @@ std::unique_ptr<URLRequest> req(context->CreateRequest( http_test_server()->GetURL(kStorageAccessRetryPath), DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS)); - req->set_storage_access_status(cookie_util::StorageAccessStatus::kInactive); + req->set_storage_access_status( + StorageAccessStatusCache(cookie_util::StorageAccessStatus::kInactive)); req->Start(); d.RunUntilRedirect(); EXPECT_EQ(req->url().path(), kStorageAccessRetryPath); - req->set_storage_access_status(cookie_util::StorageAccessStatus::kActive); + req->set_storage_access_status( + StorageAccessStatusCache(cookie_util::StorageAccessStatus::kActive)); req->FollowDeferredRedirect(/*removed_headers=*/{}, /*modified_headers=*/{}); d.RunUntilComplete(); @@ -13931,7 +13935,8 @@ std::unique_ptr<URLRequest> req(context->CreateRequest( http_test_server()->GetURL(kStorageAccessRetryPath), DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS)); - req->set_storage_access_status(cookie_util::StorageAccessStatus::kInactive); + req->set_storage_access_status( + StorageAccessStatusCache(cookie_util::StorageAccessStatus::kInactive)); req->Start(); d.RunUntilComplete(); @@ -13975,7 +13980,8 @@ std::unique_ptr<URLRequest> req(context->CreateRequest( http_test_server()->GetURL(kStorageAccessRetryPath), DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS)); - req->set_storage_access_status(cookie_util::StorageAccessStatus::kInactive); + req->set_storage_access_status( + StorageAccessStatusCache(cookie_util::StorageAccessStatus::kInactive)); req->Start(); d.RunUntilComplete(); @@ -14013,7 +14019,8 @@ std::unique_ptr<URLRequest> req(context->CreateRequest( http_test_server()->GetURL(kStorageAccessRetryPath), DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS)); - req->set_storage_access_status(cookie_util::StorageAccessStatus::kInactive); + req->set_storage_access_status( + StorageAccessStatusCache(cookie_util::StorageAccessStatus::kInactive)); req->Start(); d.RunUntilComplete();
diff --git a/pdf/pdfium/pdfium_api_wrappers.cc b/pdf/pdfium/pdfium_api_wrappers.cc index b13fe20..7f749f9c 100644 --- a/pdf/pdfium/pdfium_api_wrappers.cc +++ b/pdf/pdfium/pdfium_api_wrappers.cc
@@ -12,6 +12,7 @@ #include <utility> #include "base/check_op.h" +#include "base/compiler_specific.h" #include "base/containers/span.h" #include "base/numerics/checked_math.h" #include "base/numerics/safe_conversions.h" @@ -240,7 +241,7 @@ rotate, flags); int stride = FPDFBitmap_GetStride(bitmap.get()); BITMAPINFO bmi; - memset(&bmi, 0, sizeof(bmi)); + UNSAFE_TODO(memset(&bmi, 0, sizeof(bmi))); bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bmi.bmiHeader.biWidth = dest.width(); bmi.bmiHeader.biHeight = -dest.height(); // top-down image
diff --git a/printing/backend/win_helper.cc b/printing/backend/win_helper.cc index 5150a27..ad90c11 100644 --- a/printing/backend/win_helper.cc +++ b/printing/backend/win_helper.cc
@@ -12,6 +12,7 @@ #include <string_view> #include "base/check_op.h" +#include "base/compiler_specific.h" #include "base/containers/fixed_flat_set.h" #include "base/debug/alias.h" #include "base/file_version_info.h" @@ -586,8 +587,9 @@ const DRIVER_INFO_6* p = info_6.get(); // Only HP known to have issues. - if (!p->pszMfgName || wcscmp(p->pszMfgName, L"HP") != 0) + if (!p->pszMfgName || UNSAFE_TODO(wcscmp(p->pszMfgName, L"HP")) != 0) { return default_ticket; + } // Need XPS for this workaround. ScopedXPSInitializer xps_initializer;
diff --git a/printing/emf_win.cc b/printing/emf_win.cc index 6f688db5..82eed7d 100644 --- a/printing/emf_win.cc +++ b/printing/emf_win.cc
@@ -222,7 +222,7 @@ } Emf::EnumerationContext::EnumerationContext() { - memset(this, 0, sizeof(*this)); + UNSAFE_TODO(memset(this, 0, sizeof(*this))); } Emf::Record::Record(const ENHMETARECORD* record) : record_(record) {
diff --git a/printing/print_settings_initializer_win.cc b/printing/print_settings_initializer_win.cc index 8de799f..d21f592e 100644 --- a/printing/print_settings_initializer_win.cc +++ b/printing/print_settings_initializer_win.cc
@@ -6,6 +6,8 @@ #include <windows.h> +#include "base/check_op.h" +#include "base/compiler_specific.h" #include "printing/backend/win_helper.h" #include "printing/mojom/print.mojom.h" #include "printing/print_settings.h" @@ -28,10 +30,10 @@ return false; char buf[256]; - memset(buf, 0, sizeof(buf)); + UNSAFE_TODO(memset(buf, 0, sizeof(buf))); if (ExtEscape(hdc, GETTECHNOLOGY, 0, nullptr, sizeof(buf) - 1, buf) <= 0) return false; - return strcmp(buf, technology) == 0; + return UNSAFE_TODO(strcmp(buf, technology)) == 0; } void SetPrinterToGdiMode(HDC hdc) {
diff --git a/printing/printing_context_system_dialog_win.cc b/printing/printing_context_system_dialog_win.cc index 858e1bb..d5eec01f 100644 --- a/printing/printing_context_system_dialog_win.cc +++ b/printing/printing_context_system_dialog_win.cc
@@ -74,7 +74,7 @@ dialog_options.nStartPage = START_PAGE_GENERAL; if (max_pages) { // Default initialize to print all the pages. - memset(ranges, 0, sizeof(ranges)); + UNSAFE_TODO(memset(ranges, 0, sizeof(ranges))); ranges[0].nFromPage = 1; ranges[0].nToPage = max_pages; dialog_options.nPageRanges = 1;
diff --git a/printing/printing_context_win.cc b/printing/printing_context_win.cc index 5f46560..608fcc2 100644 --- a/printing/printing_context_win.cc +++ b/printing/printing_context_win.cc
@@ -186,7 +186,7 @@ wchar_t paper_type_buffer[paper_type_buffer_len] = {}; GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_IPAPERSIZE, paper_type_buffer, paper_type_buffer_len); - if (wcslen(paper_type_buffer)) { // The call succeeded. + if (UNSAFE_TODO(wcslen(paper_type_buffer))) { // The call succeeded. int paper_code = _wtoi(paper_type_buffer); switch (paper_code) { case DMPAPER_LEGAL:
diff --git a/printing/printing_context_win_unittest.cc b/printing/printing_context_win_unittest.cc index 1e639bb..2021e3b 100644 --- a/printing/printing_context_win_unittest.cc +++ b/printing/printing_context_win_unittest.cc
@@ -106,7 +106,7 @@ void* dev_mode_ptr = GlobalLock(dev_mode_mem.Get()); if (!dev_mode_ptr) return E_FAIL; - memcpy(dev_mode_ptr, dev_mode, dev_mode_size); + UNSAFE_TODO(memcpy(dev_mode_ptr, dev_mode, dev_mode_size)); GlobalUnlock(dev_mode_mem.Get()); dev_mode_ptr = nullptr;
diff --git a/remoting/base/url_loader_network_service_observer.cc b/remoting/base/url_loader_network_service_observer.cc index a294d6f..0d52287 100644 --- a/remoting/base/url_loader_network_service_observer.cc +++ b/remoting/base/url_loader_network_service_observer.cc
@@ -127,6 +127,9 @@ const std::optional<std::string>& private_network_device_name, OnPrivateNetworkAccessPermissionRequiredCallback callback) {} +void UrlLoaderNetworkServiceObserver::OnLocalNetworkAccessPermissionRequired( + OnLocalNetworkAccessPermissionRequiredCallback callback) {} + void UrlLoaderNetworkServiceObserver::OnClearSiteData( const GURL& url, const std::string& header_value,
diff --git a/remoting/base/url_loader_network_service_observer.h b/remoting/base/url_loader_network_service_observer.h index 753ca89d..ab1cf60 100644 --- a/remoting/base/url_loader_network_service_observer.h +++ b/remoting/base/url_loader_network_service_observer.h
@@ -63,6 +63,8 @@ const std::optional<std::string>& private_network_device_id, const std::optional<std::string>& private_network_device_name, OnPrivateNetworkAccessPermissionRequiredCallback callback) override; + void OnLocalNetworkAccessPermissionRequired( + OnLocalNetworkAccessPermissionRequiredCallback callback) override; void OnClearSiteData( const GURL& url, const std::string& header_value,
diff --git a/remoting/host/desktop_resizer_win.cc b/remoting/host/desktop_resizer_win.cc index eea636d..b0c39412 100644 --- a/remoting/host/desktop_resizer_win.cc +++ b/remoting/host/desktop_resizer_win.cc
@@ -9,6 +9,7 @@ #include <map> #include "base/check.h" +#include "base/compiler_specific.h" #include "base/logging.h" #include "base/memory/ptr_util.h" #include "base/notreached.h" @@ -255,7 +256,7 @@ bool DesktopResizerWin::GetPrimaryDisplayMode(DWORD mode_number, DWORD flags, DEVMODE* mode) { - memset(mode, 0, sizeof(DEVMODE)); + UNSAFE_TODO(memset(mode, 0, sizeof(DEVMODE))); mode->dmSize = sizeof(DEVMODE); if (!EnumDisplaySettingsEx(nullptr, mode_number, mode, flags)) { return false;
diff --git a/remoting/host/win/host_service.cc b/remoting/host/win/host_service.cc index 93d4a8e..9a58ebb 100644 --- a/remoting/host/win/host_service.cc +++ b/remoting/host/win/host_service.cc
@@ -15,6 +15,7 @@ #include "base/base_paths.h" #include "base/base_switches.h" #include "base/command_line.h" +#include "base/compiler_specific.h" #include "base/files/file_path.h" #include "base/functional/bind.h" #include "base/message_loop/message_pump_type.h" @@ -252,7 +253,7 @@ // Report running status of the service. SERVICE_STATUS service_status; - ZeroMemory(&service_status, sizeof(service_status)); + UNSAFE_TODO(ZeroMemory(&service_status, sizeof(service_status))); service_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS; service_status.dwCurrentState = SERVICE_RUNNING; service_status.dwControlsAccepted = SERVICE_ACCEPT_SHUTDOWN |
diff --git a/remoting/host/win/launch_native_messaging_host_process.cc b/remoting/host/win/launch_native_messaging_host_process.cc index 8646f76..1c9e66a 100644 --- a/remoting/host/win/launch_native_messaging_host_process.cc +++ b/remoting/host/win/launch_native_messaging_host_process.cc
@@ -12,6 +12,7 @@ #include <string> #include "base/command_line.h" +#include "base/compiler_specific.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/logging.h" @@ -136,7 +137,7 @@ // Launch the child process, requesting elevation if needed. SHELLEXECUTEINFO info; - memset(&info, 0, sizeof(info)); + UNSAFE_TODO(memset(&info, 0, sizeof(info))); info.cbSize = sizeof(info); info.hwnd = reinterpret_cast<HWND>(parent_window_handle); info.lpFile = binary_path.value().c_str();
diff --git a/remoting/host/win/wts_session_process_delegate.cc b/remoting/host/win/wts_session_process_delegate.cc index 8a072e6f..297f5c9 100644 --- a/remoting/host/win/wts_session_process_delegate.cc +++ b/remoting/host/win/wts_session_process_delegate.cc
@@ -11,6 +11,7 @@ #include <utility> #include "base/command_line.h" +#include "base/compiler_specific.h" #include "base/files/file_path.h" #include "base/functional/bind.h" #include "base/logging.h" @@ -204,7 +205,7 @@ // process performing elevation and the worker process itself) and make sure // that all processes will be killed once the job object is destroyed. JOBOBJECT_EXTENDED_LIMIT_INFORMATION info; - memset(&info, 0, sizeof(info)); + UNSAFE_TODO(memset(&info, 0, sizeof(info))); info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_ACTIVE_PROCESS | JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; info.BasicLimitInformation.ActiveProcessLimit = 2;
diff --git a/remoting/tools/breakpad_tester_win.cc b/remoting/tools/breakpad_tester_win.cc index d27178fb..73bba3c 100644 --- a/remoting/tools/breakpad_tester_win.cc +++ b/remoting/tools/breakpad_tester_win.cc
@@ -8,6 +8,7 @@ #include "base/at_exit.h" #include "base/command_line.h" +#include "base/compiler_specific.h" #include "base/win/scoped_handle.h" #include "remoting/base/logging.h" @@ -32,7 +33,7 @@ const int kErrorExitCode = 2; void usage(const char* program_name) { - fprintf(stderr, kUsageMessage, program_name); + UNSAFE_TODO(fprintf(stderr, kUsageMessage, program_name)); } } // namespace
diff --git a/services/device/generic_sensor/platform_sensor_and_provider_unittest_win.cc b/services/device/generic_sensor/platform_sensor_and_provider_unittest_win.cc index f0ebd9e49..fe26ab7 100644 --- a/services/device/generic_sensor/platform_sensor_and_provider_unittest_win.cc +++ b/services/device/generic_sensor/platform_sensor_and_provider_unittest_win.cc
@@ -6,6 +6,7 @@ #include <sensors.h> #include <wrl/implements.h> +#include "base/compiler_specific.h" #include "base/functional/bind.h" #include "base/memory/read_only_shared_memory_region.h" #include "base/memory/shared_memory_mapping.h" @@ -747,7 +748,8 @@ // InitPropVariantFromGUIDAsBuffer with quaternion format GUID. InitPropVariantFromGUIDAsBuffer(SENSOR_DATA_TYPE_QUATERNION.fmtid, pvQuat.Receive()); - memcpy(pvQuat.get().caub.pElems, &quat_elements, sizeof(quat_elements)); + UNSAFE_TODO( + memcpy(pvQuat.get().caub.pElems, &quat_elements, sizeof(quat_elements))); GenerateDataUpdatedEvent({{SENSOR_DATA_TYPE_QUATERNION, pvQuat.ptr()}}); base::RunLoop().RunUntilIdle();
diff --git a/services/device/hid/hid_connection_win.cc b/services/device/hid/hid_connection_win.cc index b7e4a56..ab2e4d65 100644 --- a/services/device/hid/hid_connection_win.cc +++ b/services/device/hid/hid_connection_win.cc
@@ -8,6 +8,7 @@ #include <cstring> #include <utility> +#include "base/compiler_specific.h" #include "base/containers/contains.h" #include "base/feature_list.h" #include "base/files/file.h" @@ -83,7 +84,7 @@ : buffer_(buffer), callback_(std::move(callback)), event_(CreateEvent(NULL, FALSE, FALSE, NULL)) { - memset(&overlapped_, 0, sizeof(OVERLAPPED)); + UNSAFE_TODO(memset(&overlapped_, 0, sizeof(OVERLAPPED))); overlapped_.hEvent = event_.Get(); }
diff --git a/services/network/brokered_tcp_client_socket_unittest.cc b/services/network/brokered_tcp_client_socket_unittest.cc index 4203b0fd..e14765e 100644 --- a/services/network/brokered_tcp_client_socket_unittest.cc +++ b/services/network/brokered_tcp_client_socket_unittest.cc
@@ -4,6 +4,7 @@ #include "services/network/brokered_tcp_client_socket.h" +#include "base/compiler_specific.h" #include "base/test/bind.h" #include "base/test/scoped_run_loop_timeout.h" #include "base/test/task_environment.h" @@ -378,7 +379,7 @@ auto request_buffer = base::MakeRefCounted<net::IOBufferWithSize>(kWriteBufLen); char* request_data = request_buffer->data(); - memset(request_data, 'A', kWriteBufLen); + UNSAFE_TODO(memset(request_data, 'A', kWriteBufLen)); net::TestCompletionCallback write_callback; int bytes_written = 0; @@ -412,7 +413,7 @@ auto request_buffer = base::MakeRefCounted<net::IOBufferWithSize>(kWriteBufLen); char* request_data = request_buffer->data(); - memset(request_data, 'A', kWriteBufLen); + UNSAFE_TODO(memset(request_data, 'A', kWriteBufLen)); net::TestCompletionCallback write_callback; int bytes_written = 0;
diff --git a/services/network/public/cpp/sri_message_signatures.cc b/services/network/public/cpp/sri_message_signatures.cc index a630e26..a07b5f1 100644 --- a/services/network/public/cpp/sri_message_signatures.cc +++ b/services/network/public/cpp/sri_message_signatures.cc
@@ -29,11 +29,12 @@ constexpr std::string_view kAcceptSignature = "accept-signature"; constexpr std::array<std::string_view, 9u> kDerivedComponents = { - "@authority", "@query-param", "@query", "@path", "@status" + "@authority", "@query-param", "@query", "@path", + "@scheme", "@status" // TODO(383409584): We should support the remaining derived components from // https://www.rfc-editor.org/rfc/rfc9421.html#name-derived-components: // - // "@method", "@request-target", "@scheme", "@target-uri", + // "@method", "@request-target", "@target-uri", }; ParameterType ParamNameToType(std::string_view name) { @@ -174,26 +175,18 @@ for (const auto& param : params) { const std::string& name = param.first; const net::structured_headers::Item& value = param.second; - param_list << ';'; + param_list << ';' << name; - // We only care about three parameter types for this specific application: - // - // 1. Boolean for `sf` and `req` (which must be `true`). - // 2. Integers for `created` and `expires`. - // 3. String for everything else. - DCHECK((value.is_boolean() && value.GetBoolean()) || value.is_integer() || - value.is_string()); - param_list << name; - - // For boolean parameters, we're done (as they wouldn't be in the list if - // they weren't true, and we don't serialize `?1` for parameters. For other - // types, we'll serialize the value: - if (!value.is_boolean()) { - std::optional<std::string> serialized_item = - net::structured_headers::SerializeItem(value); - DCHECK(serialized_item.has_value()); - param_list << '=' << serialized_item.value(); + // For boolean parameters, we're done if the parameter's value is true (as + // per https://www.rfc-editor.org/rfc/rfc9651#section-3.1.2-6). For any + // other value or type, we'll serialize the value explicitly. + if (value.is_boolean() && value.GetBoolean()) { + continue; } + std::optional<std::string> serialized_item = + net::structured_headers::SerializeItem(value); + DCHECK(serialized_item.has_value()); + param_list << '=' << serialized_item.value(); } return param_list.str(); } @@ -313,6 +306,8 @@ } else if (component->name == "@path") { // https://www.rfc-editor.org/rfc/rfc9421.html#content-request-path return request_url.path(); + } else if (component->name == "@scheme") { + return request_url.scheme(); } else if (component->name == "@status") { // https://www.rfc-editor.org/rfc/rfc9421.html#content-status-code return base::NumberToString(response_status_code); @@ -507,18 +502,24 @@ } else if (param.first == "tag" && param.second.is_string() && param.second.GetString() == "sri") { message_signature->tag = "sri"; - } else { - // The `alg` parameter must not be included in the signature input. Any - // other parameters that aren't defined in the registry also - // invalidate the signature. + } else if (param.first == "alg" || param.first == "created" || + param.first == "expires" || param.first == "keyid" || + param.first == "nonce" || param.first == "tag") { + // The `alg` parameter must not be included in the signature input, and + // we'll only reach this branch for other known parameter names if they + // didn't meet the type constraints tested above. In either case, we'll + // throw an error and reject this signature. // - // https://www.iana.org/assignments/http-message-signature/http-message-signature.xhtml#signature-metadata-parameters + // https://wicg.github.io/signature-based-sri/#profile AddIssueFromErrorEnum(mojom::SRIMessageSignatureError:: kSignatureInputHeaderInvalidParameter, parsed_headers->issues); message_signature.reset(); break; } + // We do not otherwise act upon unknown signature parameters. They'll be + // part of the serialized `@signature-params`, but will not have any + // additional effect. } if (message_signature) {
diff --git a/services/network/public/cpp/sri_message_signatures_unittest.cc b/services/network/public/cpp/sri_message_signatures_unittest.cc index 89c1d656..92317140 100644 --- a/services/network/public/cpp/sri_message_signatures_unittest.cc +++ b/services/network/public/cpp/sri_message_signatures_unittest.cc
@@ -486,9 +486,6 @@ "keyid=\"[KEY]\";keyid=\"not-[KEY]\";tag=\"sri\"", "keyid=\"[KEY]\";tag=\"sri\";tag=\"not-sri\"", - // Unknown parameter: - "keyid=\"[KEY]\";tag=\"sri\";unknown=1", - // Alg is present: "alg=;keyid=\"[KEY]\";tag=\"sri\"", "alg=1;keyid=\"[KEY]\";tag=\"sri\"", @@ -1030,6 +1027,42 @@ } } +TEST_F(SRIMessageSignatureBaseTest, SchemeComponent) { + struct { + std::string_view url; + std::string_view scheme; + } cases[] = { + {"https://url.test/", url::kHttpsScheme}, + {"HTTPS://url.test/", url::kHttpsScheme}, + {"http://url.test/", url::kHttpScheme}, + {"HTTP://url.test/", url::kHttpScheme}, + }; + for (const auto& test : cases) { + SCOPED_TRACE(test.url); + + std::string input_header = + base::StrCat({"signature=(\"unencoded-digest\";sf \"@scheme\";req);", + "keyid=\"", kPublicKey, "\";tag=\"sri\""}); + + std::stringstream expected_base; + expected_base + << "\"unencoded-digest\";sf: " << kValidDigestHeader << '\n' + << "\"@scheme\";req: " << test.scheme << '\n' + << "\"@signature-params\": (\"unencoded-digest\";sf \"@scheme\";req);" + << "keyid=\"" << kPublicKey << "\";tag=\"sri\""; + + auto headers = ValidHeadersPlusInput(input_header.c_str()); + auto parsed = ParseSRIMessageSignaturesFromHeaders(*headers); + ASSERT_EQ(1u, parsed->signatures.size()); + EXPECT_EQ(0u, parsed->issues.size()); + + std::optional<std::string> result = + ConstructSignatureBase(parsed->signatures[0], GURL(test.url), *headers); + ASSERT_TRUE(result.has_value()); + EXPECT_EQ(expected_base.str(), result.value()); + } +} + TEST_F(SRIMessageSignatureBaseTest, StatusComponent) { for (int i = 0; i < net::HttpStatusCode::HTTP_STATUS_CODE_MAX; i++) { std::optional<net::HttpStatusCode> test_code = @@ -1154,6 +1187,36 @@ } while (std::next_permutation(params.begin(), params.end())); } +TEST_F(SRIMessageSignatureBaseTest, UnknownParameters) { + std::vector<const char*> cases = { + "unknown", "unknown=1", "unknown=1.1", "unknown=\"string\"", + "unknown=:YQ==:", "unknown=token", "unknown=?0", + // We don't support Date or Display String yet. + // "unknown=@12345", + // "unknown=%\"display\"", + }; + + for (auto* const test : cases) { + SCOPED_TRACE(test); + std::string test_header = + base::StrCat({kValidSignatureInputHeader, ";", test}); + auto headers = ValidHeadersPlusInput(test_header.data()); + auto parsed = ParseSRIMessageSignaturesFromHeaders(*headers); + ASSERT_EQ(1u, parsed->signatures.size()); + EXPECT_EQ(0u, parsed->issues.size()); + + std::optional<std::string> result = + ConstructSignatureBase(parsed->signatures[0], this->url(), *headers); + ASSERT_TRUE(result.has_value()); + std::string expected_base = + base::StrCat({"\"unencoded-digest\";sf: ", kValidDigestHeader, + "\n\"@signature-params\": " + "(\"unencoded-digest\";sf);keyid=\"", + kPublicKey, "\";tag=\"sri\"", ";", test}); + EXPECT_EQ(expected_base, result.value()); + } +} + // // Validation Tests //
diff --git a/services/network/public/mojom/restricted_cookie_manager.mojom b/services/network/public/mojom/restricted_cookie_manager.mojom index f1ed583..497453f 100644 --- a/services/network/public/mojom/restricted_cookie_manager.mojom +++ b/services/network/public/mojom/restricted_cookie_manager.mojom
@@ -110,6 +110,7 @@ url.mojom.Origin top_frame_origin, StorageAccessApiStatus storage_access_api_status, CookieInclusionStatus status, + bool is_ad_tagged, bool apply_devtools_overrides) => (bool success); // Subscribes to changes in the cookies transmitted in a request to an URL. @@ -144,6 +145,7 @@ url.mojom.Origin top_frame_origin, StorageAccessApiStatus storage_access_api_status, bool get_version_shared_memory, + bool is_ad_tagged, bool apply_devtools_overrides, string cookie) => (CookiesResponse? response);
diff --git a/services/network/public/mojom/url_loader_network_service_observer.mojom b/services/network/public/mojom/url_loader_network_service_observer.mojom index 4d550b0..05e7044 100644 --- a/services/network/public/mojom/url_loader_network_service_observer.mojom +++ b/services/network/public/mojom/url_loader_network_service_observer.mojom
@@ -149,6 +149,13 @@ string? private_network_device_id, string? private_network_device_name) => (bool permission_granted); + // Asks the URL loader observer if the caller has permission to connect to + // devices on the local network. + // + // `permission_granted` is a bool specifying whether the user granted the + // local network access permission. + OnLocalNetworkAccessPermissionRequired() => (bool permission_granted); + // Called when the Clear-Site-Data header has been received. The callback // should be run after the data is deleted. // https://www.w3.org/TR/clear-site-data/
diff --git a/services/network/restricted_cookie_manager.cc b/services/network/restricted_cookie_manager.cc index 1c81128..f29b11f 100644 --- a/services/network/restricted_cookie_manager.cc +++ b/services/network/restricted_cookie_manager.cc
@@ -559,7 +559,6 @@ GetCookieSettingOverrides( storage_access_api_status, /*is_ad_tagged=*/is_ad_tagged, /*apply_devtools_overrides=*/apply_devtools_overrides, - /*force_disable_third_party_cookies=*/ force_disable_third_party_cookies), net_options, std::move(options), std::move(callback))); } @@ -710,6 +709,7 @@ const url::Origin& top_frame_origin, net::StorageAccessApiStatus storage_access_api_status, net::CookieInclusionStatus status, + bool is_ad_tagged, bool apply_devtools_overrides, SetCanonicalCookieCallback callback) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); @@ -730,11 +730,9 @@ } const net::CookieSettingOverrides cookie_setting_overrides = - GetCookieSettingOverrides( - storage_access_api_status, - /*is_ad_tagged=*/false, - /*apply_devtools_overrides=*/apply_devtools_overrides, - /*force_disable_third_party_cookies=*/false); + GetCookieSettingOverrides(storage_access_api_status, is_ad_tagged, + apply_devtools_overrides, + /*force_disable_third_party_cookies=*/false); // Check cookie accessibility with cookie_settings. // TODO(morlovich): Try to validate site_for_cookies as well. bool blocked = !cookie_settings_->IsCookieAccessible( @@ -773,8 +771,8 @@ OnCookiesAccessed(mojom::CookieAccessDetails::New( mojom::CookieAccessDetails::Type::kChange, url, isolated_top_frame_origin, site_for_cookies, - std::move(result_with_access_result), std::nullopt, - /*is_ad_tagged=*/false, cookie_setting_overrides)); + std::move(result_with_access_result), std::nullopt, is_ad_tagged, + cookie_setting_overrides)); } std::move(callback).Run(false); return; @@ -865,7 +863,8 @@ base::BindOnce(&RestrictedCookieManager::SetCanonicalCookieResult, weak_ptr_factory_.GetWeakPtr(), url, isolated_top_frame_origin, cookie_setting_overrides, - site_for_cookies, cookie_copy, std::move(callback)), + site_for_cookies, cookie_copy, is_ad_tagged, + std::move(callback)), cookie_access_result); } @@ -875,6 +874,7 @@ const net::CookieSettingOverrides& cookie_setting_overrides, const net::SiteForCookies& site_for_cookies, const net::CanonicalCookie& cookie, + bool is_ad_tagged, SetCanonicalCookieCallback user_callback, net::CookieAccessResult access_result) { // TODO(crbug.com/40632967): Only report pure INCLUDE once samesite @@ -894,8 +894,7 @@ OnCookiesAccessed(mojom::CookieAccessDetails::New( mojom::CookieAccessDetails::Type::kChange, url, isolated_top_frame_origin, site_for_cookies, std::move(notify), - std::nullopt, - /*is_ad_tagged=*/false, cookie_setting_overrides)); + std::nullopt, is_ad_tagged, cookie_setting_overrides)); } } std::move(user_callback).Run(access_result.status.IsInclude()); @@ -940,6 +939,7 @@ const url::Origin& top_frame_origin, net::StorageAccessApiStatus storage_access_api_status, bool get_version_shared_memory, + bool is_ad_tagged, bool apply_devtools_overrides, const std::string& cookie, SetCookieFromStringCallback callback) { @@ -981,11 +981,9 @@ mojom::CookieAccessDetails::Type::kChange, url, isolation_info_.top_frame_origin().value_or(url::Origin()), site_for_cookies, std::move(result_with_access_result), std::nullopt, - /*is_ad_tagged=*/false, + is_ad_tagged, GetCookieSettingOverrides( - storage_access_api_status, - /*is_ad_tagged=*/false, - /*apply_devtools_overrides=*/apply_devtools_overrides, + storage_access_api_status, is_ad_tagged, apply_devtools_overrides, /*force_disable_third_party_cookies=*/false))); } if (get_cookies_on_set) { @@ -998,19 +996,19 @@ HistogramScriptCookieExpiration(*parsed_cookie); } - auto on_set = - get_cookies_on_set - ? base::BindOnce(&RestrictedCookieManager::GetCookiesAfterSet, - weak_ptr_factory_.GetWeakPtr(), url, - site_for_cookies, top_frame_origin, - storage_access_api_status, apply_devtools_overrides, - std::move(callback), std::move(shared_memory_region)) - : base::DoNothing(); + auto on_set = get_cookies_on_set + ? base::BindOnce( + &RestrictedCookieManager::GetCookiesAfterSet, + weak_ptr_factory_.GetWeakPtr(), url, site_for_cookies, + top_frame_origin, storage_access_api_status, + is_ad_tagged, apply_devtools_overrides, + std::move(callback), std::move(shared_memory_region)) + : base::DoNothing(); // Further checks (origin_, settings), as well as logging done by // SetCanonicalCookie() SetCanonicalCookie(*parsed_cookie, url, site_for_cookies, top_frame_origin, - storage_access_api_status, status, + storage_access_api_status, status, is_ad_tagged, apply_devtools_overrides, std::move(on_set)); if (metrics_subsampler_.ShouldSample(net::kHistogramSampleProbability)) { @@ -1184,6 +1182,7 @@ const net::SiteForCookies& site_for_cookies, const url::Origin& top_frame_origin, net::StorageAccessApiStatus storage_access_api_status, + bool is_ad_tagged, bool apply_devtools_overrides, SetCookieFromStringCallback callback, base::ReadOnlySharedMemoryRegion shared_memory_region, @@ -1205,7 +1204,7 @@ // The caller will be unblocked by GetAllForUrl. GetAllForUrl(url, site_for_cookies, top_frame_origin, storage_access_api_status, std::move(match_options), - /*is_ad_tagged=*/false, apply_devtools_overrides, + is_ad_tagged, apply_devtools_overrides, /*force_disable_third_party_cookies=*/false, base::BindOnce([](const std::vector<net::CookieWithAccessResult>& cookies) {
diff --git a/services/network/restricted_cookie_manager.h b/services/network/restricted_cookie_manager.h index 267af8d..12c7575 100644 --- a/services/network/restricted_cookie_manager.h +++ b/services/network/restricted_cookie_manager.h
@@ -132,6 +132,7 @@ const url::Origin& top_frame_origin, net::StorageAccessApiStatus storage_access_api_status, net::CookieInclusionStatus status, + bool is_ad_tagged, bool apply_devtools_overrides, SetCanonicalCookieCallback callback) override; @@ -149,6 +150,7 @@ const url::Origin& top_frame_origin, net::StorageAccessApiStatus storage_access_api_status, bool get_version_shared_memory, + bool is_ad_tagged, bool apply_devtools_overrides, const std::string& cookie, SetCookieFromStringCallback callback) override; @@ -236,6 +238,7 @@ const net::CookieSettingOverrides& cookie_setting_overrides, const net::SiteForCookies& site_for_cookies, const net::CanonicalCookie& cookie, + bool is_ad_tagged, SetCanonicalCookieCallback user_callback, net::CookieAccessResult access_result); @@ -292,6 +295,7 @@ const net::SiteForCookies& site_for_cookies, const url::Origin& top_frame_origin, net::StorageAccessApiStatus storage_access_api_status, + bool is_ad_tagged, bool apply_devtools_overrides, SetCookieFromStringCallback callback, base::ReadOnlySharedMemoryRegion shared_memory_region,
diff --git a/services/network/restricted_cookie_manager_unittest.cc b/services/network/restricted_cookie_manager_unittest.cc index c18663f..41b472f 100644 --- a/services/network/restricted_cookie_manager_unittest.cc +++ b/services/network/restricted_cookie_manager_unittest.cc
@@ -208,6 +208,7 @@ cookie_service_->SetCanonicalCookie( cookie, url, site_for_cookies, top_frame_origin, storage_access_api_status, status, + /*is_ad_tagged=*/false, /*apply_devtools_overrides=*/apply_devtools_overrides, future.GetCallback()); return future.Get(); @@ -219,13 +220,14 @@ const url::Origin& top_frame_origin, net::StorageAccessApiStatus storage_access_api_status, bool get_version_shared_memory, + bool is_ad_tagged, bool apply_devtools_overrides, const std::string& cookie) { base::test::TestFuture<mojom::CookiesResponsePtr> future; cookie_service_->SetCookieFromString( url, site_for_cookies, top_frame_origin, storage_access_api_status, - get_version_shared_memory, apply_devtools_overrides, cookie, - future.GetCallback()); + get_version_shared_memory, is_ad_tagged, apply_devtools_overrides, + cookie, future.GetCallback()); return future.Take(); } @@ -594,6 +596,7 @@ auto response = sync_service_->SetCookieFromString( kDefaultUrlWithPath, kDefaultSiteForCookies, kDefaultOrigin, net::StorageAccessApiStatus::kNone, /*get_version_shared_memory=*/false, + /*is_ad_tagged=*/false, /*apply_devtools_overrides=*/false, "new-name=new-value;path=/"); if (GetCookiesOnSetEnabled()) { ASSERT_TRUE(response); @@ -861,6 +864,26 @@ EXPECT_THAT(recorded_activity().back().is_ad_tagged, false); } +TEST_P(RestrictedCookieManagerTest, SetCookieAdTagged) { + service_->OverrideIsolationInfoForTesting(kOtherIsolationInfo); + sync_service_->SetCookieFromString( + kDefaultUrlWithPath, net::SiteForCookies(), kDefaultOrigin, + net::StorageAccessApiStatus::kNone, + /*get_version_shared_memory=*/false, /*is_ad_tagged=*/true, + /*apply_devtools_overrides=*/false, "cookie-name=cookie-value;path=/"); + WaitForCallback(); + EXPECT_THAT(recorded_activity().back().is_ad_tagged, true); + + sync_service_->SetCookieFromString( + kDefaultUrlWithPath, net::SiteForCookies(), kDefaultOrigin, + net::StorageAccessApiStatus::kNone, + /*get_version_shared_memory=*/false, /*is_ad_tagged=*/false, + /*apply_devtools_overrides=*/false, "cookie-name=cookie-value;path=/"); + WaitForCallback(); + + EXPECT_THAT(recorded_activity().back().is_ad_tagged, false); +} + TEST_P(RestrictedCookieManagerTest, GetAllForUrlPolicy) { service_->OverrideIsolationInfoForTesting(kOtherIsolationInfo); SetSessionCookie("cookie-name", "cookie-value", "example.com", "/"); @@ -1187,6 +1210,7 @@ auto response = sync_service_->SetCookieFromString( kDefaultUrlWithPath, kDefaultSiteForCookies, kDefaultOrigin, net::StorageAccessApiStatus::kNone, /*get_version_shared_memory=*/true, + /*is_ad_tagged=*/false, /*apply_devtools_overrides=*/false, "new-name=new-value;path=/"); std::optional<mojo::SharedMemoryVersionClient> client; if (GetCookiesOnSetEnabled()) { @@ -1214,6 +1238,7 @@ response = sync_service_->SetCookieFromString( kDefaultUrlWithPath, kDefaultSiteForCookies, kDefaultOrigin, net::StorageAccessApiStatus::kNone, /*get_version_shared_memory=*/false, + /*is_ad_tagged=*/false, /*apply_devtools_overrides=*/false, "new-name=updated-value;path=/"); if (GetCookiesOnSetEnabled()) { EXPECT_EQ(response->cookies, "new-name=updated-value"); @@ -1235,6 +1260,7 @@ auto response = sync_service_->SetCookieFromString( kDefaultUrlWithPath, net::SiteForCookies(), kDefaultOrigin, net::StorageAccessApiStatus::kNone, /*get_version_shared_memory=*/false, + /*is_ad_tagged=*/false, /*apply_devtools_overrides=*/ThirdPartyCookieDisabledByDevtools(), "new-name=new-value;path=/; SameSite=none; Secure"); if (GetCookiesOnSetEnabled() && !ThirdPartyCookieDisabledByDevtools()) { @@ -1308,6 +1334,7 @@ auto response = sync_service_->SetCookieFromString( kOtherUrlWithPath, kDefaultSiteForCookies, kDefaultOrigin, net::StorageAccessApiStatus::kNone, /*get_version_shared_memory=*/false, + /*is_ad_tagged=*/false, /*apply_devtools_overrides=*/false, "new-name=new-value;path=/"); EXPECT_FALSE(response); ASSERT_TRUE(received_bad_message()); @@ -1811,6 +1838,7 @@ kCookieURL, kSiteForCookies, kTopFrameOrigin, net::StorageAccessApiStatus::kNone, /*get_version_shared_memory=*/false, + /*is_ad_tagged=*/false, /*apply_devtools_overrides=*/false, "__Host-foo=bar; Secure; SameSite=None; Path=/; Partitioned");
diff --git a/services/network/sec_header_helpers.cc b/services/network/sec_header_helpers.cc index e49c123a..878da237 100644 --- a/services/network/sec_header_helpers.cc +++ b/services/network/sec_header_helpers.cc
@@ -137,7 +137,7 @@ net::cookie_util::SecFetchStorageAccessOutcome ComputeSecFetchStorageAccessOutcome(const net::URLRequest& request, mojom::CredentialsMode credentials_mode) { - if (!request.storage_access_status()) { + if (!request.storage_access_status().GetStatusForThirdPartyContext()) { return net::cookie_util::SecFetchStorageAccessOutcome:: kOmittedStatusMissing; } @@ -145,7 +145,8 @@ return net::cookie_util::SecFetchStorageAccessOutcome:: kOmittedRequestOmitsCredentials; } - switch (request.storage_access_status().value()) { + switch ( + request.storage_access_status().GetStatusForThirdPartyContext().value()) { case net::cookie_util::StorageAccessStatus::kInactive: return net::cookie_util::SecFetchStorageAccessOutcome::kValueInactive; case net::cookie_util::StorageAccessStatus::kActive: @@ -204,7 +205,7 @@ ComputeSecFetchStorageAccessOutcome(request, credentials_mode)); if (credentials_mode != mojom::CredentialsMode::kInclude || - !request.storage_access_status()) { + !request.storage_access_status().GetStatusForThirdPartyContext()) { // A credentials mode of "same-origin" or "omit" prevents including cookies // on the request in the first place, so we don't bother to include the // `Sec-Fetch-Storage-Access` header in that case. @@ -217,8 +218,9 @@ } request.SetExtraRequestHeaderByName( kSecFetchStorageAccess, - GetSecFetchStorageAccessHeaderValue( - request.storage_access_status().value()), + GetSecFetchStorageAccessHeaderValue(request.storage_access_status() + .GetStatusForThirdPartyContext() + .value()), /*overwrite=*/true); }
diff --git a/services/network/sec_header_helpers_unittest.cc b/services/network/sec_header_helpers_unittest.cc index 7435704c..4fd4352 100644 --- a/services/network/sec_header_helpers_unittest.cc +++ b/services/network/sec_header_helpers_unittest.cc
@@ -14,6 +14,7 @@ #include "net/cookies/cookie_util.h" #include "net/http/http_request_headers.h" #include "net/traffic_annotation/network_traffic_annotation_test_helper.h" +#include "net/url_request/storage_access_status_cache.h" #include "net/url_request/url_request.h" #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_context_builder.h" @@ -181,8 +182,8 @@ // unprivileged requests from chrome extension background page. TEST_F(SecHeaderHelpersTest, UnprivilegedRequestOnExtension) { net::URLRequest* current_url_request = url_request(); - url_request()->set_storage_access_status( - net::cookie_util::StorageAccessStatus::kNone); + url_request()->set_storage_access_status(net::StorageAccessStatusCache( + net::cookie_util::StorageAccessStatus::kNone)); GURL url = GURL(kSecureSite); // Set the request's net::IsolationInfo for Sec-Fetch-Frame-Top. @@ -220,8 +221,8 @@ // requests from chrome extension background page. TEST_F(SecHeaderHelpersTest, PrivilegedRequestOnExtension) { net::URLRequest* current_url_request = url_request(); - current_url_request->set_storage_access_status( - net::cookie_util::StorageAccessStatus::kNone); + current_url_request->set_storage_access_status(net::StorageAccessStatusCache( + net::cookie_util::StorageAccessStatus::kNone)); GURL url = GURL(kSecureSite); // Set the request's net::IsolationInfo for Sec-Fetch-Frame-Top. @@ -353,7 +354,7 @@ std::string_view("cross-site")})); struct StorageAccessTestData { - std::optional<net::cookie_util::StorageAccessStatus> status; + net::StorageAccessStatusCache status; mojom::CredentialsMode credentials_mode; std::optional<std::string> expected_value; net::cookie_util::SecFetchStorageAccessOutcome expected_sample; @@ -391,82 +392,91 @@ StorageAccessSecHeaderHelpersTest, testing::Values( StorageAccessTestData{ - std::nullopt, + net::StorageAccessStatusCache(std::nullopt), mojom::CredentialsMode::kOmit, std::nullopt, net::cookie_util::SecFetchStorageAccessOutcome:: kOmittedStatusMissing, }, StorageAccessTestData{ - std::nullopt, + net::StorageAccessStatusCache(std::nullopt), mojom::CredentialsMode::kSameOrigin, std::nullopt, net::cookie_util::SecFetchStorageAccessOutcome:: kOmittedStatusMissing, }, StorageAccessTestData{ - std::nullopt, + net::StorageAccessStatusCache(std::nullopt), mojom::CredentialsMode::kInclude, std::nullopt, net::cookie_util::SecFetchStorageAccessOutcome:: kOmittedStatusMissing, }, StorageAccessTestData{ - net::cookie_util::StorageAccessStatus::kNone, + net::StorageAccessStatusCache( + net::cookie_util::StorageAccessStatus::kNone), mojom::CredentialsMode::kOmit, std::nullopt, net::cookie_util::SecFetchStorageAccessOutcome:: kOmittedRequestOmitsCredentials, }, StorageAccessTestData{ - net::cookie_util::StorageAccessStatus::kNone, + net::StorageAccessStatusCache( + net::cookie_util::StorageAccessStatus::kNone), mojom::CredentialsMode::kSameOrigin, std::nullopt, net::cookie_util::SecFetchStorageAccessOutcome:: kOmittedRequestOmitsCredentials, }, StorageAccessTestData{ - net::cookie_util::StorageAccessStatus::kNone, + net::StorageAccessStatusCache( + net::cookie_util::StorageAccessStatus::kNone), mojom::CredentialsMode::kInclude, "none", net::cookie_util::SecFetchStorageAccessOutcome::kValueNone, }, StorageAccessTestData{ - net::cookie_util::StorageAccessStatus::kInactive, + net::StorageAccessStatusCache( + net::cookie_util::StorageAccessStatus::kInactive), mojom::CredentialsMode::kOmit, std::nullopt, net::cookie_util::SecFetchStorageAccessOutcome:: kOmittedRequestOmitsCredentials, }, StorageAccessTestData{ - net::cookie_util::StorageAccessStatus::kInactive, + net::StorageAccessStatusCache( + net::cookie_util::StorageAccessStatus::kInactive), mojom::CredentialsMode::kSameOrigin, std::nullopt, net::cookie_util::SecFetchStorageAccessOutcome:: kOmittedRequestOmitsCredentials, }, StorageAccessTestData{ - net::cookie_util::StorageAccessStatus::kInactive, + net::StorageAccessStatusCache( + net::cookie_util::StorageAccessStatus::kInactive), mojom::CredentialsMode::kInclude, "inactive", net::cookie_util::SecFetchStorageAccessOutcome::kValueInactive, }, StorageAccessTestData{ - net::cookie_util::StorageAccessStatus::kActive, + net::StorageAccessStatusCache( + net::cookie_util::StorageAccessStatus::kActive), mojom::CredentialsMode::kOmit, std::nullopt, net::cookie_util::SecFetchStorageAccessOutcome:: kOmittedRequestOmitsCredentials, }, StorageAccessTestData{ - net::cookie_util::StorageAccessStatus::kActive, + net::StorageAccessStatusCache( + net::cookie_util::StorageAccessStatus::kActive), mojom::CredentialsMode::kSameOrigin, std::nullopt, net::cookie_util::SecFetchStorageAccessOutcome:: kOmittedRequestOmitsCredentials, }, StorageAccessTestData{ - net::cookie_util::StorageAccessStatus::kActive, + net::StorageAccessStatusCache( + net::cookie_util::StorageAccessStatus::kActive), mojom::CredentialsMode::kInclude, "active", net::cookie_util::SecFetchStorageAccessOutcome::kValueActive,
diff --git a/services/network/test/test_url_loader_network_observer.cc b/services/network/test/test_url_loader_network_observer.cc index 6e2b9a89..342a662 100644 --- a/services/network/test/test_url_loader_network_observer.cc +++ b/services/network/test/test_url_loader_network_observer.cc
@@ -57,6 +57,11 @@ std::move(callback).Run(false); } +void TestURLLoaderNetworkObserver::OnLocalNetworkAccessPermissionRequired( + OnLocalNetworkAccessPermissionRequiredCallback callback) { + std::move(callback).Run(false); +} + void TestURLLoaderNetworkObserver::OnClearSiteData( const GURL& url, const std::string& header_value,
diff --git a/services/network/test/test_url_loader_network_observer.h b/services/network/test/test_url_loader_network_observer.h index 81774b1..5765481 100644 --- a/services/network/test/test_url_loader_network_observer.h +++ b/services/network/test/test_url_loader_network_observer.h
@@ -54,6 +54,8 @@ const std::optional<std::string>& private_network_device_id, const std::optional<std::string>& private_network_device_name, OnPrivateNetworkAccessPermissionRequiredCallback callback) override; + void OnLocalNetworkAccessPermissionRequired( + OnLocalNetworkAccessPermissionRequiredCallback callback) override; void OnClearSiteData( const GURL& url, const std::string& header_value,
diff --git a/services/network/url_loader.cc b/services/network/url_loader.cc index 68338022..a9ede3f8 100644 --- a/services/network/url_loader.cc +++ b/services/network/url_loader.cc
@@ -3568,11 +3568,14 @@ return net::cookie_util::ActivateStorageAccessLoadOutcome:: kFailureHeaderDisabled; } - if (!url_request_->storage_access_status()) { + if (!url_request_->storage_access_status() + .GetStatusForThirdPartyContext()) { return net::cookie_util::ActivateStorageAccessLoadOutcome:: kFailureInvalidStatus; } - switch (url_request_->storage_access_status().value()) { + switch (url_request_->storage_access_status() + .GetStatusForThirdPartyContext() + .value()) { case net::cookie_util::StorageAccessStatus::kNone: return net::cookie_util::ActivateStorageAccessLoadOutcome:: kFailureInvalidStatus;
diff --git a/services/viz/public/mojom/compositing/layer.mojom b/services/viz/public/mojom/compositing/layer.mojom index 41c8f4c..38773a9 100644 --- a/services/viz/public/mojom/compositing/layer.mojom +++ b/services/viz/public/mojom/compositing/layer.mojom
@@ -179,6 +179,8 @@ // Actual transformation parameters for this node. See cc::TransformNode. gfx.mojom.Transform local; gfx.mojom.Point3F origin; + gfx.mojom.Vector2dF post_translation; + gfx.mojom.Transform to_parent; gfx.mojom.PointF scroll_offset; gfx.mojom.Vector2dF snap_amount;
diff --git a/services/webnn/dml/command_recorder_test.cc b/services/webnn/dml/command_recorder_test.cc index b69d61c3..b3018b7 100644 --- a/services/webnn/dml/command_recorder_test.cc +++ b/services/webnn/dml/command_recorder_test.cc
@@ -2,6 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#ifdef UNSAFE_BUFFERS_BUILD +// TODO(crbug.com/390223051): Remove C-library calls to fix the errors. +#pragma allow_unsafe_libc_calls +#endif + #include <wrl.h> #include "base/numerics/safe_conversions.h"
diff --git a/storage/browser/blob/blob_url_registry.cc b/storage/browser/blob/blob_url_registry.cc index 1fc67b0..e683f3cd 100644 --- a/storage/browser/blob/blob_url_registry.cc +++ b/storage/browser/blob/blob_url_registry.cc
@@ -37,12 +37,15 @@ base::RepeatingCallback< void(const GURL&, std::optional<blink::mojom::PartitioningBlobURLInfo>)> partitioning_blob_url_closure, + base::RepeatingCallback<void(base::OnceCallback<void(bool)>)> + storage_access_check_callback, bool partitioning_disabled_by_policy) { mojo::ReceiverId receiver_id = frame_receivers_.Add( std::make_unique<storage::BlobURLStoreImpl>( storage_key, renderer_origin, render_process_host_id, AsWeakPtr(), storage::BlobURLValidityCheckBehavior::DEFAULT, std::move(partitioning_blob_url_closure), + std::move(storage_access_check_callback), partitioning_disabled_by_policy), std::move(receiver)); @@ -62,6 +65,9 @@ std::make_unique<storage::BlobURLStoreImpl>( storage_key, renderer_origin, render_process_host_id, AsWeakPtr(), validity_check_behavior, base::DoNothing(), + base::BindRepeating([](base::OnceCallback<void(bool)> callback) { + std::move(callback).Run(false); + }), partitioning_disabled_by_policy), std::move(receiver)); }
diff --git a/storage/browser/blob/blob_url_registry.h b/storage/browser/blob/blob_url_registry.h index 228f575..29fa7cb 100644 --- a/storage/browser/blob/blob_url_registry.h +++ b/storage/browser/blob/blob_url_registry.h
@@ -64,6 +64,8 @@ void(const GURL&, std::optional<blink::mojom::PartitioningBlobURLInfo>)> partitioning_blob_url_closure, + base::RepeatingCallback<void(base::OnceCallback<void(bool)>)> + storage_access_check_callback, bool partitioning_disabled_by_policy = false); // Binds receivers corresponding to connections from renderer worker
diff --git a/storage/browser/blob/blob_url_store_impl.cc b/storage/browser/blob/blob_url_store_impl.cc index 33060da..3b5a8a7 100644 --- a/storage/browser/blob/blob_url_store_impl.cc +++ b/storage/browser/blob/blob_url_store_impl.cc
@@ -9,6 +9,7 @@ #include "base/functional/callback.h" #include "base/strings/strcat.h" #include "components/crash/core/common/crash_key.h" +#include "mojo/public/cpp/bindings/callback_helpers.h" #include "mojo/public/cpp/bindings/receiver_set.h" #include "net/base/features.h" #include "storage/browser/blob/blob_impl.h" @@ -75,6 +76,8 @@ base::RepeatingCallback< void(const GURL&, std::optional<blink::mojom::PartitioningBlobURLInfo>)> partitioning_blob_url_closure, + base::RepeatingCallback<void(base::OnceCallback<void(bool)>)> + storage_access_check_callback, bool partitioning_disabled_by_policy) : storage_key_(storage_key), renderer_origin_(renderer_origin), @@ -82,6 +85,7 @@ registry_(std::move(registry)), validity_check_behavior_(validity_check_behavior), partitioning_blob_url_closure_(std::move(partitioning_blob_url_closure)), + storage_access_check_callback_(std::move(storage_access_check_callback)), partitioning_disabled_by_policy_(partitioning_disabled_by_policy) {} BlobURLStoreImpl::~BlobURLStoreImpl() { @@ -131,7 +135,17 @@ std::move(callback).Run(std::nullopt, std::nullopt); return; } + storage_access_check_callback_.Run( + base::BindOnce(&BlobURLStoreImpl::FinishResolveAsURLLoaderFactory, + weak_ptr_factory_.GetWeakPtr(), url, std::move(receiver), + std::move(callback))); +} +void BlobURLStoreImpl::FinishResolveAsURLLoaderFactory( + const GURL& url, + mojo::PendingReceiver<network::mojom::URLLoaderFactory> receiver, + ResolveAsURLLoaderFactoryCallback callback, + bool has_storage_access_handle) { if (registry_->IsUrlMapped(BlobUrlUtils::ClearUrlFragment(url), storage_key_) == BlobUrlRegistry::MappingStatus::kNotMappedCrossPartitionSameOrigin) { @@ -139,7 +153,7 @@ base::FeatureList::IsEnabled( features::kBlockCrossPartitionBlobUrlFetching) && !partitioning_disabled_by_policy_; - if (feature_and_policy_check) { + if (feature_and_policy_check && !has_storage_access_handle) { partitioning_blob_url_closure_.Run(url, blink::mojom::PartitioningBlobURLInfo:: kBlockedCrossPartitionFetching); @@ -171,7 +185,20 @@ std::move(callback).Run(std::nullopt); return; } + storage_access_check_callback_.Run( + mojo::WrapCallbackWithDefaultInvokeIfNotRun( + base::BindOnce(&BlobURLStoreImpl::FinishResolveAsBlobURLToken, + weak_ptr_factory_.GetWeakPtr(), url, std::move(token), + is_top_level_navigation, std::move(callback)), + false)); +} +void BlobURLStoreImpl::FinishResolveAsBlobURLToken( + const GURL& url, + mojo::PendingReceiver<blink::mojom::BlobURLToken> token, + bool is_top_level_navigation, + ResolveAsBlobURLTokenCallback callback, + bool has_storage_access_handle) { if (!is_top_level_navigation && (registry_->IsUrlMapped(BlobUrlUtils::ClearUrlFragment(url), storage_key_) == @@ -180,7 +207,7 @@ base::FeatureList::IsEnabled( features::kBlockCrossPartitionBlobUrlFetching) && !partitioning_disabled_by_policy_; - if (feature_and_policy_check) { + if (feature_and_policy_check && !has_storage_access_handle) { partitioning_blob_url_closure_.Run(url, blink::mojom::PartitioningBlobURLInfo:: kBlockedCrossPartitionFetching);
diff --git a/storage/browser/blob/blob_url_store_impl.h b/storage/browser/blob/blob_url_store_impl.h index fd1a66af..792a4ea 100644 --- a/storage/browser/blob/blob_url_store_impl.h +++ b/storage/browser/blob/blob_url_store_impl.h
@@ -39,6 +39,11 @@ const GURL&, std::optional<blink::mojom::PartitioningBlobURLInfo>)> partitioning_blob_url_closure = base::DoNothing(), + base::RepeatingCallback<void(base::OnceCallback<void(bool)>)> + storage_access_check_closure = base::BindRepeating( + [](base::OnceCallback<void(bool)> callback) { + std::move(callback).Run(false); + }), bool partitioning_disabled_by_policy = false); BlobURLStoreImpl(const BlobURLStoreImpl&) = delete; @@ -71,6 +76,19 @@ // `Revoke()`. bool BlobUrlIsValid(const GURL& url, const char* method) const; + void FinishResolveAsURLLoaderFactory( + const GURL& url, + mojo::PendingReceiver<network::mojom::URLLoaderFactory> receiver, + ResolveAsURLLoaderFactoryCallback callback, + bool has_storage_access_handle); + + void FinishResolveAsBlobURLToken( + const GURL& url, + mojo::PendingReceiver<blink::mojom::BlobURLToken> token, + bool is_top_level_navigation, + ResolveAsBlobURLTokenCallback callback, + bool has_storage_access_handle); + const blink::StorageKey storage_key_; // The origin used by the worker/document associated with this BlobURLStore on // the renderer side. This will almost always be the same as `storage_key_`'s @@ -90,6 +108,9 @@ void(const GURL&, std::optional<blink::mojom::PartitioningBlobURLInfo>)> partitioning_blob_url_closure_; + base::RepeatingCallback<void(base::OnceCallback<void(bool)>)> + storage_access_check_callback_; + const bool partitioning_disabled_by_policy_; base::WeakPtrFactory<BlobURLStoreImpl> weak_ptr_factory_{this};
diff --git a/storage/browser/blob/blob_url_store_impl_unittest.cc b/storage/browser/blob/blob_url_store_impl_unittest.cc index 6b6cdea8..945b0d8 100644 --- a/storage/browser/blob/blob_url_store_impl_unittest.cc +++ b/storage/browser/blob/blob_url_store_impl_unittest.cc
@@ -75,17 +75,18 @@ bool BlockCrossPartitionBlobUrlFetchingEnabled() { switch (test_case_) { case PartitionedBlobUrlTestCase:: - kBlockCrossPartitionBlobUrlFetchingDisabled: - case PartitionedBlobUrlTestCase:: kBlockCrossPartitionBlobUrlFetchingEnabled: return true; + case PartitionedBlobUrlTestCase:: + kBlockCrossPartitionBlobUrlFetchingDisabled: default: return false; } } bool StoragePartitioningEnabled() { - return test_case_ != PartitionedBlobUrlTestCase::kPartitioningDisabled; + return test_case_ == PartitionedBlobUrlTestCase:: + kBlockCrossPartitionBlobUrlFetchingEnabled; } void TearDown() override {
diff --git a/testing/buildbot/filters/ozone-linux.interactive_ui_tests_mutter.filter b/testing/buildbot/filters/ozone-linux.interactive_ui_tests_mutter.filter index 765595b..faed2d6 100644 --- a/testing/buildbot/filters/ozone-linux.interactive_ui_tests_mutter.filter +++ b/testing/buildbot/filters/ozone-linux.interactive_ui_tests_mutter.filter
@@ -57,6 +57,3 @@ # TODO(crbug.com/391903220) Now flaky on mutter -AppMenuFullscreenInteractiveTest.ContextMenu --AnimationTimingTestSuiteInstantiation/PictureInPictureBrowserFrameViewTest.TestAnimationTiming/WithoutContentSettingView_WithoutBackToTabButton --AnimationTimingTestSuiteInstantiation/PictureInPictureBrowserFrameViewTest.TestAnimationTiming/WithoutContentSettingView_WithBackToTabButton --PictureInPictureBrowserFrameViewTest.RespectsUserLocationChangesAfterChildDialogCloses
diff --git a/testing/buildbot/filters/pixel_tests.filter b/testing/buildbot/filters/pixel_tests.filter index b9d452c..b8c9177 100644 --- a/testing/buildbot/filters/pixel_tests.filter +++ b/testing/buildbot/filters/pixel_tests.filter
@@ -110,6 +110,7 @@ *PopupViewViewsPlusAddressSuggestionBrowsertest* PrivacySandboxDialogViewBrowserTest.* PrivacySandboxDialogViewAdsApiUxEnhancementBrowserTest.* +PrivacySandboxDialogViewAdsApiUxEnhancementsLearnMoreBrowserTest.* PrivacySandboxDialogViewPrivacyPolicyBrowserTest.* PrivacySandboxDialogViewAdsApiUxEnhancementPrivacyPolicyBrowserTest.* PrivacySandboxNoticeBubbleBrowserTest.*
diff --git a/testing/buildbot/filters/trees_in_viz.cc_unittests.filter b/testing/buildbot/filters/trees_in_viz.cc_unittests.filter index d609735..04a2ef4 100644 --- a/testing/buildbot/filters/trees_in_viz.cc_unittests.filter +++ b/testing/buildbot/filters/trees_in_viz.cc_unittests.filter
@@ -131,17 +131,6 @@ -All/LayerTreeHostCopyRequestTestMultipleRequestsOutOfOrder.Test/SkiaGraphiteDawn_SingleThreaded -All/LayerTreeHostCopyRequestTestMultipleRequestsOutOfOrder.Test/SkiaVulkan_MultiThreaded -All/LayerTreeHostCopyRequestTestMultipleRequestsOutOfOrder.Test/SkiaVulkan_SingleThreaded --All/LayerTreeHostFiltersPixelTest.BackdropFilterBlurOutsets/SkiaGL --All/LayerTreeHostFiltersPixelTest.BackdropFilterBlurOutsets/SkiaGraphiteDawn --All/LayerTreeHostFiltersPixelTest.BackdropFilterBlurOutsets/SkiaVulkan --All/LayerTreeHostFiltersPixelTest.BackdropFilterBlurOutsets/Software --All/LayerTreeHostFiltersPixelTest.BackdropFilterBlurRadius/SkiaGL --All/LayerTreeHostFiltersPixelTest.BackdropFilterBlurRadius/SkiaGraphiteDawn --All/LayerTreeHostFiltersPixelTest.BackdropFilterBlurRadius/SkiaVulkan --All/LayerTreeHostFiltersPixelTest.BackdropFilterBlurRect/SkiaGL --All/LayerTreeHostFiltersPixelTest.BackdropFilterBlurRect/SkiaGraphiteDawn --All/LayerTreeHostFiltersPixelTest.BackdropFilterBlurRect/SkiaVulkan --All/LayerTreeHostFiltersPixelTest.BackdropFilterBlurRect/Software -All/LayerTreeHostFiltersPixelTest.BackdropFilterBlurRounded/SkiaGL -All/LayerTreeHostFiltersPixelTest.BackdropFilterBlurRounded/SkiaGraphiteDawn -All/LayerTreeHostFiltersPixelTest.BackdropFilterBlurRounded/SkiaVulkan @@ -173,14 +162,6 @@ -All/LayerTreeHostFiltersPixelTest.ImageFilterClipped/SkiaGraphiteDawn -All/LayerTreeHostFiltersPixelTest.ImageFilterClipped/SkiaVulkan -All/LayerTreeHostFiltersPixelTest.ImageFilterClipped/Software --All/LayerTreeHostFiltersPixelTest.ImageFilterScaled/SkiaGL --All/LayerTreeHostFiltersPixelTest.ImageFilterScaled/SkiaGraphiteDawn --All/LayerTreeHostFiltersPixelTest.ImageFilterScaled/SkiaVulkan --All/LayerTreeHostFiltersPixelTest.ImageFilterScaled/Software --All/LayerTreeHostFiltersPixelTest.ImageRenderSurfaceScaled/SkiaGL --All/LayerTreeHostFiltersPixelTest.ImageRenderSurfaceScaled/SkiaGraphiteDawn --All/LayerTreeHostFiltersPixelTest.ImageRenderSurfaceScaled/SkiaVulkan --All/LayerTreeHostFiltersPixelTest.ImageRenderSurfaceScaled/Software -All/LayerTreeHostFiltersPixelTest.RotatedDropShadowFilter/SkiaGL -All/LayerTreeHostFiltersPixelTest.RotatedDropShadowFilter/SkiaGraphiteDawn -All/LayerTreeHostFiltersPixelTest.RotatedDropShadowFilter/SkiaVulkan @@ -193,9 +174,6 @@ -All/LayerTreeHostFiltersPixelTest.TranslatedFilter/SkiaGraphiteDawn -All/LayerTreeHostFiltersPixelTest.TranslatedFilter/SkiaVulkan -All/LayerTreeHostFiltersPixelTest.TranslatedFilter/Software --All/LayerTreeHostFiltersPixelTest.ZoomFilter/SkiaGL --All/LayerTreeHostFiltersPixelTest.ZoomFilter/SkiaGraphiteDawn --All/LayerTreeHostFiltersPixelTest.ZoomFilter/SkiaVulkan -All/LayerTreeHostFiltersPixelTestGPU.FilterWithGiantCropRect/SkiaGL -All/LayerTreeHostFiltersPixelTestGPU.FilterWithGiantCropRect/SkiaGraphiteDawn -All/LayerTreeHostFiltersPixelTestGPU.FilterWithGiantCropRect/SkiaVulkan @@ -210,10 +188,6 @@ -All/LayerTreeHostFiltersScaledPixelTest.StandardDpi/SkiaGraphiteDawn -All/LayerTreeHostFiltersScaledPixelTest.StandardDpi/SkiaVulkan -All/LayerTreeHostFiltersScaledPixelTest.StandardDpi/Software --All/LayerTreeHostMaskAsBlendingPixelTest.PixelAlignedClippedCircle/Software_Bitmap_0 --All/LayerTreeHostMaskAsBlendingPixelTest.PixelAlignedClippedCircleUnderflow/Software_Bitmap_0 --All/LayerTreeHostMaskAsBlendingPixelTest.RotatedClippedCircle/Software_Bitmap_0 --All/LayerTreeHostMaskAsBlendingPixelTest.RotatedClippedCircleUnderflow/Software_Bitmap_0 -All/LayerTreeHostMirrorPixelTest.MirrorLayer/SkiaGL -All/LayerTreeHostMirrorPixelTest.MirrorLayer/SkiaGraphiteDawn -All/LayerTreeHostMirrorPixelTest.MirrorLayer/SkiaVulkan @@ -224,36 +198,12 @@ -All/LayerTreeHostOverlayScrollbarsPixelTest.NinePatchScrollbarScaledUp/SkiaGL -All/LayerTreeHostOverlayScrollbarsPixelTest.NinePatchScrollbarScaledUp/SkiaGraphiteDawn -All/LayerTreeHostOverlayScrollbarsPixelTest.NinePatchScrollbarScaledUp/SkiaVulkan --All/LayerTreeHostReadbackColorSpacePixelTest.Readback/SkiaGL_Bitmap --All/LayerTreeHostReadbackColorSpacePixelTest.Readback/SkiaGL_Texture --All/LayerTreeHostReadbackColorSpacePixelTest.Readback/SkiaGraphiteDawn_Bitmap --All/LayerTreeHostReadbackColorSpacePixelTest.Readback/SkiaVulkan_Bitmap --All/LayerTreeHostReadbackColorSpacePixelTest.Readback/SkiaVulkan_Texture --All/LayerTreeHostReadbackColorSpacePixelTest.Readback/Software_Bitmap --All/LayerTreeHostReadbackDeviceScalePixelTest.ReadbackNonRootLayerSubrect/SkiaGL_Bitmap --All/LayerTreeHostReadbackDeviceScalePixelTest.ReadbackNonRootLayerSubrect/SkiaGL_Texture --All/LayerTreeHostReadbackDeviceScalePixelTest.ReadbackNonRootLayerSubrect/SkiaGraphiteDawn_Bitmap --All/LayerTreeHostReadbackDeviceScalePixelTest.ReadbackNonRootLayerSubrect/SkiaVulkan_Bitmap --All/LayerTreeHostReadbackDeviceScalePixelTest.ReadbackNonRootLayerSubrect/SkiaVulkan_Texture --All/LayerTreeHostReadbackDeviceScalePixelTest.ReadbackNonRootLayerSubrect/Software_Bitmap --All/LayerTreeHostReadbackDeviceScalePixelTest.ReadbackSubrect/SkiaGL_Bitmap --All/LayerTreeHostReadbackDeviceScalePixelTest.ReadbackSubrect/SkiaGL_Texture --All/LayerTreeHostReadbackDeviceScalePixelTest.ReadbackSubrect/SkiaGraphiteDawn_Bitmap --All/LayerTreeHostReadbackDeviceScalePixelTest.ReadbackSubrect/SkiaVulkan_Bitmap --All/LayerTreeHostReadbackDeviceScalePixelTest.ReadbackSubrect/SkiaVulkan_Texture --All/LayerTreeHostReadbackDeviceScalePixelTest.ReadbackSubrect/Software_Bitmap -All/LayerTreeHostReadbackPixelTest.HiddenSubtreeNotVisibleWhenDrawnForReadback/SkiaGL_Bitmap -All/LayerTreeHostReadbackPixelTest.HiddenSubtreeNotVisibleWhenDrawnForReadback/SkiaGL_Texture -All/LayerTreeHostReadbackPixelTest.HiddenSubtreeNotVisibleWhenDrawnForReadback/SkiaGraphiteDawn_Bitmap -All/LayerTreeHostReadbackPixelTest.HiddenSubtreeNotVisibleWhenDrawnForReadback/SkiaVulkan_Bitmap -All/LayerTreeHostReadbackPixelTest.HiddenSubtreeNotVisibleWhenDrawnForReadback/SkiaVulkan_Texture -All/LayerTreeHostReadbackPixelTest.HiddenSubtreeNotVisibleWhenDrawnForReadback/Software_Bitmap --All/LayerTreeHostReadbackPixelTest.ReadbackNonRootOrFirstLayer/SkiaGL_Bitmap --All/LayerTreeHostReadbackPixelTest.ReadbackNonRootOrFirstLayer/SkiaGL_Texture --All/LayerTreeHostReadbackPixelTest.ReadbackNonRootOrFirstLayer/SkiaGraphiteDawn_Bitmap --All/LayerTreeHostReadbackPixelTest.ReadbackNonRootOrFirstLayer/SkiaVulkan_Bitmap --All/LayerTreeHostReadbackPixelTest.ReadbackNonRootOrFirstLayer/SkiaVulkan_Texture --All/LayerTreeHostReadbackPixelTest.ReadbackNonRootOrFirstLayer/Software_Bitmap -All/LayerTreeHostScrollbarsPixelTest.DeviceScaleFactor/SkiaGL -All/LayerTreeHostScrollbarsPixelTest.DeviceScaleFactor/SkiaGraphiteDawn -All/LayerTreeHostScrollbarsPixelTest.DeviceScaleFactor/SkiaVulkan @@ -281,54 +231,6 @@ -All/LayerTreeHostTilesTestPartialInvalidation.PartialRaster/Software_Bitmap -All/LayerTreeHostTilesTestPartialInvalidationMultiThread.PartialRaster/SkiaGraphiteDawn_GPU -All/LayerTreeHostTilesTestPartialInvalidationMultiThread.PartialRaster/SkiaVulkan_GPU --B/LayerTreeHostBlendingPixelTest.BlendingWithBackdropFilter/SkiaGL_GPU_ColorBurn --B/LayerTreeHostBlendingPixelTest.BlendingWithBackdropFilter/SkiaGL_GPU_ColorDodge --B/LayerTreeHostBlendingPixelTest.BlendingWithBackdropFilter/SkiaGL_GPU_Difference --B/LayerTreeHostBlendingPixelTest.BlendingWithBackdropFilter/SkiaGL_GPU_Exclusion --B/LayerTreeHostBlendingPixelTest.BlendingWithBackdropFilter/SkiaGL_GPU_HardLight --B/LayerTreeHostBlendingPixelTest.BlendingWithBackdropFilter/SkiaGL_GPU_Hue --B/LayerTreeHostBlendingPixelTest.BlendingWithBackdropFilter/SkiaGL_GPU_Lighten --B/LayerTreeHostBlendingPixelTest.BlendingWithBackdropFilter/SkiaGL_GPU_Luminosity --B/LayerTreeHostBlendingPixelTest.BlendingWithBackdropFilter/SkiaGL_GPU_Multiply --B/LayerTreeHostBlendingPixelTest.BlendingWithBackdropFilter/SkiaGL_GPU_Overlay --B/LayerTreeHostBlendingPixelTest.BlendingWithBackdropFilter/SkiaGL_GPU_Screen --B/LayerTreeHostBlendingPixelTest.BlendingWithBackdropFilter/SkiaGL_GPU_SoftLight --B/LayerTreeHostBlendingPixelTest.BlendingWithBackdropFilter/SkiaGraphiteDawn_GPU_ColorBurn --B/LayerTreeHostBlendingPixelTest.BlendingWithBackdropFilter/SkiaGraphiteDawn_GPU_ColorDodge --B/LayerTreeHostBlendingPixelTest.BlendingWithBackdropFilter/SkiaGraphiteDawn_GPU_Difference --B/LayerTreeHostBlendingPixelTest.BlendingWithBackdropFilter/SkiaGraphiteDawn_GPU_Exclusion --B/LayerTreeHostBlendingPixelTest.BlendingWithBackdropFilter/SkiaGraphiteDawn_GPU_HardLight --B/LayerTreeHostBlendingPixelTest.BlendingWithBackdropFilter/SkiaGraphiteDawn_GPU_Hue --B/LayerTreeHostBlendingPixelTest.BlendingWithBackdropFilter/SkiaGraphiteDawn_GPU_Lighten --B/LayerTreeHostBlendingPixelTest.BlendingWithBackdropFilter/SkiaGraphiteDawn_GPU_Luminosity --B/LayerTreeHostBlendingPixelTest.BlendingWithBackdropFilter/SkiaGraphiteDawn_GPU_Multiply --B/LayerTreeHostBlendingPixelTest.BlendingWithBackdropFilter/SkiaGraphiteDawn_GPU_Overlay --B/LayerTreeHostBlendingPixelTest.BlendingWithBackdropFilter/SkiaGraphiteDawn_GPU_Screen --B/LayerTreeHostBlendingPixelTest.BlendingWithBackdropFilter/SkiaGraphiteDawn_GPU_SoftLight --B/LayerTreeHostBlendingPixelTest.BlendingWithBackdropFilter/SkiaVulkan_GPU_ColorBurn --B/LayerTreeHostBlendingPixelTest.BlendingWithBackdropFilter/SkiaVulkan_GPU_ColorDodge --B/LayerTreeHostBlendingPixelTest.BlendingWithBackdropFilter/SkiaVulkan_GPU_Difference --B/LayerTreeHostBlendingPixelTest.BlendingWithBackdropFilter/SkiaVulkan_GPU_Exclusion --B/LayerTreeHostBlendingPixelTest.BlendingWithBackdropFilter/SkiaVulkan_GPU_HardLight --B/LayerTreeHostBlendingPixelTest.BlendingWithBackdropFilter/SkiaVulkan_GPU_Hue --B/LayerTreeHostBlendingPixelTest.BlendingWithBackdropFilter/SkiaVulkan_GPU_Lighten --B/LayerTreeHostBlendingPixelTest.BlendingWithBackdropFilter/SkiaVulkan_GPU_Luminosity --B/LayerTreeHostBlendingPixelTest.BlendingWithBackdropFilter/SkiaVulkan_GPU_Multiply --B/LayerTreeHostBlendingPixelTest.BlendingWithBackdropFilter/SkiaVulkan_GPU_Overlay --B/LayerTreeHostBlendingPixelTest.BlendingWithBackdropFilter/SkiaVulkan_GPU_Screen --B/LayerTreeHostBlendingPixelTest.BlendingWithBackdropFilter/SkiaVulkan_GPU_SoftLight --B/LayerTreeHostBlendingPixelTest.BlendingWithBackdropFilter/Software_Bitmap_ColorBurn --B/LayerTreeHostBlendingPixelTest.BlendingWithBackdropFilter/Software_Bitmap_ColorDodge --B/LayerTreeHostBlendingPixelTest.BlendingWithBackdropFilter/Software_Bitmap_Difference --B/LayerTreeHostBlendingPixelTest.BlendingWithBackdropFilter/Software_Bitmap_Exclusion --B/LayerTreeHostBlendingPixelTest.BlendingWithBackdropFilter/Software_Bitmap_HardLight --B/LayerTreeHostBlendingPixelTest.BlendingWithBackdropFilter/Software_Bitmap_Hue --B/LayerTreeHostBlendingPixelTest.BlendingWithBackdropFilter/Software_Bitmap_Lighten --B/LayerTreeHostBlendingPixelTest.BlendingWithBackdropFilter/Software_Bitmap_Luminosity --B/LayerTreeHostBlendingPixelTest.BlendingWithBackdropFilter/Software_Bitmap_Multiply --B/LayerTreeHostBlendingPixelTest.BlendingWithBackdropFilter/Software_Bitmap_Overlay --B/LayerTreeHostBlendingPixelTest.BlendingWithBackdropFilter/Software_Bitmap_Screen --B/LayerTreeHostBlendingPixelTest.BlendingWithBackdropFilter/Software_Bitmap_SoftLight -LayerTreeHostCaptureTestLayerWithCaptureIdElevatesToSurface.RunMultiThread_DelegatingRenderer -LayerTreeHostCaptureTestLayerWithCaptureIdElevatesToSurface.RunSingleThread_DelegatingRenderer -LayerTreeHostPresentationDuringAnimation.RunMultiThread_DelegatingRenderer @@ -339,22 +241,6 @@ -MixedFilterZoomAndOffsetTest.StandardDpi/SkiaGL -MixedFilterZoomAndOffsetTest.StandardDpi/SkiaGraphiteDawn -MixedFilterZoomAndOffsetTest.StandardDpi/SkiaVulkan --PixelResourceTest/LayerTreeHostMasksForBackdropFiltersPixelTestWithLayerTree.Test/SkiaGL_GPU --PixelResourceTest/LayerTreeHostMasksForBackdropFiltersPixelTestWithLayerTree.Test/SkiaGL_OneCopy --PixelResourceTest/LayerTreeHostMasksForBackdropFiltersPixelTestWithLayerTree.Test/SkiaVulkan_GPU --PixelResourceTest/LayerTreeHostMasksForBackdropFiltersPixelTestWithLayerTree.Test/Software_Bitmap --PixelResourceTest/LayerTreeHostMasksPixelTest.ImageMaskOfLayer/SkiaGL_GPU --PixelResourceTest/LayerTreeHostMasksPixelTest.ImageMaskOfLayer/SkiaGL_OneCopy --PixelResourceTest/LayerTreeHostMasksPixelTest.ImageMaskOfLayer/SkiaVulkan_GPU --PixelResourceTest/LayerTreeHostMasksPixelTest.ImageMaskOfLayer/Software_Bitmap --PixelResourceTest/LayerTreeHostMasksPixelTest.MaskOfClippedLayer/SkiaGL_GPU --PixelResourceTest/LayerTreeHostMasksPixelTest.MaskOfClippedLayer/SkiaGL_OneCopy --PixelResourceTest/LayerTreeHostMasksPixelTest.MaskOfClippedLayer/SkiaVulkan_GPU --PixelResourceTest/LayerTreeHostMasksPixelTest.MaskOfClippedLayer/Software_Bitmap --PixelResourceTest/LayerTreeHostMasksPixelTest.MaskOfLayer/SkiaGL_GPU --PixelResourceTest/LayerTreeHostMasksPixelTest.MaskOfLayer/SkiaGL_OneCopy --PixelResourceTest/LayerTreeHostMasksPixelTest.MaskOfLayer/SkiaVulkan_GPU --PixelResourceTest/LayerTreeHostMasksPixelTest.MaskOfLayer/Software_Bitmap -SoftwareTextureLayerLoseFrameSinkTest.RunMultiThread_DelegatingRenderer -SoftwareTextureLayerLoseFrameSinkTest.RunSingleThread_DelegatingRenderer -SoftwareTextureLayerMultipleResourceTest.RunMultiThread_DelegatingRenderer
diff --git a/testing/unexpected_passes_common/result_output.py b/testing/unexpected_passes_common/result_output.py index f9c7585..3be5728 100644 --- a/testing/unexpected_passes_common/result_output.py +++ b/testing/unexpected_passes_common/result_output.py
@@ -8,6 +8,7 @@ import collections import logging +import re import sys import tempfile from typing import Any, Dict, IO, List, Optional, Set, Union @@ -18,9 +19,10 @@ # //testing imports. from unexpected_passes_common import data_types -# //third_party/blink/tools imports. -# Used for posting Buganizer comments. +# //third_party/ imports. +# Used for generating and posting Buganizer comments. from blinkpy.w3c import buganizer +from typ import expectations_parser FULL_PASS = 'Fully passed in the following' PARTIAL_PASS = 'Partially passed in the following' @@ -251,6 +253,9 @@ RemovedUrlsType = Union[List[str], Set[str]] +_BUG_PREFIX_PATTERN = re.compile( + expectations_parser.TaggedTestListParser.BUG_PREFIX_REGEX) + def OutputResults(stale_dict: data_types.TestExpectationMap, semi_stale_dict: data_types.TestExpectationMap, @@ -676,7 +681,7 @@ while len(urls): current_bug = urls.popleft() - current_bug = current_bug.split('crbug.com/', 1)[1] + current_bug = _BUG_PREFIX_PATTERN.split(current_bug, 1)[1] # Handles cases like crbug.com/angleproject/1234. current_bug = current_bug.replace('/', ':')
diff --git a/testing/unexpected_passes_common/result_output_unittest.py b/testing/unexpected_passes_common/result_output_unittest.py index 4640a60..a19f458 100755 --- a/testing/unexpected_passes_common/result_output_unittest.py +++ b/testing/unexpected_passes_common/result_output_unittest.py
@@ -643,6 +643,7 @@ 'https://crbug.com/angleproject/1234', 'http://crbug.com/2345', 'crbug.com/3456', + 'b/9999', ] orphaned_urls = ['https://crbug.com/1234', 'crbug.com/3456'] result_output._OutputAffectedUrls(urls, orphaned_urls, self._file_handle) @@ -652,7 +653,8 @@ 'https://crbug.com/1234 ' 'https://crbug.com/angleproject/1234 ' 'http://crbug.com/2345 ' - 'https://crbug.com/3456\n' + 'https://crbug.com/3456 ' + 'https://b/9999\n' 'Closable bugs: ' 'https://crbug.com/1234 ' 'https://crbug.com/3456\n')) @@ -669,12 +671,13 @@ urls = [ 'crbug.com/1234', 'https://crbug.com/angleproject/2345', + 'b/9999', ] result_output._OutputUrlsForClDescription(urls, [], self._file_handle) self._file_handle.close() with open(self._filepath) as f: self.assertEqual(f.read(), ('Affected bugs for CL description:\n' - 'Bug: 1234, angleproject:2345\n')) + 'Bug: 9999, 1234, angleproject:2345\n')) def testBugLimit(self) -> None: """Tests that only a certain number of bugs are allowed per line."""
diff --git a/testing/variations/fieldtrial_testing_config.json b/testing/variations/fieldtrial_testing_config.json index 7facc869..2bfa069 100644 --- a/testing/variations/fieldtrial_testing_config.json +++ b/testing/variations/fieldtrial_testing_config.json
@@ -1485,6 +1485,24 @@ ] } ], + "AutoPictureInPictureForVideoPlayback": [ + { + "platforms": [ + "chromeos", + "linux", + "mac", + "windows" + ], + "experiments": [ + { + "name": "Enabled", + "enable_features": [ + "AutoPictureInPictureForVideoPlayback" + ] + } + ] + } + ], "AutoSpeculationRules": [ { "platforms": [ @@ -8091,12 +8109,26 @@ ] } ], - "DirectCompositorThreadIpcDesktop": [ + "DirectCompositorThreadIpcMacLinuxChromeOS": [ { "platforms": [ "chromeos", "linux", - "mac", + "mac" + ], + "experiments": [ + { + "name": "Enabled", + "enable_features": [ + "DirectCompositorThreadIpc" + ] + } + ] + } + ], + "DirectCompositorThreadIpcWin": [ + { + "platforms": [ "windows" ], "experiments": [ @@ -11827,6 +11859,21 @@ ] } ], + "IOSCleanupHangingPasswordFormExtractionRequests": [ + { + "platforms": [ + "ios" + ], + "experiments": [ + { + "name": "Enabled", + "enable_features": [ + "IosCleanupHangingPasswordFormExtractionRequests" + ] + } + ] + } + ], "IOSCriteriaExperimentEnabled": [ { "platforms": [ @@ -12375,6 +12422,15 @@ "enable_features": [ "IOSReactivationNotifications" ] + }, + { + "name": "ESBFirst", + "params": { + "reactivation_order": "8,7,1" + }, + "enable_features": [ + "IOSReactivationNotifications" + ] } ] }
diff --git a/third_party/angle b/third_party/angle index a4d4a77..1166eec 160000 --- a/third_party/angle +++ b/third_party/angle
@@ -1 +1 @@ -Subproject commit a4d4a7735efc9c1e367867f73568e4fb0a8f1a66 +Subproject commit 1166eec4c0b125e9e945196acfc549983ef72b18
diff --git a/third_party/blink/common/messaging/string_message_codec_unittest.cc b/third_party/blink/common/messaging/string_message_codec_unittest.cc index 68eec7c..6274b93 100644 --- a/third_party/blink/common/messaging/string_message_codec_unittest.cc +++ b/third_party/blink/common/messaging/string_message_codec_unittest.cc
@@ -32,6 +32,7 @@ v8::ArrayBuffer::Allocator::NewDefaultAllocator(); v8::Isolate* isolate = v8::Isolate::New(params); { + v8::Isolate::Scope isolate_scope(isolate); v8::HandleScope scope(isolate); v8::TryCatch try_catch(isolate); @@ -91,6 +92,7 @@ v8::ArrayBuffer::Allocator::NewDefaultAllocator(); v8::Isolate* isolate = v8::Isolate::New(params); { + v8::Isolate::Scope isolate_scope(isolate); v8::HandleScope scope(isolate); v8::TryCatch try_catch(isolate);
diff --git a/third_party/blink/public/mojom/on_device_translation/translation_manager.mojom b/third_party/blink/public/mojom/on_device_translation/translation_manager.mojom index b52528f..b40d2450 100644 --- a/third_party/blink/public/mojom/on_device_translation/translation_manager.mojom +++ b/third_party/blink/public/mojom/on_device_translation/translation_manager.mojom
@@ -130,32 +130,6 @@ pending_remote<ModelDownloadProgressObserver>? observer_remote; }; -// The availability of a translation. -enum TranslationAvailability { - kNo, - kReadily, - kAfterDownload, -}; - -// The information of a translator availability. -struct TranslatorAvailabilityInfo { - // The language categories for the availability matrix. - // Each language code is the language code which is supported by the - // Translator API's implementation library. - // Note: `preferred` means that the language is in the user's accept language. - array<array<TranslatorLanguageCode>> language_categories; - - // The availability matrix for each language category. The availability matrix - // is a 2D array, where the first dimension represents the source language - // category, and the second dimension represents the target language category. - // The size of the availability matrix must be len(language_categories) * - // len(language_categories). - array<array<TranslationAvailability>> language_availability_matrix; - - // The availability of the translation service. - TranslationAvailability availability; -}; - // Interface to manage translation between languages on-device. Process called // from the renderer and used to implement the translation in the browser process. interface TranslationManager { @@ -179,9 +153,6 @@ pending_remote<TranslationManagerCreateTranslatorClient> client, TranslatorCreateOptions options); - // Get the necessary information to calculate translator availability. - GetTranslatorAvailabilityInfo() => (TranslatorAvailabilityInfo info); - // Returns the availability of the language pair translation. TranslationAvailable( TranslatorLanguageCode source_lang, TranslatorLanguageCode target_lang)
diff --git a/third_party/blink/public/mojom/worker/dedicated_worker_host_factory.mojom b/third_party/blink/public/mojom/worker/dedicated_worker_host_factory.mojom index 428e13d..cc3ca9b 100644 --- a/third_party/blink/public/mojom/worker/dedicated_worker_host_factory.mojom +++ b/third_party/blink/public/mojom/worker/dedicated_worker_host_factory.mojom
@@ -93,37 +93,6 @@ // An interface used to instantiate a dedicated worker host. The implementation // of this interface lives in the browser process. interface DedicatedWorkerHostFactory { - // TODO(crbug.com/906991): Remove this after PlzDedicatedWorker ships. - // Non-PlzDedicatedWorker: - // The factory client should call this instead of - // CreateWorkerHostAndStartScriptLoad() when PlzDedicatedWorker is disabled. - // - // Creates a new DedicatedWorkerHost, and requests `browser_interface_broker` - // to provide the worker access to mojo interfaces. - // `script_url` is used only for UMA purposes. - // `origin` is the origin that will be used by the worker on the renderer - // side. It might differ from the origin that is used on the browser side - // when `script_url` is a data: URL, due to the linked bug. We are passing the - // origin to the browser side so that it can use it in cases like blob URL - // origin resolving, which is based on the renderer side's origin. - // TODO(crbug.com/40051700): Remove the mismatch cases. - CreateWorkerHost( - blink.mojom.DedicatedWorkerToken token, - url.mojom.Url script_url, - url.mojom.Origin origin, - pending_receiver<blink.mojom.BrowserInterfaceBroker> - browser_interface_broker, - pending_receiver<DedicatedWorkerHost> host) => - (network.mojom.CrossOriginEmbedderPolicy parent_coep, - // Used to notify feature usages that might affect back-forward cache - // usages. - pending_remote<BackForwardCacheControllerHost>? - back_forward_cache_controller_host); - - // PlzDedicatedWorker: - // The factory client should call this instead of CreateWorkerHost() when - // PlzDedicatedWorker is enabled. - // // Creates a new DedicatedWorkerHost, and requests to start top-level worker // script loading for `script_url` using `credentials_mode` and // `outside_fetch_client_settings_object`.
diff --git a/third_party/blink/public/platform/web_dedicated_worker_host_factory_client.h b/third_party/blink/public/platform/web_dedicated_worker_host_factory_client.h index 1969688..449d2db 100644 --- a/third_party/blink/public/platform/web_dedicated_worker_host_factory_client.h +++ b/third_party/blink/public/platform/web_dedicated_worker_host_factory_client.h
@@ -16,7 +16,6 @@ #include "third_party/blink/public/mojom/frame/lifecycle.mojom-shared.h" #include "third_party/blink/public/platform/cross_variant_mojo_util.h" #include "third_party/blink/public/platform/web_fetch_client_settings_object.h" -#include "third_party/blink/public/platform/web_security_origin.h" namespace base { class SingleThreadTaskRunner; @@ -43,14 +42,6 @@ virtual ~WebDedicatedWorkerHostFactoryClient() = default; // Requests the creation of DedicatedWorkerHost in the browser process. - // For non-PlzDedicatedWorker. This will be removed once PlzDedicatedWorker is - // enabled by default. - virtual void CreateWorkerHostDeprecated( - const DedicatedWorkerToken& dedicated_worker_token, - const blink::WebURL& script_url, - const WebSecurityOrigin& origin, - CreateWorkerHostCallback callback) = 0; - // For PlzDedicatedWorker. virtual void CreateWorkerHost( const DedicatedWorkerToken& dedicated_worker_token, const blink::WebURL& script_url,
diff --git a/third_party/blink/renderer/core/accessibility/aria_notification_options.idl b/third_party/blink/renderer/core/accessibility/aria_notification_options.idl index 97ab91b..9a97b7c 100644 --- a/third_party/blink/renderer/core/accessibility/aria_notification_options.idl +++ b/third_party/blink/renderer/core/accessibility/aria_notification_options.idl
@@ -4,5 +4,5 @@ dictionary AriaNotificationOptions { AriaNotifyPriority priority = "normal"; [RuntimeEnabled=AriaNotifyV2] AriaNotifyInterrupt interrupt = "none"; - [RuntimeEnabled=AriaNotifyV2] DOMString notificationId = ""; + [RuntimeEnabled=AriaNotifyV2] DOMString type = ""; }; \ No newline at end of file
diff --git a/third_party/blink/renderer/core/dom/range.cc b/third_party/blink/renderer/core/dom/range.cc index b0e1831..c22ebce3 100644 --- a/third_party/blink/renderer/core/dom/range.cc +++ b/third_party/blink/renderer/core/dom/range.cc
@@ -100,6 +100,7 @@ range_->RemoveFromSelectionIfInDifferentRoot(*old_document_); range_->UpdateSelectionIfAddedToSelection(); } + range_->ResetUpdateSelectionBehavior(); range_->ScheduleVisualUpdateIfInRegisteredHighlight( range_->OwnerDocument()); @@ -292,7 +293,7 @@ // Further, if collapse is not due to being in different tree scopes, the // range should update both selection's start and end positions. collapse(collapse_to_start); - update_selection_behavior_ = UpdateSelectionBehavior::kAll; + ResetUpdateSelectionBehavior(); } } @@ -1787,19 +1788,21 @@ DCHECK(endContainer()->GetDocument() == OwnerDocument()); EventDispatchForbiddenScope no_events; - // Given this range's update_selection_behavior_, update selection to either - // the range's new position or keep using current selection's position. - const Position& start_position = - RuntimeEnabledFeatures::SelectionAcrossShadowDOMEnabled() && - update_selection_behavior_ == UpdateSelectionBehavior::kEndOnly - ? selection.GetSelectionInDOMTree().ComputeStartPosition() - : StartPosition(); - const Position& end_position = - RuntimeEnabledFeatures::SelectionAcrossShadowDOMEnabled() && - update_selection_behavior_ == UpdateSelectionBehavior::kStartOnly - ? selection.GetSelectionInDOMTree().ComputeEndPosition() - : EndPosition(); - update_selection_behavior_ = UpdateSelectionBehavior::kAll; + Position start_position = StartPosition(); + Position end_position = EndPosition(); + if (RuntimeEnabledFeatures::SelectionAcrossShadowDOMEnabled()) { + switch (update_selection_behavior_) { + case UpdateSelectionBehavior::kEndOnly: + start_position = + selection.GetSelectionInDOMTree().ComputeStartPosition(); + break; + case UpdateSelectionBehavior::kStartOnly: + end_position = selection.GetSelectionInDOMTree().ComputeEndPosition(); + break; + case UpdateSelectionBehavior::kAll: + break; + } + } selection.SetSelection(SelectionInDOMTree::Builder() .Collapse(start_position) @@ -1813,6 +1816,10 @@ selection.CacheRangeOfDocument(this); } +void Range::ResetUpdateSelectionBehavior() { + update_selection_behavior_ = UpdateSelectionBehavior::kAll; +} + void Range::ScheduleVisualUpdateIfInRegisteredHighlight(Document& document) { if (LocalDOMWindow* window = document.domWindow()) { if (HighlightRegistry* highlight_registry =
diff --git a/third_party/blink/renderer/core/dom/range.h b/third_party/blink/renderer/core/dom/range.h index 01fb6be..8d527e3 100644 --- a/third_party/blink/renderer/core/dom/range.h +++ b/third_party/blink/renderer/core/dom/range.h
@@ -223,6 +223,7 @@ }; UpdateSelectionBehavior update_selection_behavior_ = UpdateSelectionBehavior::kAll; + void ResetUpdateSelectionBehavior(); friend class RangeUpdateScope; };
diff --git a/third_party/blink/renderer/core/frame/deprecation/deprecation.json5 b/third_party/blink/renderer/core/frame/deprecation/deprecation.json5 index 0a8bfe5..6f3386e 100644 --- a/third_party/blink/renderer/core/frame/deprecation/deprecation.json5 +++ b/third_party/blink/renderer/core/frame/deprecation/deprecation.json5
@@ -244,8 +244,8 @@ }, { name: "H1UserAgentFontSizeInSection", - message: "The website has an <h1> tag within an <article>, <aside>, <nav>, or <section>, and relies on deprecated UA stylesheet rules for the resulting font size. See the second block of 'x h1' styles in https://html.spec.whatwg.org/multipage/rendering.html#sections-and-headings. These special rules are deprecated and will be removed. See https://github.com/whatwg/html/issues/7867.", - translation_note: "This warning occurs when a site uses <h1> inside <section>. It means the behavior may change in a future Chrome release, when these special rules are removed.", + message: "Found an <h1> tag within an <article>, <aside>, <nav>, or <section> which does not have a specified font-size. The size of this heading text will be changing in this browser in the near future. See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Heading_Elements#specifying_a_uniform_font_size_for_h1 for more information.", + translation_note: "This warning occurs when a site uses <h1> inside <article>, <aside>, <nav>, or <section>. It means the behavior (font size) may change in a future Chrome release, when some special rules are removed from the browser.", web_features: [ "kH1UserAgentFontSizeInSectionApplied", ],
diff --git a/third_party/blink/renderer/core/html/canvas/canvas_rendering_context.h b/third_party/blink/renderer/core/html/canvas/canvas_rendering_context.h index ec0f7ef..229aab03 100644 --- a/third_party/blink/renderer/core/html/canvas/canvas_rendering_context.h +++ b/third_party/blink/renderer/core/html/canvas/canvas_rendering_context.h
@@ -327,6 +327,8 @@ return false; } + virtual bool ShouldTriggerIntervention() const { return false; } + bool did_print_in_current_task() const { return did_print_in_current_task_; } protected:
diff --git a/third_party/blink/renderer/core/loader/cookie_jar.cc b/third_party/blink/renderer/core/loader/cookie_jar.cc index 5dd18c7..37e6898 100644 --- a/third_party/blink/renderer/core/loader/cookie_jar.cc +++ b/third_party/blink/renderer/core/loader/cookie_jar.cc
@@ -70,6 +70,8 @@ base::ElapsedTimer timer; RequestRestrictedCookieManagerIfNeeded(); + bool is_ad_tagged = + document_->GetFrame() && document_->GetFrame()->IsAdFrame(); CookiesResponsePtr response; const bool get_version_shared_memory = @@ -80,7 +82,8 @@ backend_->SetCookieFromString( cookie_url, document_->SiteForCookies(), document_->TopFrameOrigin(), document_->GetExecutionContext()->GetStorageAccessApiStatus(), - get_version_shared_memory, apply_devtools_overrides, value, + get_version_shared_memory, is_ad_tagged, apply_devtools_overrides, + value, WTF::BindOnce(&CookieJar::OnSetCookieResponse, WrapWeakPersistent(this), cookie_url, apply_devtools_overrides)); } else { @@ -88,8 +91,8 @@ cookie_url, document_->SiteForCookies(), document_->TopFrameOrigin(), document_->GetExecutionContext()->GetStorageAccessApiStatus(), - get_version_shared_memory, apply_devtools_overrides, value, - &response)) { + get_version_shared_memory, is_ad_tagged, apply_devtools_overrides, + value, &response)) { // On IPC failure invalidate cached values and return empty string since // there is no guarantee the client can still validly access cookies in // the current context. See crbug.com/1468909.
diff --git a/third_party/blink/renderer/core/page/autoscroll_controller.h b/third_party/blink/renderer/core/page/autoscroll_controller.h index 5f180e7d..d4dc9a1 100644 --- a/third_party/blink/renderer/core/page/autoscroll_controller.h +++ b/third_party/blink/renderer/core/page/autoscroll_controller.h
@@ -145,6 +145,9 @@ FRIEND_TEST_ALL_PREFIXES(AutoscrollControllerTest, AutoscrollIsPropagatedInYDirection); FRIEND_TEST_ALL_PREFIXES(AutoscrollControllerTest, TextSelectionAutoScroll); + FRIEND_TEST_ALL_PREFIXES(AutoscrollControllerTest, + PageVisibilityChangeCancelsAutoscroll); + FRIEND_TEST_ALL_PREFIXES(AutoscrollControllerTest, PageLoadCancelsAutoscroll); }; } // namespace blink
diff --git a/third_party/blink/renderer/core/page/autoscroll_controller_test.cc b/third_party/blink/renderer/core/page/autoscroll_controller_test.cc index 6815a78..7b79e209 100644 --- a/third_party/blink/renderer/core/page/autoscroll_controller_test.cc +++ b/third_party/blink/renderer/core/page/autoscroll_controller_test.cc
@@ -431,4 +431,68 @@ EXPECT_GT(range->GetText().length(), 0u); } +TEST_F(AutoscrollControllerTest, PageVisibilityChangeCancelsAutoscroll) { + WebView().MainFrameViewWidget()->Resize(gfx::Size(800, 600)); + + GetDocument().GetSettings()->SetScriptEnabled(true); + static const char* kAutoscrollHTML = R"HTML( + <!DOCTYPE html> + <meta name='viewport' content='width=device-width'/> + <style> + html, body { margin: 0; } + .spacer { height: 10000px; } + </style> + <div class=spacer></div> + )HTML"; + SimRequest request("https://example.com/test.html", "text/html"); + LoadURL("https://example.com/test.html"); + request.Complete(kAutoscrollHTML); + AutoscrollController& controller = GetAutoscrollController(); + + EXPECT_FALSE(controller.IsAutoscrolling()); + + LocalFrame* frame = GetDocument().GetFrame(); + controller.StartMiddleClickAutoscroll(frame, GetDocument().GetLayoutView(), + gfx::PointF(), gfx::PointF()); + + EXPECT_TRUE(controller.IsAutoscrolling()); + + frame->GetPage()->SetVisibilityState( + mojom::blink::PageVisibilityState::kHidden, /*is_initial_state=*/false); + + EXPECT_FALSE(controller.IsAutoscrolling()); +} + +TEST_F(AutoscrollControllerTest, PageLoadCancelsAutoscroll) { + WebView().MainFrameViewWidget()->Resize(gfx::Size(800, 600)); + + GetDocument().GetSettings()->SetScriptEnabled(true); + static const char* kAutoscrollHTML = R"HTML( + <!DOCTYPE html> + <meta name='viewport' content='width=device-width'/> + <style> + html, body { margin: 0; } + .spacer { height: 10000px; } + </style> + <div class=spacer></div> + )HTML"; + SimRequest request("https://example.com/test.html", "text/html"); + LoadURL("https://example.com/test.html"); + request.Complete(kAutoscrollHTML); + AutoscrollController& controller = GetAutoscrollController(); + + EXPECT_FALSE(controller.IsAutoscrolling()); + + LocalFrame* frame = GetDocument().GetFrame(); + controller.StartMiddleClickAutoscroll(frame, GetDocument().GetLayoutView(), + gfx::PointF(), gfx::PointF()); + + EXPECT_TRUE(controller.IsAutoscrolling()); + + SimRequest request_2("https://example.com/test_2.html", "text/html"); + LoadURL("https://example.com/test_2.html"); + request_2.Complete(kAutoscrollHTML); + + EXPECT_FALSE(controller.IsAutoscrolling()); +} } // namespace blink
diff --git a/third_party/blink/renderer/core/page/page.cc b/third_party/blink/renderer/core/page/page.cc index e7b60858..d5f8515 100644 --- a/third_party/blink/renderer/core/page/page.cc +++ b/third_party/blink/renderer/core/page/page.cc
@@ -873,6 +873,13 @@ was_visible || is_visible) { main_frame_->DidChangeVisibilityState(); } + + // Ensure that autoscrolling ends whenever the page transitions to + // non-visible. + if (!is_visible) { + GetAutoscrollController().StopMiddleClickAutoscroll( + DynamicTo<LocalFrame>(GetFocusController().FocusedOrMainFrame())); + } } }
diff --git a/third_party/blink/renderer/core/paint/paint_layer_painter.cc b/third_party/blink/renderer/core/paint/paint_layer_painter.cc index ed1d50d..7119ab0 100644 --- a/third_party/blink/renderer/core/paint/paint_layer_painter.cc +++ b/third_party/blink/renderer/core/paint/paint_layer_painter.cc
@@ -396,7 +396,7 @@ // by the layer (see `SVGContainerPainter::Paint`). auto* properties = object.FirstFragment().PaintProperties(); if (properties && properties->Filter() && - properties->Filter()->Filter().HasReferenceFilter()) { + properties->Filter()->HasReferenceFilter()) { context.GetPaintController().EnsureChunk(); } }
diff --git a/third_party/blink/renderer/core/paint/paint_property_tree_builder.cc b/third_party/blink/renderer/core/paint/paint_property_tree_builder.cc index be0d133..95596fd8 100644 --- a/third_party/blink/renderer/core/paint/paint_property_tree_builder.cc +++ b/third_party/blink/renderer/core/paint/paint_property_tree_builder.cc
@@ -2062,13 +2062,14 @@ return false; } -static void UpdateFilterEffect(const LayoutObject& object, - const EffectPaintPropertyNode* effect_node, - CompositorFilterOperations& filter) { +static void UpdateFilterEffect( + const LayoutObject& object, + const EffectPaintPropertyNode* effect_node, + EffectPaintPropertyNode::FilterInfo& filter_info) { if (object.HasLayer()) { // Try to use the cached filter. - if (effect_node) { - filter = effect_node->Filter(); + if (effect_node && effect_node->Filter()) { + filter_info.operations = *effect_node->Filter(); } PaintLayer* layer = To<LayoutBoxModelObject>(object).Layer(); #if DCHECK_IS_ON() @@ -2077,7 +2078,9 @@ layer->UpdateFilterReferenceBox(); DCHECK_EQ(reference_box, layer->FilterReferenceBox()); #endif - layer->UpdateCompositorFilterOperationsForFilter(filter); + layer->UpdateCompositorFilterOperationsForFilter(filter_info.operations); + filter_info.output_bounds = filter_info.operations.MapRect( + ToEnclosingRect(layer->FilterReferenceBox())); return; } if (object.IsSVGChild() && !object.IsText()) { @@ -2087,9 +2090,12 @@ if (!object.StyleRef().HasFilter()) return; // Try to use the cached filter. - if (effect_node) - filter = effect_node->Filter(); - client->UpdateFilterData(filter); + if (effect_node && effect_node->Filter()) { + filter_info.operations = *effect_node->Filter(); + } + client->UpdateFilterData(filter_info.operations); + filter_info.output_bounds = filter_info.operations.MapRect( + gfx::ToEnclosingRect(object.VisualRectInLocalSVGCoordinates())); } } @@ -2099,8 +2105,13 @@ if (NeedsFilter(object_, full_context_)) { EffectPaintPropertyNode::State state; state.local_transform_space = context_.current.transform; - - UpdateFilterEffect(object_, properties_->Filter(), state.filter); + EffectPaintPropertyNode::FilterInfo filter_info; + UpdateFilterEffect(object_, properties_->Filter(), filter_info); + if (!filter_info.operations.IsEmpty()) { + state.filter_info = + std::make_unique<EffectPaintPropertyNode::FilterInfo>( + std::move(filter_info)); + } // The CSS filter spec didn't specify how filters interact with overflow // clips. The implementation here mimics the old Blink/WebKit behavior for @@ -2140,20 +2151,13 @@ state.self_or_ancestor_participates_in_view_transition = context_.self_or_ancestor_participates_in_view_transition; - // This must be computed before std::move(state) below. - bool needs_pixel_moving_filter_clip_expander = - (state.direct_compositing_reasons & - (CompositingReason::kWillChangeFilter | - CompositingReason::kActiveFilterAnimation)) || - state.filter.HasFilterThatMovesPixels(); - EffectPaintPropertyNode::AnimationState animation_state; animation_state.is_running_filter_animation_on_compositor = object_.StyleRef().IsRunningFilterAnimationOnCompositor(); OnUpdateEffect(properties_->UpdateFilter( *context_.current_effect, std::move(state), animation_state)); - if (needs_pixel_moving_filter_clip_expander) { + if (properties_->Filter()->NeedsPixelMovingFilterClipExpander()) { OnUpdateClip(properties_->UpdatePixelMovingFilterClipExpander( *context_.current.clip, ClipPaintPropertyNode::State(*context_.current.transform,
diff --git a/third_party/blink/renderer/core/paint/paint_property_tree_builder_test.cc b/third_party/blink/renderer/core/paint/paint_property_tree_builder_test.cc index 6d27f0a..a11e1cd9 100644 --- a/third_party/blink/renderer/core/paint/paint_property_tree_builder_test.cc +++ b/third_party/blink/renderer/core/paint/paint_property_tree_builder_test.cc
@@ -7159,7 +7159,7 @@ auto* properties = PaintPropertiesForElement("target"); ASSERT_TRUE(properties); ASSERT_TRUE(properties->Filter()); - EXPECT_TRUE(properties->Filter()->Filter().IsEmpty()); + EXPECT_FALSE(properties->Filter()->Filter()); EXPECT_TRUE(properties->Filter()->RequiresCompositingForWillChangeFilter()); // will-change:filter should not cause transform or effect node. @@ -7176,7 +7176,7 @@ auto* properties = PaintPropertiesForElement("target"); ASSERT_TRUE(properties); ASSERT_TRUE(properties->Filter()); - EXPECT_TRUE(properties->Filter()->Filter().IsEmpty()); + EXPECT_FALSE(properties->Filter()->Filter()); EXPECT_TRUE(properties->Filter()->RequiresCompositingForWillChangeFilter()); // will-change:filter should not add compositing reason for the transform or
diff --git a/third_party/blink/renderer/core/paint/paint_property_tree_update_tests.cc b/third_party/blink/renderer/core/paint/paint_property_tree_update_tests.cc index 05f60f8b..e5a0c06 100644 --- a/third_party/blink/renderer/core/paint/paint_property_tree_update_tests.cc +++ b/third_party/blink/renderer/core/paint/paint_property_tree_update_tests.cc
@@ -1770,8 +1770,11 @@ const auto* properties = PaintPropertiesForElement("span"); ASSERT_TRUE(properties); ASSERT_TRUE(properties->Filter()); + ASSERT_TRUE(properties->Filter()->Filter()); EXPECT_EQ(gfx::PointF(0, 20), - properties->Filter()->Filter().ReferenceBox().origin()); + properties->Filter()->Filter()->ReferenceBox().origin()); + EXPECT_EQ(gfx::Point(-3, 17), + properties->Filter()->FilterOutputBounds().origin()); GetDocument() .getElementById(AtomicString("spacer")) @@ -1780,7 +1783,9 @@ UpdateAllLifecyclePhasesForTest(); ASSERT_EQ(properties, PaintPropertiesForElement("span")); EXPECT_EQ(gfx::PointF(0, 100), - properties->Filter()->Filter().ReferenceBox().origin()); + properties->Filter()->Filter()->ReferenceBox().origin()); + EXPECT_EQ(gfx::Point(-3, 97), + properties->Filter()->FilterOutputBounds().origin()); } TEST_P(PaintPropertyTreeUpdateTest, StartSVGAnimation) {
diff --git a/third_party/blink/renderer/core/paint/svg_container_painter.cc b/third_party/blink/renderer/core/paint/svg_container_painter.cc index 08db50028..bce8e737 100644 --- a/third_party/blink/renderer/core/paint/svg_container_painter.cc +++ b/third_party/blink/renderer/core/paint/svg_container_painter.cc
@@ -25,8 +25,7 @@ namespace { bool HasReferenceFilterEffect(const ObjectPaintProperties& properties) { - return properties.Filter() && - properties.Filter()->Filter().HasReferenceFilter(); + return properties.Filter() && properties.Filter()->HasReferenceFilter(); } } // namespace
diff --git a/third_party/blink/renderer/core/workers/dedicated_worker.cc b/third_party/blink/renderer/core/workers/dedicated_worker.cc index 4f0a5dda..1b8dda8 100644 --- a/third_party/blink/renderer/core/workers/dedicated_worker.cc +++ b/third_party/blink/renderer/core/workers/dedicated_worker.cc
@@ -273,76 +273,31 @@ // calling into the debugger can cause a breakpoint. v8_stack_trace_id_ = ThreadDebugger::From(GetExecutionContext()->GetIsolate()) ->StoreCurrentStackTrace("Worker Created"); - if (base::FeatureList::IsEnabled(features::kPlzDedicatedWorker)) { - TRACE_EVENT_NESTABLE_ASYNC_BEGIN0("blink.worker", - "PlzDedicatedWorker Specific Setup", - TRACE_ID_LOCAL(this)); - // For classic script, always use "same-origin" credentials mode. - // https://html.spec.whatwg.org/C/#fetch-a-classic-worker-script - // For module script, respect the credentials mode specified by - // WorkerOptions. - // https://html.spec.whatwg.org/C/#workeroptions - auto credentials_mode = network::mojom::CredentialsMode::kSameOrigin; - if (options_->type() == script_type_names::kModule) { - credentials_mode = Request::V8RequestCredentialsToCredentialsMode( - options_->credentials().AsEnum()); - } - mojo::PendingRemote<mojom::blink::BlobURLToken> blob_url_token; - if (script_request_url_.ProtocolIs("blob")) { - GetExecutionContext()->GetPublicURLManager().ResolveAsBlobURLToken( - script_request_url_, blob_url_token.InitWithNewPipeAndPassReceiver(), - /*is_top_level_navigation=*/false); - } - - factory_client_->CreateWorkerHost( - token_, script_request_url_, credentials_mode, - WebFetchClientSettingsObject(*outside_fetch_client_settings_object_), - std::move(blob_url_token), - GetExecutionContext()->GetStorageAccessApiStatus()); - // Continue in OnScriptLoadStarted() or OnScriptLoadStartFailed(). - return; + // For classic script, always use "same-origin" credentials mode. + // https://html.spec.whatwg.org/C/#fetch-a-classic-worker-script + // For module script, respect the credentials mode specified by + // WorkerOptions. + // https://html.spec.whatwg.org/C/#workeroptions + auto credentials_mode = network::mojom::CredentialsMode::kSameOrigin; + if (options_->type() == script_type_names::kModule) { + credentials_mode = Request::V8RequestCredentialsToCredentialsMode( + options_->credentials().AsEnum()); } - TRACE_EVENT_NESTABLE_ASYNC_BEGIN0("blink.worker", - "LegacyDedicatedWorker Specific Setup", - TRACE_ID_LOCAL(this)); - mojo::PendingRemote<network::mojom::blink::URLLoaderFactory> - blob_url_loader_factory; + mojo::PendingRemote<mojom::blink::BlobURLToken> blob_url_token; if (script_request_url_.ProtocolIs("blob")) { - GetExecutionContext()->GetPublicURLManager().Resolve( - script_request_url_, - blob_url_loader_factory.InitWithNewPipeAndPassReceiver()); + GetExecutionContext()->GetPublicURLManager().ResolveAsBlobURLToken( + script_request_url_, blob_url_token.InitWithNewPipeAndPassReceiver(), + /*is_top_level_navigation=*/false); } - // Calculate the origin on the renderer side when PlzDedicatedWorker is not - // enabled, as the starting of the worker will not wait for the browser side - // host creation and origin calculation. This follows the existing logic at - // worker_global_scope.cc, so see the comments there for details. - if (script_request_url_.ProtocolIsData()) { - origin_ = - GetExecutionContext()->GetSecurityOrigin()->DeriveNewOpaqueOrigin(); - } else { - origin_ = GetExecutionContext()->GetSecurityOrigin()->IsolatedCopy(); - } - - if (GetExecutionContext()->GetSecurityOrigin()->IsLocal()) { - // Local resources always have empty COEP, and Worker creation - // from a blob URL in a local resource cannot work with - // asynchronous OnHostCreated call, so we call it directly here. - // See https://crbug.com/1101603#c8. - factory_client_->CreateWorkerHostDeprecated(token_, script_request_url_, - WebSecurityOrigin(origin_), - base::DoNothing()); - OnHostCreated(std::move(blob_url_loader_factory), - network::CrossOriginEmbedderPolicy(), mojo::NullRemote()); - return; - } - - factory_client_->CreateWorkerHostDeprecated( - token_, script_request_url_, WebSecurityOrigin(origin_), - WTF::BindOnce(&DedicatedWorker::OnHostCreated, WrapWeakPersistent(this), - std::move(blob_url_loader_factory))); + factory_client_->CreateWorkerHost( + token_, script_request_url_, credentials_mode, + WebFetchClientSettingsObject(*outside_fetch_client_settings_object_), + std::move(blob_url_token), + GetExecutionContext()->GetStorageAccessApiStatus()); + // Continue in OnScriptLoadStarted() or OnScriptLoadStartFailed(). } void DedicatedWorker::OnHostCreated(
diff --git a/third_party/blink/renderer/core/workers/dedicated_worker_test.cc b/third_party/blink/renderer/core/workers/dedicated_worker_test.cc index c1f77c1..6666696 100644 --- a/third_party/blink/renderer/core/workers/dedicated_worker_test.cc +++ b/third_party/blink/renderer/core/workers/dedicated_worker_test.cc
@@ -352,11 +352,6 @@ : public WebDedicatedWorkerHostFactoryClient { public: // Implements WebDedicatedWorkerHostFactoryClient. - void CreateWorkerHostDeprecated( - const DedicatedWorkerToken& dedicated_worker_token, - const WebURL& script_url, - const WebSecurityOrigin& origin, - CreateWorkerHostCallback callback) override {} void CreateWorkerHost( const DedicatedWorkerToken& dedicated_worker_token, const WebURL& script_url,
diff --git a/third_party/blink/renderer/modules/BUILD.gn b/third_party/blink/renderer/modules/BUILD.gn index 82d70b6..594693a 100644 --- a/third_party/blink/renderer/modules/BUILD.gn +++ b/third_party/blink/renderer/modules/BUILD.gn
@@ -432,6 +432,7 @@ "canvas/canvas2d/canvas_style_test_utils.cc", "canvas/canvas2d/canvas_style_test_utils.h", "canvas/canvas2d/identifiability_study_helper_test.cc", + "canvas/canvas_noise_test.cc", "canvas/htmlcanvas/html_canvas_element_module_test.cc", "canvas/offscreencanvas/offscreen_canvas_rendering_api_ukm_metrics_test.cc", "canvas/offscreencanvas/offscreen_canvas_test.cc",
diff --git a/third_party/blink/renderer/modules/accessibility/aria_notification.cc b/third_party/blink/renderer/modules/accessibility/aria_notification.cc index 82162c261..6ed8f7d5 100644 --- a/third_party/blink/renderer/modules/accessibility/aria_notification.cc +++ b/third_party/blink/renderer/modules/accessibility/aria_notification.cc
@@ -39,9 +39,9 @@ AriaNotification::AriaNotification(const String& announcement, const AriaNotificationOptions* options) : announcement_(announcement), - notification_id_(options->notificationId()), + priority_(AsEnum(options->priority())), interrupt_(AsEnum(options->interrupt())), - priority_(AsEnum(options->priority())) {} + type_(options->type()) {} void AriaNotifications::Add(const String& announcement, const AriaNotificationOptions* options) {
diff --git a/third_party/blink/renderer/modules/accessibility/aria_notification.h b/third_party/blink/renderer/modules/accessibility/aria_notification.h index 3e88347e..b35a725 100644 --- a/third_party/blink/renderer/modules/accessibility/aria_notification.h +++ b/third_party/blink/renderer/modules/accessibility/aria_notification.h
@@ -22,15 +22,15 @@ const AriaNotificationOptions* options); const String& Announcement() const { return announcement_; } - const String& NotificationId() const { return notification_id_; } - AriaNotificationInterrupt Interrupt() const { return interrupt_; } AriaNotificationPriority Priority() const { return priority_; } + AriaNotificationInterrupt Interrupt() const { return interrupt_; } + const String& Type() const { return type_; } private: String announcement_; - String notification_id_; - AriaNotificationInterrupt interrupt_; AriaNotificationPriority priority_; + AriaNotificationInterrupt interrupt_; + String type_; }; class AriaNotifications {
diff --git a/third_party/blink/renderer/modules/accessibility/ax_object.cc b/third_party/blink/renderer/modules/accessibility/ax_object.cc index fe9e09d..489773f 100644 --- a/third_party/blink/renderer/modules/accessibility/ax_object.cc +++ b/third_party/blink/renderer/modules/accessibility/ax_object.cc
@@ -1300,25 +1300,24 @@ std::vector<std::string> announcements; std::vector<int32_t> priority_properties; - std::vector<std::string> notification_ids; std::vector<int32_t> interrupt_properties; + std::vector<std::string> notification_types; announcements.reserve(size); priority_properties.reserve(size); - notification_ids.reserve(size); interrupt_properties.reserve(size); + notification_types.reserve(size); for (const auto& notification : notifications) { announcements.emplace_back(TruncateString(notification.Announcement())); priority_properties.emplace_back( static_cast<int32_t>(notification.Priority())); if (RuntimeEnabledFeatures::AriaNotifyV2Enabled()) { - notification_ids.emplace_back( - TruncateString(notification.NotificationId())); + notification_types.emplace_back(TruncateString(notification.Type())); interrupt_properties.emplace_back( static_cast<int32_t>(notification.Interrupt())); } else { - notification_ids.emplace_back(); + notification_types.emplace_back(); interrupt_properties.emplace_back(static_cast<int32_t>( ax::mojom::blink::AriaNotificationInterrupt::kNone)); } @@ -1330,12 +1329,12 @@ node_data->AddIntListAttribute( ax::mojom::blink::IntListAttribute::kAriaNotificationPriorityProperties, priority_properties); - node_data->AddStringListAttribute( - ax::mojom::blink::StringListAttribute::kAriaNotificationIds, - notification_ids); node_data->AddIntListAttribute( ax::mojom::blink::IntListAttribute::kAriaNotificationInterruptProperties, interrupt_properties); + node_data->AddStringListAttribute( + ax::mojom::blink::StringListAttribute::kAriaNotificationTypes, + notification_types); } } // namespace
diff --git a/third_party/blink/renderer/modules/canvas/OWNERS b/third_party/blink/renderer/modules/canvas/OWNERS index 2d58b15..24d6e2a 100644 --- a/third_party/blink/renderer/modules/canvas/OWNERS +++ b/third_party/blink/renderer/modules/canvas/OWNERS
@@ -3,3 +3,6 @@ jpgravel@chromium.org junov@chromium.org yiyix@chromium.org + +# Canvas interventions +per-file canvas_noise_test.cc=file://third_party/blink/renderer/core/canvas_interventions/OWNERS
diff --git a/third_party/blink/renderer/modules/canvas/canvas2d/base_rendering_context_2d.cc b/third_party/blink/renderer/modules/canvas/canvas2d/base_rendering_context_2d.cc index b526f33..a92cf1cf 100644 --- a/third_party/blink/renderer/modules/canvas/canvas2d/base_rendering_context_2d.cc +++ b/third_party/blink/renderer/modules/canvas/canvas2d/base_rendering_context_2d.cc
@@ -1076,6 +1076,7 @@ location.set_x(location.x() / ClampTo<float>(width / font_width)); } + SetTriggerForCanvasIntervention(); Draw<OverdrawOp::kNone>( [font, text = std::move(text), direction, bidi_override, location, run_start, run_end, canvas, text_painter](
diff --git a/third_party/blink/renderer/modules/canvas/canvas2d/canvas_2d_recorder_context.cc b/third_party/blink/renderer/modules/canvas/canvas2d/canvas_2d_recorder_context.cc index 97a3f175..e842220 100644 --- a/third_party/blink/renderer/modules/canvas/canvas2d/canvas_2d_recorder_context.cc +++ b/third_party/blink/renderer/modules/canvas/canvas2d/canvas_2d_recorder_context.cc
@@ -1309,6 +1309,9 @@ identifiability_study_helper_.UpdateBuilder(CanvasOps::kSetShadowBlur, blur); } + if (blur > 0) { + SetTriggerForCanvasIntervention(); + } state.SetShadowBlur(ClampTo<float>(blur)); } @@ -1332,6 +1335,7 @@ identifiability_study_helper_.UpdateBuilder(CanvasOps::kSetShadowColor, color.Rgb()); } + SetTriggerForCanvasIntervention(); state.SetShadowColor(color); } @@ -1412,6 +1416,9 @@ identifiability_study_helper_.UpdateBuilder( CanvasOps::kSetGlobalCompositeOpertion, sk_blend_mode); } + if (op != kCompositeSourceOver || blend_mode != BlendMode::kNormal) { + SetTriggerForCanvasIntervention(); + } state.SetGlobalComposite(sk_blend_mode); } @@ -1845,6 +1852,9 @@ identifiability_study_helper_.UpdateBuilder( CanvasOps::kFill__Path, dom_path->GetIdentifiableToken(), winding_rule); } + if (dom_path->HasTriggerForIntervention()) { + SetTriggerForCanvasIntervention(); + } DrawPathInternal(*dom_path, CanvasRenderingContext2DState::kFillPaintType, winding_rule, path2d_use_paint_cache_); } @@ -1862,6 +1872,9 @@ identifiability_study_helper_.UpdateBuilder( CanvasOps::kStroke__Path, dom_path->GetIdentifiableToken()); } + if (dom_path->HasTriggerForIntervention()) { + SetTriggerForCanvasIntervention(); + } DrawPathInternal(*dom_path, CanvasRenderingContext2DState::kStrokePaintType, SkPathFillType::kWinding, path2d_use_paint_cache_); }
diff --git a/third_party/blink/renderer/modules/canvas/canvas2d/canvas_path.cc b/third_party/blink/renderer/modules/canvas/canvas2d/canvas_path.cc index 0b7425f..d276d6e 100644 --- a/third_party/blink/renderer/modules/canvas/canvas2d/canvas_path.cc +++ b/third_party/blink/renderer/modules/canvas/canvas2d/canvas_path.cc
@@ -479,6 +479,7 @@ CanvasOps::kArc, double_x, double_y, double_radius, double_start_angle, double_end_angle, anticlockwise); } + SetTriggerForCanvasIntervention(); if (!radius || start_angle == end_angle) [[unlikely]] { // The arc is empty but we still need to draw the connecting line. @@ -563,6 +564,7 @@ return; } + SetTriggerForCanvasIntervention(); path_.AddEllipse(gfx::PointF(x, y), radius_x, radius_y, rotation, start_angle, adjusted_end_angle); }
diff --git a/third_party/blink/renderer/modules/canvas/canvas2d/canvas_path.h b/third_party/blink/renderer/modules/canvas/canvas2d/canvas_path.h index d6985b3..a6510c87 100644 --- a/third_party/blink/renderer/modules/canvas/canvas2d/canvas_path.h +++ b/third_party/blink/renderer/modules/canvas/canvas2d/canvas_path.h
@@ -180,6 +180,10 @@ // than necessary. gfx::RectF BoundingRect() const; + bool HasTriggerForIntervention() const { + return has_trigger_for_intervention_; + } + void Trace(Visitor*) const override; protected: @@ -202,6 +206,12 @@ return path_; } + // Called when a canvas operation is made that would trigger a canvas + // intervention. + void SetTriggerForCanvasIntervention() { + has_trigger_for_intervention_ = true; + } + // This mirrors state that is stored in CanvasRenderingContext2DState. We // replicate it here so that IsTransformInvertible() can be a non-virtual // inline-able call. We do not replicate the whole CTM. Therefore @@ -211,6 +221,8 @@ IdentifiabilityStudyHelper identifiability_study_helper_; + bool has_trigger_for_intervention_ = false; + private: // Used to build up a line. class LineBuilder {
diff --git a/third_party/blink/renderer/modules/canvas/canvas2d/canvas_rendering_context_2d.h b/third_party/blink/renderer/modules/canvas/canvas2d/canvas_rendering_context_2d.h index 9e27597..35561de 100644 --- a/third_party/blink/renderer/modules/canvas/canvas2d/canvas_rendering_context_2d.h +++ b/third_party/blink/renderer/modules/canvas/canvas2d/canvas_rendering_context_2d.h
@@ -247,6 +247,10 @@ int LayerCount() const override; + bool ShouldTriggerIntervention() const override { + return HasTriggerForIntervention(); + } + protected: HTMLCanvasElement* HostAsHTMLCanvasElement() const final; UniqueFontSelector* GetFontSelector() const final;
diff --git a/third_party/blink/renderer/modules/canvas/canvas_noise_test.cc b/third_party/blink/renderer/modules/canvas/canvas_noise_test.cc new file mode 100644 index 0000000..53bfadde --- /dev/null +++ b/third_party/blink/renderer/modules/canvas/canvas_noise_test.cc
@@ -0,0 +1,147 @@ +// Copyright 2025 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_testing.h" +#include "third_party/blink/renderer/core/frame/frame_test_helpers.h" +#include "third_party/blink/renderer/core/frame/local_dom_window.h" +#include "third_party/blink/renderer/core/html/canvas/html_canvas_element.h" +#include "third_party/blink/renderer/core/testing/page_test_base.h" +#include "third_party/blink/renderer/modules/canvas/canvas2d/canvas_rendering_context_2d.h" +#include "third_party/blink/renderer/modules/canvas/canvas2d/canvas_style_test_utils.h" +#include "third_party/blink/renderer/modules/canvas/canvas2d/path_2d.h" +#include "third_party/blink/renderer/platform/heap/persistent.h" +#include "third_party/blink/renderer/platform/runtime_feature_state/runtime_feature_state_override_context.h" + +namespace blink { + +class CanvasNoiseTest : public PageTestBase { + public: + CanvasNoiseTest() = default; + + void SetUp() override { + PageTestBase::SetUp(); + SetHtmlInnerHTML("<body><canvas id='c' width='300' height='300'></body>"); + UpdateAllLifecyclePhasesForTest(); + + canvas_element_ = To<HTMLCanvasElement>(GetElementById("c")); + + CanvasContextCreationAttributesCore attributes; + attributes.alpha = true; + attributes.desynchronized = true; + attributes.will_read_frequently = + CanvasContextCreationAttributesCore::WillReadFrequently::kFalse; + canvas_element_->GetCanvasRenderingContext(/*canvas_type=*/"2d", + attributes); + GetFrame() + .DomWindow() + ->GetRuntimeFeatureStateOverrideContext() + ->SetCanvasInterventionsForceEnabled(); + } + + void TearDown() override { + PageTestBase::TearDown(); + CanvasRenderingContext::GetCanvasPerformanceMonitor().ResetForTesting(); + } + + HTMLCanvasElement& CanvasElement() const { return *canvas_element_; } + + CanvasRenderingContext2D* Context2D() const { + return static_cast<CanvasRenderingContext2D*>( + CanvasElement().RenderingContext()); + } + + Document& GetDocument() const { return *GetFrame().DomWindow()->document(); } + + ScriptState* GetScriptState() { + return ToScriptStateForMainWorld(GetDocument().GetFrame()); + } + + std::unique_ptr<frame_test_helpers::WebViewHelper> web_view_helper_; + Persistent<HTMLCanvasElement> canvas_element_; +}; + +TEST_F(CanvasNoiseTest, NoTriggerOnFillRect) { + V8TestingScope scope; + SetFillStyleString(Context2D(), GetScriptState(), "red"); + Context2D()->fillRect(0, 0, 10, 10); + EXPECT_FALSE(Context2D()->HasTriggerForIntervention()); + EXPECT_FALSE(Context2D()->ShouldTriggerIntervention()); +} + +TEST_F(CanvasNoiseTest, TriggerOnShadowBlur) { + Context2D()->setShadowBlur(10); + Context2D()->setShadowColor("red"); + Context2D()->fillRect(0, 0, 10, 10); + EXPECT_TRUE(Context2D()->HasTriggerForIntervention()); + EXPECT_TRUE(Context2D()->ShouldTriggerIntervention()); +} + +TEST_F(CanvasNoiseTest, TriggerOnArc) { + Context2D()->beginPath(); + NonThrowableExceptionState exception_state; + Context2D()->arc(10, 10, 10, 0, 6, false, exception_state); + Context2D()->stroke(); + EXPECT_TRUE(Context2D()->HasTriggerForIntervention()); + EXPECT_TRUE(Context2D()->ShouldTriggerIntervention()); +} + +TEST_F(CanvasNoiseTest, TriggerOnEllipse) { + Context2D()->beginPath(); + NonThrowableExceptionState exception_state; + Context2D()->ellipse(10, 10, 5, 7, 3, 0, 3, false, exception_state); + Context2D()->fill(); + EXPECT_TRUE(Context2D()->HasTriggerForIntervention()); + EXPECT_TRUE(Context2D()->ShouldTriggerIntervention()); +} + +TEST_F(CanvasNoiseTest, TriggerOnSetGlobalCompositeOperation) { + Context2D()->setGlobalCompositeOperation("multiply"); + V8TestingScope scope; + SetFillStyleString(Context2D(), GetScriptState(), "red"); + Context2D()->fillRect(0, 0, 10, 10); + EXPECT_TRUE(Context2D()->HasTriggerForIntervention()); + EXPECT_TRUE(Context2D()->ShouldTriggerIntervention()); +} + +TEST_F(CanvasNoiseTest, TriggerOnFillText) { + Context2D()->fillText("CanvasNoiseTest", 0, 0); + EXPECT_TRUE(Context2D()->HasTriggerForIntervention()); + EXPECT_TRUE(Context2D()->ShouldTriggerIntervention()); +} + +TEST_F(CanvasNoiseTest, TriggerOnStrokeText) { + Context2D()->strokeText("CanvasNoiseTest", 0, 0); + EXPECT_TRUE(Context2D()->HasTriggerForIntervention()); + EXPECT_TRUE(Context2D()->ShouldTriggerIntervention()); +} + +TEST_F(CanvasNoiseTest, TriggerOnFillWithPath2DNoNoise) { + Path2D* canvas_path = Path2D::Create(GetScriptState()); + canvas_path->lineTo(10, 10); + canvas_path->lineTo(15, 15); + canvas_path->closePath(); + Context2D()->fill(canvas_path); + EXPECT_FALSE(canvas_path->HasTriggerForIntervention()); + EXPECT_FALSE(Context2D()->HasTriggerForIntervention()); + EXPECT_FALSE(Context2D()->ShouldTriggerIntervention()); +} + +TEST_F(CanvasNoiseTest, TriggerOnFillWithPath2DWithNoise) { + Path2D* canvas_path = Path2D::Create(GetScriptState()); + canvas_path->lineTo(10, 10); + canvas_path->lineTo(15, 15); + canvas_path->closePath(); + NonThrowableExceptionState exception_state; + EXPECT_FALSE(canvas_path->HasTriggerForIntervention()); + canvas_path->arc(10, 10, 10, 0, 6, false, exception_state); + EXPECT_TRUE(canvas_path->HasTriggerForIntervention()); + EXPECT_FALSE(Context2D()->HasTriggerForIntervention()); + EXPECT_FALSE(Context2D()->ShouldTriggerIntervention()); + Context2D()->fill(canvas_path); + EXPECT_TRUE(Context2D()->HasTriggerForIntervention()); + EXPECT_TRUE(Context2D()->ShouldTriggerIntervention()); +} + +} // namespace blink
diff --git a/third_party/blink/renderer/modules/canvas/offscreencanvas2d/offscreen_canvas_rendering_context_2d.h b/third_party/blink/renderer/modules/canvas/offscreencanvas2d/offscreen_canvas_rendering_context_2d.h index 5cf25c5e..6be962b6 100644 --- a/third_party/blink/renderer/modules/canvas/offscreencanvas2d/offscreen_canvas_rendering_context_2d.h +++ b/third_party/blink/renderer/modules/canvas/offscreencanvas2d/offscreen_canvas_rendering_context_2d.h
@@ -154,6 +154,10 @@ return identifiability_study_helper_.encountered_partially_digested_image(); } + bool ShouldTriggerIntervention() const override { + return HasTriggerForIntervention(); + } + std::optional<cc::PaintRecord> FlushCanvas(FlushReason) override; int LayerCount() const override;
diff --git a/third_party/blink/renderer/modules/content_extraction/ai_page_content_agent_unittest.cc b/third_party/blink/renderer/modules/content_extraction/ai_page_content_agent_unittest.cc index 9314279..5280f7f 100644 --- a/third_party/blink/renderer/modules/content_extraction/ai_page_content_agent_unittest.cc +++ b/third_party/blink/renderer/modules/content_extraction/ai_page_content_agent_unittest.cc
@@ -2294,6 +2294,64 @@ "HTML, CSS, JavaScript"); } +TEST_F(AIPageContentAgentTest, NestedIframesMetaTags) { + frame_test_helpers::LoadHTMLString( + helper_.LocalMainFrame(), + "<head><meta name=author content=George></head>" + "<body>parent" + " <iframe srcdoc=\"" + " <head><meta name=author content=Gary></head>" + " <body>child" + " <iframe srcdoc='" + " <head><meta name=author content=Jordan></head>" + " <body>grandchild</body" + " '></iframe>" + " </body>" + " \"></iframe>" + "</body>", + url_test_helpers::ToKURL("http://foobar.com")); + + mojom::blink::AIPageContentOptions options; + options.max_meta_elements = 32; + auto content = GetAIPageContent(options); + ASSERT_TRUE(content); + ASSERT_TRUE(content->root_node); + + EXPECT_EQ(content->frame_data->meta_data.size(), 1u); + + EXPECT_EQ(content->frame_data->meta_data[0]->name, "author"); + EXPECT_EQ(content->frame_data->meta_data[0]->content, "George"); + + const auto& root = *content->root_node; + EXPECT_EQ(root.children_nodes.size(), 2u); + + const auto& iframe = *root.children_nodes[1]; + EXPECT_EQ(iframe.content_attributes->attribute_type, + mojom::blink::AIPageContentAttributeType::kIframe); + + const auto& iframe_data = *iframe.content_attributes->iframe_data; + EXPECT_EQ(iframe_data.local_frame_data->meta_data.size(), 1u); + + EXPECT_EQ(iframe_data.local_frame_data->meta_data[0]->name, "author"); + EXPECT_EQ(iframe_data.local_frame_data->meta_data[0]->content, "Gary"); + + EXPECT_EQ(iframe.children_nodes.size(), 1u); + + // In the iframe children_nodes there is a root node that has two children. + // The first child is a text node and the second is the subiframe. The key + // thing we want to check here is that the subiframe has the correct meta + // data. + const auto& subiframe = *iframe.children_nodes[0]->children_nodes[1]; + EXPECT_EQ(subiframe.content_attributes->attribute_type, + mojom::blink::AIPageContentAttributeType::kIframe); + + const auto& subiframe_data = *subiframe.content_attributes->iframe_data; + EXPECT_EQ(subiframe_data.local_frame_data->meta_data.size(), 1u); + + EXPECT_EQ(subiframe_data.local_frame_data->meta_data[0]->name, "author"); + EXPECT_EQ(subiframe_data.local_frame_data->meta_data[0]->content, "Jordan"); +} + TEST_F(AIPageContentAgentTest, Title) { frame_test_helpers::LoadHTMLString( helper_.LocalMainFrame(),
diff --git a/third_party/blink/renderer/modules/cookie_store/cookie_store.cc b/third_party/blink/renderer/modules/cookie_store/cookie_store.cc index 3bb30ac..3c0bca4 100644 --- a/third_party/blink/renderer/modules/cookie_store/cookie_store.cc +++ b/third_party/blink/renderer/modules/cookie_store/cookie_store.cc
@@ -259,6 +259,15 @@ url::Origin::Create(net::SchemefulSite(key.GetTopLevelSite()).GetURL())); } +bool IsAdTagged(ExecutionContext* context) { + if (auto* window = DynamicTo<LocalDOMWindow>(context)) { + if (auto* local_frame = window->GetFrame()) { + return local_frame->IsAdFrame(); + } + } + return false; +} + } // namespace CookieStore::CookieStore( @@ -464,13 +473,7 @@ return; } - bool is_ad_tagged = false; - if (auto* window = DynamicTo<LocalDOMWindow>(context)) { - if (auto* local_frame = window->GetFrame()) { - is_ad_tagged = local_frame->IsAdFrame(); - } - } - + bool is_ad_tagged = IsAdTagged(context); bool should_apply_devtools_overrides = false; probe::ShouldApplyDevtoolsCookieSettingOverrides( GetExecutionContext(), &should_apply_devtools_overrides); @@ -557,6 +560,7 @@ return EmptyPromise(); } + bool is_ad_tagged = IsAdTagged(context); bool should_apply_devtools_overrides = false; probe::ShouldApplyDevtoolsCookieSettingOverrides( GetExecutionContext(), &should_apply_devtools_overrides); @@ -566,7 +570,7 @@ backend_->SetCanonicalCookie( *std::move(canonical_cookie), default_cookie_url_, default_site_for_cookies_, default_top_frame_origin_, - context->GetStorageAccessApiStatus(), status, + context->GetStorageAccessApiStatus(), status, is_ad_tagged, should_apply_devtools_overrides, WTF::BindOnce(&CookieStore::OnSetCanonicalCookieResult, WrapPersistent(resolver)));
diff --git a/third_party/blink/renderer/platform/fonts/font_cache.cc b/third_party/blink/renderer/platform/fonts/font_cache.cc index b3a4c782..6cc6c46 100644 --- a/third_party/blink/renderer/platform/fonts/font_cache.cc +++ b/third_party/blink/renderer/platform/fonts/font_cache.cc
@@ -218,6 +218,11 @@ bool FontCache::IsPlatformFontUniqueNameMatchAvailable( const FontDescription& font_description, const AtomicString& unique_font_name) { + // Return early to avoid attempting fallback. + if (unique_font_name.empty()) { + return false; + } + return GetFontPlatformData(font_description, FontFaceCreationParams(unique_font_name), AlternateFontName::kLocalUniqueFace);
diff --git a/third_party/blink/renderer/platform/fonts/font_cache_test.cc b/third_party/blink/renderer/platform/fonts/font_cache_test.cc index ccf12e15..1ad8e4a 100644 --- a/third_party/blink/renderer/platform/fonts/font_cache_test.cc +++ b/third_party/blink/renderer/platform/fonts/font_cache_test.cc
@@ -156,6 +156,21 @@ FontCache::FirstAvailableOrFirst(", not exist, not exist")); } +TEST_F(FontCacheTest, FontUniqueNameMatchAvailable) { + FontCache& font_cache = FontCache::Get(); + + FontDescription font_description; + font_description.SetGenericFamily(FontDescription::kStandardFamily); + font_description.SetComputedSize(12.f); + FontFaceCreationParams creation_params; + EXPECT_FALSE(font_cache.IsPlatformFontUniqueNameMatchAvailable( + font_description, AtomicString())); + EXPECT_TRUE(font_cache.IsPlatformFontUniqueNameMatchAvailable( + font_description, AtomicString("Arial"))); + EXPECT_FALSE(font_cache.IsPlatformFontUniqueNameMatchAvailable( + font_description, AtomicString("INVALID_FONT_NAME"))); +} + // Unfortunately, we can't ensure a font here since on Android and Mac the // unittests can't access the font configuration. However, this test passes // when it's not crashing in FontCache.
diff --git a/third_party/blink/renderer/platform/graphics/canvas_resource_provider.cc b/third_party/blink/renderer/platform/graphics/canvas_resource_provider.cc index d1baa70..fb08b9a7 100644 --- a/third_party/blink/renderer/platform/graphics/canvas_resource_provider.cc +++ b/third_party/blink/renderer/platform/graphics/canvas_resource_provider.cc
@@ -369,7 +369,7 @@ return true; } - scoped_refptr<CanvasResource> CreateResource() final { + scoped_refptr<CanvasResource> CreateResource() { TRACE_EVENT0("blink", "CanvasResourceProviderSharedImage::CreateResource"); if (is_software_) { @@ -774,6 +774,32 @@ // BitmapGpuChannelLostObserver implementation. void OnGpuChannelLost() override { resource_host()->NotifyGpuContextLost(); } + scoped_refptr<CanvasResource> NewOrRecycledResource() { + if (canvas_resources_.empty()) { + scoped_refptr<CanvasResource> resource = CreateResource(); + if (!resource) { + return nullptr; + } + + RegisterUnusedResource(std::move(resource)); + ++num_inflight_resources_; + if (num_inflight_resources_ > max_inflight_resources_) { + max_inflight_resources_ = num_inflight_resources_; + } + } + + if (IsSingleBuffered()) { + DCHECK_EQ(canvas_resources_.size(), 1u); + return canvas_resources_.back().resource; + } + + scoped_refptr<CanvasResource> resource = + std::move(canvas_resources_.back().resource); + canvas_resources_.pop_back(); + DCHECK(resource->HasOneRef()); + return resource; + } + bool IsResourceUsable(CanvasResource* resource) final { // The only resources that should be coming in here are // CanvasResourceSharedImage instances, since that is the only type of @@ -1848,11 +1874,6 @@ return GetSkSurface()->generationID(); } -scoped_refptr<CanvasResource> CanvasResourceProvider::CreateResource() { - // Needs to be implemented in subclasses that use resource recycling. - NOTREACHED(); -} - cc::ImageDecodeCache* CanvasResourceProvider::ImageDecodeCacheRGBA8() { if (UseHardwareDecodeCache()) { return context_provider_wrapper_->ContextProvider().ImageDecodeCache( @@ -1937,31 +1958,6 @@ MaybePostUnusedResourcesReclaimTask(); } -scoped_refptr<CanvasResource> CanvasResourceProvider::NewOrRecycledResource() { - if (canvas_resources_.empty()) { - scoped_refptr<CanvasResource> resource = CreateResource(); - if (!resource) { - return nullptr; - } - - RegisterUnusedResource(std::move(resource)); - ++num_inflight_resources_; - if (num_inflight_resources_ > max_inflight_resources_) - max_inflight_resources_ = num_inflight_resources_; - } - - if (IsSingleBuffered()) { - DCHECK_EQ(canvas_resources_.size(), 1u); - return canvas_resources_.back().resource; - } - - scoped_refptr<CanvasResource> resource = - std::move(canvas_resources_.back().resource); - canvas_resources_.pop_back(); - DCHECK(resource->HasOneRef()); - return resource; -} - void CanvasResourceProvider::RestoreBackBuffer(const cc::PaintImage& image) { DCHECK_EQ(image.height(), Size().height()); DCHECK_EQ(image.width(), Size().width());
diff --git a/third_party/blink/renderer/platform/graphics/canvas_resource_provider.h b/third_party/blink/renderer/platform/graphics/canvas_resource_provider.h index 50b4fd9..841596ec 100644 --- a/third_party/blink/renderer/platform/graphics/canvas_resource_provider.h +++ b/third_party/blink/renderer/platform/graphics/canvas_resource_provider.h
@@ -218,7 +218,6 @@ void RecycleResource(scoped_refptr<CanvasResource>&&); void SetResourceRecyclingEnabled(bool); void ClearRecycledResources(); - scoped_refptr<CanvasResource> NewOrRecycledResource(); SkSurface* GetSkSurface() const; bool IsGpuContextLost() const; @@ -413,10 +412,17 @@ // IsResourceUsable() must be true for `resource`. void RegisterUnusedResource(scoped_refptr<CanvasResource>&& resource); + // TODO(crbug.com/352263194): Move these fields inside of + // CanvasResourceProviderSharedImage. + // When and if |resource_recycling_enabled_| is false, |canvas_resources_| + // will only hold one CanvasResource at most. + WTF::Vector<UnusedResource> canvas_resources_; + int num_inflight_resources_ = 0; + int max_inflight_resources_ = 0; + private: friend class FlushForImageListener; virtual sk_sp<SkSurface> CreateSkSurface() const = 0; - virtual scoped_refptr<CanvasResource> CreateResource(); virtual bool UseOopRasterization() { return false; } bool UseHardwareDecodeCache() const { return IsAccelerated() && context_provider_wrapper_; @@ -466,9 +472,6 @@ cc::PaintImage::kInvalidContentId; uint32_t snapshot_sk_image_id_ = 0u; - // When and if |resource_recycling_enabled_| is false, |canvas_resources_| - // will only hold one CanvasResource at most. - WTF::Vector<UnusedResource> canvas_resources_; base::OneShotTimer unused_resources_reclaim_timer_; bool resource_recycling_enabled_ = true; bool oopr_uses_dmsaa_ = false; @@ -483,9 +486,6 @@ // See kMaxRecordedOpBytes above. static constexpr int kMaxDrawsBeforeContextFlush = 50; - int num_inflight_resources_ = 0; - int max_inflight_resources_ = 0; - // Parameters for the auto-flushing heuristic. size_t max_recorded_op_bytes_; size_t max_pinned_image_bytes_;
diff --git a/third_party/blink/renderer/platform/graphics/canvas_resource_provider_test.cc b/third_party/blink/renderer/platform/graphics/canvas_resource_provider_test.cc index 576c9a4..c44f83e5a 100644 --- a/third_party/blink/renderer/platform/graphics/canvas_resource_provider_test.cc +++ b/third_party/blink/renderer/platform/graphics/canvas_resource_provider_test.cc
@@ -666,46 +666,6 @@ #endif } -TEST_F(CanvasResourceProviderTest, - CanvasResourceProviderDirect3DGpuMemoryBuffer) { - const gfx::Size kSize(10, 10); - const SkImageInfo kInfo = - SkImageInfo::MakeN32Premul(10, 10, SkColorSpace::MakeSRGB()); - - auto provider = CanvasResourceProvider::CreatePassThroughProvider( - kSize, GetN32FormatForCanvas(), kInfo.alphaType(), - gfx::ColorSpace::CreateSRGB(), context_provider_wrapper_); - - EXPECT_EQ(provider->Size(), kSize); - EXPECT_TRUE(provider->IsValid()); - EXPECT_TRUE(provider->IsAccelerated()); - EXPECT_TRUE(provider->SupportsDirectCompositing()); - EXPECT_TRUE(provider->IsSingleBuffered()); - EXPECT_TRUE(provider->GetSkImageInfo() == kInfo); - - auto client_si = gpu::ClientSharedImage::CreateForTesting(); - - viz::TransferableResource tr; - tr.set_mailbox(client_si->mailbox()); - tr.set_texture_target(GL_TEXTURE_2D); - tr.set_sync_token(gpu::SyncToken()); - tr.size = kSize; - tr.is_overlay_candidate = true; - - scoped_refptr<ExternalCanvasResource> resource = - ExternalCanvasResource::Create( - client_si, tr.sync_token(), tr.resource_source, tr.hdr_metadata, - viz::ReleaseCallback(), SharedGpuContext::ContextProviderWrapper(), - provider->CreateWeakPtr()); - - // NewOrRecycledResource() would return nullptr before an ImportResource(). - auto* raw_resource = resource.get(); - provider->ImportResource(std::move(resource)); - EXPECT_EQ(provider->NewOrRecycledResource().get(), raw_resource); - // NewOrRecycledResource() will always return the same |resource|. - EXPECT_EQ(provider->NewOrRecycledResource().get(), raw_resource); -} - TEST_F(CanvasResourceProviderTest, DimensionsExceedMaxTextureSize_Bitmap) { auto provider = CanvasResourceProvider::CreateBitmapProvider( gfx::Size(kMaxTextureSize - 1, kMaxTextureSize), GetN32FormatForCanvas(),
diff --git a/third_party/blink/renderer/platform/graphics/compositing/chunk_to_layer_mapper_test.cc b/third_party/blink/renderer/platform/graphics/compositing/chunk_to_layer_mapper_test.cc index b062519..7601e1d 100644 --- a/third_party/blink/renderer/platform/graphics/compositing/chunk_to_layer_mapper_test.cc +++ b/third_party/blink/renderer/platform/graphics/compositing/chunk_to_layer_mapper_test.cc
@@ -37,9 +37,9 @@ layer_clip_ = CreateClip(c0(), *layer_transform_, FloatRoundedRect(12, 34, 56, 78)); layer_effect_ = EffectPaintPropertyNode::Create( - e0(), EffectPaintPropertyNode::State{ - layer_transform_, layer_clip_, CompositorFilterOperations(), - nullptr, 0.789f, SkBlendMode::kSrcIn}); + e0(), + EffectPaintPropertyNode::State{layer_transform_, layer_clip_, nullptr, + nullptr, 0.789f, SkBlendMode::kSrcIn}); } return PropertyTreeState(*layer_transform_, *layer_clip_, *layer_effect_); }
diff --git a/third_party/blink/renderer/platform/graphics/compositing/paint_chunks_to_cc_layer.cc b/third_party/blink/renderer/platform/graphics/compositing/paint_chunks_to_cc_layer.cc index 400e84e..f6f5c28 100644 --- a/third_party/blink/renderer/platform/graphics/compositing/paint_chunks_to_cc_layer.cc +++ b/third_party/blink/renderer/platform/graphics/compositing/paint_chunks_to_cc_layer.cc
@@ -673,7 +673,7 @@ return action; } - bool has_filter = !effect.Filter().IsEmpty(); + bool has_filter = !!effect.Filter(); bool has_opacity = effect.Opacity() != 1.f; // TODO(crbug.com/1334293): Normally backdrop filters should be composited and // effect.BackdropFilter() should be null, but compositing can be disabled in @@ -702,7 +702,7 @@ // bounds, which we never generate. cc::PaintFlags filter_flags; filter_flags.setImageFilter(cc::RenderSurfaceFilters::BuildImageFilter( - effect.Filter().AsCcFilterOperations())); + effect.Filter()->AsCcFilterOperations())); save_layer_id = push<cc::SaveLayerOp>(filter_flags); } result_.EndPaintOfPairedBegin(); @@ -718,27 +718,17 @@ current_clip_ = input_clip; current_effect_ = &effect; - if (effect.Filter().HasReferenceFilter()) { - // Map the input rect through the filter to determine the bounds of the - // effect on an empty source. For empty chunks, or chunks with empty bounds, - // with a filter applied that produces output even when there's no input - // this will expand the bounds to match. - gfx::RectF input_rect; - if (RuntimeEnabledFeatures::ReferenceFilterMapsReferenceBoxEnabled()) { - // Use the reference box as the input rect. - input_rect = effect.Filter().ReferenceBox(); - } else { - // Use a random point as the input rect. - input_rect = gfx::RectF(effect.Filter().ReferenceBox().CenterPoint(), - gfx::SizeF()); - } - gfx::RectF filtered_bounds = current_effect_->MapRect(input_rect); - effect_bounds_stack_.back().bounds = filtered_bounds; + if (effect.HasReferenceFilter()) { + // For empty chunks, or chunks with empty bounds, with a filter applied + // that produces output even when there's no input this will expand the + // bounds to match. + gfx::Rect filtered_bounds = effect.FilterOutputBounds(); + effect_bounds_stack_.back().bounds = gfx::RectF(filtered_bounds); // Emit an empty paint operation to add the filtered bounds (mapped to layer // space) to the visual rect of the filter's SaveLayerOp. result_.StartPaint(); - result_.EndPaintOfUnpaired(chunk_to_layer_mapper_.MapVisualRect( - gfx::ToEnclosingRect(filtered_bounds))); + result_.EndPaintOfUnpaired( + chunk_to_layer_mapper_.MapVisualRect(filtered_bounds)); } return {}; } @@ -771,18 +761,18 @@ DCHECK(effect_bounds_stack_.size()); const auto& bounds_info = effect_bounds_stack_.back(); gfx::RectF bounds = bounds_info.bounds; - if (current_effect_->Filter().IsEmpty()) { + if (!current_effect_->Filter()) { if (!bounds.IsEmpty()) { result_.UpdateSaveLayerBounds(bounds_info.save_layer_id, gfx::RectFToSkRect(bounds)); } } else { - // We need an empty bounds for empty filter to avoid performance issue of - // PDF renderer. See crbug.com/740824. + // Don't check bounds.IsEmpty() because we need an empty bounds for empty + // filter to avoid performance issue of PDF renderer. See crbug.com/740824. result_.UpdateSaveLayerBounds(bounds_info.save_layer_id, gfx::RectFToSkRect(bounds)); // We need to propagate the filtered bounds to the parent. - bounds = current_effect_->MapRect(bounds); + bounds = gfx::RectF(current_effect_->MapRect(gfx::ToEnclosingRect(bounds))); } effect_bounds_stack_.pop_back();
diff --git a/third_party/blink/renderer/platform/graphics/compositing/property_tree_manager.cc b/third_party/blink/renderer/platform/graphics/compositing/property_tree_manager.cc index 0869065..9828719 100644 --- a/third_party/blink/renderer/platform/graphics/compositing/property_tree_manager.cc +++ b/third_party/blink/renderer/platform/graphics/compositing/property_tree_manager.cc
@@ -1263,8 +1263,7 @@ static cc::RenderSurfaceReason RenderSurfaceReasonForEffect( const EffectPaintPropertyNode& effect) { - if (!effect.Filter().IsEmpty() || - effect.RequiresCompositingForWillChangeFilter()) { + if (effect.Filter() || effect.RequiresCompositingForWillChangeFilter()) { return cc::RenderSurfaceReason::kFilter; } if (effect.HasActiveFilterAnimation()) @@ -1313,15 +1312,15 @@ if (effect.MayHaveBackdropEffect()) { effect_node.may_have_backdrop_effect = true; // We never have backdrop effect and filter on the same effect node. - DCHECK(effect.Filter().IsEmpty()); + DCHECK(!effect.Filter()); if (auto* backdrop_filter = effect.BackdropFilter()) { effect_node.backdrop_filters = backdrop_filter->AsCcFilterOperations(); effect_node.backdrop_filter_bounds = effect.BackdropFilterBounds(); effect_node.backdrop_mask_element_id = effect.BackdropMaskElementId(); } effect_node.blend_mode = effect.BlendMode(); - } else { - effect_node.filters = effect.Filter().AsCcFilterOperations(); + } else if (auto* filter = effect.Filter()) { + effect_node.filters = filter->AsCcFilterOperations(); } effect_node.double_sided = !transform.IsBackfaceHidden(); effect_node.effect_changed = effect.NodeChangeAffectsRaster();
diff --git a/third_party/blink/renderer/platform/graphics/compositor_filter_operations.cc b/third_party/blink/renderer/platform/graphics/compositor_filter_operations.cc index 550f2ba..3820e6a 100644 --- a/third_party/blink/renderer/platform/graphics/compositor_filter_operations.cc +++ b/third_party/blink/renderer/platform/graphics/compositor_filter_operations.cc
@@ -7,7 +7,6 @@ #include "third_party/blink/renderer/platform/graphics/color.h" #include "third_party/blink/renderer/platform/runtime_enabled_features.h" #include "ui/gfx/geometry/rect.h" -#include "ui/gfx/geometry/rect_conversions.h" namespace blink { @@ -108,10 +107,9 @@ return filter_operations_.IsEmpty(); } -gfx::RectF CompositorFilterOperations::MapRect( - const gfx::RectF& input_rect) const { - return gfx::RectF( - filter_operations_.MapRect(gfx::ToEnclosingRect(input_rect))); +gfx::Rect CompositorFilterOperations::MapRect( + const gfx::Rect& input_rect) const { + return filter_operations_.MapRect(input_rect); } bool CompositorFilterOperations::HasFilterThatMovesPixels() const {
diff --git a/third_party/blink/renderer/platform/graphics/compositor_filter_operations.h b/third_party/blink/renderer/platform/graphics/compositor_filter_operations.h index f58dbdd..1407ba3 100644 --- a/third_party/blink/renderer/platform/graphics/compositor_filter_operations.h +++ b/third_party/blink/renderer/platform/graphics/compositor_filter_operations.h
@@ -48,8 +48,8 @@ size_t size() const { return filter_operations_.size(); } // Returns a rect covering the destination pixels that can be affected by - // source pixels in |inputRect|. - gfx::RectF MapRect(const gfx::RectF& input_rect) const; + // source pixels in `input_rect`. + gfx::Rect MapRect(const gfx::Rect& input_rect) const; bool HasFilterThatMovesPixels() const; bool HasReferenceFilter() const;
diff --git a/third_party/blink/renderer/platform/graphics/paint/effect_paint_property_node.cc b/third_party/blink/renderer/platform/graphics/paint/effect_paint_property_node.cc index 0ce6c3e..d2d2778 100644 --- a/third_party/blink/renderer/platform/graphics/paint/effect_paint_property_node.cc +++ b/third_party/blink/renderer/platform/graphics/paint/effect_paint_property_node.cc
@@ -13,6 +13,24 @@ namespace { +PaintPropertyChangeType ComputeFilterChange( + const EffectPaintPropertyNode::FilterInfo* a, + const EffectPaintPropertyNode::FilterInfo* b, + bool is_running_filter_animation_on_compositor) { + if (!a && !b) { + return PaintPropertyChangeType::kUnchanged; + } + if (!a || !b || a->output_bounds != b->output_bounds) { + return PaintPropertyChangeType::kChangedOnlyValues; + } + if (a->operations != b->operations) { + return is_running_filter_animation_on_compositor + ? PaintPropertyChangeType::kChangedOnlyCompositedValues + : PaintPropertyChangeType::kChangedOnlyValues; + } + return PaintPropertyChangeType::kUnchanged; +} + PaintPropertyChangeType ComputeBackdropFilterChange( const EffectPaintPropertyNode::BackdropFilterInfo* a, const EffectPaintPropertyNode::BackdropFilterInfo* b, @@ -51,17 +69,21 @@ DCHECK(!animation_state.is_running_opacity_animation_on_compositor); return PaintPropertyChangeType::kChangedOnlyValues; } - bool filter_changed = filter != other.filter; - if (filter_changed && - !animation_state.is_running_filter_animation_on_compositor) { + + auto filter_changed = ComputeFilterChange( + filter_info.get(), other.filter_info.get(), + animation_state.is_running_filter_animation_on_compositor); + if (filter_changed == PaintPropertyChangeType::kChangedOnlyValues) { return PaintPropertyChangeType::kChangedOnlyValues; } + auto backdrop_filter_changed = ComputeBackdropFilterChange( backdrop_filter_info.get(), other.backdrop_filter_info.get(), animation_state.is_running_backdrop_filter_animation_on_compositor); if (backdrop_filter_changed == PaintPropertyChangeType::kChangedOnlyValues) { return PaintPropertyChangeType::kChangedOnlyValues; } + bool non_reraster_values_changed = direct_compositing_reasons != other.direct_compositing_reasons || compositor_element_id != other.compositor_element_id; @@ -80,7 +102,8 @@ if (simple_values_changed) return PaintPropertyChangeType::kChangedOnlySimpleValues; - if (opacity_changed || filter_changed || + if (opacity_changed || + filter_changed != PaintPropertyChangeType::kUnchanged || backdrop_filter_changed != PaintPropertyChangeType::kUnchanged) { return PaintPropertyChangeType::kChangedOnlyCompositedValues; } @@ -197,17 +220,15 @@ return change; } -gfx::RectF EffectPaintPropertyNode::MapRect( - const gfx::RectF& input_rect) const { - if (state_.filter.IsEmpty()) { +gfx::Rect EffectPaintPropertyNode::MapRect(const gfx::Rect& input_rect) const { + if (!state_.filter_info) { return input_rect; } - gfx::RectF rect = input_rect; - if (RuntimeEnabledFeatures::ReferenceFilterMapsReferenceBoxEnabled() && - state_.filter.HasReferenceFilter()) { - rect.UnionEvenIfEmpty(state_.filter.ReferenceBox()); + if (RuntimeEnabledFeatures::ReferenceFilterOutputBoundsEnabled() && + state_.filter_info->operations.HasReferenceFilter()) { + return state_.filter_info->output_bounds; } - return state_.filter.MapRect(rect); + return state_.filter_info->operations.MapRect(input_rect); } std::unique_ptr<JSONObject> EffectPaintPropertyNode::ToJSON() const { @@ -215,8 +236,9 @@ json->SetString("localTransformSpace", String::Format("%p", state_.local_transform_space.Get())); json->SetString("outputClip", String::Format("%p", state_.output_clip.Get())); - if (!state_.filter.IsEmpty()) - json->SetString("filter", state_.filter.ToString()); + if (state_.filter_info) { + json->SetString("filter", state_.filter_info->operations.ToString()); + } if (auto* backdrop_filter = BackdropFilter()) json->SetString("backdrop_filter", backdrop_filter->ToString()); if (state_.opacity != 1.0f)
diff --git a/third_party/blink/renderer/platform/graphics/paint/effect_paint_property_node.h b/third_party/blink/renderer/platform/graphics/paint/effect_paint_property_node.h index 94c8df8..a7acf74 100644 --- a/third_party/blink/renderer/platform/graphics/paint/effect_paint_property_node.h +++ b/third_party/blink/renderer/platform/graphics/paint/effect_paint_property_node.h
@@ -83,6 +83,13 @@ STACK_ALLOCATED(); }; + struct FilterInfo { + CompositorFilterOperations operations; + gfx::Rect output_bounds; + + USING_FAST_MALLOC(FilterInfo); + }; + struct BackdropFilterInfo { CompositorFilterOperations operations; gfx::RRectF bounds; @@ -111,7 +118,7 @@ // Optionally a number of effects can be applied to the composited output. // The chain of effects will be applied in the following order: // === Begin of effects === - CompositorFilterOperations filter; + std::unique_ptr<FilterInfo> filter_info; std::unique_ptr<BackdropFilterInfo> backdrop_filter_info; float opacity = 1; SkBlendMode blend_mode = SkBlendMode::kSrcOver; @@ -204,7 +211,13 @@ SkBlendMode BlendMode() const { return state_.blend_mode; } float Opacity() const { return state_.opacity; } - const CompositorFilterOperations& Filter() const { return state_.filter; } + const CompositorFilterOperations* Filter() const { + return state_.filter_info ? &state_.filter_info->operations : nullptr; + } + const gfx::Rect& FilterOutputBounds() const { + CHECK(state_.filter_info); + return state_.filter_info->output_bounds; + } const CompositorFilterOperations* BackdropFilter() const { if (!state_.backdrop_filter_info) { @@ -224,23 +237,28 @@ return state_.backdrop_filter_info->mask_element_id; } + bool HasReferenceFilter() const { + return state_.filter_info && + state_.filter_info->operations.HasReferenceFilter(); + } bool HasFilterThatMovesPixels() const { - return state_.filter.HasFilterThatMovesPixels(); + return state_.filter_info && + state_.filter_info->operations.HasFilterThatMovesPixels(); } bool HasRealEffects() const { return Opacity() != 1.0f || BlendMode() != SkBlendMode::kSrcOver || - !Filter().IsEmpty() || BackdropFilter(); + Filter() || BackdropFilter(); } bool IsOpacityOnly() const { - return BlendMode() == SkBlendMode::kSrcOver && Filter().IsEmpty() && + return BlendMode() == SkBlendMode::kSrcOver && !Filter() && !BackdropFilter(); } // Returns a rect covering the pixels that can be affected by pixels in // `input_rect`. The rects are in the space of `LocalTransformSpace`. - gfx::RectF MapRect(const gfx::RectF& input_rect) const; + gfx::Rect MapRect(const gfx::Rect& input_rect) const; bool HasDirectCompositingReasons() const { return state_.direct_compositing_reasons != CompositingReason::kNone; @@ -290,7 +308,7 @@ // True if the filter is not empty, or could become non-empty without a // compositing update via a compositor animation or direct update. bool MayHaveFilter() const { - return !Filter().IsEmpty() || HasActiveFilterAnimation() || + return Filter() || HasActiveFilterAnimation() || RequiresCompositingForWillChangeFilter(); } // True if the backdrop filter is not empty, or could become non-empty @@ -300,6 +318,12 @@ RequiresCompositingForWillChangeBackdropFilter(); } + bool NeedsPixelMovingFilterClipExpander() const { + return HasActiveFilterAnimation() || + RequiresCompositingForWillChangeFilter() || + HasFilterThatMovesPixels(); + } + // Whether the effect node uses the backdrop as an input. This includes // exotic blending modes and backdrop filters. bool MayHaveBackdropEffect() const {
diff --git a/third_party/blink/renderer/platform/graphics/paint/geometry_mapper.cc b/third_party/blink/renderer/platform/graphics/paint/geometry_mapper.cc index bcada61d..5a1f1a2 100644 --- a/third_party/blink/renderer/platform/graphics/paint/geometry_mapper.cc +++ b/third_party/blink/renderer/platform/graphics/paint/geometry_mapper.cc
@@ -9,6 +9,7 @@ #include "third_party/blink/renderer/platform/graphics/paint/scroll_paint_property_node.h" #include "third_party/blink/renderer/platform/heap/collection_support/heap_vector.h" #include "third_party/blink/renderer/platform/runtime_enabled_features.h" +#include "ui/gfx/geometry/rect_conversions.h" namespace blink { @@ -325,8 +326,10 @@ rect_to_map = FloatClipRect(gfx::RectF()); return false; } - if (!rect_to_map.IsInfinite()) - rect_to_map.Rect() = filter->MapRect(rect_to_map.Rect()); + if (!rect_to_map.IsInfinite()) { + rect_to_map.Rect() = gfx::RectF( + filter->MapRect(gfx::ToEnclosingRect(rect_to_map.Rect()))); + } } last_state = new_state;
diff --git a/third_party/blink/renderer/platform/graphics/paint/geometry_mapper_test.cc b/third_party/blink/renderer/platform/graphics/paint/geometry_mapper_test.cc index b05d97c..34b49ee 100644 --- a/third_party/blink/renderer/platform/graphics/paint/geometry_mapper_test.cc +++ b/third_party/blink/renderer/platform/graphics/paint/geometry_mapper_test.cc
@@ -930,7 +930,7 @@ output.Intersect(clip_below_effect->LayoutClipRect().Rect()); EXPECT_EQ(gfx::RectF(20, 30, 90, 80), output); // 3. effect (the outset is 3 times of blur amount). - output = filters.MapRect(output); + output = gfx::RectF(filters.MapRect(gfx::ToEnclosingRect(output))); EXPECT_EQ(gfx::RectF(-40, -30, 210, 200), output); // 4. clip_above_effect output.Intersect(clip_above_effect->LayoutClipRect().Rect()); @@ -981,7 +981,7 @@ output.Intersect(clip_below_effect->LayoutClipRect().Rect()); EXPECT_EQ(gfx::RectF(20, 30, 90, 80), output); // 3. effect (the outset is 3 times of blur amount). - output = filters.MapRect(output); + output = gfx::RectF(filters.MapRect(gfx::ToEnclosingRect(output))); EXPECT_EQ(gfx::RectF(-40, -30, 210, 200), output); // 4. clipAboveEffect output.Intersect(clip_above_effect->LayoutClipRect().Rect());
diff --git a/third_party/blink/renderer/platform/graphics/paint/paint_property_node_test.cc b/third_party/blink/renderer/platform/graphics/paint/paint_property_node_test.cc index 45b2eac..e1d69ad 100644 --- a/third_party/blink/renderer/platform/graphics/paint/paint_property_node_test.cc +++ b/third_party/blink/renderer/platform/graphics/paint/paint_property_node_test.cc
@@ -749,7 +749,8 @@ TEST_F(PaintPropertyNodeTest, EffectLocalTransformSpaceChange) { // Let effect.child1 have pixel-moving filter. EffectPaintPropertyNode::State state{transform.child1, clip.child1}; - state.filter.AppendBlurFilter(20); + state.filter_info = std::make_unique<EffectPaintPropertyNode::FilterInfo>(); + state.filter_info->operations.AppendBlurFilter(20); effect.child1->Update(*effect.ancestor, std::move(state)); ResetAllChanged();
diff --git a/third_party/blink/renderer/platform/runtime_enabled_features.json5 b/third_party/blink/renderer/platform/runtime_enabled_features.json5 index 4fdc7454..19b2cae 100644 --- a/third_party/blink/renderer/platform/runtime_enabled_features.json5 +++ b/third_party/blink/renderer/platform/runtime_enabled_features.json5
@@ -435,12 +435,12 @@ }, { name: "AriaNotify", - status: "test", + status: {"Android": "test", "Win": "test", "Mac": "test", "Linux": "test"}, implied_by: ["AriaNotifyV2"], }, { name: "AriaNotifyV2", - status: "test", + status: {"Android": "test", "Win": "test", "Mac": "test", "Linux": "test"}, }, { name: "AriaRowColIndexText", @@ -3596,7 +3596,7 @@ }, { // Killswitch M136. - name: "ReferenceFilterMapsReferenceBox", + name: "ReferenceFilterOutputBounds", status: "stable", }, {
diff --git a/third_party/blink/renderer/platform/testing/paint_property_test_helpers.h b/third_party/blink/renderer/platform/testing/paint_property_test_helpers.h index 75f73c8..61105a6e 100644 --- a/third_party/blink/renderer/platform/testing/paint_property_test_helpers.h +++ b/third_party/blink/renderer/platform/testing/paint_property_test_helpers.h
@@ -10,6 +10,7 @@ #include "third_party/blink/renderer/platform/graphics/paint/property_tree_state.h" #include "third_party/blink/renderer/platform/graphics/paint/scroll_paint_property_node.h" #include "third_party/blink/renderer/platform/graphics/paint/transform_paint_property_node.h" +#include "ui/gfx/geometry/rect_conversions.h" #include "ui/gfx/geometry/transform.h" namespace blink { @@ -114,7 +115,8 @@ EffectPaintPropertyNode::State state; state.local_transform_space = &local_transform_space; state.output_clip = output_clip; - state.filter = std::move(filter); + state.filter_info = std::make_unique<EffectPaintPropertyNode::FilterInfo>( + filter, filter.MapRect(gfx::ToEnclosingRect(filter.ReferenceBox()))); state.direct_compositing_reasons = compositing_reasons; state.compositor_element_id = CompositorElementIdFromUniqueObjectId( NewUniqueObjectId(), CompositorElementIdNamespace::kEffectFilter); @@ -137,7 +139,8 @@ EffectPaintPropertyNode::State state; state.local_transform_space = &parent.Unalias().LocalTransformSpace(); state.output_clip = output_clip; - state.filter = std::move(filter); + state.filter_info = std::make_unique<EffectPaintPropertyNode::FilterInfo>( + filter, filter.MapRect(gfx::ToEnclosingRect(filter.ReferenceBox()))); state.direct_compositing_reasons = CompositingReason::kActiveFilterAnimation; state.compositor_element_id = CompositorElementIdFromUniqueObjectId( NewUniqueObjectId(), CompositorElementIdNamespace::kEffectFilter);
diff --git a/third_party/blink/web_tests/TestExpectations b/third_party/blink/web_tests/TestExpectations index 79b13c76..88b80c0 100644 --- a/third_party/blink/web_tests/TestExpectations +++ b/third_party/blink/web_tests/TestExpectations
@@ -7450,9 +7450,6 @@ # Gardener 2023-07-26 crbug.com/1364187 http/tests/misc/scroll-cross-origin-iframes.html [ Failure Pass ] -# Gardener 2023-07-27 -crbug.com/1468169 external/wpt/html/canvas/element/manual/drawing-text-to-the-canvas/canvas.2d.disconnected-font-size-math.html [ Failure Pass ] - # Gardener 2023-07-31 crbug.com/1468996 fast/events/touch/gesture/gesture-tap-active-state.html [ Failure Pass ] # flaky crbug.com/1468996 fast/events/touch/gesture/gesture-tap-active-state-hidden-iframe.html [ Failure Pass ] # flaky
diff --git a/third_party/blink/web_tests/TestLists/chrome.filter b/third_party/blink/web_tests/TestLists/chrome.filter index c06af49..a014525 100644 --- a/third_party/blink/web_tests/TestLists/chrome.filter +++ b/third_party/blink/web_tests/TestLists/chrome.filter
@@ -33,6 +33,7 @@ external/wpt/partitioned-popins/partitioned-popins.cookies-allowed.tentative.sub.https.window.html external/wpt/partitioned-popins/partitioned-popins.cookies-blocked.tentative.sub.https.window.html external/wpt/partitioned-popins/partitioned-popins.localStorage.tentative.sub.https.window.html +virtual/cross-partition-blob-url/external/wpt/* virtual/partitioned-popins-disabled/external/wpt/partitioned-popins/partitioned-popins.cookies-allowed.tentative.sub.https.window.html virtual/partitioned-popins-disabled/external/wpt/partitioned-popins/partitioned-popins.cookies-blocked.tentative.sub.https.window.html virtual/partitioned-popins-disabled/external/wpt/partitioned-popins/partitioned-popins.localStorage.tentative.sub.https.window.html
diff --git a/third_party/blink/web_tests/TestLists/content_shell.filter b/third_party/blink/web_tests/TestLists/content_shell.filter index c1358727..e98eae3 100644 --- a/third_party/blink/web_tests/TestLists/content_shell.filter +++ b/third_party/blink/web_tests/TestLists/content_shell.filter
@@ -561,60 +561,13 @@ external/wpt/html/browsers/the-window-object/open-close/open-features-non-integer-innerwidth.html external/wpt/html/browsers/the-window-object/open-close/open-features-tokenization* external/wpt/html/browsers/the-window-object/window-open-popup-behavior.html -external/wpt/html/canvas/element/compositing/2d.composite.grid.filter.no_shadow.drawImage.html -external/wpt/html/canvas/element/compositing/2d.composite.grid.filter.no_shadow.fillRect.html -external/wpt/html/canvas/element/compositing/2d.composite.grid.filter.no_shadow.pattern.html -external/wpt/html/canvas/element/compositing/2d.composite.grid.filter.shadow.drawImage.html -external/wpt/html/canvas/element/compositing/2d.composite.grid.filter.shadow.fillRect.html -external/wpt/html/canvas/element/compositing/2d.composite.grid.filter.shadow.pattern.html -external/wpt/html/canvas/element/compositing/2d.composite.grid.no_filter.no_shadow.drawImage.html -external/wpt/html/canvas/element/compositing/2d.composite.grid.no_filter.no_shadow.fillRect.html -external/wpt/html/canvas/element/compositing/2d.composite.grid.no_filter.no_shadow.pattern.html -external/wpt/html/canvas/element/compositing/2d.composite.grid.no_filter.shadow.drawImage.html -external/wpt/html/canvas/element/compositing/2d.composite.grid.no_filter.shadow.fillRect.html -external/wpt/html/canvas/element/compositing/2d.composite.grid.no_filter.shadow.pattern.html external/wpt/html/canvas/element/filters/2d.filter.canvasFilterObject.dropShadow.tentative.html -external/wpt/html/canvas/element/filters/2d.filter.canvasFilterObject.gaussianBlur.tentative.html external/wpt/html/canvas/element/filters/2d.filter.layers.dropShadow.tentative.html -external/wpt/html/canvas/element/filters/2d.filter.layers.gaussianBlur.tentative.html -external/wpt/html/canvas/element/manual/fill-and-stroke-styles/canvas_colorsandstyles_createlineargradient_001.htm external/wpt/html/canvas/element/manual/filters/svg-filter-lh-rlh.html -external/wpt/html/canvas/element/manual/filters/tentative/canvas-filter-object-turbulence.html -external/wpt/html/canvas/element/text/direction-inherit-rtl.html -external/wpt/html/canvas/element/text/direction-rtl.html -external/wpt/html/canvas/offscreen/compositing/2d.composite.grid.filter.no_shadow.drawImage.html -external/wpt/html/canvas/offscreen/compositing/2d.composite.grid.filter.no_shadow.drawImage.w.html -external/wpt/html/canvas/offscreen/compositing/2d.composite.grid.filter.no_shadow.fillRect.html -external/wpt/html/canvas/offscreen/compositing/2d.composite.grid.filter.no_shadow.fillRect.w.html -external/wpt/html/canvas/offscreen/compositing/2d.composite.grid.filter.no_shadow.pattern.html -external/wpt/html/canvas/offscreen/compositing/2d.composite.grid.filter.no_shadow.pattern.w.html -external/wpt/html/canvas/offscreen/compositing/2d.composite.grid.filter.shadow.drawImage.html -external/wpt/html/canvas/offscreen/compositing/2d.composite.grid.filter.shadow.drawImage.w.html -external/wpt/html/canvas/offscreen/compositing/2d.composite.grid.filter.shadow.fillRect.html -external/wpt/html/canvas/offscreen/compositing/2d.composite.grid.filter.shadow.fillRect.w.html -external/wpt/html/canvas/offscreen/compositing/2d.composite.grid.filter.shadow.pattern.html -external/wpt/html/canvas/offscreen/compositing/2d.composite.grid.filter.shadow.pattern.w.html -external/wpt/html/canvas/offscreen/compositing/2d.composite.grid.no_filter.no_shadow.drawImage.html -external/wpt/html/canvas/offscreen/compositing/2d.composite.grid.no_filter.no_shadow.drawImage.w.html -external/wpt/html/canvas/offscreen/compositing/2d.composite.grid.no_filter.no_shadow.fillRect.html -external/wpt/html/canvas/offscreen/compositing/2d.composite.grid.no_filter.no_shadow.fillRect.w.html -external/wpt/html/canvas/offscreen/compositing/2d.composite.grid.no_filter.no_shadow.pattern.html -external/wpt/html/canvas/offscreen/compositing/2d.composite.grid.no_filter.no_shadow.pattern.w.html -external/wpt/html/canvas/offscreen/compositing/2d.composite.grid.no_filter.shadow.drawImage.html -external/wpt/html/canvas/offscreen/compositing/2d.composite.grid.no_filter.shadow.drawImage.w.html -external/wpt/html/canvas/offscreen/compositing/2d.composite.grid.no_filter.shadow.fillRect.html -external/wpt/html/canvas/offscreen/compositing/2d.composite.grid.no_filter.shadow.fillRect.w.html -external/wpt/html/canvas/offscreen/compositing/2d.composite.grid.no_filter.shadow.pattern.html -external/wpt/html/canvas/offscreen/compositing/2d.composite.grid.no_filter.shadow.pattern.w.html external/wpt/html/canvas/offscreen/filters/2d.filter.canvasFilterObject.dropShadow.tentative.html external/wpt/html/canvas/offscreen/filters/2d.filter.canvasFilterObject.dropShadow.tentative.w.html -external/wpt/html/canvas/offscreen/filters/2d.filter.canvasFilterObject.gaussianBlur.tentative.html -external/wpt/html/canvas/offscreen/filters/2d.filter.canvasFilterObject.gaussianBlur.tentative.w.html external/wpt/html/canvas/offscreen/filters/2d.filter.layers.dropShadow.tentative.html external/wpt/html/canvas/offscreen/filters/2d.filter.layers.dropShadow.tentative.w.html -external/wpt/html/canvas/offscreen/filters/2d.filter.layers.gaussianBlur.tentative.html -external/wpt/html/canvas/offscreen/filters/2d.filter.layers.gaussianBlur.tentative.w.html -external/wpt/html/canvas/offscreen/manual/filter/offscreencanvas.filter.w.html external/wpt/html/canvas/offscreen/manual/the-offscreen-canvas/offscreencanvas.getcontext.html external/wpt/html/canvas/offscreen/manual/the-offscreen-canvas/offscreencanvas.getcontext.worker.html external/wpt/html/canvas/offscreen/manual/the-offscreen-canvas/offscreencanvas.resize.html
diff --git a/third_party/blink/web_tests/VirtualTestSuites b/third_party/blink/web_tests/VirtualTestSuites index 39f40eed..48d3993 100644 --- a/third_party/blink/web_tests/VirtualTestSuites +++ b/third_party/blink/web_tests/VirtualTestSuites
@@ -1116,10 +1116,11 @@ "bases": [ "external/wpt/FileAPI/BlobURL/cross-partition.https.html", "external/wpt/FileAPI/BlobURL/cross-partition-worker-creation.https.html", - "external/wpt/FileAPI/BlobURL/cross-partition-navigation.https.html" + "external/wpt/FileAPI/BlobURL/cross-partition-navigation.https.html", + "external/wpt/storage-access-api/storage-access-beyond-cookies.blobStorage.sub.https.window.html" ], "args": ["--enable-features=BlockCrossPartitionBlobUrlFetching,EnforceNoopenerOnBlobURLNavigation"], - "expires": "Mar 1, 2025", + "expires": "Sep 1, 2025", "owners": ["janiceliu@chromium.org"] },
diff --git a/third_party/blink/web_tests/external/wpt/css/filter-effects/feComposite-intersection-feTile-input-svg.html b/third_party/blink/web_tests/external/wpt/css/filter-effects/feComposite-intersection-feTile-input-svg.html new file mode 100644 index 0000000..7c9fd6a --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/filter-effects/feComposite-intersection-feTile-input-svg.html
@@ -0,0 +1,22 @@ +<!DOCTYPE html> +<meta charset="utf-8"> +<link rel="help" href="https://crbug.com/373759987"> +<link rel="match" href="feComposite-intersection-feTile-input-ref.html"> +<style>body { margin: 0; }</style> +<svg> + <filter id="test" filterUnits="userSpaceOnUse" + color-interpolation-filters="sRGB" x="0" y="0"> + <feColorMatrix width="5" height="5"></feColorMatrix> + <feTile result="fill"></feTile> + <feColorMatrix in="SourceGraphic" values="0 0 0 0 0 + 0 0 0 0 0 + 0 0 0 0 0 + 0 1 0 0 0"> + </feColorMatrix> + <feComposite in="fill" operator="in"></feComposite> + </filter> + <g filter="url(#test)"> + <rect fill="none" stroke="black" stroke-width="20" x="10" y="10" width="120" height="120"/> + <rect fill="#0f0" x="20" y="20" width="100" height="100" opacity="0.5"/> + </g> +</svg>
diff --git a/third_party/blink/web_tests/external/wpt/selection/shadow-dom/tentative/Selection-getComposedRanges-range-update-expected.txt b/third_party/blink/web_tests/external/wpt/selection/shadow-dom/tentative/Selection-getComposedRanges-range-update-expected.txt new file mode 100644 index 0000000..14ce3b12 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/selection/shadow-dom/tentative/Selection-getComposedRanges-range-update-expected.txt
@@ -0,0 +1,7 @@ +This is a testharness.js-based test. +[FAIL] If selection crosses shadow boundaries, getRangeAt(0) should throw an IndexSizeError because the end is not in the document tree. + assert_throws_dom: function "function () { selection.getRangeAt(0) }" did not throw +[FAIL] modify getRangeAt() range: setStart() crosses shadow boundary into the shadow DOM and after end, which collapses both live range and composed selection range. + assert_true: expected true got false +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/external/wpt/selection/shadow-dom/tentative/Selection-getComposedRanges-range-update.html b/third_party/blink/web_tests/external/wpt/selection/shadow-dom/tentative/Selection-getComposedRanges-range-update.html index 15f0730..2e54b32 100644 --- a/third_party/blink/web_tests/external/wpt/selection/shadow-dom/tentative/Selection-getComposedRanges-range-update.html +++ b/third_party/blink/web_tests/external/wpt/selection/shadow-dom/tentative/Selection-getComposedRanges-range-update.html
@@ -1,7 +1,7 @@ <!DOCTYPE html> <html> <body> -<meta name="assert" content="Selection's getComposedRanges should be updated when its associated live range changes"> +<meta name="assert" content="Selection's composed range should be updated when its associated legacy uncomposed range changes"> <link rel="help" href="https://w3c.github.io/selection-api/#dom-selection-getcomposedranges"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> @@ -17,6 +17,7 @@ </div> </template> </div> +<div id="lightEnd">End outside shadow DOM</div> <script> @@ -27,48 +28,150 @@ const innerRoot = innerHost.shadowRoot; test(() => { - // Step 1: Setting a composed live range that crosses boundaries + // Setting a selction crossing to shadow tree selection.setBaseAndExtent(light.firstChild, 10, innerHost.firstChild, 5); - const liveRange = selection.getRangeAt(0); - const composedRange = selection.getComposedRanges({ shadowRoots: [outerRoot, innerRoot] })[0]; + assert_throws_dom("INDEX_SIZE_ERR", function () { selection.getRangeAt(0) }); +}, 'If selection crosses shadow boundaries, getRangeAt(0) should throw an IndexSizeError because the end is not in the document tree.'); +test(() => { + // Setting a selection within light tree + selection.setBaseAndExtent(light.firstChild, 10, lightEnd.firstChild, 20); + const liveRange = selection.getRangeAt(0); + const newSpan = document.createElement("span"); + liveRange.setStart(newSpan, 0); + + assert_true(liveRange.collapsed); + assert_equals(liveRange.startContainer, newSpan); + assert_equals(liveRange.startOffset, 0); + + assert_true(selection.isCollapsed); + assert_equals(selection.anchorNode, null); + assert_equals(selection.anchorOffset, 0); + + assert_throws_dom("INDEX_SIZE_ERR", function () { selection.getRangeAt(0) }); + assert_equals(selection.getComposedRanges({ shadowRoots: [outerRoot, innerRoot] }).length, 0); + +}, 'modify getRangeAt() range: setStart() to disconnected node will collapse and remove the live range from the selection.'); + +test(() => { + // Setting a selection within light tree + selection.setBaseAndExtent(light.firstChild, 10, light.firstChild, 20); + const liveRange = selection.getRangeAt(0); + let composedRange = selection.getComposedRanges({ shadowRoots: [outerRoot, innerRoot] })[0]; + + assert_equals(liveRange.startContainer, light.firstChild); + assert_equals(liveRange.startOffset, 10); + assert_equals(liveRange.endContainer, light.firstChild); + assert_equals(liveRange.endOffset, 20); + + assert_equals(selection.anchorNode, light.firstChild); + assert_equals(selection.anchorOffset, 10); + assert_equals(selection.focusNode, light.firstChild); + assert_equals(selection.focusOffset, 20); + + assert_equals(composedRange.startContainer, light.firstChild); + assert_equals(composedRange.startOffset, 10); + assert_equals(composedRange.endContainer, light.firstChild); + assert_equals(composedRange.endOffset, 20); + + liveRange.setEnd(innerHost.firstChild, 5); + composedRange = selection.getComposedRanges({ shadowRoots: [outerRoot, innerRoot] })[0]; + + assert_true(liveRange.collapsed); assert_equals(liveRange.startContainer, innerHost.firstChild); assert_equals(liveRange.startOffset, 5); - assert_equals(liveRange.endContainer, innerHost.firstChild); - assert_equals(liveRange.endOffset, 5); + assert_true(selection.isCollapsed); assert_equals(selection.anchorNode, innerHost.firstChild); assert_equals(selection.anchorOffset, 5); - assert_equals(selection.focusNode, innerHost.firstChild); - assert_equals(selection.focusOffset, 5); assert_equals(composedRange.startContainer, light.firstChild); assert_equals(composedRange.startOffset, 10); assert_equals(composedRange.endContainer, innerHost.firstChild); assert_equals(composedRange.endOffset, 5); +}, 'modify getRangeAt() range: setEnd() crosses shadow boundary into the shadow DOM and after start, which collapses live range. Composed selection range is not collapsed.'); - // Step 2: Update the live range only using setEnd - liveRange.setEnd(innerHost.firstChild, 6); - const composedRange2 = selection.getComposedRanges({ shadowRoots: [outerRoot, innerRoot] })[0]; +test(() => { + // Setting a selection within light tree + selection.setBaseAndExtent(lightEnd.firstChild, 10, lightEnd.firstChild, 20); + const liveRange = selection.getRangeAt(0); + let composedRange = selection.getComposedRanges({ shadowRoots: [outerRoot, innerRoot] })[0]; + assert_equals(liveRange.startContainer, lightEnd.firstChild); + assert_equals(liveRange.startOffset, 10); + assert_equals(liveRange.endContainer, lightEnd.firstChild); + assert_equals(liveRange.endOffset, 20); + + assert_equals(selection.anchorNode, lightEnd.firstChild); + assert_equals(selection.anchorOffset, 10); + assert_equals(selection.focusNode, lightEnd.firstChild); + assert_equals(selection.focusOffset, 20); + + assert_equals(composedRange.startContainer, lightEnd.firstChild); + assert_equals(composedRange.startOffset, 10); + assert_equals(composedRange.endContainer, lightEnd.firstChild); + assert_equals(composedRange.endOffset, 20); + + liveRange.setStart(innerHost.firstChild, 5); + composedRange = selection.getComposedRanges({ shadowRoots: [outerRoot, innerRoot] })[0]; + + assert_true(liveRange.collapsed); assert_equals(liveRange.startContainer, innerHost.firstChild); assert_equals(liveRange.startOffset, 5); - assert_equals(liveRange.endContainer, innerHost.firstChild); - assert_equals(liveRange.endOffset, 6); + assert_true(selection.isCollapsed); assert_equals(selection.anchorNode, innerHost.firstChild); assert_equals(selection.anchorOffset, 5); - assert_equals(selection.focusNode, innerHost.firstChild); - assert_equals(selection.focusOffset, 6); - assert_equals(composedRange2.startContainer, light.firstChild); - assert_equals(composedRange2.startOffset, 10); - assert_equals(composedRange2.endContainer, innerHost.firstChild); - assert_equals(composedRange2.endOffset, 6); + assert_equals(composedRange.startContainer, innerHost.firstChild); + assert_equals(composedRange.startOffset, 5); + assert_equals(composedRange.endContainer, lightEnd.firstChild); + assert_equals(composedRange.endOffset, 20); +}, 'modify getRangeAt() range: setStart() crosses shadow boundary into the shadow DOM and before end, which collapses live range. Composed selection range is not collapsed.'); - // Step 3: selectNode() calls both setStart/setEnd +test(() => { + // Setting a selection within light tree + selection.setBaseAndExtent(light.firstChild, 10, light.firstChild, 20); + const liveRange = selection.getRangeAt(0); + let composedRange = selection.getComposedRanges({ shadowRoots: [outerRoot, innerRoot] })[0]; + + assert_equals(liveRange.startContainer, light.firstChild); + assert_equals(liveRange.startOffset, 10); + assert_equals(liveRange.endContainer, light.firstChild); + assert_equals(liveRange.endOffset, 20); + + assert_equals(selection.anchorNode, light.firstChild); + assert_equals(selection.anchorOffset, 10); + assert_equals(selection.focusNode, light.firstChild); + assert_equals(selection.focusOffset, 20); + + assert_equals(composedRange.startContainer, light.firstChild); + assert_equals(composedRange.startOffset, 10); + assert_equals(composedRange.endContainer, light.firstChild); + assert_equals(composedRange.endOffset, 20); + + liveRange.setStart(innerHost.firstChild, 5); + composedRange = selection.getComposedRanges({ shadowRoots: [outerRoot, innerRoot] })[0]; + + assert_true(liveRange.collapsed); + assert_equals(liveRange.startContainer, innerHost.firstChild); + assert_equals(liveRange.startOffset, 5); + + assert_true(selection.isCollapsed); + assert_equals(selection.anchorNode, innerHost.firstChild); + assert_equals(selection.anchorOffset, 5); + + assert_true(composedRange.collapsed); + assert_equals(composedRange.startContainer, innerHost.firstChild); + assert_equals(composedRange.startOffset, 5); +}, 'modify getRangeAt() range: setStart() crosses shadow boundary into the shadow DOM and after end, which collapses both live range and composed selection range.'); + +test(() => { + // Setting a selection within light tree + selection.setBaseAndExtent(light.firstChild, 10, lightEnd.firstChild, 20); + const liveRange = selection.getRangeAt(0); liveRange.selectNode(innerHost); - const composedRange3 = selection.getComposedRanges({ shadowRoots: [outerRoot, innerRoot] })[0]; + const composedRange = selection.getComposedRanges({ shadowRoots: [outerRoot, innerRoot] })[0]; assert_equals(liveRange.startContainer, outerRoot); assert_equals(liveRange.startOffset, 3); @@ -80,30 +183,31 @@ assert_equals(selection.focusNode, outerRoot); assert_equals(selection.focusOffset, 4); - assert_equals(composedRange3.startContainer, outerRoot); - assert_equals(composedRange3.startOffset, 3); - assert_equals(composedRange3.endContainer, outerRoot); - assert_equals(composedRange3.endOffset, 4); + assert_equals(composedRange.startContainer, outerRoot); + assert_equals(composedRange.startOffset, 3); + assert_equals(composedRange.endContainer, outerRoot); + assert_equals(composedRange.endOffset, 4); +}, 'modify getRangeAt() range: selectNode() innerHost for all ranges.'); - // Step 4: collapse(false) calls setEnd only +test(() => { + // Setting a selection within light tree + selection.setBaseAndExtent(light.firstChild, 10, lightEnd.firstChild, 20); + const liveRange = selection.getRangeAt(0); liveRange.collapse(); - const composedRange4 = selection.getComposedRanges({ shadowRoots: [outerRoot, innerRoot] })[0]; + const composedRange = selection.getComposedRanges({ shadowRoots: [outerRoot, innerRoot] })[0]; - assert_equals(liveRange.startContainer, outerRoot); - assert_equals(liveRange.startOffset, 4); - assert_equals(liveRange.endContainer, outerRoot); - assert_equals(liveRange.endOffset, 4); + assert_true(liveRange.collapsed); + assert_equals(liveRange.startContainer, lightEnd.firstChild); + assert_equals(liveRange.startOffset, 20); - assert_equals(selection.anchorNode, outerRoot); - assert_equals(selection.anchorOffset, 4); - assert_equals(selection.focusNode, outerRoot); - assert_equals(selection.focusOffset, 4); + assert_true(selection.isCollapsed); + assert_equals(selection.anchorNode, lightEnd.firstChild); + assert_equals(selection.anchorOffset, 20); - assert_equals(composedRange4.startContainer, outerRoot); - assert_equals(composedRange4.startOffset, 4); - assert_equals(composedRange4.endContainer, outerRoot); - assert_equals(composedRange4.endOffset, 4); -}, 'modify getRangeAt() range.'); + assert_true(composedRange.collapsed); + assert_equals(composedRange.startContainer, lightEnd.firstChild); + assert_equals(composedRange.startOffset, 20); + }, 'modify getRangeAt() range: collapse() collapses all ranges.'); test(() => { // Step 1: Creating a live range and only setting its end/anchor @@ -112,37 +216,32 @@ liveRange.setEnd(innerHost.firstChild, 5); const composedRanges = selection.getComposedRanges({ shadowRoots: [outerRoot, innerRoot] }); + assert_true(liveRange.collapsed); assert_equals(liveRange.startContainer, innerHost.firstChild); assert_equals(liveRange.startOffset, 5); - assert_equals(liveRange.endContainer, innerHost.firstChild); - assert_equals(liveRange.endOffset, 5); + assert_true(selection.isCollapsed); assert_equals(selection.anchorNode, null); assert_equals(selection.anchorOffset, 0); - assert_equals(selection.focusNode, null); - assert_equals(selection.focusOffset, 0); - assert_equals(composedRanges.length, 0); + assert_equals(composedRanges.length, 0, 'range is not added to selection yet.'); // Step 2: Add range to selection so range API updates will change selection selection.addRange(liveRange); const composedRange = selection.getComposedRanges({ shadowRoots: [outerRoot, innerRoot] })[0]; - assert_equals(liveRange.startContainer, innerHost.firstChild); - assert_equals(liveRange.startOffset, 5); + assert_true(liveRange.collapsed); assert_equals(liveRange.endContainer, innerHost.firstChild); assert_equals(liveRange.endOffset, 5); + assert_true(selection.isCollapsed); assert_equals(selection.anchorNode, innerHost.firstChild); assert_equals(selection.anchorOffset, 5); - assert_equals(selection.focusNode, innerHost.firstChild); - assert_equals(selection.focusOffset, 5); + assert_true(composedRange.collapsed); assert_equals(composedRange.startContainer, innerHost.firstChild); assert_equals(composedRange.startOffset, 5); - assert_equals(composedRange.endContainer, innerHost.firstChild); - assert_equals(composedRange.endOffset, 5); -}, 'modify createRange() range added to selection after setEnd call.'); +}, 'modify createRange() range: adding to selection sets the selection'); test(() => { // Step 1: Creating a live range and only setting its end/anchor @@ -151,17 +250,15 @@ // Add range to selection so range API updates will change selection selection.addRange(liveRange); liveRange.setEnd(innerHost.firstChild, 5); - const composedRange = selection.getComposedRanges({ shadowRoots: [outerRoot, innerRoot] })[0]; + let composedRange = selection.getComposedRanges({ shadowRoots: [outerRoot, innerRoot] })[0]; + assert_true(liveRange.collapsed); assert_equals(liveRange.startContainer, innerHost.firstChild); assert_equals(liveRange.startOffset, 5); - assert_equals(liveRange.endContainer, innerHost.firstChild); - assert_equals(liveRange.endOffset, 5); + assert_true(selection.isCollapsed); assert_equals(selection.anchorNode, innerHost.firstChild); assert_equals(selection.anchorOffset, 5); - assert_equals(selection.focusNode, innerHost.firstChild); - assert_equals(selection.focusOffset, 5); assert_equals(composedRange.startContainer, document); assert_equals(composedRange.startOffset, 0); @@ -170,21 +267,19 @@ // Step 2: Update the live range by setting its start/focus liveRange.setStart(light.firstChild, 10); - const composedRangeAfter = selection.getComposedRanges({ shadowRoots: [outerRoot, innerRoot] })[0]; + composedRange = selection.getComposedRanges({ shadowRoots: [outerRoot, innerRoot] })[0]; + assert_true(liveRange.collapsed); assert_equals(liveRange.startContainer, light.firstChild); assert_equals(liveRange.startOffset, 10); - assert_equals(liveRange.endContainer, light.firstChild); - assert_equals(liveRange.endOffset, 10); + assert_true(selection.isCollapsed); assert_equals(selection.anchorNode, light.firstChild); assert_equals(selection.anchorOffset, 10); - assert_equals(selection.focusNode, light.firstChild); - assert_equals(selection.focusOffset, 10); - assert_equals(composedRangeAfter.startContainer, light.firstChild); - assert_equals(composedRangeAfter.startOffset, 10); - assert_equals(composedRangeAfter.endContainer, innerHost.firstChild); - assert_equals(composedRangeAfter.endOffset, 5); -}, 'modify createRange() range added to selection before setStart/setEnd calls.'); + assert_equals(composedRange.startContainer, light.firstChild); + assert_equals(composedRange.startOffset, 10); + assert_equals(composedRange.endContainer, innerHost.firstChild); + assert_equals(composedRange.endOffset, 5); +}, 'modify createRange() range: added to selection before setStart/setEnd calls.'); </script>
diff --git a/third_party/blink/web_tests/external/wpt/subresource-integrity/signatures/tentative/client-initiated.cross-origin.window.js b/third_party/blink/web_tests/external/wpt/subresource-integrity/signatures/tentative/client-initiated.cross-origin.window.js index ce7b817f..26e1a30 100644 --- a/third_party/blink/web_tests/external/wpt/subresource-integrity/signatures/tentative/client-initiated.cross-origin.window.js +++ b/third_party/blink/web_tests/external/wpt/subresource-integrity/signatures/tentative/client-initiated.cross-origin.window.js
@@ -26,14 +26,14 @@ // Unsigned responses are blocked when integrity is asserted: generate_fetch_test({}, { - host: get_host_info().REMOTE_HOST, + origin: get_host_info().REMOTE_ORIGIN, integrity: `ed25519-${kValidKeys['rfc']}`, }, EXPECT_BLOCKED, "No signature, valid integrity check, w/o cors: blocked."); generate_fetch_test({ cors: true }, { - host: get_host_info().REMOTE_HOST, + origin: get_host_info().REMOTE_ORIGIN, mode: 'cors', integrity: `ed25519-${kValidKeys['rfc']}`, }, @@ -51,7 +51,7 @@ }; generate_fetch_test(kRequestWithValidSignature, { - host: get_host_info().REMOTE_HOST, + origin: get_host_info().REMOTE_ORIGIN, integrity: `ed25519-${kValidKeys['rfc']}`, }, EXPECT_BLOCKED, @@ -59,7 +59,7 @@ generate_fetch_test(kRequestWithValidSignature, { - host: get_host_info().REMOTE_HOST, + origin: get_host_info().REMOTE_ORIGIN, integrity: `ed25519-${kInvalidKey}`, }, EXPECT_BLOCKED, @@ -67,7 +67,7 @@ generate_fetch_test(kRequestWithValidSignature, { - host: get_host_info().REMOTE_HOST, + origin: get_host_info().REMOTE_ORIGIN, integrity:`ed25519-${kValidKeys['rfc']} ed25519-${kInvalidKey}` }, EXPECT_BLOCKED, @@ -83,7 +83,7 @@ }; generate_fetch_test(kRequestWithValidSignatureAndCORS, { - host: get_host_info().REMOTE_HOST, + origin: get_host_info().REMOTE_ORIGIN, mode: "cors", integrity: `ed25519-${kValidKeys['rfc']}`, }, @@ -92,7 +92,7 @@ generate_fetch_test(kRequestWithValidSignatureAndCORS, { - host: get_host_info().REMOTE_HOST, + origin: get_host_info().REMOTE_ORIGIN, mode: "cors", integrity: `ed25519-${kInvalidKey}`, }, @@ -101,7 +101,7 @@ generate_fetch_test(kRequestWithValidSignatureAndCORS, { - host: get_host_info().REMOTE_HOST, + origin: get_host_info().REMOTE_ORIGIN, mode: "cors", integrity:`ed25519-${kValidKeys['rfc']} ed25519-${kInvalidKey}` }, @@ -118,7 +118,7 @@ }; generate_fetch_test(kRequestWithInvalidSignature, { - host: get_host_info().REMOTE_HOST, + origin: get_host_info().REMOTE_ORIGIN, integrity: `ed25519-${kValidKeys['rfc']}`, }, EXPECT_BLOCKED, @@ -126,7 +126,7 @@ generate_fetch_test(kRequestWithInvalidSignature, { - host: get_host_info().REMOTE_HOST, + origin: get_host_info().REMOTE_ORIGIN, integrity: `ed25519-${kInvalidKey}`, }, EXPECT_BLOCKED, @@ -134,7 +134,7 @@ generate_fetch_test(kRequestWithInvalidSignature, { - host: get_host_info().REMOTE_HOST, + origin: get_host_info().REMOTE_ORIGIN, integrity:`ed25519-${kValidKeys['rfc']} ed25519-${kInvalidKey}` }, EXPECT_BLOCKED, @@ -149,7 +149,7 @@ }; generate_fetch_test(kRequestWithInvalidSignatureAndCORS, { - host: get_host_info().REMOTE_HOST, + origin: get_host_info().REMOTE_ORIGIN, integrity: `ed25519-${kValidKeys['rfc']}`, mode: "cors", }, @@ -158,7 +158,7 @@ generate_fetch_test(kRequestWithInvalidSignatureAndCORS, { - host: get_host_info().REMOTE_HOST, + origin: get_host_info().REMOTE_ORIGIN, integrity: `ed25519-${kInvalidKey}`, mode: "cors", }, @@ -167,7 +167,7 @@ generate_fetch_test(kRequestWithInvalidSignatureAndCORS, { - host: get_host_info().REMOTE_HOST, + origin: get_host_info().REMOTE_ORIGIN, integrity:`ed25519-${kValidKeys['rfc']} ed25519-${kInvalidKey}`, mode: "cors", },
diff --git a/third_party/blink/web_tests/external/wpt/subresource-integrity/signatures/tentative/helper.js b/third_party/blink/web_tests/external/wpt/subresource-integrity/signatures/tentative/helper.js index 458da382..c5b7de6 100644 --- a/third_party/blink/web_tests/external/wpt/subresource-integrity/signatures/tentative/helper.js +++ b/third_party/blink/web_tests/external/wpt/subresource-integrity/signatures/tentative/helper.js
@@ -53,15 +53,12 @@ // Given `{ digest: "...", body: "...", cors: true, type: "..." }`, generates // the URL to a script resource that has the given characteristics. let counter = 0; -function resourceURL(data, host) { +function resourceURL(data, server_origin) { counter++; data.type ??= "application/javascript"; data.counter = counter; let params = new URLSearchParams(data); - let result = new URL("/subresource-integrity/signatures/resource.py?" + params.toString(), self.location); - if (host) { - result.host = host; - } + let result = new URL("/subresource-integrity/signatures/resource.py?" + params.toString(), server_origin ?? self.location.origin); return result.href; } @@ -92,10 +89,12 @@ function generate_fetch_test(request_data, options, expectation, description) { promise_test(test => { - const url = resourceURL(request_data, options.host); + const url = resourceURL(request_data, options.origin); let fetch_options = {}; if (options.mode) { fetch_options.mode = options.mode; + } else if (options.origin) { + fetch_options.mode = "cors"; } if (options.integrity) { fetch_options.integrity = options.integrity;
diff --git a/third_party/blink/web_tests/external/wpt/subresource-integrity/signatures/tentative/scheme.window.js b/third_party/blink/web_tests/external/wpt/subresource-integrity/signatures/tentative/scheme.window.js new file mode 100644 index 0000000..69ff21d --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/subresource-integrity/signatures/tentative/scheme.window.js
@@ -0,0 +1,73 @@ +// META: script=/common/get-host-info.sub.js +// META: script=helper.js + +// The following tests validate the behavior of the `@scheme` derived component. +// They'll all be rooted in the following response, generated using the steps at +// https://wicg.github.io/signature-based-sri/#examples, relying on the test +// key from https://www.rfc-editor.org/rfc/rfc9421.html#name-example-ed25519-test-key: +// +// ``` +// NOTE: '\' line wrapping per RFC 8792 +// +// HTTP/1.1 200 OK +// Date: Tue, 20 Apr 2021 02:07:56 GMT +// Content-Type: application/json +// Unencoded-Digest: sha-256=:PZJ+9CdAAIacg7wfUe4t/RkDQJVKM0mCZ2K7qiRhHFc=: +// Content-Length: 18 +// Signature-Input: signature=("unencoded-digest";sf "@scheme";req); \ +// keyid="JrQLj5P/89iXES9+vFgrIy29clF9CC/oPPsw3c5D0bs="; \ +// tag="sri" +// Signature: signature=:oVQ+s/OqXLAVdfvgZ3HaPiyzkpNXZSit9l6e1FB/gOOL3t8FOrIRDV \ +// CkcIEcJjd3MA1mROn39/WQShTmnKmlDg==: +// +// +// window.hello = `world`; +// ``` + +const test_cases = [ + // ``` + // "unencoded-digest";sf: sha-256=:PZJ+9CdAAIacg7wfUe4t/RkDQJVKM0mCZ2K7qiRhHFc=: + // "@scheme";req: http + // "@signature-params": ("unencoded-digest";sf "@scheme";req);keyid="JrQLj5P/89iXES9+vFgrIy29clF9CC/oPPsw3c5D0bs=";tag="sri" + // ``` + { + origin: get_host_info().HTTP_REMOTE_ORIGIN, + signature: `signature=:WZp87p7X3ELfgIKL/qxsY/CT6XArMvZRaxcJ3uy1QklEcLf0c8tol2+W2pvaXX4jnd7hGevFVkzWE77rCOIzAA==:`, + }, + // ``` + // "unencoded-digest";sf: sha-256=:PZJ+9CdAAIacg7wfUe4t/RkDQJVKM0mCZ2K7qiRhHFc=: + // "@scheme";req: https + // "@signature-params": ("unencoded-digest";sf "@scheme";req);keyid="JrQLj5P/89iXES9+vFgrIy29clF9CC/oPPsw3c5D0bs=";tag="sri" + // ``` + { + origin: get_host_info().HTTPS_REMOTE_ORIGIN, + signature: `signature=:lMzR8lIXYG0Iz0MmTXcRTcBfNw6TgBAPfaNLAU1LzsxWC5dlez8SNe7aCW7avHTWKgaqTGBCMW1LgxkHlijgDA==:`, + } +] + +// Valid signatures depend upon integrity checks. +// +// We're testing our handling of malformed and multiple keys generally in +// the broader `client-initiated.*` tests. Here we'll just focus on ensuring +// that responses with `@scheme` components load at all (no integrity check), +// load when integrity checks match, and fail when integrity checks mismatch. +for (const test_case of test_cases) { + const request = { + cors: true, + body: "window.hello = `world`;", + digest: "sha-256=:PZJ+9CdAAIacg7wfUe4t/RkDQJVKM0mCZ2K7qiRhHFc=:", + signatureInput: `signature=("unencoded-digest";sf "@scheme";req);keyid="${kValidKeys['rfc']}";tag="sri"`, + signature: test_case.signature + }; + + // fetch(): + generate_fetch_test(request, {origin: test_case.origin}, EXPECT_LOADED, + `Valid signature (${request.signature}), no integrity check: loads.`); + generate_fetch_test(request, {origin: test_case.origin, + integrity:`ed25519-${kValidKeys['rfc']}`}, EXPECT_LOADED, + `Valid signature (${request.signature}), matching integrity check: loads.`); + + generate_fetch_test(request, {origin: test_case.origin, + integrity:`ed25519-${kInvalidKey}`}, EXPECT_BLOCKED, + `Valid signature (${request.signature}), mismatched integrity check: blocked.`); +}
diff --git a/third_party/blink/web_tests/external/wpt/subresource-integrity/signatures/tentative/server-initiated.window.js b/third_party/blink/web_tests/external/wpt/subresource-integrity/signatures/tentative/server-initiated.window.js index e2b3e78..8dec3da 100644 --- a/third_party/blink/web_tests/external/wpt/subresource-integrity/signatures/tentative/server-initiated.window.js +++ b/third_party/blink/web_tests/external/wpt/subresource-integrity/signatures/tentative/server-initiated.window.js
@@ -38,14 +38,14 @@ "Valid signature, same-origin: loads."); generate_fetch_test(kRequestWithValidSignature, { - host: get_host_info().REMOTE_HOST, + origin: get_host_info().REMOTE_ORIGIN, mode: "no-cors", }, EXPECT_LOADED, "Valid signature, cross-origin w/o cors, mode: no-cors: loads."); generate_fetch_test(kRequestWithValidSignature, { - host: get_host_info().REMOTE_HOST, + origin: get_host_info().REMOTE_ORIGIN, mode: "cors", }, EXPECT_BLOCKED, @@ -65,14 +65,14 @@ "Valid signature, same-origin w/ cors: loads."); generate_fetch_test(kRequestWithValidSignatureAndCORS, { - host: get_host_info().REMOTE_HOST, + origin: get_host_info().REMOTE_ORIGIN, mode: "no-cors", }, EXPECT_LOADED, "Valid signature, cross-origin w/ cors, mode: no-cors: loads."); generate_fetch_test(kRequestWithValidSignatureAndCORS, { - host: get_host_info().REMOTE_HOST, + origin: get_host_info().REMOTE_ORIGIN, mode: "cors", }, EXPECT_LOADED, @@ -91,14 +91,14 @@ "Invalid signature, same-origin: blocked."); generate_fetch_test(kRequestWithInvalidSignature, { - host: get_host_info().REMOTE_HOST, + origin: get_host_info().REMOTE_ORIGIN, mode: "no-cors", }, EXPECT_BLOCKED, "Invalid signature, cross-origin w/o cors, mode: no-cors: blocked."); generate_fetch_test(kRequestWithInvalidSignature, { - host: get_host_info().REMOTE_HOST, + origin: get_host_info().REMOTE_ORIGIN, mode: "cors", }, EXPECT_BLOCKED, @@ -118,14 +118,14 @@ "Invalid signature, same-origin w/ cors: blocked."); generate_fetch_test(kRequestWithInvalidSignatureAndCORS, { - host: get_host_info().REMOTE_HOST, + origin: get_host_info().REMOTE_ORIGIN, mode: "no-cors", }, EXPECT_BLOCKED, "Invalid signature, cross-origin w/ cors, mode: no-cors: blocked."); generate_fetch_test(kRequestWithInvalidSignatureAndCORS, { - host: get_host_info().REMOTE_HOST, + origin: get_host_info().REMOTE_ORIGIN, mode: "cors", }, EXPECT_BLOCKED,
diff --git a/third_party/blink/web_tests/external/wpt/subresource-integrity/signatures/tentative/unknown-parameter.window.js b/third_party/blink/web_tests/external/wpt/subresource-integrity/signatures/tentative/unknown-parameter.window.js new file mode 100644 index 0000000..2b4df54 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/subresource-integrity/signatures/tentative/unknown-parameter.window.js
@@ -0,0 +1,73 @@ +// META: script=helper.js + +// The following tests validate the behavior of unknown signature parameters. +// They'll all be rooted in the following response, generated using the steps at +// https://wicg.github.io/signature-based-sri/#examples, relying on the test +// key from https://www.rfc-editor.org/rfc/rfc9421.html#name-example-ed25519-test-key: +// +// ``` +// NOTE: '\' line wrapping per RFC 8792 +// +// HTTP/1.1 200 OK +// Date: Tue, 20 Apr 2021 02:07:56 GMT +// Content-Type: application/json +// Unencoded-Digest: sha-256=:X48E9qOokqqrvdts8nOJRJN3OWDUoyWxBf7kbu9DBPE=: +// Content-Length: 18 +// Signature-Input: signature=("unencoded-digest";sf "@status"); \ +// keyid="JrQLj5P/89iXES9+vFgrIy29clF9CC/oPPsw3c5D0bs="; \ +// tag="sri" +// Signature: signature=:oVQ+s/OqXLAVdfvgZ3HaPiyzkpNXZSit9l6e1FB/gOOL3t8FOrIRDV \ +// CkcIEcJjd3MA1mROn39/WQShTmnKmlDg==: +// +// +// {"hello": "world"} +// ``` + +// Metadata from the response above: +const kRequestsWithValidSignature = [ + // ``` + // "unencoded-digest";sf: sha-256=:PZJ+9CdAAIacg7wfUe4t/RkDQJVKM0mCZ2K7qiRhHFc=: + // "@signature-params": ("unencoded-digest";sf "@status");keyid="JrQLj5P/89iXES9+vFgrIy29clF9CC/oPPsw3c5D0bs=";tag="sri";unknown=1 + // ``` + { + body: "window.hello = `world`;", + digest: "sha-256=:PZJ+9CdAAIacg7wfUe4t/RkDQJVKM0mCZ2K7qiRhHFc=:", + signature: `signature=:eZ2DGIHUsTNMxFReOMkbOrTmn+CqDckCZ5/635x1Apl2ws0nA+qZcHqZFMdjBvcGw0WElh3zYD0ynkQ+cHiWCA==:`, + signatureInput: `signature=("unencoded-digest";sf);keyid="${kValidKeys['rfc']}";tag="sri";unknown=1` + }, + // ``` + // "unencoded-digest";sf: sha-256=:PZJ+9CdAAIacg7wfUe4t/RkDQJVKM0mCZ2K7qiRhHFc=: + // "@signature-params": ("unencoded-digest";sf "@status");unknown=1;keyid="JrQLj5P/89iXES9+vFgrIy29clF9CC/oPPsw3c5D0bs=";tag="sri" + // ``` + { + body: "window.hello = `world`;", + digest: "sha-256=:PZJ+9CdAAIacg7wfUe4t/RkDQJVKM0mCZ2K7qiRhHFc=:", + signature: `signature=:YXQH8lkKBcGOMNSFbS56j3d5nK3j15HbFPIdsljzQVGFFd93T6FmXb2cLsoINYQbnMUOQBSROIzFZpgUQTBTBA==:`, + signatureInput: `signature=("unencoded-digest";sf);unknown=1;keyid="${kValidKeys['rfc']}";tag="sri"` + }, +]; + +// Valid signatures depend upon integrity checks. +// +// We're testing our handling of malformed and multiple keys generally in +// the broader `client-initiated.*` tests. Here we'll just focus on ensuring +// that responses with unknown parameters load at all (no integrity check), +// load when integrity checks match, and fail when integrity checks mismatch. +for (const request of kRequestsWithValidSignature) { + // fetch(): + generate_fetch_test(request, {}, EXPECT_LOADED, + `Valid signature (${request.signature}), no integrity check: loads.`); + generate_fetch_test(request, {integrity:`ed25519-${kValidKeys['rfc']}`}, EXPECT_LOADED, + `Valid signature (${request.signature}), matching integrity check: loads.`); + + generate_fetch_test(request, {integrity:`ed25519-${kInvalidKey}`}, EXPECT_BLOCKED, + `Valid signature (${request.signature}), mismatched integrity check: blocked.`); + + // <script>: + generate_script_test(request, "", EXPECT_LOADED, + `Valid signature (${request.signature}), no integrity check: loads.`); + generate_script_test(request, `ed25519-${kValidKeys['rfc']}`, EXPECT_LOADED, + `Valid signature (${request.signature}), matching integrity check: loads.`); + generate_script_test(request, `ed25519-${kInvalidKey}`, EXPECT_BLOCKED, + `Valid signature (${request.signature}), mismatched integrity check: blocked.`); +}
diff --git a/third_party/blink/web_tests/fast/reflections/reflection-with-zoom-expected.png b/third_party/blink/web_tests/fast/reflections/reflection-with-zoom-expected.png index 707881a4..b4e3e61 100644 --- a/third_party/blink/web_tests/fast/reflections/reflection-with-zoom-expected.png +++ b/third_party/blink/web_tests/fast/reflections/reflection-with-zoom-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/http/tests/inspector-protocol/resources/shared-storage-module.js b/third_party/blink/web_tests/http/tests/inspector-protocol/shared-storage/resources/shared-storage-module.js similarity index 100% rename from third_party/blink/web_tests/http/tests/inspector-protocol/resources/shared-storage-module.js rename to third_party/blink/web_tests/http/tests/inspector-protocol/shared-storage/resources/shared-storage-module.js
diff --git a/third_party/blink/web_tests/http/tests/inspector-protocol/shared-storage/shared-storage-expected.txt b/third_party/blink/web_tests/http/tests/inspector-protocol/shared-storage/shared-storage-expected.txt index f88d7c5f..62aa087 100644 --- a/third_party/blink/web_tests/http/tests/inspector-protocol/shared-storage/shared-storage-expected.txt +++ b/third_party/blink/web_tests/http/tests/inspector-protocol/shared-storage/shared-storage-expected.txt
@@ -96,7 +96,7 @@ mainFrameId : <string> ownerOrigin : http://127.0.0.1:8000 params : { - scriptSourceUrl : http://127.0.0.1:8000/inspector-protocol/resources/shared-storage-module.js + scriptSourceUrl : http://127.0.0.1:8000/inspector-protocol/shared-storage/resources/shared-storage-module.js } type : documentAddModule }
diff --git a/third_party/blink/web_tests/http/tests/inspector-protocol/shared-storage/shared-storage.js b/third_party/blink/web_tests/http/tests/inspector-protocol/shared-storage/shared-storage.js index 4ff92946..07429d8e 100644 --- a/third_party/blink/web_tests/http/tests/inspector-protocol/shared-storage/shared-storage.js +++ b/third_party/blink/web_tests/http/tests/inspector-protocol/shared-storage/shared-storage.js
@@ -8,7 +8,7 @@ } const baseOrigin = 'http://127.0.0.1:8000/'; - const base = baseOrigin + 'inspector-protocol/resources/'; + const resources = baseOrigin + 'inspector-protocol/shared-storage/resources/'; async function getSharedStorageMetadata(dp, testRunner, origin) { const data = await dp.Storage.getSharedStorageMetadata( @@ -60,7 +60,7 @@ sharedStorage.set('key2-set-from-document', 'value3', {ignoreIfPresent: true}); sharedStorage.delete('key2-set-from-document'); - const script_url = "${base}shared-storage-module.js"; + const script_url = "${resources}shared-storage-module.js"; sharedStorage.worklet.addModule(script_url); `);
diff --git a/third_party/blink/web_tests/platform/mac-mac11-arm64/fast/reflections/reflection-with-zoom-expected.png b/third_party/blink/web_tests/platform/mac-mac11-arm64/fast/reflections/reflection-with-zoom-expected.png index 09e9a133..0e0b5dd 100644 --- a/third_party/blink/web_tests/platform/mac-mac11-arm64/fast/reflections/reflection-with-zoom-expected.png +++ b/third_party/blink/web_tests/platform/mac-mac11-arm64/fast/reflections/reflection-with-zoom-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac12-arm64/fast/reflections/reflection-with-zoom-expected.png b/third_party/blink/web_tests/platform/mac-mac12-arm64/fast/reflections/reflection-with-zoom-expected.png index 09e9a133..0e0b5dd 100644 --- a/third_party/blink/web_tests/platform/mac-mac12-arm64/fast/reflections/reflection-with-zoom-expected.png +++ b/third_party/blink/web_tests/platform/mac-mac12-arm64/fast/reflections/reflection-with-zoom-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac13-arm64/fast/reflections/reflection-with-zoom-expected.png b/third_party/blink/web_tests/platform/mac-mac13-arm64/fast/reflections/reflection-with-zoom-expected.png index 09e9a133..0e0b5dd 100644 --- a/third_party/blink/web_tests/platform/mac-mac13-arm64/fast/reflections/reflection-with-zoom-expected.png +++ b/third_party/blink/web_tests/platform/mac-mac13-arm64/fast/reflections/reflection-with-zoom-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac14-arm64/fast/reflections/reflection-with-zoom-expected.png b/third_party/blink/web_tests/platform/mac-mac14-arm64/fast/reflections/reflection-with-zoom-expected.png index 09e9a133..0e0b5dd 100644 --- a/third_party/blink/web_tests/platform/mac-mac14-arm64/fast/reflections/reflection-with-zoom-expected.png +++ b/third_party/blink/web_tests/platform/mac-mac14-arm64/fast/reflections/reflection-with-zoom-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac15-arm64/fast/reflections/reflection-with-zoom-expected.png b/third_party/blink/web_tests/platform/mac-mac15-arm64/fast/reflections/reflection-with-zoom-expected.png index 09e9a133..0e0b5dd 100644 --- a/third_party/blink/web_tests/platform/mac-mac15-arm64/fast/reflections/reflection-with-zoom-expected.png +++ b/third_party/blink/web_tests/platform/mac-mac15-arm64/fast/reflections/reflection-with-zoom-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/svg/batik/text/textFeatures-expected.png b/third_party/blink/web_tests/platform/mac/svg/batik/text/textFeatures-expected.png index 42d1349..4266baf 100644 --- a/third_party/blink/web_tests/platform/mac/svg/batik/text/textFeatures-expected.png +++ b/third_party/blink/web_tests/platform/mac/svg/batik/text/textFeatures-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win11-arm64/fast/reflections/reflection-with-zoom-expected.png b/third_party/blink/web_tests/platform/win11-arm64/fast/reflections/reflection-with-zoom-expected.png index 09e9a133..0e0b5dd 100644 --- a/third_party/blink/web_tests/platform/win11-arm64/fast/reflections/reflection-with-zoom-expected.png +++ b/third_party/blink/web_tests/platform/win11-arm64/fast/reflections/reflection-with-zoom-expected.png Binary files differ
diff --git a/third_party/chromite b/third_party/chromite index 4bf6cc9..295110e 160000 --- a/third_party/chromite +++ b/third_party/chromite
@@ -1 +1 @@ -Subproject commit 4bf6cc9908997fa11eb71f6969741ce49b676aca +Subproject commit 295110e661c6392bfc34ec77edd7c5910ea604d8
diff --git a/third_party/dawn b/third_party/dawn index 516500a..46d76d4 160000 --- a/third_party/dawn +++ b/third_party/dawn
@@ -1 +1 @@ -Subproject commit 516500a25109a6f42705c912e7bc72b8a0364c7d +Subproject commit 46d76d4aad3b9e3c84dbf0d9565f3b7bdabd3434
diff --git a/third_party/devtools-frontend/src b/third_party/devtools-frontend/src index 22ebcbc1..3353eed 160000 --- a/third_party/devtools-frontend/src +++ b/third_party/devtools-frontend/src
@@ -1 +1 @@ -Subproject commit 22ebcbc1b76b65436c8dc57536f2c2a0aac7675d +Subproject commit 3353eedcf87f8f80af884cfd867006b89d0b961b
diff --git a/third_party/perfetto b/third_party/perfetto index 7da1b16..ea324cf 160000 --- a/third_party/perfetto +++ b/third_party/perfetto
@@ -1 +1 @@ -Subproject commit 7da1b1676f326e67cc3eb38774daf3154f876fd0 +Subproject commit ea324cfbfd21cbbfbc1122e33575ab24b81cecbe
diff --git a/third_party/rust/byteorder/v1/BUILD.gn b/third_party/rust/byteorder/v1/BUILD.gn deleted file mode 100644 index 2731f4a..0000000 --- a/third_party/rust/byteorder/v1/BUILD.gn +++ /dev/null
@@ -1,45 +0,0 @@ -# Copyright 2023 The Chromium Authors -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -# @generated from third_party/rust/chromium_crates_io/BUILD.gn.hbs by -# tools/crates/gnrt. -# Do not edit! - -import("//build/rust/cargo_crate.gni") - -cargo_crate("lib") { - crate_name = "byteorder" - epoch = "1" - crate_type = "rlib" - crate_root = - "//third_party/rust/chromium_crates_io/vendor/byteorder-1.5.0/src/lib.rs" - sources = [ - "//third_party/rust/chromium_crates_io/vendor/byteorder-1.5.0/src/io.rs", - "//third_party/rust/chromium_crates_io/vendor/byteorder-1.5.0/src/lib.rs", - ] - inputs = [] - - build_native_rust_unit_tests = false - edition = "2021" - cargo_pkg_version = "1.5.0" - cargo_pkg_authors = "Andrew Gallant <jamslam@gmail.com>" - cargo_pkg_name = "byteorder" - cargo_pkg_description = - "Library for reading/writing numbers in big-endian and little-endian." - library_configs -= [ "//build/config/coverage:default_coverage" ] - library_configs -= [ "//build/config/compiler:chromium_code" ] - library_configs += [ "//build/config/compiler:no_chromium_code" ] - executable_configs -= [ "//build/config/compiler:chromium_code" ] - executable_configs += [ "//build/config/compiler:no_chromium_code" ] - proc_macro_configs -= [ "//build/config/compiler:chromium_code" ] - proc_macro_configs += [ "//build/config/compiler:no_chromium_code" ] - rustflags = [ - "--cap-lints=allow", # Suppress all warnings in crates.io crates - ] - - # Only for usage from third-party crates. Add the crate to - # //third_party/rust/chromium_crates_io/Cargo.toml to use - # it from first-party code. - visibility = [ "//third_party/rust/*" ] -}
diff --git a/third_party/rust/byteorder/v1/README.chromium b/third_party/rust/byteorder/v1/README.chromium deleted file mode 100644 index 41d1a13..0000000 --- a/third_party/rust/byteorder/v1/README.chromium +++ /dev/null
@@ -1,10 +0,0 @@ -Name: byteorder -URL: https://crates.io/crates/byteorder -Version: 1.5.0 -Revision: ec068eefa042d494475db125c4b034bd8e9e34dd -License: MIT -License File: //third_party/rust/chromium_crates_io/vendor/byteorder-1.5.0/LICENSE-MIT -Shipped: yes -Security Critical: yes - -Description: Library for reading/writing numbers in big-endian and little-endian.
diff --git a/third_party/rust/chromium_crates_io/Cargo.lock b/third_party/rust/chromium_crates_io/Cargo.lock index 14ef2f1..04f71d3d 100644 --- a/third_party/rust/chromium_crates_io/Cargo.lock +++ b/third_party/rust/chromium_crates_io/Cargo.lock
@@ -86,11 +86,6 @@ ] [[package]] -name = "byteorder" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] name = "bytes" version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -166,7 +161,6 @@ "temporal_capi", "tinyvec", "unicode-linebreak", - "zerocopy 0.7.35", ] [[package]] @@ -1019,7 +1013,7 @@ version = "0.2.21" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "zerocopy 0.8.23", + "zerocopy", ] [[package]] @@ -1593,29 +1587,10 @@ [[package]] name = "zerocopy" -version = "0.7.35" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "byteorder", - "zerocopy-derive 0.7.35", -] - -[[package]] -name = "zerocopy" version = "0.8.23" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "zerocopy-derive 0.8.23", -] - -[[package]] -name = "zerocopy-derive" -version = "0.7.35" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "proc-macro2", - "quote", - "syn", + "zerocopy-derive", ] [[package]]
diff --git a/third_party/rust/chromium_crates_io/Cargo.toml b/third_party/rust/chromium_crates_io/Cargo.toml index d5c0510..b614b36 100644 --- a/third_party/rust/chromium_crates_io/Cargo.toml +++ b/third_party/rust/chromium_crates_io/Cargo.toml
@@ -105,10 +105,6 @@ [dependencies.unicode-linebreak] version = "0.1" -[dependencies.zerocopy] -version = "0.7.35" -features = ["derive", "simd"] - [dependencies.bytemuck] version = "1" features = ["nightly_portable_simd"] # For std::simd coverage.
diff --git a/third_party/rust/chromium_crates_io/supply-chain/config.toml b/third_party/rust/chromium_crates_io/supply-chain/config.toml index 7425f66..eb77302 100644 --- a/third_party/rust/chromium_crates_io/supply-chain/config.toml +++ b/third_party/rust/chromium_crates_io/supply-chain/config.toml
@@ -80,9 +80,6 @@ [policy."bytemuck_derive:1.9.2"] criteria = ["crypto-safe", "safe-to-deploy", "ub-risk-2"] -[policy."byteorder:1.5.0"] -criteria = ["crypto-safe", "safe-to-deploy", "ub-risk-2"] - [policy."bytes:1.10.1"] criteria = ["crypto-safe", "safe-to-run"] @@ -578,15 +575,9 @@ [policy."yoke:0.8.0"] criteria = ["crypto-safe", "safe-to-deploy", "ub-risk-2"] -[policy."zerocopy-derive:0.7.35"] -criteria = ["crypto-safe", "safe-to-deploy", "ub-risk-2"] - [policy."zerocopy-derive:0.8.23"] criteria = [] -[policy."zerocopy:0.7.35"] -criteria = ["crypto-safe", "safe-to-deploy", "ub-risk-2"] - [policy."zerocopy:0.8.23"] criteria = ["crypto-safe", "safe-to-run"]
diff --git a/third_party/rust/chromium_crates_io/vendor/byteorder-1.5.0/.cargo-checksum.json b/third_party/rust/chromium_crates_io/vendor/byteorder-1.5.0/.cargo-checksum.json deleted file mode 100644 index 697c9ce..0000000 --- a/third_party/rust/chromium_crates_io/vendor/byteorder-1.5.0/.cargo-checksum.json +++ /dev/null
@@ -1 +0,0 @@ -{"files":{}}
diff --git a/third_party/rust/chromium_crates_io/vendor/byteorder-1.5.0/.cargo_vcs_info.json b/third_party/rust/chromium_crates_io/vendor/byteorder-1.5.0/.cargo_vcs_info.json deleted file mode 100644 index 39b39eff..0000000 --- a/third_party/rust/chromium_crates_io/vendor/byteorder-1.5.0/.cargo_vcs_info.json +++ /dev/null
@@ -1,6 +0,0 @@ -{ - "git": { - "sha1": "ec068eefa042d494475db125c4b034bd8e9e34dd" - }, - "path_in_vcs": "" -} \ No newline at end of file
diff --git a/third_party/rust/chromium_crates_io/vendor/byteorder-1.5.0/.github/workflows/ci.yml b/third_party/rust/chromium_crates_io/vendor/byteorder-1.5.0/.github/workflows/ci.yml deleted file mode 100644 index 1aa3c3b..0000000 --- a/third_party/rust/chromium_crates_io/vendor/byteorder-1.5.0/.github/workflows/ci.yml +++ /dev/null
@@ -1,183 +0,0 @@ -name: ci -on: - pull_request: - branches: - - master - push: - branches: - - master - schedule: - - cron: '00 01 * * *' - -# The section is needed to drop write-all permissions that are granted on -# `schedule` event. By specifying any permission explicitly all others are set -# to none. By using the principle of least privilege the damage a compromised -# workflow can do (because of an injection or compromised third party tool or -# action) is restricted. Currently the worklow doesn't need any additional -# permission except for pulling the code. Adding labels to issues, commenting -# on pull-requests, etc. may need additional permissions: -# -# Syntax for this section: -# https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#permissions -# -# Reference for how to assign permissions on a job-by-job basis: -# https://docs.github.com/en/actions/using-jobs/assigning-permissions-to-jobs -# -# Reference for available permissions that we can enable if needed: -# https://docs.github.com/en/actions/security-guides/automatic-token-authentication#permissions-for-the-github_token -permissions: - # to fetch code (actions/checkout) - contents: read - -jobs: - test: - name: test - env: - # For some builds, we use cross to test on 32-bit and big-endian - # systems. - CARGO: cargo - # When CARGO is set to CROSS, TARGET is set to `--target matrix.target`. - # Note that we only use cross on Linux, so setting a target on a - # different OS will just use normal cargo. - TARGET: - # Bump this as appropriate. We pin to a version to make sure CI - # continues to work as cross releases in the past have broken things - # in subtle ways. - CROSS_VERSION: v0.2.5 - runs-on: ${{ matrix.os }} - strategy: - fail-fast: false - matrix: - include: - - build: pinned - os: ubuntu-latest - rust: 1.60.0 - - build: stable - os: ubuntu-latest - rust: stable - - build: beta - os: ubuntu-latest - rust: beta - - build: nightly - os: ubuntu-latest - rust: nightly - - build: macos - os: macos-latest - rust: stable - - build: win-msvc - os: windows-latest - rust: stable - - build: win-gnu - os: windows-latest - rust: stable-x86_64-gnu - - build: stable-x86 - os: ubuntu-latest - rust: stable - target: i686-unknown-linux-gnu - - build: stable-aarch64 - os: ubuntu-latest - rust: stable - target: aarch64-unknown-linux-gnu - - build: stable-powerpc64 - os: ubuntu-latest - rust: stable - target: powerpc64-unknown-linux-gnu - - build: stable-s390x - os: ubuntu-latest - rust: stable - target: s390x-unknown-linux-gnu - steps: - - name: Checkout repository - uses: actions/checkout@v4 - - name: Install Rust - uses: dtolnay/rust-toolchain@master - with: - toolchain: ${{ matrix.rust }} - - name: Use Cross - if: matrix.os == 'ubuntu-latest' && matrix.target != '' - run: | - # In the past, new releases of 'cross' have broken CI. So for now, we - # pin it. We also use their pre-compiled binary releases because cross - # has over 100 dependencies and takes a bit to compile. - dir="$RUNNER_TEMP/cross-download" - mkdir "$dir" - echo "$dir" >> $GITHUB_PATH - cd "$dir" - curl -LO "https://github.com/cross-rs/cross/releases/download/$CROSS_VERSION/cross-x86_64-unknown-linux-musl.tar.gz" - tar xf cross-x86_64-unknown-linux-musl.tar.gz - echo "CARGO=cross" >> $GITHUB_ENV - echo "TARGET=--target ${{ matrix.target }}" >> $GITHUB_ENV - - name: Show command used for Cargo - run: | - echo "cargo command is: ${{ env.CARGO }}" - echo "target flag is: ${{ env.TARGET }}" - - name: Show CPU info for debugging - if: matrix.os == 'ubuntu-latest' - run: lscpu - - name: Build - run: ${{ env.CARGO }} build --verbose $TARGET - - name: Build (no default) - run: ${{ env.CARGO }} build --verbose $TARGET --no-default-features - - name: Build docs - run: ${{ env.CARGO }} doc --verbose $TARGET - - # Our dev dependencies evolve more rapidly than we'd like, so only run - # tests when we aren't pinning the Rust version. - - name: Tests - if: matrix.build != 'pinned' - run: ${{ env.CARGO }} test --verbose $TARGET - - - name: Tests (no default, lib only) - if: matrix.build != 'pinned' - run: ${{ env.CARGO }} test --verbose --no-default-features --lib $TARGET - - - name: Tests (i128) - if: matrix.build != 'pinned' - run: ${{ env.CARGO }} test --verbose --features i128 $TARGET - - - name: Tests (no default, lib only, i128) - if: matrix.build != 'pinned' - run: ${{ env.CARGO }} test --verbose --no-default-features --features i128 --lib $TARGET - - - name: Compile benchmarks - if: matrix.build == 'nightly' - run: cargo bench --verbose --no-run $TARGET - - - name: Compile benchmarks (no default) - if: matrix.build == 'nightly' - run: cargo bench --verbose --no-run --no-default-features $TARGET - - - name: Compile benchmarks (i128) - if: matrix.build == 'nightly' - run: cargo bench --verbose --no-run --features i128 $TARGET - - - name: Compile benchmarks (no default, i128) - if: matrix.build == 'nightly' - run: cargo bench --verbose --no-run --no-default-features --features i128 $TARGET - - miri: - runs-on: ubuntu-latest - steps: - - name: Checkout repository - uses: actions/checkout@v4 - - name: Install Rust - uses: dtolnay/rust-toolchain@master - with: - # We use nightly here so that we can use miri I guess? - toolchain: nightly - components: miri - - name: Run full test suite - run: cargo miri test --verbose - - rustfmt: - runs-on: ubuntu-latest - steps: - - name: Checkout repository - uses: actions/checkout@v4 - - name: Install Rust - uses: dtolnay/rust-toolchain@master - with: - toolchain: stable - components: rustfmt - - name: Check formatting - run: cargo fmt -- --check
diff --git a/third_party/rust/chromium_crates_io/vendor/byteorder-1.5.0/.gitignore b/third_party/rust/chromium_crates_io/vendor/byteorder-1.5.0/.gitignore deleted file mode 100644 index 1fec0efb8..0000000 --- a/third_party/rust/chromium_crates_io/vendor/byteorder-1.5.0/.gitignore +++ /dev/null
@@ -1,6 +0,0 @@ -.*.swp -doc -tags -build -target -Cargo.lock
diff --git a/third_party/rust/chromium_crates_io/vendor/byteorder-1.5.0/CHANGELOG.md b/third_party/rust/chromium_crates_io/vendor/byteorder-1.5.0/CHANGELOG.md deleted file mode 100644 index 9efb7ed2..0000000 --- a/third_party/rust/chromium_crates_io/vendor/byteorder-1.5.0/CHANGELOG.md +++ /dev/null
@@ -1,143 +0,0 @@ -**WARNING:** This CHANGELOG is no longer updated. The activity for this project -is sparse enough that you should refer to the commit log instead. - - -1.3.4 -===== -This patch release squashes deprecation warnings for the `try!` macro, in -accordance with byteorder's minimum supported Rust version (currently at Rust -1.12.0). - - -1.3.3 -===== -This patch release adds `ByteOrder::write_i8_into()` as a simple, safe interface -for ordinarily unsafe or tedious code. - - -1.3.2 -===== -This patch release adds `ReadBytesExt::read_i8_into()` as a simple, safe interface -for ordinarily unsafe or tedious code. - - -1.3.1 -===== -This minor release performs mostly small internal changes. Going forward, these -are not going to be incorporated into the changelog. - - -1.3.0 -===== -This new minor release now enables `i128` support automatically on Rust -compilers that support 128-bit integers. The `i128` feature is now a no-op, but -continues to exist for backward compatibility purposes. The crate continues to -maintain compatibility with Rust 1.12.0. - -This release also deprecates the `ByteOrder` trait methods -`read_f32_into_unchecked` and `read_f64_into_unchecked` in favor of -`read_f32_into` and `read_f64_into`. This was an oversight from the 1.2 release -where the corresponding methods on `ReadBytesExt` were deprecated. - -`quickcheck` and `rand` were bumped to `0.8` and `0.6`, respectively. - -A few small documentation related bugs have been fixed. - - -1.2.7 -===== -This patch release excludes some CI files from the crate release and updates -the license field to use `OR` instead of `/`. - - -1.2.6 -===== -This patch release fixes some test compilation errors introduced by an -over-eager release of 1.2.5. - - -1.2.5 -===== -This patch release fixes some typos in the docs, adds doc tests to methods on -`WriteByteExt` and bumps the quickcheck dependency to `0.7`. - - -1.2.4 -===== -This patch release adds support for 48-bit integers by adding the following -methods to the `ByteOrder` trait: `read_u48`, `read_i48`, `write_u48` and -`write_i48`. Corresponding methods have been added to the `ReadBytesExt` and -`WriteBytesExt` traits as well. - - -1.2.3 -===== -This patch release removes the use of `feature(i128_type)` from byteorder, -since it has been stabilized. We leave byteorder's `i128` feature in place -in order to continue supporting compilation on older versions of Rust. - - -1.2.2 -===== -This patch release only consists of internal improvements and refactorings. -Notably, this removes all uses of `transmute` and instead uses pointer casts. - - -1.2.1 -===== -This patch release removes more unnecessary uses of `unsafe` that -were overlooked in the prior `1.2.0` release. In particular, the -`ReadBytesExt::read_{f32,f64}_into_checked` methods have been deprecated and -replaced by more appropriately named `read_{f32,f64}_into` methods. - - -1.2.0 -===== -The most prominent change in this release of `byteorder` is the removal of -unnecessary signaling NaN masking, and in turn, the `unsafe` annotations -associated with methods that didn't do masking. See -[#103](https://github.com/BurntSushi/byteorder/issues/103) -for more details. - -* [BUG #102](https://github.com/BurntSushi/byteorder/issues/102): - Fix big endian tests. -* [BUG #103](https://github.com/BurntSushi/byteorder/issues/103): - Remove sNaN masking. - - -1.1.0 -===== -This release of `byteorder` features a number of fixes and improvements, mostly -as a result of the -[Litz Blitz evaluation](https://public.etherpad-mozilla.org/p/rust-crate-eval-byteorder). - -Feature enhancements: - -* [FEATURE #63](https://github.com/BurntSushi/byteorder/issues/63): - Add methods for reading/writing slices of numbers for a specific - endianness. -* [FEATURE #65](https://github.com/BurntSushi/byteorder/issues/65): - Add support for `u128`/`i128` types. (Behind the nightly only `i128` - feature.) -* [FEATURE #72](https://github.com/BurntSushi/byteorder/issues/72): - Add "panics" and "errors" sections for each relevant public API item. -* [FEATURE #74](https://github.com/BurntSushi/byteorder/issues/74): - Add CI badges to Cargo.toml. -* [FEATURE #75](https://github.com/BurntSushi/byteorder/issues/75): - Add more examples to public API items. -* Add 24-bit read/write methods. -* Add `BE` and `LE` type aliases for `BigEndian` and `LittleEndian`, - respectively. - -Bug fixes: - -* [BUG #68](https://github.com/BurntSushi/byteorder/issues/68): - Panic in {BigEndian,LittleEndian}::default. -* [BUG #69](https://github.com/BurntSushi/byteorder/issues/69): - Seal the `ByteOrder` trait to prevent out-of-crate implementations. -* [BUG #71](https://github.com/BurntSushi/byteorder/issues/71): - Guarantee that the results of `read_f32`/`read_f64` are always defined. -* [BUG #73](https://github.com/BurntSushi/byteorder/issues/73): - Add crates.io categories. -* [BUG #77](https://github.com/BurntSushi/byteorder/issues/77): - Add `html_root` doc attribute.
diff --git a/third_party/rust/chromium_crates_io/vendor/byteorder-1.5.0/COPYING b/third_party/rust/chromium_crates_io/vendor/byteorder-1.5.0/COPYING deleted file mode 100644 index bb9c20a0..0000000 --- a/third_party/rust/chromium_crates_io/vendor/byteorder-1.5.0/COPYING +++ /dev/null
@@ -1,3 +0,0 @@ -This project is dual-licensed under the Unlicense and MIT licenses. - -You may use this code under the terms of either license.
diff --git a/third_party/rust/chromium_crates_io/vendor/byteorder-1.5.0/Cargo.toml b/third_party/rust/chromium_crates_io/vendor/byteorder-1.5.0/Cargo.toml deleted file mode 100644 index da515d9d..0000000 --- a/third_party/rust/chromium_crates_io/vendor/byteorder-1.5.0/Cargo.toml +++ /dev/null
@@ -1,54 +0,0 @@ -# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO -# -# When uploading crates to the registry Cargo will automatically -# "normalize" Cargo.toml files for maximal compatibility -# with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g., crates.io) dependencies. -# -# If you are reading this file be aware that the original Cargo.toml -# will likely look very different (and much more reasonable). -# See Cargo.toml.orig for the original contents. - -[package] -edition = "2021" -rust-version = "1.60" -name = "byteorder" -version = "1.5.0" -authors = ["Andrew Gallant <jamslam@gmail.com>"] -description = "Library for reading/writing numbers in big-endian and little-endian." -homepage = "https://github.com/BurntSushi/byteorder" -documentation = "https://docs.rs/byteorder" -readme = "README.md" -keywords = [ - "byte", - "endian", - "big-endian", - "little-endian", - "binary", -] -categories = [ - "encoding", - "parsing", - "no-std", -] -license = "Unlicense OR MIT" -repository = "https://github.com/BurntSushi/byteorder" - -[profile.bench] -opt-level = 3 - -[lib] -name = "byteorder" -bench = false - -[dev-dependencies.quickcheck] -version = "0.9.2" -default-features = false - -[dev-dependencies.rand] -version = "0.7" - -[features] -default = ["std"] -i128 = [] -std = []
diff --git a/third_party/rust/chromium_crates_io/vendor/byteorder-1.5.0/Cargo.toml.orig b/third_party/rust/chromium_crates_io/vendor/byteorder-1.5.0/Cargo.toml.orig deleted file mode 100644 index 91e6ab1..0000000 --- a/third_party/rust/chromium_crates_io/vendor/byteorder-1.5.0/Cargo.toml.orig +++ /dev/null
@@ -1,34 +0,0 @@ -[package] -name = "byteorder" -version = "1.5.0" #:version -authors = ["Andrew Gallant <jamslam@gmail.com>"] -description = "Library for reading/writing numbers in big-endian and little-endian." -documentation = "https://docs.rs/byteorder" -homepage = "https://github.com/BurntSushi/byteorder" -repository = "https://github.com/BurntSushi/byteorder" -readme = "README.md" -categories = ["encoding", "parsing", "no-std"] -keywords = ["byte", "endian", "big-endian", "little-endian", "binary"] -license = "Unlicense OR MIT" -edition = "2021" -rust-version = "1.60" - -[lib] -name = "byteorder" -bench = false - -[dev-dependencies] -quickcheck = { version = "0.9.2", default-features = false } -rand = "0.7" - -[features] -default = ["std"] -std = [] - -# This feature is no longer used and is DEPRECATED. This crate now -# automatically enables i128 support for Rust compilers that support it. The -# feature will be removed if and when a new major version is released. -i128 = [] - -[profile.bench] -opt-level = 3
diff --git a/third_party/rust/chromium_crates_io/vendor/byteorder-1.5.0/LICENSE-MIT b/third_party/rust/chromium_crates_io/vendor/byteorder-1.5.0/LICENSE-MIT deleted file mode 100644 index 3b0a5dc..0000000 --- a/third_party/rust/chromium_crates_io/vendor/byteorder-1.5.0/LICENSE-MIT +++ /dev/null
@@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Andrew Gallant - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE.
diff --git a/third_party/rust/chromium_crates_io/vendor/byteorder-1.5.0/README.md b/third_party/rust/chromium_crates_io/vendor/byteorder-1.5.0/README.md deleted file mode 100644 index 7c46019..0000000 --- a/third_party/rust/chromium_crates_io/vendor/byteorder-1.5.0/README.md +++ /dev/null
@@ -1,77 +0,0 @@ -byteorder -========= -This crate provides convenience methods for encoding and decoding -numbers in either big-endian or little-endian order. - -[](https://github.com/BurntSushi/byteorder/actions) -[](https://crates.io/crates/byteorder) - -Dual-licensed under MIT or the [UNLICENSE](https://unlicense.org/). - - -### Documentation - -https://docs.rs/byteorder - - -### Installation - -This crate works with Cargo and is on -[crates.io](https://crates.io/crates/byteorder). Add it to your `Cargo.toml` -like so: - -```toml -[dependencies] -byteorder = "1" -``` - -If you want to augment existing `Read` and `Write` traits, then import the -extension methods like so: - -```rust -use byteorder::{ReadBytesExt, WriteBytesExt, BigEndian, LittleEndian}; -``` - -For example: - -```rust -use std::io::Cursor; -use byteorder::{BigEndian, ReadBytesExt}; - -let mut rdr = Cursor::new(vec![2, 5, 3, 0]); -// Note that we use type parameters to indicate which kind of byte order -// we want! -assert_eq!(517, rdr.read_u16::<BigEndian>().unwrap()); -assert_eq!(768, rdr.read_u16::<BigEndian>().unwrap()); -``` - -### `no_std` crates - -This crate has a feature, `std`, that is enabled by default. To use this crate -in a `no_std` context, add the following to your `Cargo.toml`: - -```toml -[dependencies] -byteorder = { version = "1", default-features = false } -``` - - -### Minimum Rust version policy - -This crate's minimum supported `rustc` version is `1.60.0`. - -The current policy is that the minimum Rust version required to use this crate -can be increased in minor version updates. For example, if `crate 1.0` requires -Rust 1.20.0, then `crate 1.0.z` for all values of `z` will also require Rust -1.20.0 or newer. However, `crate 1.y` for `y > 0` may require a newer minimum -version of Rust. - -In general, this crate will be conservative with respect to the minimum -supported version of Rust. - - -### Alternatives - -Note that as of Rust 1.32, the standard numeric types provide built-in methods -like `to_le_bytes` and `from_le_bytes`, which support some of the same use -cases.
diff --git a/third_party/rust/chromium_crates_io/vendor/byteorder-1.5.0/UNLICENSE b/third_party/rust/chromium_crates_io/vendor/byteorder-1.5.0/UNLICENSE deleted file mode 100644 index 68a49da..0000000 --- a/third_party/rust/chromium_crates_io/vendor/byteorder-1.5.0/UNLICENSE +++ /dev/null
@@ -1,24 +0,0 @@ -This is free and unencumbered software released into the public domain. - -Anyone is free to copy, modify, publish, use, compile, sell, or -distribute this software, either in source code form or as a compiled -binary, for any purpose, commercial or non-commercial, and by any -means. - -In jurisdictions that recognize copyright laws, the author or authors -of this software dedicate any and all copyright interest in the -software to the public domain. We make this dedication for the benefit -of the public at large and to the detriment of our heirs and -successors. We intend this dedication to be an overt act of -relinquishment in perpetuity of all present and future rights to this -software under copyright law. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR -OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, -ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -OTHER DEALINGS IN THE SOFTWARE. - -For more information, please refer to <http://unlicense.org/>
diff --git a/third_party/rust/chromium_crates_io/vendor/byteorder-1.5.0/benches/bench.rs b/third_party/rust/chromium_crates_io/vendor/byteorder-1.5.0/benches/bench.rs deleted file mode 100644 index 963251ce..0000000 --- a/third_party/rust/chromium_crates_io/vendor/byteorder-1.5.0/benches/bench.rs +++ /dev/null
@@ -1,326 +0,0 @@ -#![feature(test)] - -extern crate test; - -macro_rules! bench_num { - ($name:ident, $read:ident, $bytes:expr, $data:expr) => { - mod $name { - use byteorder::{ - BigEndian, ByteOrder, LittleEndian, NativeEndian, - }; - use test::black_box as bb; - use test::Bencher; - - const NITER: usize = 100_000; - - #[bench] - fn read_big_endian(b: &mut Bencher) { - let buf = $data; - b.iter(|| { - for _ in 0..NITER { - bb(BigEndian::$read(&buf, $bytes)); - } - }); - } - - #[bench] - fn read_little_endian(b: &mut Bencher) { - let buf = $data; - b.iter(|| { - for _ in 0..NITER { - bb(LittleEndian::$read(&buf, $bytes)); - } - }); - } - - #[bench] - fn read_native_endian(b: &mut Bencher) { - let buf = $data; - b.iter(|| { - for _ in 0..NITER { - bb(NativeEndian::$read(&buf, $bytes)); - } - }); - } - } - }; - ($ty:ident, $max:ident, - $read:ident, $write:ident, $size:expr, $data:expr) => { - mod $ty { - use byteorder::{ - BigEndian, ByteOrder, LittleEndian, NativeEndian, - }; - use std::$ty; - use test::black_box as bb; - use test::Bencher; - - const NITER: usize = 100_000; - - #[bench] - fn read_big_endian(b: &mut Bencher) { - let buf = $data; - b.iter(|| { - for _ in 0..NITER { - bb(BigEndian::$read(&buf)); - } - }); - } - - #[bench] - fn read_little_endian(b: &mut Bencher) { - let buf = $data; - b.iter(|| { - for _ in 0..NITER { - bb(LittleEndian::$read(&buf)); - } - }); - } - - #[bench] - fn read_native_endian(b: &mut Bencher) { - let buf = $data; - b.iter(|| { - for _ in 0..NITER { - bb(NativeEndian::$read(&buf)); - } - }); - } - - #[bench] - fn write_big_endian(b: &mut Bencher) { - let mut buf = $data; - let n = $ty::$max; - b.iter(|| { - for _ in 0..NITER { - bb(BigEndian::$write(&mut buf, n)); - } - }); - } - - #[bench] - fn write_little_endian(b: &mut Bencher) { - let mut buf = $data; - let n = $ty::$max; - b.iter(|| { - for _ in 0..NITER { - bb(LittleEndian::$write(&mut buf, n)); - } - }); - } - - #[bench] - fn write_native_endian(b: &mut Bencher) { - let mut buf = $data; - let n = $ty::$max; - b.iter(|| { - for _ in 0..NITER { - bb(NativeEndian::$write(&mut buf, n)); - } - }); - } - } - }; -} - -bench_num!(u16, MAX, read_u16, write_u16, 2, [1, 2]); -bench_num!(i16, MAX, read_i16, write_i16, 2, [1, 2]); -bench_num!(u32, MAX, read_u32, write_u32, 4, [1, 2, 3, 4]); -bench_num!(i32, MAX, read_i32, write_i32, 4, [1, 2, 3, 4]); -bench_num!(u64, MAX, read_u64, write_u64, 8, [1, 2, 3, 4, 5, 6, 7, 8]); -bench_num!(i64, MAX, read_i64, write_i64, 8, [1, 2, 3, 4, 5, 6, 7, 8]); -bench_num!(f32, MAX, read_f32, write_f32, 4, [1, 2, 3, 4]); -bench_num!(f64, MAX, read_f64, write_f64, 8, [1, 2, 3, 4, 5, 6, 7, 8]); - -bench_num!(uint_1, read_uint, 1, [1]); -bench_num!(uint_2, read_uint, 2, [1, 2]); -bench_num!(uint_3, read_uint, 3, [1, 2, 3]); -bench_num!(uint_4, read_uint, 4, [1, 2, 3, 4]); -bench_num!(uint_5, read_uint, 5, [1, 2, 3, 4, 5]); -bench_num!(uint_6, read_uint, 6, [1, 2, 3, 4, 5, 6]); -bench_num!(uint_7, read_uint, 7, [1, 2, 3, 4, 5, 6, 7]); -bench_num!(uint_8, read_uint, 8, [1, 2, 3, 4, 5, 6, 7, 8]); - -bench_num!(int_1, read_int, 1, [1]); -bench_num!(int_2, read_int, 2, [1, 2]); -bench_num!(int_3, read_int, 3, [1, 2, 3]); -bench_num!(int_4, read_int, 4, [1, 2, 3, 4]); -bench_num!(int_5, read_int, 5, [1, 2, 3, 4, 5]); -bench_num!(int_6, read_int, 6, [1, 2, 3, 4, 5, 6]); -bench_num!(int_7, read_int, 7, [1, 2, 3, 4, 5, 6, 7]); -bench_num!(int_8, read_int, 8, [1, 2, 3, 4, 5, 6, 7, 8]); - -bench_num!( - u128, - MAX, - read_u128, - write_u128, - 16, - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] -); -bench_num!( - i128, - MAX, - read_i128, - write_i128, - 16, - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] -); - -bench_num!(uint128_1, read_uint128, 1, [1]); -bench_num!(uint128_2, read_uint128, 2, [1, 2]); -bench_num!(uint128_3, read_uint128, 3, [1, 2, 3]); -bench_num!(uint128_4, read_uint128, 4, [1, 2, 3, 4]); -bench_num!(uint128_5, read_uint128, 5, [1, 2, 3, 4, 5]); -bench_num!(uint128_6, read_uint128, 6, [1, 2, 3, 4, 5, 6]); -bench_num!(uint128_7, read_uint128, 7, [1, 2, 3, 4, 5, 6, 7]); -bench_num!(uint128_8, read_uint128, 8, [1, 2, 3, 4, 5, 6, 7, 8]); -bench_num!(uint128_9, read_uint128, 9, [1, 2, 3, 4, 5, 6, 7, 8, 9]); -bench_num!(uint128_10, read_uint128, 10, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); -bench_num!(uint128_11, read_uint128, 11, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]); -bench_num!( - uint128_12, - read_uint128, - 12, - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] -); -bench_num!( - uint128_13, - read_uint128, - 13, - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] -); -bench_num!( - uint128_14, - read_uint128, - 14, - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] -); -bench_num!( - uint128_15, - read_uint128, - 15, - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] -); -bench_num!( - uint128_16, - read_uint128, - 16, - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] -); - -bench_num!(int128_1, read_int128, 1, [1]); -bench_num!(int128_2, read_int128, 2, [1, 2]); -bench_num!(int128_3, read_int128, 3, [1, 2, 3]); -bench_num!(int128_4, read_int128, 4, [1, 2, 3, 4]); -bench_num!(int128_5, read_int128, 5, [1, 2, 3, 4, 5]); -bench_num!(int128_6, read_int128, 6, [1, 2, 3, 4, 5, 6]); -bench_num!(int128_7, read_int128, 7, [1, 2, 3, 4, 5, 6, 7]); -bench_num!(int128_8, read_int128, 8, [1, 2, 3, 4, 5, 6, 7, 8]); -bench_num!(int128_9, read_int128, 9, [1, 2, 3, 4, 5, 6, 7, 8, 9]); -bench_num!(int128_10, read_int128, 10, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); -bench_num!(int128_11, read_int128, 11, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]); -bench_num!( - int128_12, - read_int128, - 12, - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] -); -bench_num!( - int128_13, - read_int128, - 13, - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] -); -bench_num!( - int128_14, - read_int128, - 14, - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] -); -bench_num!( - int128_15, - read_int128, - 15, - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] -); -bench_num!( - int128_16, - read_int128, - 16, - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] -); - -macro_rules! bench_slice { - ($name:ident, $numty:ty, $read:ident, $write:ident) => { - mod $name { - use std::mem::size_of; - - use byteorder::{BigEndian, ByteOrder, LittleEndian}; - use rand::distributions; - use rand::{self, Rng}; - use test::Bencher; - - #[bench] - fn read_big_endian(b: &mut Bencher) { - let mut numbers: Vec<$numty> = rand::thread_rng() - .sample_iter(&distributions::Standard) - .take(100000) - .collect(); - let mut bytes = vec![0; numbers.len() * size_of::<$numty>()]; - BigEndian::$write(&numbers, &mut bytes); - - b.bytes = bytes.len() as u64; - b.iter(|| { - BigEndian::$read(&bytes, &mut numbers); - }); - } - - #[bench] - fn read_little_endian(b: &mut Bencher) { - let mut numbers: Vec<$numty> = rand::thread_rng() - .sample_iter(&distributions::Standard) - .take(100000) - .collect(); - let mut bytes = vec![0; numbers.len() * size_of::<$numty>()]; - LittleEndian::$write(&numbers, &mut bytes); - - b.bytes = bytes.len() as u64; - b.iter(|| { - LittleEndian::$read(&bytes, &mut numbers); - }); - } - - #[bench] - fn write_big_endian(b: &mut Bencher) { - let numbers: Vec<$numty> = rand::thread_rng() - .sample_iter(&distributions::Standard) - .take(100000) - .collect(); - let mut bytes = vec![0; numbers.len() * size_of::<$numty>()]; - - b.bytes = bytes.len() as u64; - b.iter(|| { - BigEndian::$write(&numbers, &mut bytes); - }); - } - - #[bench] - fn write_little_endian(b: &mut Bencher) { - let numbers: Vec<$numty> = rand::thread_rng() - .sample_iter(&distributions::Standard) - .take(100000) - .collect(); - let mut bytes = vec![0; numbers.len() * size_of::<$numty>()]; - - b.bytes = bytes.len() as u64; - b.iter(|| { - LittleEndian::$write(&numbers, &mut bytes); - }); - } - } - }; -} - -bench_slice!(slice_u16, u16, read_u16_into, write_u16_into); -bench_slice!(slice_u64, u64, read_u64_into, write_u64_into); -bench_slice!(slice_i64, i64, read_i64_into, write_i64_into);
diff --git a/third_party/rust/chromium_crates_io/vendor/byteorder-1.5.0/rustfmt.toml b/third_party/rust/chromium_crates_io/vendor/byteorder-1.5.0/rustfmt.toml deleted file mode 100644 index aa37a218..0000000 --- a/third_party/rust/chromium_crates_io/vendor/byteorder-1.5.0/rustfmt.toml +++ /dev/null
@@ -1,2 +0,0 @@ -max_width = 79 -use_small_heuristics = "max"
diff --git a/third_party/rust/chromium_crates_io/vendor/byteorder-1.5.0/src/io.rs b/third_party/rust/chromium_crates_io/vendor/byteorder-1.5.0/src/io.rs deleted file mode 100644 index dfad2ca..0000000 --- a/third_party/rust/chromium_crates_io/vendor/byteorder-1.5.0/src/io.rs +++ /dev/null
@@ -1,1592 +0,0 @@ -use std::{ - io::{self, Result}, - slice, -}; - -use crate::ByteOrder; - -/// Extends [`Read`] with methods for reading numbers. (For `std::io`.) -/// -/// Most of the methods defined here have an unconstrained type parameter that -/// must be explicitly instantiated. Typically, it is instantiated with either -/// the [`BigEndian`] or [`LittleEndian`] types defined in this crate. -/// -/// # Examples -/// -/// Read unsigned 16 bit big-endian integers from a [`Read`]: -/// -/// ```rust -/// use std::io::Cursor; -/// use byteorder::{BigEndian, ReadBytesExt}; -/// -/// let mut rdr = Cursor::new(vec![2, 5, 3, 0]); -/// assert_eq!(517, rdr.read_u16::<BigEndian>().unwrap()); -/// assert_eq!(768, rdr.read_u16::<BigEndian>().unwrap()); -/// ``` -/// -/// [`BigEndian`]: enum.BigEndian.html -/// [`LittleEndian`]: enum.LittleEndian.html -/// [`Read`]: https://doc.rust-lang.org/std/io/trait.Read.html -pub trait ReadBytesExt: io::Read { - /// Reads an unsigned 8 bit integer from the underlying reader. - /// - /// Note that since this reads a single byte, no byte order conversions - /// are used. It is included for completeness. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read unsigned 8 bit integers from a `Read`: - /// - /// ```rust - /// use std::io::Cursor; - /// use byteorder::ReadBytesExt; - /// - /// let mut rdr = Cursor::new(vec![2, 5]); - /// assert_eq!(2, rdr.read_u8().unwrap()); - /// assert_eq!(5, rdr.read_u8().unwrap()); - /// ``` - #[inline] - fn read_u8(&mut self) -> Result<u8> { - let mut buf = [0; 1]; - self.read_exact(&mut buf)?; - Ok(buf[0]) - } - - /// Reads a signed 8 bit integer from the underlying reader. - /// - /// Note that since this reads a single byte, no byte order conversions - /// are used. It is included for completeness. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read signed 8 bit integers from a `Read`: - /// - /// ```rust - /// use std::io::Cursor; - /// use byteorder::ReadBytesExt; - /// - /// let mut rdr = Cursor::new(vec![0x02, 0xfb]); - /// assert_eq!(2, rdr.read_i8().unwrap()); - /// assert_eq!(-5, rdr.read_i8().unwrap()); - /// ``` - #[inline] - fn read_i8(&mut self) -> Result<i8> { - let mut buf = [0; 1]; - self.read_exact(&mut buf)?; - Ok(buf[0] as i8) - } - - /// Reads an unsigned 16 bit integer from the underlying reader. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read unsigned 16 bit big-endian integers from a `Read`: - /// - /// ```rust - /// use std::io::Cursor; - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![2, 5, 3, 0]); - /// assert_eq!(517, rdr.read_u16::<BigEndian>().unwrap()); - /// assert_eq!(768, rdr.read_u16::<BigEndian>().unwrap()); - /// ``` - #[inline] - fn read_u16<T: ByteOrder>(&mut self) -> Result<u16> { - let mut buf = [0; 2]; - self.read_exact(&mut buf)?; - Ok(T::read_u16(&buf)) - } - - /// Reads a signed 16 bit integer from the underlying reader. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read signed 16 bit big-endian integers from a `Read`: - /// - /// ```rust - /// use std::io::Cursor; - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![0x00, 0xc1, 0xff, 0x7c]); - /// assert_eq!(193, rdr.read_i16::<BigEndian>().unwrap()); - /// assert_eq!(-132, rdr.read_i16::<BigEndian>().unwrap()); - /// ``` - #[inline] - fn read_i16<T: ByteOrder>(&mut self) -> Result<i16> { - let mut buf = [0; 2]; - self.read_exact(&mut buf)?; - Ok(T::read_i16(&buf)) - } - - /// Reads an unsigned 24 bit integer from the underlying reader. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read unsigned 24 bit big-endian integers from a `Read`: - /// - /// ```rust - /// use std::io::Cursor; - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![0x00, 0x01, 0x0b]); - /// assert_eq!(267, rdr.read_u24::<BigEndian>().unwrap()); - /// ``` - #[inline] - fn read_u24<T: ByteOrder>(&mut self) -> Result<u32> { - let mut buf = [0; 3]; - self.read_exact(&mut buf)?; - Ok(T::read_u24(&buf)) - } - - /// Reads a signed 24 bit integer from the underlying reader. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read signed 24 bit big-endian integers from a `Read`: - /// - /// ```rust - /// use std::io::Cursor; - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![0xff, 0x7a, 0x33]); - /// assert_eq!(-34253, rdr.read_i24::<BigEndian>().unwrap()); - /// ``` - #[inline] - fn read_i24<T: ByteOrder>(&mut self) -> Result<i32> { - let mut buf = [0; 3]; - self.read_exact(&mut buf)?; - Ok(T::read_i24(&buf)) - } - - /// Reads an unsigned 32 bit integer from the underlying reader. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read unsigned 32 bit big-endian integers from a `Read`: - /// - /// ```rust - /// use std::io::Cursor; - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![0x00, 0x00, 0x01, 0x0b]); - /// assert_eq!(267, rdr.read_u32::<BigEndian>().unwrap()); - /// ``` - #[inline] - fn read_u32<T: ByteOrder>(&mut self) -> Result<u32> { - let mut buf = [0; 4]; - self.read_exact(&mut buf)?; - Ok(T::read_u32(&buf)) - } - - /// Reads a signed 32 bit integer from the underlying reader. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read signed 32 bit big-endian integers from a `Read`: - /// - /// ```rust - /// use std::io::Cursor; - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![0xff, 0xff, 0x7a, 0x33]); - /// assert_eq!(-34253, rdr.read_i32::<BigEndian>().unwrap()); - /// ``` - #[inline] - fn read_i32<T: ByteOrder>(&mut self) -> Result<i32> { - let mut buf = [0; 4]; - self.read_exact(&mut buf)?; - Ok(T::read_i32(&buf)) - } - - /// Reads an unsigned 48 bit integer from the underlying reader. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read unsigned 48 bit big-endian integers from a `Read`: - /// - /// ```rust - /// use std::io::Cursor; - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![0xb6, 0x71, 0x6b, 0xdc, 0x2b, 0x31]); - /// assert_eq!(200598257150769, rdr.read_u48::<BigEndian>().unwrap()); - /// ``` - #[inline] - fn read_u48<T: ByteOrder>(&mut self) -> Result<u64> { - let mut buf = [0; 6]; - self.read_exact(&mut buf)?; - Ok(T::read_u48(&buf)) - } - - /// Reads a signed 48 bit integer from the underlying reader. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read signed 48 bit big-endian integers from a `Read`: - /// - /// ```rust - /// use std::io::Cursor; - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![0x9d, 0x71, 0xab, 0xe7, 0x97, 0x8f]); - /// assert_eq!(-108363435763825, rdr.read_i48::<BigEndian>().unwrap()); - /// ``` - #[inline] - fn read_i48<T: ByteOrder>(&mut self) -> Result<i64> { - let mut buf = [0; 6]; - self.read_exact(&mut buf)?; - Ok(T::read_i48(&buf)) - } - - /// Reads an unsigned 64 bit integer from the underlying reader. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read an unsigned 64 bit big-endian integer from a `Read`: - /// - /// ```rust - /// use std::io::Cursor; - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![0x00, 0x03, 0x43, 0x95, 0x4d, 0x60, 0x86, 0x83]); - /// assert_eq!(918733457491587, rdr.read_u64::<BigEndian>().unwrap()); - /// ``` - #[inline] - fn read_u64<T: ByteOrder>(&mut self) -> Result<u64> { - let mut buf = [0; 8]; - self.read_exact(&mut buf)?; - Ok(T::read_u64(&buf)) - } - - /// Reads a signed 64 bit integer from the underlying reader. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read a signed 64 bit big-endian integer from a `Read`: - /// - /// ```rust - /// use std::io::Cursor; - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![0x80, 0, 0, 0, 0, 0, 0, 0]); - /// assert_eq!(i64::min_value(), rdr.read_i64::<BigEndian>().unwrap()); - /// ``` - #[inline] - fn read_i64<T: ByteOrder>(&mut self) -> Result<i64> { - let mut buf = [0; 8]; - self.read_exact(&mut buf)?; - Ok(T::read_i64(&buf)) - } - - /// Reads an unsigned 128 bit integer from the underlying reader. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read an unsigned 128 bit big-endian integer from a `Read`: - /// - /// ```rust - /// use std::io::Cursor; - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![ - /// 0x00, 0x03, 0x43, 0x95, 0x4d, 0x60, 0x86, 0x83, - /// 0x00, 0x03, 0x43, 0x95, 0x4d, 0x60, 0x86, 0x83 - /// ]); - /// assert_eq!(16947640962301618749969007319746179, rdr.read_u128::<BigEndian>().unwrap()); - /// ``` - #[inline] - fn read_u128<T: ByteOrder>(&mut self) -> Result<u128> { - let mut buf = [0; 16]; - self.read_exact(&mut buf)?; - Ok(T::read_u128(&buf)) - } - - /// Reads a signed 128 bit integer from the underlying reader. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read a signed 128 bit big-endian integer from a `Read`: - /// - /// ```rust - /// use std::io::Cursor; - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); - /// assert_eq!(i128::min_value(), rdr.read_i128::<BigEndian>().unwrap()); - /// ``` - #[inline] - fn read_i128<T: ByteOrder>(&mut self) -> Result<i128> { - let mut buf = [0; 16]; - self.read_exact(&mut buf)?; - Ok(T::read_i128(&buf)) - } - - /// Reads an unsigned n-bytes integer from the underlying reader. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read an unsigned n-byte big-endian integer from a `Read`: - /// - /// ```rust - /// use std::io::Cursor; - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![0x80, 0x74, 0xfa]); - /// assert_eq!(8418554, rdr.read_uint::<BigEndian>(3).unwrap()); - #[inline] - fn read_uint<T: ByteOrder>(&mut self, nbytes: usize) -> Result<u64> { - let mut buf = [0; 8]; - self.read_exact(&mut buf[..nbytes])?; - Ok(T::read_uint(&buf[..nbytes], nbytes)) - } - - /// Reads a signed n-bytes integer from the underlying reader. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read an unsigned n-byte big-endian integer from a `Read`: - /// - /// ```rust - /// use std::io::Cursor; - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![0xc1, 0xff, 0x7c]); - /// assert_eq!(-4063364, rdr.read_int::<BigEndian>(3).unwrap()); - #[inline] - fn read_int<T: ByteOrder>(&mut self, nbytes: usize) -> Result<i64> { - let mut buf = [0; 8]; - self.read_exact(&mut buf[..nbytes])?; - Ok(T::read_int(&buf[..nbytes], nbytes)) - } - - /// Reads an unsigned n-bytes integer from the underlying reader. - #[inline] - fn read_uint128<T: ByteOrder>(&mut self, nbytes: usize) -> Result<u128> { - let mut buf = [0; 16]; - self.read_exact(&mut buf[..nbytes])?; - Ok(T::read_uint128(&buf[..nbytes], nbytes)) - } - - /// Reads a signed n-bytes integer from the underlying reader. - #[inline] - fn read_int128<T: ByteOrder>(&mut self, nbytes: usize) -> Result<i128> { - let mut buf = [0; 16]; - self.read_exact(&mut buf[..nbytes])?; - Ok(T::read_int128(&buf[..nbytes], nbytes)) - } - - /// Reads a IEEE754 single-precision (4 bytes) floating point number from - /// the underlying reader. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read a big-endian single-precision floating point number from a `Read`: - /// - /// ```rust - /// use std::f32; - /// use std::io::Cursor; - /// - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![ - /// 0x40, 0x49, 0x0f, 0xdb, - /// ]); - /// assert_eq!(f32::consts::PI, rdr.read_f32::<BigEndian>().unwrap()); - /// ``` - #[inline] - fn read_f32<T: ByteOrder>(&mut self) -> Result<f32> { - let mut buf = [0; 4]; - self.read_exact(&mut buf)?; - Ok(T::read_f32(&buf)) - } - - /// Reads a IEEE754 double-precision (8 bytes) floating point number from - /// the underlying reader. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read a big-endian double-precision floating point number from a `Read`: - /// - /// ```rust - /// use std::f64; - /// use std::io::Cursor; - /// - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![ - /// 0x40, 0x09, 0x21, 0xfb, 0x54, 0x44, 0x2d, 0x18, - /// ]); - /// assert_eq!(f64::consts::PI, rdr.read_f64::<BigEndian>().unwrap()); - /// ``` - #[inline] - fn read_f64<T: ByteOrder>(&mut self) -> Result<f64> { - let mut buf = [0; 8]; - self.read_exact(&mut buf)?; - Ok(T::read_f64(&buf)) - } - - /// Reads a sequence of unsigned 16 bit integers from the underlying - /// reader. - /// - /// The given buffer is either filled completely or an error is returned. - /// If an error is returned, the contents of `dst` are unspecified. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read a sequence of unsigned 16 bit big-endian integers from a `Read`: - /// - /// ```rust - /// use std::io::Cursor; - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![2, 5, 3, 0]); - /// let mut dst = [0; 2]; - /// rdr.read_u16_into::<BigEndian>(&mut dst).unwrap(); - /// assert_eq!([517, 768], dst); - /// ``` - #[inline] - fn read_u16_into<T: ByteOrder>(&mut self, dst: &mut [u16]) -> Result<()> { - { - let buf = unsafe { slice_to_u8_mut(dst) }; - self.read_exact(buf)?; - } - T::from_slice_u16(dst); - Ok(()) - } - - /// Reads a sequence of unsigned 32 bit integers from the underlying - /// reader. - /// - /// The given buffer is either filled completely or an error is returned. - /// If an error is returned, the contents of `dst` are unspecified. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read a sequence of unsigned 32 bit big-endian integers from a `Read`: - /// - /// ```rust - /// use std::io::Cursor; - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![0, 0, 2, 5, 0, 0, 3, 0]); - /// let mut dst = [0; 2]; - /// rdr.read_u32_into::<BigEndian>(&mut dst).unwrap(); - /// assert_eq!([517, 768], dst); - /// ``` - #[inline] - fn read_u32_into<T: ByteOrder>(&mut self, dst: &mut [u32]) -> Result<()> { - { - let buf = unsafe { slice_to_u8_mut(dst) }; - self.read_exact(buf)?; - } - T::from_slice_u32(dst); - Ok(()) - } - - /// Reads a sequence of unsigned 64 bit integers from the underlying - /// reader. - /// - /// The given buffer is either filled completely or an error is returned. - /// If an error is returned, the contents of `dst` are unspecified. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read a sequence of unsigned 64 bit big-endian integers from a `Read`: - /// - /// ```rust - /// use std::io::Cursor; - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![ - /// 0, 0, 0, 0, 0, 0, 2, 5, - /// 0, 0, 0, 0, 0, 0, 3, 0, - /// ]); - /// let mut dst = [0; 2]; - /// rdr.read_u64_into::<BigEndian>(&mut dst).unwrap(); - /// assert_eq!([517, 768], dst); - /// ``` - #[inline] - fn read_u64_into<T: ByteOrder>(&mut self, dst: &mut [u64]) -> Result<()> { - { - let buf = unsafe { slice_to_u8_mut(dst) }; - self.read_exact(buf)?; - } - T::from_slice_u64(dst); - Ok(()) - } - - /// Reads a sequence of unsigned 128 bit integers from the underlying - /// reader. - /// - /// The given buffer is either filled completely or an error is returned. - /// If an error is returned, the contents of `dst` are unspecified. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read a sequence of unsigned 128 bit big-endian integers from a `Read`: - /// - /// ```rust - /// use std::io::Cursor; - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![ - /// 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 5, - /// 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, - /// ]); - /// let mut dst = [0; 2]; - /// rdr.read_u128_into::<BigEndian>(&mut dst).unwrap(); - /// assert_eq!([517, 768], dst); - /// ``` - #[inline] - fn read_u128_into<T: ByteOrder>( - &mut self, - dst: &mut [u128], - ) -> Result<()> { - { - let buf = unsafe { slice_to_u8_mut(dst) }; - self.read_exact(buf)?; - } - T::from_slice_u128(dst); - Ok(()) - } - - /// Reads a sequence of signed 8 bit integers from the underlying reader. - /// - /// The given buffer is either filled completely or an error is returned. - /// If an error is returned, the contents of `dst` are unspecified. - /// - /// Note that since each `i8` is a single byte, no byte order conversions - /// are used. This method is included because it provides a safe, simple - /// way for the caller to read into a `&mut [i8]` buffer. (Without this - /// method, the caller would have to either use `unsafe` code or convert - /// each byte to `i8` individually.) - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read a sequence of signed 8 bit integers from a `Read`: - /// - /// ```rust - /// use std::io::Cursor; - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![2, 251, 3]); - /// let mut dst = [0; 3]; - /// rdr.read_i8_into(&mut dst).unwrap(); - /// assert_eq!([2, -5, 3], dst); - /// ``` - #[inline] - fn read_i8_into(&mut self, dst: &mut [i8]) -> Result<()> { - let buf = unsafe { slice_to_u8_mut(dst) }; - self.read_exact(buf) - } - - /// Reads a sequence of signed 16 bit integers from the underlying - /// reader. - /// - /// The given buffer is either filled completely or an error is returned. - /// If an error is returned, the contents of `dst` are unspecified. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read a sequence of signed 16 bit big-endian integers from a `Read`: - /// - /// ```rust - /// use std::io::Cursor; - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![2, 5, 3, 0]); - /// let mut dst = [0; 2]; - /// rdr.read_i16_into::<BigEndian>(&mut dst).unwrap(); - /// assert_eq!([517, 768], dst); - /// ``` - #[inline] - fn read_i16_into<T: ByteOrder>(&mut self, dst: &mut [i16]) -> Result<()> { - { - let buf = unsafe { slice_to_u8_mut(dst) }; - self.read_exact(buf)?; - } - T::from_slice_i16(dst); - Ok(()) - } - - /// Reads a sequence of signed 32 bit integers from the underlying - /// reader. - /// - /// The given buffer is either filled completely or an error is returned. - /// If an error is returned, the contents of `dst` are unspecified. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read a sequence of signed 32 bit big-endian integers from a `Read`: - /// - /// ```rust - /// use std::io::Cursor; - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![0, 0, 2, 5, 0, 0, 3, 0]); - /// let mut dst = [0; 2]; - /// rdr.read_i32_into::<BigEndian>(&mut dst).unwrap(); - /// assert_eq!([517, 768], dst); - /// ``` - #[inline] - fn read_i32_into<T: ByteOrder>(&mut self, dst: &mut [i32]) -> Result<()> { - { - let buf = unsafe { slice_to_u8_mut(dst) }; - self.read_exact(buf)?; - } - T::from_slice_i32(dst); - Ok(()) - } - - /// Reads a sequence of signed 64 bit integers from the underlying - /// reader. - /// - /// The given buffer is either filled completely or an error is returned. - /// If an error is returned, the contents of `dst` are unspecified. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read a sequence of signed 64 bit big-endian integers from a `Read`: - /// - /// ```rust - /// use std::io::Cursor; - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![ - /// 0, 0, 0, 0, 0, 0, 2, 5, - /// 0, 0, 0, 0, 0, 0, 3, 0, - /// ]); - /// let mut dst = [0; 2]; - /// rdr.read_i64_into::<BigEndian>(&mut dst).unwrap(); - /// assert_eq!([517, 768], dst); - /// ``` - #[inline] - fn read_i64_into<T: ByteOrder>(&mut self, dst: &mut [i64]) -> Result<()> { - { - let buf = unsafe { slice_to_u8_mut(dst) }; - self.read_exact(buf)?; - } - T::from_slice_i64(dst); - Ok(()) - } - - /// Reads a sequence of signed 128 bit integers from the underlying - /// reader. - /// - /// The given buffer is either filled completely or an error is returned. - /// If an error is returned, the contents of `dst` are unspecified. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read a sequence of signed 128 bit big-endian integers from a `Read`: - /// - /// ```rust - /// use std::io::Cursor; - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![ - /// 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 5, - /// 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, - /// ]); - /// let mut dst = [0; 2]; - /// rdr.read_i128_into::<BigEndian>(&mut dst).unwrap(); - /// assert_eq!([517, 768], dst); - /// ``` - #[inline] - fn read_i128_into<T: ByteOrder>( - &mut self, - dst: &mut [i128], - ) -> Result<()> { - { - let buf = unsafe { slice_to_u8_mut(dst) }; - self.read_exact(buf)?; - } - T::from_slice_i128(dst); - Ok(()) - } - - /// Reads a sequence of IEEE754 single-precision (4 bytes) floating - /// point numbers from the underlying reader. - /// - /// The given buffer is either filled completely or an error is returned. - /// If an error is returned, the contents of `dst` are unspecified. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read a sequence of big-endian single-precision floating point number - /// from a `Read`: - /// - /// ```rust - /// use std::f32; - /// use std::io::Cursor; - /// - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![ - /// 0x40, 0x49, 0x0f, 0xdb, - /// 0x3f, 0x80, 0x00, 0x00, - /// ]); - /// let mut dst = [0.0; 2]; - /// rdr.read_f32_into::<BigEndian>(&mut dst).unwrap(); - /// assert_eq!([f32::consts::PI, 1.0], dst); - /// ``` - #[inline] - fn read_f32_into<T: ByteOrder>(&mut self, dst: &mut [f32]) -> Result<()> { - { - let buf = unsafe { slice_to_u8_mut(dst) }; - self.read_exact(buf)?; - } - T::from_slice_f32(dst); - Ok(()) - } - - /// **DEPRECATED**. - /// - /// This method is deprecated. Use `read_f32_into` instead. - /// - /// Reads a sequence of IEEE754 single-precision (4 bytes) floating - /// point numbers from the underlying reader. - /// - /// The given buffer is either filled completely or an error is returned. - /// If an error is returned, the contents of `dst` are unspecified. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read a sequence of big-endian single-precision floating point number - /// from a `Read`: - /// - /// ```rust - /// use std::f32; - /// use std::io::Cursor; - /// - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![ - /// 0x40, 0x49, 0x0f, 0xdb, - /// 0x3f, 0x80, 0x00, 0x00, - /// ]); - /// let mut dst = [0.0; 2]; - /// rdr.read_f32_into_unchecked::<BigEndian>(&mut dst).unwrap(); - /// assert_eq!([f32::consts::PI, 1.0], dst); - /// ``` - #[inline] - #[deprecated(since = "1.2.0", note = "please use `read_f32_into` instead")] - fn read_f32_into_unchecked<T: ByteOrder>( - &mut self, - dst: &mut [f32], - ) -> Result<()> { - self.read_f32_into::<T>(dst) - } - - /// Reads a sequence of IEEE754 double-precision (8 bytes) floating - /// point numbers from the underlying reader. - /// - /// The given buffer is either filled completely or an error is returned. - /// If an error is returned, the contents of `dst` are unspecified. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read a sequence of big-endian single-precision floating point number - /// from a `Read`: - /// - /// ```rust - /// use std::f64; - /// use std::io::Cursor; - /// - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![ - /// 0x40, 0x09, 0x21, 0xfb, 0x54, 0x44, 0x2d, 0x18, - /// 0x3f, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - /// ]); - /// let mut dst = [0.0; 2]; - /// rdr.read_f64_into::<BigEndian>(&mut dst).unwrap(); - /// assert_eq!([f64::consts::PI, 1.0], dst); - /// ``` - #[inline] - fn read_f64_into<T: ByteOrder>(&mut self, dst: &mut [f64]) -> Result<()> { - { - let buf = unsafe { slice_to_u8_mut(dst) }; - self.read_exact(buf)?; - } - T::from_slice_f64(dst); - Ok(()) - } - - /// **DEPRECATED**. - /// - /// This method is deprecated. Use `read_f64_into` instead. - /// - /// Reads a sequence of IEEE754 double-precision (8 bytes) floating - /// point numbers from the underlying reader. - /// - /// The given buffer is either filled completely or an error is returned. - /// If an error is returned, the contents of `dst` are unspecified. - /// - /// # Safety - /// - /// This method is unsafe because there are no guarantees made about the - /// floating point values. In particular, this method does not check for - /// signaling NaNs, which may result in undefined behavior. - /// - /// # Errors - /// - /// This method returns the same errors as [`Read::read_exact`]. - /// - /// [`Read::read_exact`]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact - /// - /// # Examples - /// - /// Read a sequence of big-endian single-precision floating point number - /// from a `Read`: - /// - /// ```rust - /// use std::f64; - /// use std::io::Cursor; - /// - /// use byteorder::{BigEndian, ReadBytesExt}; - /// - /// let mut rdr = Cursor::new(vec![ - /// 0x40, 0x09, 0x21, 0xfb, 0x54, 0x44, 0x2d, 0x18, - /// 0x3f, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - /// ]); - /// let mut dst = [0.0; 2]; - /// rdr.read_f64_into_unchecked::<BigEndian>(&mut dst).unwrap(); - /// assert_eq!([f64::consts::PI, 1.0], dst); - /// ``` - #[inline] - #[deprecated(since = "1.2.0", note = "please use `read_f64_into` instead")] - fn read_f64_into_unchecked<T: ByteOrder>( - &mut self, - dst: &mut [f64], - ) -> Result<()> { - self.read_f64_into::<T>(dst) - } -} - -/// All types that implement `Read` get methods defined in `ReadBytesExt` -/// for free. -impl<R: io::Read + ?Sized> ReadBytesExt for R {} - -/// Extends [`Write`] with methods for writing numbers. (For `std::io`.) -/// -/// Most of the methods defined here have an unconstrained type parameter that -/// must be explicitly instantiated. Typically, it is instantiated with either -/// the [`BigEndian`] or [`LittleEndian`] types defined in this crate. -/// -/// # Examples -/// -/// Write unsigned 16 bit big-endian integers to a [`Write`]: -/// -/// ```rust -/// use byteorder::{BigEndian, WriteBytesExt}; -/// -/// let mut wtr = vec![]; -/// wtr.write_u16::<BigEndian>(517).unwrap(); -/// wtr.write_u16::<BigEndian>(768).unwrap(); -/// assert_eq!(wtr, vec![2, 5, 3, 0]); -/// ``` -/// -/// [`BigEndian`]: enum.BigEndian.html -/// [`LittleEndian`]: enum.LittleEndian.html -/// [`Write`]: https://doc.rust-lang.org/std/io/trait.Write.html -pub trait WriteBytesExt: io::Write { - /// Writes an unsigned 8 bit integer to the underlying writer. - /// - /// Note that since this writes a single byte, no byte order conversions - /// are used. It is included for completeness. - /// - /// # Errors - /// - /// This method returns the same errors as [`Write::write_all`]. - /// - /// [`Write::write_all`]: https://doc.rust-lang.org/std/io/trait.Write.html#method.write_all - /// - /// # Examples - /// - /// Write unsigned 8 bit integers to a `Write`: - /// - /// ```rust - /// use byteorder::WriteBytesExt; - /// - /// let mut wtr = Vec::new(); - /// wtr.write_u8(2).unwrap(); - /// wtr.write_u8(5).unwrap(); - /// assert_eq!(wtr, b"\x02\x05"); - /// ``` - #[inline] - fn write_u8(&mut self, n: u8) -> Result<()> { - self.write_all(&[n]) - } - - /// Writes a signed 8 bit integer to the underlying writer. - /// - /// Note that since this writes a single byte, no byte order conversions - /// are used. It is included for completeness. - /// - /// # Errors - /// - /// This method returns the same errors as [`Write::write_all`]. - /// - /// [`Write::write_all`]: https://doc.rust-lang.org/std/io/trait.Write.html#method.write_all - /// - /// # Examples - /// - /// Write signed 8 bit integers to a `Write`: - /// - /// ```rust - /// use byteorder::WriteBytesExt; - /// - /// let mut wtr = Vec::new(); - /// wtr.write_i8(2).unwrap(); - /// wtr.write_i8(-5).unwrap(); - /// assert_eq!(wtr, b"\x02\xfb"); - /// ``` - #[inline] - fn write_i8(&mut self, n: i8) -> Result<()> { - self.write_all(&[n as u8]) - } - - /// Writes an unsigned 16 bit integer to the underlying writer. - /// - /// # Errors - /// - /// This method returns the same errors as [`Write::write_all`]. - /// - /// [`Write::write_all`]: https://doc.rust-lang.org/std/io/trait.Write.html#method.write_all - /// - /// # Examples - /// - /// Write unsigned 16 bit big-endian integers to a `Write`: - /// - /// ```rust - /// use byteorder::{BigEndian, WriteBytesExt}; - /// - /// let mut wtr = Vec::new(); - /// wtr.write_u16::<BigEndian>(517).unwrap(); - /// wtr.write_u16::<BigEndian>(768).unwrap(); - /// assert_eq!(wtr, b"\x02\x05\x03\x00"); - /// ``` - #[inline] - fn write_u16<T: ByteOrder>(&mut self, n: u16) -> Result<()> { - let mut buf = [0; 2]; - T::write_u16(&mut buf, n); - self.write_all(&buf) - } - - /// Writes a signed 16 bit integer to the underlying writer. - /// - /// # Errors - /// - /// This method returns the same errors as [`Write::write_all`]. - /// - /// [`Write::write_all`]: https://doc.rust-lang.org/std/io/trait.Write.html#method.write_all - /// - /// # Examples - /// - /// Write signed 16 bit big-endian integers to a `Write`: - /// - /// ```rust - /// use byteorder::{BigEndian, WriteBytesExt}; - /// - /// let mut wtr = Vec::new(); - /// wtr.write_i16::<BigEndian>(193).unwrap(); - /// wtr.write_i16::<BigEndian>(-132).unwrap(); - /// assert_eq!(wtr, b"\x00\xc1\xff\x7c"); - /// ``` - #[inline] - fn write_i16<T: ByteOrder>(&mut self, n: i16) -> Result<()> { - let mut buf = [0; 2]; - T::write_i16(&mut buf, n); - self.write_all(&buf) - } - - /// Writes an unsigned 24 bit integer to the underlying writer. - /// - /// # Errors - /// - /// This method returns the same errors as [`Write::write_all`]. - /// - /// [`Write::write_all`]: https://doc.rust-lang.org/std/io/trait.Write.html#method.write_all - /// - /// # Examples - /// - /// Write unsigned 24 bit big-endian integers to a `Write`: - /// - /// ```rust - /// use byteorder::{BigEndian, WriteBytesExt}; - /// - /// let mut wtr = Vec::new(); - /// wtr.write_u24::<BigEndian>(267).unwrap(); - /// wtr.write_u24::<BigEndian>(120111).unwrap(); - /// assert_eq!(wtr, b"\x00\x01\x0b\x01\xd5\x2f"); - /// ``` - #[inline] - fn write_u24<T: ByteOrder>(&mut self, n: u32) -> Result<()> { - let mut buf = [0; 3]; - T::write_u24(&mut buf, n); - self.write_all(&buf) - } - - /// Writes a signed 24 bit integer to the underlying writer. - /// - /// # Errors - /// - /// This method returns the same errors as [`Write::write_all`]. - /// - /// [`Write::write_all`]: https://doc.rust-lang.org/std/io/trait.Write.html#method.write_all - /// - /// # Examples - /// - /// Write signed 24 bit big-endian integers to a `Write`: - /// - /// ```rust - /// use byteorder::{BigEndian, WriteBytesExt}; - /// - /// let mut wtr = Vec::new(); - /// wtr.write_i24::<BigEndian>(-34253).unwrap(); - /// wtr.write_i24::<BigEndian>(120111).unwrap(); - /// assert_eq!(wtr, b"\xff\x7a\x33\x01\xd5\x2f"); - /// ``` - #[inline] - fn write_i24<T: ByteOrder>(&mut self, n: i32) -> Result<()> { - let mut buf = [0; 3]; - T::write_i24(&mut buf, n); - self.write_all(&buf) - } - - /// Writes an unsigned 32 bit integer to the underlying writer. - /// - /// # Errors - /// - /// This method returns the same errors as [`Write::write_all`]. - /// - /// [`Write::write_all`]: https://doc.rust-lang.org/std/io/trait.Write.html#method.write_all - /// - /// # Examples - /// - /// Write unsigned 32 bit big-endian integers to a `Write`: - /// - /// ```rust - /// use byteorder::{BigEndian, WriteBytesExt}; - /// - /// let mut wtr = Vec::new(); - /// wtr.write_u32::<BigEndian>(267).unwrap(); - /// wtr.write_u32::<BigEndian>(1205419366).unwrap(); - /// assert_eq!(wtr, b"\x00\x00\x01\x0b\x47\xd9\x3d\x66"); - /// ``` - #[inline] - fn write_u32<T: ByteOrder>(&mut self, n: u32) -> Result<()> { - let mut buf = [0; 4]; - T::write_u32(&mut buf, n); - self.write_all(&buf) - } - - /// Writes a signed 32 bit integer to the underlying writer. - /// - /// # Errors - /// - /// This method returns the same errors as [`Write::write_all`]. - /// - /// [`Write::write_all`]: https://doc.rust-lang.org/std/io/trait.Write.html#method.write_all - /// - /// # Examples - /// - /// Write signed 32 bit big-endian integers to a `Write`: - /// - /// ```rust - /// use byteorder::{BigEndian, WriteBytesExt}; - /// - /// let mut wtr = Vec::new(); - /// wtr.write_i32::<BigEndian>(-34253).unwrap(); - /// wtr.write_i32::<BigEndian>(1205419366).unwrap(); - /// assert_eq!(wtr, b"\xff\xff\x7a\x33\x47\xd9\x3d\x66"); - /// ``` - #[inline] - fn write_i32<T: ByteOrder>(&mut self, n: i32) -> Result<()> { - let mut buf = [0; 4]; - T::write_i32(&mut buf, n); - self.write_all(&buf) - } - - /// Writes an unsigned 48 bit integer to the underlying writer. - /// - /// # Errors - /// - /// This method returns the same errors as [`Write::write_all`]. - /// - /// [`Write::write_all`]: https://doc.rust-lang.org/std/io/trait.Write.html#method.write_all - /// - /// # Examples - /// - /// Write unsigned 48 bit big-endian integers to a `Write`: - /// - /// ```rust - /// use byteorder::{BigEndian, WriteBytesExt}; - /// - /// let mut wtr = Vec::new(); - /// wtr.write_u48::<BigEndian>(52360336390828).unwrap(); - /// wtr.write_u48::<BigEndian>(541).unwrap(); - /// assert_eq!(wtr, b"\x2f\x9f\x17\x40\x3a\xac\x00\x00\x00\x00\x02\x1d"); - /// ``` - #[inline] - fn write_u48<T: ByteOrder>(&mut self, n: u64) -> Result<()> { - let mut buf = [0; 6]; - T::write_u48(&mut buf, n); - self.write_all(&buf) - } - - /// Writes a signed 48 bit integer to the underlying writer. - /// - /// # Errors - /// - /// This method returns the same errors as [`Write::write_all`]. - /// - /// [`Write::write_all`]: https://doc.rust-lang.org/std/io/trait.Write.html#method.write_all - /// - /// # Examples - /// - /// Write signed 48 bit big-endian integers to a `Write`: - /// - /// ```rust - /// use byteorder::{BigEndian, WriteBytesExt}; - /// - /// let mut wtr = Vec::new(); - /// wtr.write_i48::<BigEndian>(-108363435763825).unwrap(); - /// wtr.write_i48::<BigEndian>(77).unwrap(); - /// assert_eq!(wtr, b"\x9d\x71\xab\xe7\x97\x8f\x00\x00\x00\x00\x00\x4d"); - /// ``` - #[inline] - fn write_i48<T: ByteOrder>(&mut self, n: i64) -> Result<()> { - let mut buf = [0; 6]; - T::write_i48(&mut buf, n); - self.write_all(&buf) - } - - /// Writes an unsigned 64 bit integer to the underlying writer. - /// - /// # Errors - /// - /// This method returns the same errors as [`Write::write_all`]. - /// - /// [`Write::write_all`]: https://doc.rust-lang.org/std/io/trait.Write.html#method.write_all - /// - /// # Examples - /// - /// Write unsigned 64 bit big-endian integers to a `Write`: - /// - /// ```rust - /// use byteorder::{BigEndian, WriteBytesExt}; - /// - /// let mut wtr = Vec::new(); - /// wtr.write_u64::<BigEndian>(918733457491587).unwrap(); - /// wtr.write_u64::<BigEndian>(143).unwrap(); - /// assert_eq!(wtr, b"\x00\x03\x43\x95\x4d\x60\x86\x83\x00\x00\x00\x00\x00\x00\x00\x8f"); - /// ``` - #[inline] - fn write_u64<T: ByteOrder>(&mut self, n: u64) -> Result<()> { - let mut buf = [0; 8]; - T::write_u64(&mut buf, n); - self.write_all(&buf) - } - - /// Writes a signed 64 bit integer to the underlying writer. - /// - /// # Errors - /// - /// This method returns the same errors as [`Write::write_all`]. - /// - /// [`Write::write_all`]: https://doc.rust-lang.org/std/io/trait.Write.html#method.write_all - /// - /// # Examples - /// - /// Write signed 64 bit big-endian integers to a `Write`: - /// - /// ```rust - /// use byteorder::{BigEndian, WriteBytesExt}; - /// - /// let mut wtr = Vec::new(); - /// wtr.write_i64::<BigEndian>(i64::min_value()).unwrap(); - /// wtr.write_i64::<BigEndian>(i64::max_value()).unwrap(); - /// assert_eq!(wtr, b"\x80\x00\x00\x00\x00\x00\x00\x00\x7f\xff\xff\xff\xff\xff\xff\xff"); - /// ``` - #[inline] - fn write_i64<T: ByteOrder>(&mut self, n: i64) -> Result<()> { - let mut buf = [0; 8]; - T::write_i64(&mut buf, n); - self.write_all(&buf) - } - - /// Writes an unsigned 128 bit integer to the underlying writer. - #[inline] - fn write_u128<T: ByteOrder>(&mut self, n: u128) -> Result<()> { - let mut buf = [0; 16]; - T::write_u128(&mut buf, n); - self.write_all(&buf) - } - - /// Writes a signed 128 bit integer to the underlying writer. - #[inline] - fn write_i128<T: ByteOrder>(&mut self, n: i128) -> Result<()> { - let mut buf = [0; 16]; - T::write_i128(&mut buf, n); - self.write_all(&buf) - } - - /// Writes an unsigned n-bytes integer to the underlying writer. - /// - /// # Errors - /// - /// This method returns the same errors as [`Write::write_all`]. - /// - /// [`Write::write_all`]: https://doc.rust-lang.org/std/io/trait.Write.html#method.write_all - /// - /// # Panics - /// - /// If the given integer is not representable in the given number of bytes, - /// this method panics. If `nbytes > 8`, this method panics. - /// - /// # Examples - /// - /// Write unsigned 40 bit big-endian integers to a `Write`: - /// - /// ```rust - /// use byteorder::{BigEndian, WriteBytesExt}; - /// - /// let mut wtr = Vec::new(); - /// wtr.write_uint::<BigEndian>(312550384361, 5).unwrap(); - /// wtr.write_uint::<BigEndian>(43, 5).unwrap(); - /// assert_eq!(wtr, b"\x48\xc5\x74\x62\xe9\x00\x00\x00\x00\x2b"); - /// ``` - #[inline] - fn write_uint<T: ByteOrder>( - &mut self, - n: u64, - nbytes: usize, - ) -> Result<()> { - let mut buf = [0; 8]; - T::write_uint(&mut buf, n, nbytes); - self.write_all(&buf[0..nbytes]) - } - - /// Writes a signed n-bytes integer to the underlying writer. - /// - /// # Errors - /// - /// This method returns the same errors as [`Write::write_all`]. - /// - /// [`Write::write_all`]: https://doc.rust-lang.org/std/io/trait.Write.html#method.write_all - /// - /// # Panics - /// - /// If the given integer is not representable in the given number of bytes, - /// this method panics. If `nbytes > 8`, this method panics. - /// - /// # Examples - /// - /// Write signed 56 bit big-endian integers to a `Write`: - /// - /// ```rust - /// use byteorder::{BigEndian, WriteBytesExt}; - /// - /// let mut wtr = Vec::new(); - /// wtr.write_int::<BigEndian>(-3548172039376767, 7).unwrap(); - /// wtr.write_int::<BigEndian>(43, 7).unwrap(); - /// assert_eq!(wtr, b"\xf3\x64\xf4\xd1\xfd\xb0\x81\x00\x00\x00\x00\x00\x00\x2b"); - /// ``` - #[inline] - fn write_int<T: ByteOrder>( - &mut self, - n: i64, - nbytes: usize, - ) -> Result<()> { - let mut buf = [0; 8]; - T::write_int(&mut buf, n, nbytes); - self.write_all(&buf[0..nbytes]) - } - - /// Writes an unsigned n-bytes integer to the underlying writer. - /// - /// If the given integer is not representable in the given number of bytes, - /// this method panics. If `nbytes > 16`, this method panics. - #[inline] - fn write_uint128<T: ByteOrder>( - &mut self, - n: u128, - nbytes: usize, - ) -> Result<()> { - let mut buf = [0; 16]; - T::write_uint128(&mut buf, n, nbytes); - self.write_all(&buf[0..nbytes]) - } - - /// Writes a signed n-bytes integer to the underlying writer. - /// - /// If the given integer is not representable in the given number of bytes, - /// this method panics. If `nbytes > 16`, this method panics. - #[inline] - fn write_int128<T: ByteOrder>( - &mut self, - n: i128, - nbytes: usize, - ) -> Result<()> { - let mut buf = [0; 16]; - T::write_int128(&mut buf, n, nbytes); - self.write_all(&buf[0..nbytes]) - } - - /// Writes a IEEE754 single-precision (4 bytes) floating point number to - /// the underlying writer. - /// - /// # Errors - /// - /// This method returns the same errors as [`Write::write_all`]. - /// - /// [`Write::write_all`]: https://doc.rust-lang.org/std/io/trait.Write.html#method.write_all - /// - /// # Examples - /// - /// Write a big-endian single-precision floating point number to a `Write`: - /// - /// ```rust - /// use std::f32; - /// - /// use byteorder::{BigEndian, WriteBytesExt}; - /// - /// let mut wtr = Vec::new(); - /// wtr.write_f32::<BigEndian>(f32::consts::PI).unwrap(); - /// assert_eq!(wtr, b"\x40\x49\x0f\xdb"); - /// ``` - #[inline] - fn write_f32<T: ByteOrder>(&mut self, n: f32) -> Result<()> { - let mut buf = [0; 4]; - T::write_f32(&mut buf, n); - self.write_all(&buf) - } - - /// Writes a IEEE754 double-precision (8 bytes) floating point number to - /// the underlying writer. - /// - /// # Errors - /// - /// This method returns the same errors as [`Write::write_all`]. - /// - /// [`Write::write_all`]: https://doc.rust-lang.org/std/io/trait.Write.html#method.write_all - /// - /// # Examples - /// - /// Write a big-endian double-precision floating point number to a `Write`: - /// - /// ```rust - /// use std::f64; - /// - /// use byteorder::{BigEndian, WriteBytesExt}; - /// - /// let mut wtr = Vec::new(); - /// wtr.write_f64::<BigEndian>(f64::consts::PI).unwrap(); - /// assert_eq!(wtr, b"\x40\x09\x21\xfb\x54\x44\x2d\x18"); - /// ``` - #[inline] - fn write_f64<T: ByteOrder>(&mut self, n: f64) -> Result<()> { - let mut buf = [0; 8]; - T::write_f64(&mut buf, n); - self.write_all(&buf) - } -} - -/// All types that implement `Write` get methods defined in `WriteBytesExt` -/// for free. -impl<W: io::Write + ?Sized> WriteBytesExt for W {} - -/// Convert a slice of T (where T is plain old data) to its mutable binary -/// representation. -/// -/// This function is wildly unsafe because it permits arbitrary modification of -/// the binary representation of any `Copy` type. Use with care. It's intended -/// to be called only where `T` is a numeric type. -unsafe fn slice_to_u8_mut<T: Copy>(slice: &mut [T]) -> &mut [u8] { - use std::mem::size_of; - - let len = size_of::<T>() * slice.len(); - slice::from_raw_parts_mut(slice.as_mut_ptr() as *mut u8, len) -}
diff --git a/third_party/rust/chromium_crates_io/vendor/byteorder-1.5.0/src/lib.rs b/third_party/rust/chromium_crates_io/vendor/byteorder-1.5.0/src/lib.rs deleted file mode 100644 index cfd53c3..0000000 --- a/third_party/rust/chromium_crates_io/vendor/byteorder-1.5.0/src/lib.rs +++ /dev/null
@@ -1,3975 +0,0 @@ -/*! -This crate provides convenience methods for encoding and decoding numbers in -either [big-endian or little-endian order]. - -The organization of the crate is pretty simple. A trait, [`ByteOrder`], specifies -byte conversion methods for each type of number in Rust (sans numbers that have -a platform dependent size like `usize` and `isize`). Two types, [`BigEndian`] -and [`LittleEndian`] implement these methods. Finally, [`ReadBytesExt`] and -[`WriteBytesExt`] provide convenience methods available to all types that -implement [`Read`] and [`Write`]. - -An alias, [`NetworkEndian`], for [`BigEndian`] is provided to help improve -code clarity. - -An additional alias, [`NativeEndian`], is provided for the endianness of the -local platform. This is convenient when serializing data for use and -conversions are not desired. - -# Examples - -Read unsigned 16 bit big-endian integers from a [`Read`] type: - -```rust -use std::io::Cursor; -use byteorder::{BigEndian, ReadBytesExt}; - -let mut rdr = Cursor::new(vec![2, 5, 3, 0]); -// Note that we use type parameters to indicate which kind of byte order -// we want! -assert_eq!(517, rdr.read_u16::<BigEndian>().unwrap()); -assert_eq!(768, rdr.read_u16::<BigEndian>().unwrap()); -``` - -Write unsigned 16 bit little-endian integers to a [`Write`] type: - -```rust -use byteorder::{LittleEndian, WriteBytesExt}; - -let mut wtr = vec![]; -wtr.write_u16::<LittleEndian>(517).unwrap(); -wtr.write_u16::<LittleEndian>(768).unwrap(); -assert_eq!(wtr, vec![5, 2, 0, 3]); -``` - -# Optional Features - -This crate optionally provides support for 128 bit values (`i128` and `u128`) -when built with the `i128` feature enabled. - -This crate can also be used without the standard library. - -# Alternatives - -Note that as of Rust 1.32, the standard numeric types provide built-in methods -like `to_le_bytes` and `from_le_bytes`, which support some of the same use -cases. - -[big-endian or little-endian order]: https://en.wikipedia.org/wiki/Endianness -[`ByteOrder`]: trait.ByteOrder.html -[`BigEndian`]: enum.BigEndian.html -[`LittleEndian`]: enum.LittleEndian.html -[`ReadBytesExt`]: trait.ReadBytesExt.html -[`WriteBytesExt`]: trait.WriteBytesExt.html -[`NetworkEndian`]: type.NetworkEndian.html -[`NativeEndian`]: type.NativeEndian.html -[`Read`]: https://doc.rust-lang.org/std/io/trait.Read.html -[`Write`]: https://doc.rust-lang.org/std/io/trait.Write.html -*/ - -#![deny(missing_docs)] -#![cfg_attr(not(feature = "std"), no_std)] -// When testing under miri, we disable tests that take too long. But this -// provokes lots of dead code warnings. So we just squash them. -#![cfg_attr(miri, allow(dead_code, unused_macros))] - -use core::{ - convert::TryInto, fmt::Debug, hash::Hash, mem::align_of, - ptr::copy_nonoverlapping, slice, -}; - -#[cfg(feature = "std")] -pub use crate::io::{ReadBytesExt, WriteBytesExt}; - -#[cfg(feature = "std")] -mod io; - -#[inline] -fn extend_sign(val: u64, nbytes: usize) -> i64 { - let shift = (8 - nbytes) * 8; - (val << shift) as i64 >> shift -} - -#[inline] -fn extend_sign128(val: u128, nbytes: usize) -> i128 { - let shift = (16 - nbytes) * 8; - (val << shift) as i128 >> shift -} - -#[inline] -fn unextend_sign(val: i64, nbytes: usize) -> u64 { - let shift = (8 - nbytes) * 8; - (val << shift) as u64 >> shift -} - -#[inline] -fn unextend_sign128(val: i128, nbytes: usize) -> u128 { - let shift = (16 - nbytes) * 8; - (val << shift) as u128 >> shift -} - -#[inline] -fn pack_size(n: u64) -> usize { - if n < 1 << 8 { - 1 - } else if n < 1 << 16 { - 2 - } else if n < 1 << 24 { - 3 - } else if n < 1 << 32 { - 4 - } else if n < 1 << 40 { - 5 - } else if n < 1 << 48 { - 6 - } else if n < 1 << 56 { - 7 - } else { - 8 - } -} - -#[inline] -fn pack_size128(n: u128) -> usize { - if n < 1 << 8 { - 1 - } else if n < 1 << 16 { - 2 - } else if n < 1 << 24 { - 3 - } else if n < 1 << 32 { - 4 - } else if n < 1 << 40 { - 5 - } else if n < 1 << 48 { - 6 - } else if n < 1 << 56 { - 7 - } else if n < 1 << 64 { - 8 - } else if n < 1 << 72 { - 9 - } else if n < 1 << 80 { - 10 - } else if n < 1 << 88 { - 11 - } else if n < 1 << 96 { - 12 - } else if n < 1 << 104 { - 13 - } else if n < 1 << 112 { - 14 - } else if n < 1 << 120 { - 15 - } else { - 16 - } -} - -mod private { - /// Sealed stops crates other than byteorder from implementing any traits - /// that use it. - pub trait Sealed {} - impl Sealed for super::LittleEndian {} - impl Sealed for super::BigEndian {} -} - -/// `ByteOrder` describes types that can serialize integers as bytes. -/// -/// Note that `Self` does not appear anywhere in this trait's definition! -/// Therefore, in order to use it, you'll need to use syntax like -/// `T::read_u16(&[0, 1])` where `T` implements `ByteOrder`. -/// -/// This crate provides two types that implement `ByteOrder`: [`BigEndian`] -/// and [`LittleEndian`]. -/// This trait is sealed and cannot be implemented for callers to avoid -/// breaking backwards compatibility when adding new derived traits. -/// -/// # Examples -/// -/// Write and read `u32` numbers in little endian order: -/// -/// ```rust -/// use byteorder::{ByteOrder, LittleEndian}; -/// -/// let mut buf = [0; 4]; -/// LittleEndian::write_u32(&mut buf, 1_000_000); -/// assert_eq!(1_000_000, LittleEndian::read_u32(&buf)); -/// ``` -/// -/// Write and read `i16` numbers in big endian order: -/// -/// ```rust -/// use byteorder::{ByteOrder, BigEndian}; -/// -/// let mut buf = [0; 2]; -/// BigEndian::write_i16(&mut buf, -5_000); -/// assert_eq!(-5_000, BigEndian::read_i16(&buf)); -/// ``` -/// -/// [`BigEndian`]: enum.BigEndian.html -/// [`LittleEndian`]: enum.LittleEndian.html -pub trait ByteOrder: - Clone - + Copy - + Debug - + Default - + Eq - + Hash - + Ord - + PartialEq - + PartialOrd - + private::Sealed -{ - /// Reads an unsigned 16 bit integer from `buf`. - /// - /// # Panics - /// - /// Panics when `buf.len() < 2`. - fn read_u16(buf: &[u8]) -> u16; - - /// Reads an unsigned 24 bit integer from `buf`, stored in u32. - /// - /// # Panics - /// - /// Panics when `buf.len() < 3`. - /// - /// # Examples - /// - /// Write and read 24 bit `u32` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 3]; - /// LittleEndian::write_u24(&mut buf, 1_000_000); - /// assert_eq!(1_000_000, LittleEndian::read_u24(&buf)); - /// ``` - fn read_u24(buf: &[u8]) -> u32 { - Self::read_uint(buf, 3) as u32 - } - - /// Reads an unsigned 32 bit integer from `buf`. - /// - /// # Panics - /// - /// Panics when `buf.len() < 4`. - /// - /// # Examples - /// - /// Write and read `u32` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 4]; - /// LittleEndian::write_u32(&mut buf, 1_000_000); - /// assert_eq!(1_000_000, LittleEndian::read_u32(&buf)); - /// ``` - fn read_u32(buf: &[u8]) -> u32; - - /// Reads an unsigned 48 bit integer from `buf`, stored in u64. - /// - /// # Panics - /// - /// Panics when `buf.len() < 6`. - /// - /// # Examples - /// - /// Write and read 48 bit `u64` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 6]; - /// LittleEndian::write_u48(&mut buf, 1_000_000_000_000); - /// assert_eq!(1_000_000_000_000, LittleEndian::read_u48(&buf)); - /// ``` - fn read_u48(buf: &[u8]) -> u64 { - Self::read_uint(buf, 6) as u64 - } - - /// Reads an unsigned 64 bit integer from `buf`. - /// - /// # Panics - /// - /// Panics when `buf.len() < 8`. - /// - /// # Examples - /// - /// Write and read `u64` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 8]; - /// LittleEndian::write_u64(&mut buf, 1_000_000); - /// assert_eq!(1_000_000, LittleEndian::read_u64(&buf)); - /// ``` - fn read_u64(buf: &[u8]) -> u64; - - /// Reads an unsigned 128 bit integer from `buf`. - /// - /// # Panics - /// - /// Panics when `buf.len() < 16`. - /// - /// # Examples - /// - /// Write and read `u128` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 16]; - /// LittleEndian::write_u128(&mut buf, 1_000_000); - /// assert_eq!(1_000_000, LittleEndian::read_u128(&buf)); - /// ``` - fn read_u128(buf: &[u8]) -> u128; - - /// Reads an unsigned n-bytes integer from `buf`. - /// - /// # Panics - /// - /// Panics when `nbytes < 1` or `nbytes > 8` or - /// `buf.len() < nbytes` - /// - /// # Examples - /// - /// Write and read an n-byte number in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 3]; - /// LittleEndian::write_uint(&mut buf, 1_000_000, 3); - /// assert_eq!(1_000_000, LittleEndian::read_uint(&buf, 3)); - /// ``` - fn read_uint(buf: &[u8], nbytes: usize) -> u64; - - /// Reads an unsigned n-bytes integer from `buf`. - /// - /// # Panics - /// - /// Panics when `nbytes < 1` or `nbytes > 16` or - /// `buf.len() < nbytes` - /// - /// # Examples - /// - /// Write and read an n-byte number in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 3]; - /// LittleEndian::write_uint128(&mut buf, 1_000_000, 3); - /// assert_eq!(1_000_000, LittleEndian::read_uint128(&buf, 3)); - /// ``` - fn read_uint128(buf: &[u8], nbytes: usize) -> u128; - - /// Writes an unsigned 16 bit integer `n` to `buf`. - /// - /// # Panics - /// - /// Panics when `buf.len() < 2`. - /// - /// # Examples - /// - /// Write and read `u16` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 2]; - /// LittleEndian::write_u16(&mut buf, 1_000); - /// assert_eq!(1_000, LittleEndian::read_u16(&buf)); - /// ``` - fn write_u16(buf: &mut [u8], n: u16); - - /// Writes an unsigned 24 bit integer `n` to `buf`, stored in u32. - /// - /// # Panics - /// - /// Panics when `buf.len() < 3`. - /// - /// # Examples - /// - /// Write and read 24 bit `u32` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 3]; - /// LittleEndian::write_u24(&mut buf, 1_000_000); - /// assert_eq!(1_000_000, LittleEndian::read_u24(&buf)); - /// ``` - fn write_u24(buf: &mut [u8], n: u32) { - Self::write_uint(buf, n as u64, 3) - } - - /// Writes an unsigned 32 bit integer `n` to `buf`. - /// - /// # Panics - /// - /// Panics when `buf.len() < 4`. - /// - /// # Examples - /// - /// Write and read `u32` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 4]; - /// LittleEndian::write_u32(&mut buf, 1_000_000); - /// assert_eq!(1_000_000, LittleEndian::read_u32(&buf)); - /// ``` - fn write_u32(buf: &mut [u8], n: u32); - - /// Writes an unsigned 48 bit integer `n` to `buf`, stored in u64. - /// - /// # Panics - /// - /// Panics when `buf.len() < 6`. - /// - /// # Examples - /// - /// Write and read 48 bit `u64` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 6]; - /// LittleEndian::write_u48(&mut buf, 1_000_000_000_000); - /// assert_eq!(1_000_000_000_000, LittleEndian::read_u48(&buf)); - /// ``` - fn write_u48(buf: &mut [u8], n: u64) { - Self::write_uint(buf, n as u64, 6) - } - - /// Writes an unsigned 64 bit integer `n` to `buf`. - /// - /// # Panics - /// - /// Panics when `buf.len() < 8`. - /// - /// # Examples - /// - /// Write and read `u64` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 8]; - /// LittleEndian::write_u64(&mut buf, 1_000_000); - /// assert_eq!(1_000_000, LittleEndian::read_u64(&buf)); - /// ``` - fn write_u64(buf: &mut [u8], n: u64); - - /// Writes an unsigned 128 bit integer `n` to `buf`. - /// - /// # Panics - /// - /// Panics when `buf.len() < 16`. - /// - /// # Examples - /// - /// Write and read `u128` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 16]; - /// LittleEndian::write_u128(&mut buf, 1_000_000); - /// assert_eq!(1_000_000, LittleEndian::read_u128(&buf)); - /// ``` - fn write_u128(buf: &mut [u8], n: u128); - - /// Writes an unsigned integer `n` to `buf` using only `nbytes`. - /// - /// # Panics - /// - /// If `n` is not representable in `nbytes`, or if `nbytes` is `> 8`, then - /// this method panics. - /// - /// # Examples - /// - /// Write and read an n-byte number in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 3]; - /// LittleEndian::write_uint(&mut buf, 1_000_000, 3); - /// assert_eq!(1_000_000, LittleEndian::read_uint(&buf, 3)); - /// ``` - fn write_uint(buf: &mut [u8], n: u64, nbytes: usize); - - /// Writes an unsigned integer `n` to `buf` using only `nbytes`. - /// - /// # Panics - /// - /// If `n` is not representable in `nbytes`, or if `nbytes` is `> 16`, then - /// this method panics. - /// - /// # Examples - /// - /// Write and read an n-byte number in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 3]; - /// LittleEndian::write_uint128(&mut buf, 1_000_000, 3); - /// assert_eq!(1_000_000, LittleEndian::read_uint128(&buf, 3)); - /// ``` - fn write_uint128(buf: &mut [u8], n: u128, nbytes: usize); - - /// Reads a signed 16 bit integer from `buf`. - /// - /// # Panics - /// - /// Panics when `buf.len() < 2`. - /// - /// # Examples - /// - /// Write and read `i16` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 2]; - /// LittleEndian::write_i16(&mut buf, -1_000); - /// assert_eq!(-1_000, LittleEndian::read_i16(&buf)); - /// ``` - #[inline] - fn read_i16(buf: &[u8]) -> i16 { - Self::read_u16(buf) as i16 - } - - /// Reads a signed 24 bit integer from `buf`, stored in i32. - /// - /// # Panics - /// - /// Panics when `buf.len() < 3`. - /// - /// # Examples - /// - /// Write and read 24 bit `i32` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 3]; - /// LittleEndian::write_i24(&mut buf, -1_000_000); - /// assert_eq!(-1_000_000, LittleEndian::read_i24(&buf)); - /// ``` - #[inline] - fn read_i24(buf: &[u8]) -> i32 { - Self::read_int(buf, 3) as i32 - } - - /// Reads a signed 32 bit integer from `buf`. - /// - /// # Panics - /// - /// Panics when `buf.len() < 4`. - /// - /// # Examples - /// - /// Write and read `i32` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 4]; - /// LittleEndian::write_i32(&mut buf, -1_000_000); - /// assert_eq!(-1_000_000, LittleEndian::read_i32(&buf)); - /// ``` - #[inline] - fn read_i32(buf: &[u8]) -> i32 { - Self::read_u32(buf) as i32 - } - - /// Reads a signed 48 bit integer from `buf`, stored in i64. - /// - /// # Panics - /// - /// Panics when `buf.len() < 6`. - /// - /// # Examples - /// - /// Write and read 48 bit `i64` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 6]; - /// LittleEndian::write_i48(&mut buf, -1_000_000_000_000); - /// assert_eq!(-1_000_000_000_000, LittleEndian::read_i48(&buf)); - /// ``` - #[inline] - fn read_i48(buf: &[u8]) -> i64 { - Self::read_int(buf, 6) as i64 - } - - /// Reads a signed 64 bit integer from `buf`. - /// - /// # Panics - /// - /// Panics when `buf.len() < 8`. - /// - /// # Examples - /// - /// Write and read `i64` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 8]; - /// LittleEndian::write_i64(&mut buf, -1_000_000_000); - /// assert_eq!(-1_000_000_000, LittleEndian::read_i64(&buf)); - /// ``` - #[inline] - fn read_i64(buf: &[u8]) -> i64 { - Self::read_u64(buf) as i64 - } - - /// Reads a signed 128 bit integer from `buf`. - /// - /// # Panics - /// - /// Panics when `buf.len() < 16`. - /// - /// # Examples - /// - /// Write and read `i128` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 16]; - /// LittleEndian::write_i128(&mut buf, -1_000_000_000); - /// assert_eq!(-1_000_000_000, LittleEndian::read_i128(&buf)); - /// ``` - #[inline] - fn read_i128(buf: &[u8]) -> i128 { - Self::read_u128(buf) as i128 - } - - /// Reads a signed n-bytes integer from `buf`. - /// - /// # Panics - /// - /// Panics when `nbytes < 1` or `nbytes > 8` or - /// `buf.len() < nbytes` - /// - /// # Examples - /// - /// Write and read n-length signed numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 3]; - /// LittleEndian::write_int(&mut buf, -1_000, 3); - /// assert_eq!(-1_000, LittleEndian::read_int(&buf, 3)); - /// ``` - #[inline] - fn read_int(buf: &[u8], nbytes: usize) -> i64 { - extend_sign(Self::read_uint(buf, nbytes), nbytes) - } - - /// Reads a signed n-bytes integer from `buf`. - /// - /// # Panics - /// - /// Panics when `nbytes < 1` or `nbytes > 16` or - /// `buf.len() < nbytes` - /// - /// # Examples - /// - /// Write and read n-length signed numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 3]; - /// LittleEndian::write_int128(&mut buf, -1_000, 3); - /// assert_eq!(-1_000, LittleEndian::read_int128(&buf, 3)); - /// ``` - #[inline] - fn read_int128(buf: &[u8], nbytes: usize) -> i128 { - extend_sign128(Self::read_uint128(buf, nbytes), nbytes) - } - - /// Reads a IEEE754 single-precision (4 bytes) floating point number. - /// - /// # Panics - /// - /// Panics when `buf.len() < 4`. - /// - /// # Examples - /// - /// Write and read `f32` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let e = 2.71828; - /// let mut buf = [0; 4]; - /// LittleEndian::write_f32(&mut buf, e); - /// assert_eq!(e, LittleEndian::read_f32(&buf)); - /// ``` - #[inline] - fn read_f32(buf: &[u8]) -> f32 { - f32::from_bits(Self::read_u32(buf)) - } - - /// Reads a IEEE754 double-precision (8 bytes) floating point number. - /// - /// # Panics - /// - /// Panics when `buf.len() < 8`. - /// - /// # Examples - /// - /// Write and read `f64` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let phi = 1.6180339887; - /// let mut buf = [0; 8]; - /// LittleEndian::write_f64(&mut buf, phi); - /// assert_eq!(phi, LittleEndian::read_f64(&buf)); - /// ``` - #[inline] - fn read_f64(buf: &[u8]) -> f64 { - f64::from_bits(Self::read_u64(buf)) - } - - /// Writes a signed 16 bit integer `n` to `buf`. - /// - /// # Panics - /// - /// Panics when `buf.len() < 2`. - /// - /// # Examples - /// - /// Write and read `i16` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 2]; - /// LittleEndian::write_i16(&mut buf, -1_000); - /// assert_eq!(-1_000, LittleEndian::read_i16(&buf)); - /// ``` - #[inline] - fn write_i16(buf: &mut [u8], n: i16) { - Self::write_u16(buf, n as u16) - } - - /// Writes a signed 24 bit integer `n` to `buf`, stored in i32. - /// - /// # Panics - /// - /// Panics when `buf.len() < 3`. - /// - /// # Examples - /// - /// Write and read 24 bit `i32` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 3]; - /// LittleEndian::write_i24(&mut buf, -1_000_000); - /// assert_eq!(-1_000_000, LittleEndian::read_i24(&buf)); - /// ``` - #[inline] - fn write_i24(buf: &mut [u8], n: i32) { - Self::write_int(buf, n as i64, 3) - } - - /// Writes a signed 32 bit integer `n` to `buf`. - /// - /// # Panics - /// - /// Panics when `buf.len() < 4`. - /// - /// # Examples - /// - /// Write and read `i32` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 4]; - /// LittleEndian::write_i32(&mut buf, -1_000_000); - /// assert_eq!(-1_000_000, LittleEndian::read_i32(&buf)); - /// ``` - #[inline] - fn write_i32(buf: &mut [u8], n: i32) { - Self::write_u32(buf, n as u32) - } - - /// Writes a signed 48 bit integer `n` to `buf`, stored in i64. - /// - /// # Panics - /// - /// Panics when `buf.len() < 6`. - /// - /// # Examples - /// - /// Write and read 48 bit `i64` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 6]; - /// LittleEndian::write_i48(&mut buf, -1_000_000_000_000); - /// assert_eq!(-1_000_000_000_000, LittleEndian::read_i48(&buf)); - /// ``` - #[inline] - fn write_i48(buf: &mut [u8], n: i64) { - Self::write_int(buf, n as i64, 6) - } - - /// Writes a signed 64 bit integer `n` to `buf`. - /// - /// # Panics - /// - /// Panics when `buf.len() < 8`. - /// - /// # Examples - /// - /// Write and read `i64` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 8]; - /// LittleEndian::write_i64(&mut buf, -1_000_000_000); - /// assert_eq!(-1_000_000_000, LittleEndian::read_i64(&buf)); - /// ``` - #[inline] - fn write_i64(buf: &mut [u8], n: i64) { - Self::write_u64(buf, n as u64) - } - - /// Writes a signed 128 bit integer `n` to `buf`. - /// - /// # Panics - /// - /// Panics when `buf.len() < 16`. - /// - /// # Examples - /// - /// Write and read n-byte `i128` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 16]; - /// LittleEndian::write_i128(&mut buf, -1_000_000_000); - /// assert_eq!(-1_000_000_000, LittleEndian::read_i128(&buf)); - /// ``` - #[inline] - fn write_i128(buf: &mut [u8], n: i128) { - Self::write_u128(buf, n as u128) - } - - /// Writes a signed integer `n` to `buf` using only `nbytes`. - /// - /// # Panics - /// - /// If `n` is not representable in `nbytes`, or if `nbytes` is `> 8`, then - /// this method panics. - /// - /// # Examples - /// - /// Write and read an n-byte number in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 3]; - /// LittleEndian::write_int(&mut buf, -1_000, 3); - /// assert_eq!(-1_000, LittleEndian::read_int(&buf, 3)); - /// ``` - #[inline] - fn write_int(buf: &mut [u8], n: i64, nbytes: usize) { - Self::write_uint(buf, unextend_sign(n, nbytes), nbytes) - } - - /// Writes a signed integer `n` to `buf` using only `nbytes`. - /// - /// # Panics - /// - /// If `n` is not representable in `nbytes`, or if `nbytes` is `> 16`, then - /// this method panics. - /// - /// # Examples - /// - /// Write and read n-length signed numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut buf = [0; 3]; - /// LittleEndian::write_int128(&mut buf, -1_000, 3); - /// assert_eq!(-1_000, LittleEndian::read_int128(&buf, 3)); - /// ``` - #[inline] - fn write_int128(buf: &mut [u8], n: i128, nbytes: usize) { - Self::write_uint128(buf, unextend_sign128(n, nbytes), nbytes) - } - - /// Writes a IEEE754 single-precision (4 bytes) floating point number. - /// - /// # Panics - /// - /// Panics when `buf.len() < 4`. - /// - /// # Examples - /// - /// Write and read `f32` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let e = 2.71828; - /// let mut buf = [0; 4]; - /// LittleEndian::write_f32(&mut buf, e); - /// assert_eq!(e, LittleEndian::read_f32(&buf)); - /// ``` - #[inline] - fn write_f32(buf: &mut [u8], n: f32) { - Self::write_u32(buf, n.to_bits()) - } - - /// Writes a IEEE754 double-precision (8 bytes) floating point number. - /// - /// # Panics - /// - /// Panics when `buf.len() < 8`. - /// - /// # Examples - /// - /// Write and read `f64` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let phi = 1.6180339887; - /// let mut buf = [0; 8]; - /// LittleEndian::write_f64(&mut buf, phi); - /// assert_eq!(phi, LittleEndian::read_f64(&buf)); - /// ``` - #[inline] - fn write_f64(buf: &mut [u8], n: f64) { - Self::write_u64(buf, n.to_bits()) - } - - /// Reads unsigned 16 bit integers from `src` into `dst`. - /// - /// # Panics - /// - /// Panics when `src.len() != 2*dst.len()`. - /// - /// # Examples - /// - /// Write and read `u16` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut bytes = [0; 8]; - /// let numbers_given = [1, 2, 0xf00f, 0xffee]; - /// LittleEndian::write_u16_into(&numbers_given, &mut bytes); - /// - /// let mut numbers_got = [0; 4]; - /// LittleEndian::read_u16_into(&bytes, &mut numbers_got); - /// assert_eq!(numbers_given, numbers_got); - /// ``` - fn read_u16_into(src: &[u8], dst: &mut [u16]); - - /// Reads unsigned 32 bit integers from `src` into `dst`. - /// - /// # Panics - /// - /// Panics when `src.len() != 4*dst.len()`. - /// - /// # Examples - /// - /// Write and read `u32` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut bytes = [0; 16]; - /// let numbers_given = [1, 2, 0xf00f, 0xffee]; - /// LittleEndian::write_u32_into(&numbers_given, &mut bytes); - /// - /// let mut numbers_got = [0; 4]; - /// LittleEndian::read_u32_into(&bytes, &mut numbers_got); - /// assert_eq!(numbers_given, numbers_got); - /// ``` - fn read_u32_into(src: &[u8], dst: &mut [u32]); - - /// Reads unsigned 64 bit integers from `src` into `dst`. - /// - /// # Panics - /// - /// Panics when `src.len() != 8*dst.len()`. - /// - /// # Examples - /// - /// Write and read `u64` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut bytes = [0; 32]; - /// let numbers_given = [1, 2, 0xf00f, 0xffee]; - /// LittleEndian::write_u64_into(&numbers_given, &mut bytes); - /// - /// let mut numbers_got = [0; 4]; - /// LittleEndian::read_u64_into(&bytes, &mut numbers_got); - /// assert_eq!(numbers_given, numbers_got); - /// ``` - fn read_u64_into(src: &[u8], dst: &mut [u64]); - - /// Reads unsigned 128 bit integers from `src` into `dst`. - /// - /// # Panics - /// - /// Panics when `src.len() != 16*dst.len()`. - /// - /// # Examples - /// - /// Write and read `u128` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut bytes = [0; 64]; - /// let numbers_given = [1, 2, 0xf00f, 0xffee]; - /// LittleEndian::write_u128_into(&numbers_given, &mut bytes); - /// - /// let mut numbers_got = [0; 4]; - /// LittleEndian::read_u128_into(&bytes, &mut numbers_got); - /// assert_eq!(numbers_given, numbers_got); - /// ``` - fn read_u128_into(src: &[u8], dst: &mut [u128]); - - /// Reads signed 16 bit integers from `src` to `dst`. - /// - /// # Panics - /// - /// Panics when `buf.len() != 2*dst.len()`. - /// - /// # Examples - /// - /// Write and read `i16` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut bytes = [0; 8]; - /// let numbers_given = [1, 2, 0x0f, 0xee]; - /// LittleEndian::write_i16_into(&numbers_given, &mut bytes); - /// - /// let mut numbers_got = [0; 4]; - /// LittleEndian::read_i16_into(&bytes, &mut numbers_got); - /// assert_eq!(numbers_given, numbers_got); - /// ``` - #[inline] - fn read_i16_into(src: &[u8], dst: &mut [i16]) { - let dst = unsafe { - slice::from_raw_parts_mut(dst.as_mut_ptr() as *mut u16, dst.len()) - }; - Self::read_u16_into(src, dst) - } - - /// Reads signed 32 bit integers from `src` into `dst`. - /// - /// # Panics - /// - /// Panics when `src.len() != 4*dst.len()`. - /// - /// # Examples - /// - /// Write and read `i32` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut bytes = [0; 16]; - /// let numbers_given = [1, 2, 0xf00f, 0xffee]; - /// LittleEndian::write_i32_into(&numbers_given, &mut bytes); - /// - /// let mut numbers_got = [0; 4]; - /// LittleEndian::read_i32_into(&bytes, &mut numbers_got); - /// assert_eq!(numbers_given, numbers_got); - /// ``` - #[inline] - fn read_i32_into(src: &[u8], dst: &mut [i32]) { - let dst = unsafe { - slice::from_raw_parts_mut(dst.as_mut_ptr() as *mut u32, dst.len()) - }; - Self::read_u32_into(src, dst); - } - - /// Reads signed 64 bit integers from `src` into `dst`. - /// - /// # Panics - /// - /// Panics when `src.len() != 8*dst.len()`. - /// - /// # Examples - /// - /// Write and read `i64` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut bytes = [0; 32]; - /// let numbers_given = [1, 2, 0xf00f, 0xffee]; - /// LittleEndian::write_i64_into(&numbers_given, &mut bytes); - /// - /// let mut numbers_got = [0; 4]; - /// LittleEndian::read_i64_into(&bytes, &mut numbers_got); - /// assert_eq!(numbers_given, numbers_got); - /// ``` - #[inline] - fn read_i64_into(src: &[u8], dst: &mut [i64]) { - let dst = unsafe { - slice::from_raw_parts_mut(dst.as_mut_ptr() as *mut u64, dst.len()) - }; - Self::read_u64_into(src, dst); - } - - /// Reads signed 128 bit integers from `src` into `dst`. - /// - /// # Panics - /// - /// Panics when `src.len() != 16*dst.len()`. - /// - /// # Examples - /// - /// Write and read `i128` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut bytes = [0; 64]; - /// let numbers_given = [1, 2, 0xf00f, 0xffee]; - /// LittleEndian::write_i128_into(&numbers_given, &mut bytes); - /// - /// let mut numbers_got = [0; 4]; - /// LittleEndian::read_i128_into(&bytes, &mut numbers_got); - /// assert_eq!(numbers_given, numbers_got); - /// ``` - #[inline] - fn read_i128_into(src: &[u8], dst: &mut [i128]) { - let dst = unsafe { - slice::from_raw_parts_mut(dst.as_mut_ptr() as *mut u128, dst.len()) - }; - Self::read_u128_into(src, dst); - } - - /// Reads IEEE754 single-precision (4 bytes) floating point numbers from - /// `src` into `dst`. - /// - /// # Panics - /// - /// Panics when `src.len() != 4*dst.len()`. - /// - /// # Examples - /// - /// Write and read `f32` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut bytes = [0; 16]; - /// let numbers_given = [1.0, 2.0, 31.312e31, -11.32e19]; - /// LittleEndian::write_f32_into(&numbers_given, &mut bytes); - /// - /// let mut numbers_got = [0.0; 4]; - /// LittleEndian::read_f32_into(&bytes, &mut numbers_got); - /// assert_eq!(numbers_given, numbers_got); - /// ``` - #[inline] - fn read_f32_into(src: &[u8], dst: &mut [f32]) { - let dst = unsafe { - const _: () = assert!(align_of::<u32>() <= align_of::<f32>()); - slice::from_raw_parts_mut(dst.as_mut_ptr() as *mut u32, dst.len()) - }; - Self::read_u32_into(src, dst); - } - - /// **DEPRECATED**. - /// - /// This method is deprecated. Use `read_f32_into` instead. - /// Reads IEEE754 single-precision (4 bytes) floating point numbers from - /// `src` into `dst`. - /// - /// # Panics - /// - /// Panics when `src.len() != 4*dst.len()`. - /// - /// # Examples - /// - /// Write and read `f32` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut bytes = [0; 16]; - /// let numbers_given = [1.0, 2.0, 31.312e31, -11.32e19]; - /// LittleEndian::write_f32_into(&numbers_given, &mut bytes); - /// - /// let mut numbers_got = [0.0; 4]; - /// LittleEndian::read_f32_into_unchecked(&bytes, &mut numbers_got); - /// assert_eq!(numbers_given, numbers_got); - /// ``` - #[inline] - #[deprecated(since = "1.3.0", note = "please use `read_f32_into` instead")] - fn read_f32_into_unchecked(src: &[u8], dst: &mut [f32]) { - Self::read_f32_into(src, dst); - } - - /// Reads IEEE754 single-precision (4 bytes) floating point numbers from - /// `src` into `dst`. - /// - /// # Panics - /// - /// Panics when `src.len() != 8*dst.len()`. - /// - /// # Examples - /// - /// Write and read `f64` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut bytes = [0; 32]; - /// let numbers_given = [1.0, 2.0, 31.312e211, -11.32e91]; - /// LittleEndian::write_f64_into(&numbers_given, &mut bytes); - /// - /// let mut numbers_got = [0.0; 4]; - /// LittleEndian::read_f64_into(&bytes, &mut numbers_got); - /// assert_eq!(numbers_given, numbers_got); - /// ``` - #[inline] - fn read_f64_into(src: &[u8], dst: &mut [f64]) { - let dst = unsafe { - const _: () = assert!(align_of::<u64>() <= align_of::<f64>()); - slice::from_raw_parts_mut(dst.as_mut_ptr() as *mut u64, dst.len()) - }; - Self::read_u64_into(src, dst); - } - - /// **DEPRECATED**. - /// - /// This method is deprecated. Use `read_f64_into` instead. - /// - /// Reads IEEE754 single-precision (4 bytes) floating point numbers from - /// `src` into `dst`. - /// - /// # Panics - /// - /// Panics when `src.len() != 8*dst.len()`. - /// - /// # Examples - /// - /// Write and read `f64` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut bytes = [0; 32]; - /// let numbers_given = [1.0, 2.0, 31.312e211, -11.32e91]; - /// LittleEndian::write_f64_into(&numbers_given, &mut bytes); - /// - /// let mut numbers_got = [0.0; 4]; - /// LittleEndian::read_f64_into_unchecked(&bytes, &mut numbers_got); - /// assert_eq!(numbers_given, numbers_got); - /// ``` - #[inline] - #[deprecated(since = "1.3.0", note = "please use `read_f64_into` instead")] - fn read_f64_into_unchecked(src: &[u8], dst: &mut [f64]) { - Self::read_f64_into(src, dst); - } - - /// Writes unsigned 16 bit integers from `src` into `dst`. - /// - /// # Panics - /// - /// Panics when `dst.len() != 2*src.len()`. - /// - /// # Examples - /// - /// Write and read `u16` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut bytes = [0; 8]; - /// let numbers_given = [1, 2, 0xf00f, 0xffee]; - /// LittleEndian::write_u16_into(&numbers_given, &mut bytes); - /// - /// let mut numbers_got = [0; 4]; - /// LittleEndian::read_u16_into(&bytes, &mut numbers_got); - /// assert_eq!(numbers_given, numbers_got); - /// ``` - fn write_u16_into(src: &[u16], dst: &mut [u8]); - - /// Writes unsigned 32 bit integers from `src` into `dst`. - /// - /// # Panics - /// - /// Panics when `dst.len() != 4*src.len()`. - /// - /// # Examples - /// - /// Write and read `u32` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut bytes = [0; 16]; - /// let numbers_given = [1, 2, 0xf00f, 0xffee]; - /// LittleEndian::write_u32_into(&numbers_given, &mut bytes); - /// - /// let mut numbers_got = [0; 4]; - /// LittleEndian::read_u32_into(&bytes, &mut numbers_got); - /// assert_eq!(numbers_given, numbers_got); - /// ``` - fn write_u32_into(src: &[u32], dst: &mut [u8]); - - /// Writes unsigned 64 bit integers from `src` into `dst`. - /// - /// # Panics - /// - /// Panics when `dst.len() != 8*src.len()`. - /// - /// # Examples - /// - /// Write and read `u64` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut bytes = [0; 32]; - /// let numbers_given = [1, 2, 0xf00f, 0xffee]; - /// LittleEndian::write_u64_into(&numbers_given, &mut bytes); - /// - /// let mut numbers_got = [0; 4]; - /// LittleEndian::read_u64_into(&bytes, &mut numbers_got); - /// assert_eq!(numbers_given, numbers_got); - /// ``` - fn write_u64_into(src: &[u64], dst: &mut [u8]); - - /// Writes unsigned 128 bit integers from `src` into `dst`. - /// - /// # Panics - /// - /// Panics when `dst.len() != 16*src.len()`. - /// - /// # Examples - /// - /// Write and read `u128` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut bytes = [0; 64]; - /// let numbers_given = [1, 2, 0xf00f, 0xffee]; - /// LittleEndian::write_u128_into(&numbers_given, &mut bytes); - /// - /// let mut numbers_got = [0; 4]; - /// LittleEndian::read_u128_into(&bytes, &mut numbers_got); - /// assert_eq!(numbers_given, numbers_got); - /// ``` - fn write_u128_into(src: &[u128], dst: &mut [u8]); - - /// Writes signed 8 bit integers from `src` into `dst`. - /// - /// Note that since each `i8` is a single byte, no byte order conversions - /// are used. This method is included because it provides a safe, simple - /// way for the caller to write from a `&[i8]` buffer. (Without this - /// method, the caller would have to either use `unsafe` code or convert - /// each byte to `u8` individually.) - /// - /// # Panics - /// - /// Panics when `buf.len() != src.len()`. - /// - /// # Examples - /// - /// Write and read `i8` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian, ReadBytesExt}; - /// - /// let mut bytes = [0; 4]; - /// let numbers_given = [1, 2, 0xf, 0xe]; - /// LittleEndian::write_i8_into(&numbers_given, &mut bytes); - /// - /// let mut numbers_got = [0; 4]; - /// bytes.as_ref().read_i8_into(&mut numbers_got); - /// assert_eq!(numbers_given, numbers_got); - /// ``` - fn write_i8_into(src: &[i8], dst: &mut [u8]) { - let src = unsafe { - slice::from_raw_parts(src.as_ptr() as *const u8, src.len()) - }; - dst.copy_from_slice(src); - } - - /// Writes signed 16 bit integers from `src` into `dst`. - /// - /// # Panics - /// - /// Panics when `buf.len() != 2*src.len()`. - /// - /// # Examples - /// - /// Write and read `i16` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut bytes = [0; 8]; - /// let numbers_given = [1, 2, 0x0f, 0xee]; - /// LittleEndian::write_i16_into(&numbers_given, &mut bytes); - /// - /// let mut numbers_got = [0; 4]; - /// LittleEndian::read_i16_into(&bytes, &mut numbers_got); - /// assert_eq!(numbers_given, numbers_got); - /// ``` - fn write_i16_into(src: &[i16], dst: &mut [u8]) { - let src = unsafe { - slice::from_raw_parts(src.as_ptr() as *const u16, src.len()) - }; - Self::write_u16_into(src, dst); - } - - /// Writes signed 32 bit integers from `src` into `dst`. - /// - /// # Panics - /// - /// Panics when `dst.len() != 4*src.len()`. - /// - /// # Examples - /// - /// Write and read `i32` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut bytes = [0; 16]; - /// let numbers_given = [1, 2, 0xf00f, 0xffee]; - /// LittleEndian::write_i32_into(&numbers_given, &mut bytes); - /// - /// let mut numbers_got = [0; 4]; - /// LittleEndian::read_i32_into(&bytes, &mut numbers_got); - /// assert_eq!(numbers_given, numbers_got); - /// ``` - fn write_i32_into(src: &[i32], dst: &mut [u8]) { - let src = unsafe { - slice::from_raw_parts(src.as_ptr() as *const u32, src.len()) - }; - Self::write_u32_into(src, dst); - } - - /// Writes signed 64 bit integers from `src` into `dst`. - /// - /// # Panics - /// - /// Panics when `dst.len() != 8*src.len()`. - /// - /// # Examples - /// - /// Write and read `i64` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut bytes = [0; 32]; - /// let numbers_given = [1, 2, 0xf00f, 0xffee]; - /// LittleEndian::write_i64_into(&numbers_given, &mut bytes); - /// - /// let mut numbers_got = [0; 4]; - /// LittleEndian::read_i64_into(&bytes, &mut numbers_got); - /// assert_eq!(numbers_given, numbers_got); - /// ``` - fn write_i64_into(src: &[i64], dst: &mut [u8]) { - let src = unsafe { - slice::from_raw_parts(src.as_ptr() as *const u64, src.len()) - }; - Self::write_u64_into(src, dst); - } - - /// Writes signed 128 bit integers from `src` into `dst`. - /// - /// # Panics - /// - /// Panics when `dst.len() != 16*src.len()`. - /// - /// # Examples - /// - /// Write and read `i128` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut bytes = [0; 64]; - /// let numbers_given = [1, 2, 0xf00f, 0xffee]; - /// LittleEndian::write_i128_into(&numbers_given, &mut bytes); - /// - /// let mut numbers_got = [0; 4]; - /// LittleEndian::read_i128_into(&bytes, &mut numbers_got); - /// assert_eq!(numbers_given, numbers_got); - /// ``` - fn write_i128_into(src: &[i128], dst: &mut [u8]) { - let src = unsafe { - slice::from_raw_parts(src.as_ptr() as *const u128, src.len()) - }; - Self::write_u128_into(src, dst); - } - - /// Writes IEEE754 single-precision (4 bytes) floating point numbers from - /// `src` into `dst`. - /// - /// # Panics - /// - /// Panics when `src.len() != 4*dst.len()`. - /// - /// # Examples - /// - /// Write and read `f32` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut bytes = [0; 16]; - /// let numbers_given = [1.0, 2.0, 31.312e31, -11.32e19]; - /// LittleEndian::write_f32_into(&numbers_given, &mut bytes); - /// - /// let mut numbers_got = [0.0; 4]; - /// LittleEndian::read_f32_into(&bytes, &mut numbers_got); - /// assert_eq!(numbers_given, numbers_got); - /// ``` - fn write_f32_into(src: &[f32], dst: &mut [u8]) { - let src = unsafe { - slice::from_raw_parts(src.as_ptr() as *const u32, src.len()) - }; - Self::write_u32_into(src, dst); - } - - /// Writes IEEE754 double-precision (8 bytes) floating point numbers from - /// `src` into `dst`. - /// - /// # Panics - /// - /// Panics when `src.len() != 8*dst.len()`. - /// - /// # Examples - /// - /// Write and read `f64` numbers in little endian order: - /// - /// ```rust - /// use byteorder::{ByteOrder, LittleEndian}; - /// - /// let mut bytes = [0; 32]; - /// let numbers_given = [1.0, 2.0, 31.312e211, -11.32e91]; - /// LittleEndian::write_f64_into(&numbers_given, &mut bytes); - /// - /// let mut numbers_got = [0.0; 4]; - /// LittleEndian::read_f64_into(&bytes, &mut numbers_got); - /// assert_eq!(numbers_given, numbers_got); - /// ``` - fn write_f64_into(src: &[f64], dst: &mut [u8]) { - let src = unsafe { - slice::from_raw_parts(src.as_ptr() as *const u64, src.len()) - }; - Self::write_u64_into(src, dst); - } - - /// Converts the given slice of unsigned 16 bit integers to a particular - /// endianness. - /// - /// If the endianness matches the endianness of the host platform, then - /// this is a no-op. - /// - /// # Examples - /// - /// Convert the host platform's endianness to big-endian: - /// - /// ```rust - /// use byteorder::{ByteOrder, BigEndian}; - /// - /// let mut numbers = [5, 65000]; - /// BigEndian::from_slice_u16(&mut numbers); - /// assert_eq!(numbers, [5u16.to_be(), 65000u16.to_be()]); - /// ``` - fn from_slice_u16(numbers: &mut [u16]); - - /// Converts the given slice of unsigned 32 bit integers to a particular - /// endianness. - /// - /// If the endianness matches the endianness of the host platform, then - /// this is a no-op. - /// - /// # Examples - /// - /// Convert the host platform's endianness to big-endian: - /// - /// ```rust - /// use byteorder::{ByteOrder, BigEndian}; - /// - /// let mut numbers = [5, 65000]; - /// BigEndian::from_slice_u32(&mut numbers); - /// assert_eq!(numbers, [5u32.to_be(), 65000u32.to_be()]); - /// ``` - fn from_slice_u32(numbers: &mut [u32]); - - /// Converts the given slice of unsigned 64 bit integers to a particular - /// endianness. - /// - /// If the endianness matches the endianness of the host platform, then - /// this is a no-op. - /// - /// # Examples - /// - /// Convert the host platform's endianness to big-endian: - /// - /// ```rust - /// use byteorder::{ByteOrder, BigEndian}; - /// - /// let mut numbers = [5, 65000]; - /// BigEndian::from_slice_u64(&mut numbers); - /// assert_eq!(numbers, [5u64.to_be(), 65000u64.to_be()]); - /// ``` - fn from_slice_u64(numbers: &mut [u64]); - - /// Converts the given slice of unsigned 128 bit integers to a particular - /// endianness. - /// - /// If the endianness matches the endianness of the host platform, then - /// this is a no-op. - /// - /// # Examples - /// - /// Convert the host platform's endianness to big-endian: - /// - /// ```rust - /// use byteorder::{ByteOrder, BigEndian}; - /// - /// let mut numbers = [5, 65000]; - /// BigEndian::from_slice_u128(&mut numbers); - /// assert_eq!(numbers, [5u128.to_be(), 65000u128.to_be()]); - /// ``` - fn from_slice_u128(numbers: &mut [u128]); - - /// Converts the given slice of signed 16 bit integers to a particular - /// endianness. - /// - /// If the endianness matches the endianness of the host platform, then - /// this is a no-op. - /// - /// # Examples - /// - /// Convert the host platform's endianness to big-endian: - /// - /// ```rust - /// use byteorder::{ByteOrder, BigEndian}; - /// - /// let mut numbers = [5, 6500]; - /// BigEndian::from_slice_i16(&mut numbers); - /// assert_eq!(numbers, [5i16.to_be(), 6500i16.to_be()]); - /// ``` - #[inline] - fn from_slice_i16(src: &mut [i16]) { - let src = unsafe { - slice::from_raw_parts_mut(src.as_mut_ptr() as *mut u16, src.len()) - }; - Self::from_slice_u16(src); - } - - /// Converts the given slice of signed 32 bit integers to a particular - /// endianness. - /// - /// If the endianness matches the endianness of the host platform, then - /// this is a no-op. - /// - /// # Examples - /// - /// Convert the host platform's endianness to big-endian: - /// - /// ```rust - /// use byteorder::{ByteOrder, BigEndian}; - /// - /// let mut numbers = [5, 65000]; - /// BigEndian::from_slice_i32(&mut numbers); - /// assert_eq!(numbers, [5i32.to_be(), 65000i32.to_be()]); - /// ``` - #[inline] - fn from_slice_i32(src: &mut [i32]) { - let src = unsafe { - slice::from_raw_parts_mut(src.as_mut_ptr() as *mut u32, src.len()) - }; - Self::from_slice_u32(src); - } - - /// Converts the given slice of signed 64 bit integers to a particular - /// endianness. - /// - /// If the endianness matches the endianness of the host platform, then - /// this is a no-op. - /// - /// # Examples - /// - /// Convert the host platform's endianness to big-endian: - /// - /// ```rust - /// use byteorder::{ByteOrder, BigEndian}; - /// - /// let mut numbers = [5, 65000]; - /// BigEndian::from_slice_i64(&mut numbers); - /// assert_eq!(numbers, [5i64.to_be(), 65000i64.to_be()]); - /// ``` - #[inline] - fn from_slice_i64(src: &mut [i64]) { - let src = unsafe { - slice::from_raw_parts_mut(src.as_mut_ptr() as *mut u64, src.len()) - }; - Self::from_slice_u64(src); - } - - /// Converts the given slice of signed 128 bit integers to a particular - /// endianness. - /// - /// If the endianness matches the endianness of the host platform, then - /// this is a no-op. - /// - /// # Examples - /// - /// Convert the host platform's endianness to big-endian: - /// - /// ```rust - /// use byteorder::{ByteOrder, BigEndian}; - /// - /// let mut numbers = [5, 65000]; - /// BigEndian::from_slice_i128(&mut numbers); - /// assert_eq!(numbers, [5i128.to_be(), 65000i128.to_be()]); - /// ``` - #[inline] - fn from_slice_i128(src: &mut [i128]) { - let src = unsafe { - slice::from_raw_parts_mut(src.as_mut_ptr() as *mut u128, src.len()) - }; - Self::from_slice_u128(src); - } - - /// Converts the given slice of IEEE754 single-precision (4 bytes) floating - /// point numbers to a particular endianness. - /// - /// If the endianness matches the endianness of the host platform, then - /// this is a no-op. - fn from_slice_f32(numbers: &mut [f32]); - - /// Converts the given slice of IEEE754 double-precision (8 bytes) floating - /// point numbers to a particular endianness. - /// - /// If the endianness matches the endianness of the host platform, then - /// this is a no-op. - fn from_slice_f64(numbers: &mut [f64]); -} - -/// Defines big-endian serialization. -/// -/// Note that this type has no value constructor. It is used purely at the -/// type level. -/// -/// # Examples -/// -/// Write and read `u32` numbers in big endian order: -/// -/// ```rust -/// use byteorder::{ByteOrder, BigEndian}; -/// -/// let mut buf = [0; 4]; -/// BigEndian::write_u32(&mut buf, 1_000_000); -/// assert_eq!(1_000_000, BigEndian::read_u32(&buf)); -/// ``` -#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] -pub enum BigEndian {} - -impl Default for BigEndian { - fn default() -> BigEndian { - panic!("BigEndian default") - } -} - -/// A type alias for [`BigEndian`]. -/// -/// [`BigEndian`]: enum.BigEndian.html -pub type BE = BigEndian; - -/// Defines little-endian serialization. -/// -/// Note that this type has no value constructor. It is used purely at the -/// type level. -/// -/// # Examples -/// -/// Write and read `u32` numbers in little endian order: -/// -/// ```rust -/// use byteorder::{ByteOrder, LittleEndian}; -/// -/// let mut buf = [0; 4]; -/// LittleEndian::write_u32(&mut buf, 1_000_000); -/// assert_eq!(1_000_000, LittleEndian::read_u32(&buf)); -/// ``` -#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] -pub enum LittleEndian {} - -impl Default for LittleEndian { - fn default() -> LittleEndian { - panic!("LittleEndian default") - } -} - -/// A type alias for [`LittleEndian`]. -/// -/// [`LittleEndian`]: enum.LittleEndian.html -pub type LE = LittleEndian; - -/// Defines network byte order serialization. -/// -/// Network byte order is defined by [RFC 1700][1] to be big-endian, and is -/// referred to in several protocol specifications. This type is an alias of -/// [`BigEndian`]. -/// -/// [1]: https://tools.ietf.org/html/rfc1700 -/// -/// Note that this type has no value constructor. It is used purely at the -/// type level. -/// -/// # Examples -/// -/// Write and read `i16` numbers in big endian order: -/// -/// ```rust -/// use byteorder::{ByteOrder, NetworkEndian, BigEndian}; -/// -/// let mut buf = [0; 2]; -/// BigEndian::write_i16(&mut buf, -5_000); -/// assert_eq!(-5_000, NetworkEndian::read_i16(&buf)); -/// ``` -/// -/// [`BigEndian`]: enum.BigEndian.html -pub type NetworkEndian = BigEndian; - -/// Defines system native-endian serialization. -/// -/// Note that this type has no value constructor. It is used purely at the -/// type level. -/// -/// On this platform, this is an alias for [`LittleEndian`]. -/// -/// [`LittleEndian`]: enum.LittleEndian.html -#[cfg(target_endian = "little")] -pub type NativeEndian = LittleEndian; - -/// Defines system native-endian serialization. -/// -/// Note that this type has no value constructor. It is used purely at the -/// type level. -/// -/// On this platform, this is an alias for [`BigEndian`]. -/// -/// [`BigEndian`]: enum.BigEndian.html -#[cfg(target_endian = "big")] -pub type NativeEndian = BigEndian; - -/// Copies a &[u8] $src into a &mut [$ty] $dst for the endianness given by -/// $from_bytes (must be either from_be_bytes or from_le_bytes). -/// -/// Panics if $src.len() != $dst.len() * size_of::<$ty>(). -macro_rules! read_slice { - ($src:expr, $dst:expr, $ty:ty, $from_bytes:ident) => {{ - const SIZE: usize = core::mem::size_of::<$ty>(); - // Check types: - let src: &[u8] = $src; - let dst: &mut [$ty] = $dst; - assert_eq!(src.len(), dst.len() * SIZE); - for (src, dst) in src.chunks_exact(SIZE).zip(dst.iter_mut()) { - *dst = <$ty>::$from_bytes(src.try_into().unwrap()); - } - }}; -} - -/// Copies a &[$ty] $src into a &mut [u8] $dst for the endianness given by -/// $from_bytes (must be either from_be_bytes or from_le_bytes). -/// -/// Panics if $src.len() * size_of::<$ty>() != $dst.len(). -macro_rules! write_slice { - ($src:expr, $dst:expr, $ty:ty, $to_bytes:ident) => {{ - const SIZE: usize = core::mem::size_of::<$ty>(); - // Check types: - let src: &[$ty] = $src; - let dst: &mut [u8] = $dst; - assert_eq!(src.len() * SIZE, dst.len()); - for (src, dst) in src.iter().zip(dst.chunks_exact_mut(SIZE)) { - dst.copy_from_slice(&src.$to_bytes()); - } - }}; -} - -impl ByteOrder for BigEndian { - #[inline] - fn read_u16(buf: &[u8]) -> u16 { - u16::from_be_bytes(buf[..2].try_into().unwrap()) - } - - #[inline] - fn read_u32(buf: &[u8]) -> u32 { - u32::from_be_bytes(buf[..4].try_into().unwrap()) - } - - #[inline] - fn read_u64(buf: &[u8]) -> u64 { - u64::from_be_bytes(buf[..8].try_into().unwrap()) - } - - #[inline] - fn read_u128(buf: &[u8]) -> u128 { - u128::from_be_bytes(buf[..16].try_into().unwrap()) - } - - #[inline] - fn read_uint(buf: &[u8], nbytes: usize) -> u64 { - let mut out = [0; 8]; - assert!(1 <= nbytes && nbytes <= out.len() && nbytes <= buf.len()); - let start = out.len() - nbytes; - out[start..].copy_from_slice(&buf[..nbytes]); - u64::from_be_bytes(out) - } - - #[inline] - fn read_uint128(buf: &[u8], nbytes: usize) -> u128 { - let mut out = [0; 16]; - assert!(1 <= nbytes && nbytes <= out.len() && nbytes <= buf.len()); - let start = out.len() - nbytes; - out[start..].copy_from_slice(&buf[..nbytes]); - u128::from_be_bytes(out) - } - - #[inline] - fn write_u16(buf: &mut [u8], n: u16) { - buf[..2].copy_from_slice(&n.to_be_bytes()); - } - - #[inline] - fn write_u32(buf: &mut [u8], n: u32) { - buf[..4].copy_from_slice(&n.to_be_bytes()); - } - - #[inline] - fn write_u64(buf: &mut [u8], n: u64) { - buf[..8].copy_from_slice(&n.to_be_bytes()); - } - - #[inline] - fn write_u128(buf: &mut [u8], n: u128) { - buf[..16].copy_from_slice(&n.to_be_bytes()); - } - - #[inline] - fn write_uint(buf: &mut [u8], n: u64, nbytes: usize) { - assert!(pack_size(n) <= nbytes && nbytes <= 8); - assert!(nbytes <= buf.len()); - unsafe { - let bytes = *(&n.to_be() as *const u64 as *const [u8; 8]); - copy_nonoverlapping( - bytes.as_ptr().offset((8 - nbytes) as isize), - buf.as_mut_ptr(), - nbytes, - ); - } - } - - #[inline] - fn write_uint128(buf: &mut [u8], n: u128, nbytes: usize) { - assert!(pack_size128(n) <= nbytes && nbytes <= 16); - assert!(nbytes <= buf.len()); - unsafe { - let bytes = *(&n.to_be() as *const u128 as *const [u8; 16]); - copy_nonoverlapping( - bytes.as_ptr().offset((16 - nbytes) as isize), - buf.as_mut_ptr(), - nbytes, - ); - } - } - - #[inline] - fn read_u16_into(src: &[u8], dst: &mut [u16]) { - read_slice!(src, dst, u16, from_be_bytes); - } - - #[inline] - fn read_u32_into(src: &[u8], dst: &mut [u32]) { - read_slice!(src, dst, u32, from_be_bytes); - } - - #[inline] - fn read_u64_into(src: &[u8], dst: &mut [u64]) { - read_slice!(src, dst, u64, from_be_bytes); - } - - #[inline] - fn read_u128_into(src: &[u8], dst: &mut [u128]) { - read_slice!(src, dst, u128, from_be_bytes); - } - - #[inline] - fn write_u16_into(src: &[u16], dst: &mut [u8]) { - write_slice!(src, dst, u16, to_be_bytes); - } - - #[inline] - fn write_u32_into(src: &[u32], dst: &mut [u8]) { - write_slice!(src, dst, u32, to_be_bytes); - } - - #[inline] - fn write_u64_into(src: &[u64], dst: &mut [u8]) { - write_slice!(src, dst, u64, to_be_bytes); - } - - #[inline] - fn write_u128_into(src: &[u128], dst: &mut [u8]) { - write_slice!(src, dst, u128, to_be_bytes); - } - - #[inline] - fn from_slice_u16(numbers: &mut [u16]) { - if cfg!(target_endian = "little") { - for n in numbers { - *n = n.to_be(); - } - } - } - - #[inline] - fn from_slice_u32(numbers: &mut [u32]) { - if cfg!(target_endian = "little") { - for n in numbers { - *n = n.to_be(); - } - } - } - - #[inline] - fn from_slice_u64(numbers: &mut [u64]) { - if cfg!(target_endian = "little") { - for n in numbers { - *n = n.to_be(); - } - } - } - - #[inline] - fn from_slice_u128(numbers: &mut [u128]) { - if cfg!(target_endian = "little") { - for n in numbers { - *n = n.to_be(); - } - } - } - - #[inline] - fn from_slice_f32(numbers: &mut [f32]) { - if cfg!(target_endian = "little") { - for n in numbers { - unsafe { - let int = *(n as *const f32 as *const u32); - *n = *(&int.to_be() as *const u32 as *const f32); - } - } - } - } - - #[inline] - fn from_slice_f64(numbers: &mut [f64]) { - if cfg!(target_endian = "little") { - for n in numbers { - unsafe { - let int = *(n as *const f64 as *const u64); - *n = *(&int.to_be() as *const u64 as *const f64); - } - } - } - } -} - -impl ByteOrder for LittleEndian { - #[inline] - fn read_u16(buf: &[u8]) -> u16 { - u16::from_le_bytes(buf[..2].try_into().unwrap()) - } - - #[inline] - fn read_u32(buf: &[u8]) -> u32 { - u32::from_le_bytes(buf[..4].try_into().unwrap()) - } - - #[inline] - fn read_u64(buf: &[u8]) -> u64 { - u64::from_le_bytes(buf[..8].try_into().unwrap()) - } - - #[inline] - fn read_u128(buf: &[u8]) -> u128 { - u128::from_le_bytes(buf[..16].try_into().unwrap()) - } - - #[inline] - fn read_uint(buf: &[u8], nbytes: usize) -> u64 { - let mut out = [0; 8]; - assert!(1 <= nbytes && nbytes <= out.len() && nbytes <= buf.len()); - out[..nbytes].copy_from_slice(&buf[..nbytes]); - u64::from_le_bytes(out) - } - - #[inline] - fn read_uint128(buf: &[u8], nbytes: usize) -> u128 { - let mut out = [0; 16]; - assert!(1 <= nbytes && nbytes <= out.len() && nbytes <= buf.len()); - out[..nbytes].copy_from_slice(&buf[..nbytes]); - u128::from_le_bytes(out) - } - - #[inline] - fn write_u16(buf: &mut [u8], n: u16) { - buf[..2].copy_from_slice(&n.to_le_bytes()); - } - - #[inline] - fn write_u32(buf: &mut [u8], n: u32) { - buf[..4].copy_from_slice(&n.to_le_bytes()); - } - - #[inline] - fn write_u64(buf: &mut [u8], n: u64) { - buf[..8].copy_from_slice(&n.to_le_bytes()); - } - - #[inline] - fn write_u128(buf: &mut [u8], n: u128) { - buf[..16].copy_from_slice(&n.to_le_bytes()); - } - - #[inline] - fn write_uint(buf: &mut [u8], n: u64, nbytes: usize) { - assert!(pack_size(n as u64) <= nbytes && nbytes <= 8); - assert!(nbytes <= buf.len()); - unsafe { - let bytes = *(&n.to_le() as *const u64 as *const [u8; 8]); - copy_nonoverlapping(bytes.as_ptr(), buf.as_mut_ptr(), nbytes); - } - } - - #[inline] - fn write_uint128(buf: &mut [u8], n: u128, nbytes: usize) { - assert!(pack_size128(n as u128) <= nbytes && nbytes <= 16); - assert!(nbytes <= buf.len()); - unsafe { - let bytes = *(&n.to_le() as *const u128 as *const [u8; 16]); - copy_nonoverlapping(bytes.as_ptr(), buf.as_mut_ptr(), nbytes); - } - } - - #[inline] - fn read_u16_into(src: &[u8], dst: &mut [u16]) { - read_slice!(src, dst, u16, from_le_bytes); - } - - #[inline] - fn read_u32_into(src: &[u8], dst: &mut [u32]) { - read_slice!(src, dst, u32, from_le_bytes); - } - - #[inline] - fn read_u64_into(src: &[u8], dst: &mut [u64]) { - read_slice!(src, dst, u64, from_le_bytes); - } - - #[inline] - fn read_u128_into(src: &[u8], dst: &mut [u128]) { - read_slice!(src, dst, u128, from_le_bytes); - } - - #[inline] - fn write_u16_into(src: &[u16], dst: &mut [u8]) { - write_slice!(src, dst, u16, to_le_bytes); - } - - #[inline] - fn write_u32_into(src: &[u32], dst: &mut [u8]) { - write_slice!(src, dst, u32, to_le_bytes); - } - - #[inline] - fn write_u64_into(src: &[u64], dst: &mut [u8]) { - write_slice!(src, dst, u64, to_le_bytes); - } - - #[inline] - fn write_u128_into(src: &[u128], dst: &mut [u8]) { - write_slice!(src, dst, u128, to_le_bytes); - } - - #[inline] - fn from_slice_u16(numbers: &mut [u16]) { - if cfg!(target_endian = "big") { - for n in numbers { - *n = n.to_le(); - } - } - } - - #[inline] - fn from_slice_u32(numbers: &mut [u32]) { - if cfg!(target_endian = "big") { - for n in numbers { - *n = n.to_le(); - } - } - } - - #[inline] - fn from_slice_u64(numbers: &mut [u64]) { - if cfg!(target_endian = "big") { - for n in numbers { - *n = n.to_le(); - } - } - } - - #[inline] - fn from_slice_u128(numbers: &mut [u128]) { - if cfg!(target_endian = "big") { - for n in numbers { - *n = n.to_le(); - } - } - } - - #[inline] - fn from_slice_f32(numbers: &mut [f32]) { - if cfg!(target_endian = "big") { - for n in numbers { - unsafe { - let int = *(n as *const f32 as *const u32); - *n = *(&int.to_le() as *const u32 as *const f32); - } - } - } - } - - #[inline] - fn from_slice_f64(numbers: &mut [f64]) { - if cfg!(target_endian = "big") { - for n in numbers { - unsafe { - let int = *(n as *const f64 as *const u64); - *n = *(&int.to_le() as *const u64 as *const f64); - } - } - } - } -} - -#[cfg(test)] -mod test { - use quickcheck::{Arbitrary, Gen, QuickCheck, StdGen, Testable}; - use rand::{thread_rng, Rng}; - - pub const U24_MAX: u32 = 16_777_215; - pub const I24_MAX: i32 = 8_388_607; - pub const U48_MAX: u64 = 281_474_976_710_655; - pub const I48_MAX: i64 = 140_737_488_355_327; - - pub const U64_MAX: u64 = ::core::u64::MAX; - pub const I64_MAX: u64 = ::core::i64::MAX as u64; - - macro_rules! calc_max { - ($max:expr, $bytes:expr) => { - calc_max!($max, $bytes, 8) - }; - ($max:expr, $bytes:expr, $maxbytes:expr) => { - ($max - 1) >> (8 * ($maxbytes - $bytes)) - }; - } - - #[derive(Clone, Debug)] - pub struct Wi128<T>(pub T); - - impl<T: Clone> Wi128<T> { - pub fn clone(&self) -> T { - self.0.clone() - } - } - - impl<T: PartialEq> PartialEq<T> for Wi128<T> { - fn eq(&self, other: &T) -> bool { - self.0.eq(other) - } - } - - impl Arbitrary for Wi128<u128> { - fn arbitrary<G: Gen>(gen: &mut G) -> Wi128<u128> { - let max = calc_max!(::core::u128::MAX, gen.size(), 16); - let output = (gen.gen::<u64>() as u128) - | ((gen.gen::<u64>() as u128) << 64); - Wi128(output & (max - 1)) - } - } - - impl Arbitrary for Wi128<i128> { - fn arbitrary<G: Gen>(gen: &mut G) -> Wi128<i128> { - let max = calc_max!(::core::i128::MAX, gen.size(), 16); - let output = (gen.gen::<i64>() as i128) - | ((gen.gen::<i64>() as i128) << 64); - Wi128(output & (max - 1)) - } - } - - pub fn qc_sized<A: Testable>(f: A, size: u64) { - QuickCheck::new() - .gen(StdGen::new(thread_rng(), size as usize)) - .tests(1_00) - .max_tests(10_000) - .quickcheck(f); - } - - macro_rules! qc_byte_order { - ($name:ident, $ty_int:ty, $max:expr, - $bytes:expr, $read:ident, $write:ident) => { - #[cfg(not(miri))] - mod $name { - #[allow(unused_imports)] - use super::{qc_sized, Wi128}; - use crate::{ - BigEndian, ByteOrder, LittleEndian, NativeEndian, - }; - - #[test] - fn big_endian() { - fn prop(n: $ty_int) -> bool { - let mut buf = [0; 16]; - BigEndian::$write(&mut buf, n.clone(), $bytes); - n == BigEndian::$read(&buf[..$bytes], $bytes) - } - qc_sized(prop as fn($ty_int) -> bool, $max); - } - - #[test] - fn little_endian() { - fn prop(n: $ty_int) -> bool { - let mut buf = [0; 16]; - LittleEndian::$write(&mut buf, n.clone(), $bytes); - n == LittleEndian::$read(&buf[..$bytes], $bytes) - } - qc_sized(prop as fn($ty_int) -> bool, $max); - } - - #[test] - fn native_endian() { - fn prop(n: $ty_int) -> bool { - let mut buf = [0; 16]; - NativeEndian::$write(&mut buf, n.clone(), $bytes); - n == NativeEndian::$read(&buf[..$bytes], $bytes) - } - qc_sized(prop as fn($ty_int) -> bool, $max); - } - } - }; - ($name:ident, $ty_int:ty, $max:expr, - $read:ident, $write:ident) => { - #[cfg(not(miri))] - mod $name { - #[allow(unused_imports)] - use super::{qc_sized, Wi128}; - use crate::{ - BigEndian, ByteOrder, LittleEndian, NativeEndian, - }; - use core::mem::size_of; - - #[test] - fn big_endian() { - fn prop(n: $ty_int) -> bool { - let bytes = size_of::<$ty_int>(); - let mut buf = [0; 16]; - BigEndian::$write(&mut buf[16 - bytes..], n.clone()); - n == BigEndian::$read(&buf[16 - bytes..]) - } - qc_sized(prop as fn($ty_int) -> bool, $max - 1); - } - - #[test] - fn little_endian() { - fn prop(n: $ty_int) -> bool { - let bytes = size_of::<$ty_int>(); - let mut buf = [0; 16]; - LittleEndian::$write(&mut buf[..bytes], n.clone()); - n == LittleEndian::$read(&buf[..bytes]) - } - qc_sized(prop as fn($ty_int) -> bool, $max - 1); - } - - #[test] - fn native_endian() { - fn prop(n: $ty_int) -> bool { - let bytes = size_of::<$ty_int>(); - let mut buf = [0; 16]; - NativeEndian::$write(&mut buf[..bytes], n.clone()); - n == NativeEndian::$read(&buf[..bytes]) - } - qc_sized(prop as fn($ty_int) -> bool, $max - 1); - } - } - }; - } - - qc_byte_order!( - prop_u16, - u16, - ::core::u16::MAX as u64, - read_u16, - write_u16 - ); - qc_byte_order!( - prop_i16, - i16, - ::core::i16::MAX as u64, - read_i16, - write_i16 - ); - qc_byte_order!( - prop_u24, - u32, - crate::test::U24_MAX as u64, - read_u24, - write_u24 - ); - qc_byte_order!( - prop_i24, - i32, - crate::test::I24_MAX as u64, - read_i24, - write_i24 - ); - qc_byte_order!( - prop_u32, - u32, - ::core::u32::MAX as u64, - read_u32, - write_u32 - ); - qc_byte_order!( - prop_i32, - i32, - ::core::i32::MAX as u64, - read_i32, - write_i32 - ); - qc_byte_order!( - prop_u48, - u64, - crate::test::U48_MAX as u64, - read_u48, - write_u48 - ); - qc_byte_order!( - prop_i48, - i64, - crate::test::I48_MAX as u64, - read_i48, - write_i48 - ); - qc_byte_order!( - prop_u64, - u64, - ::core::u64::MAX as u64, - read_u64, - write_u64 - ); - qc_byte_order!( - prop_i64, - i64, - ::core::i64::MAX as u64, - read_i64, - write_i64 - ); - qc_byte_order!( - prop_f32, - f32, - ::core::u64::MAX as u64, - read_f32, - write_f32 - ); - qc_byte_order!( - prop_f64, - f64, - ::core::i64::MAX as u64, - read_f64, - write_f64 - ); - - qc_byte_order!(prop_u128, Wi128<u128>, 16 + 1, read_u128, write_u128); - qc_byte_order!(prop_i128, Wi128<i128>, 16 + 1, read_i128, write_i128); - - qc_byte_order!( - prop_uint_1, - u64, - calc_max!(super::U64_MAX, 1), - 1, - read_uint, - write_uint - ); - qc_byte_order!( - prop_uint_2, - u64, - calc_max!(super::U64_MAX, 2), - 2, - read_uint, - write_uint - ); - qc_byte_order!( - prop_uint_3, - u64, - calc_max!(super::U64_MAX, 3), - 3, - read_uint, - write_uint - ); - qc_byte_order!( - prop_uint_4, - u64, - calc_max!(super::U64_MAX, 4), - 4, - read_uint, - write_uint - ); - qc_byte_order!( - prop_uint_5, - u64, - calc_max!(super::U64_MAX, 5), - 5, - read_uint, - write_uint - ); - qc_byte_order!( - prop_uint_6, - u64, - calc_max!(super::U64_MAX, 6), - 6, - read_uint, - write_uint - ); - qc_byte_order!( - prop_uint_7, - u64, - calc_max!(super::U64_MAX, 7), - 7, - read_uint, - write_uint - ); - qc_byte_order!( - prop_uint_8, - u64, - calc_max!(super::U64_MAX, 8), - 8, - read_uint, - write_uint - ); - - qc_byte_order!( - prop_uint128_1, - Wi128<u128>, - 1, - 1, - read_uint128, - write_uint128 - ); - qc_byte_order!( - prop_uint128_2, - Wi128<u128>, - 2, - 2, - read_uint128, - write_uint128 - ); - qc_byte_order!( - prop_uint128_3, - Wi128<u128>, - 3, - 3, - read_uint128, - write_uint128 - ); - qc_byte_order!( - prop_uint128_4, - Wi128<u128>, - 4, - 4, - read_uint128, - write_uint128 - ); - qc_byte_order!( - prop_uint128_5, - Wi128<u128>, - 5, - 5, - read_uint128, - write_uint128 - ); - qc_byte_order!( - prop_uint128_6, - Wi128<u128>, - 6, - 6, - read_uint128, - write_uint128 - ); - qc_byte_order!( - prop_uint128_7, - Wi128<u128>, - 7, - 7, - read_uint128, - write_uint128 - ); - qc_byte_order!( - prop_uint128_8, - Wi128<u128>, - 8, - 8, - read_uint128, - write_uint128 - ); - qc_byte_order!( - prop_uint128_9, - Wi128<u128>, - 9, - 9, - read_uint128, - write_uint128 - ); - qc_byte_order!( - prop_uint128_10, - Wi128<u128>, - 10, - 10, - read_uint128, - write_uint128 - ); - qc_byte_order!( - prop_uint128_11, - Wi128<u128>, - 11, - 11, - read_uint128, - write_uint128 - ); - qc_byte_order!( - prop_uint128_12, - Wi128<u128>, - 12, - 12, - read_uint128, - write_uint128 - ); - qc_byte_order!( - prop_uint128_13, - Wi128<u128>, - 13, - 13, - read_uint128, - write_uint128 - ); - qc_byte_order!( - prop_uint128_14, - Wi128<u128>, - 14, - 14, - read_uint128, - write_uint128 - ); - qc_byte_order!( - prop_uint128_15, - Wi128<u128>, - 15, - 15, - read_uint128, - write_uint128 - ); - qc_byte_order!( - prop_uint128_16, - Wi128<u128>, - 16, - 16, - read_uint128, - write_uint128 - ); - - qc_byte_order!( - prop_int_1, - i64, - calc_max!(super::I64_MAX, 1), - 1, - read_int, - write_int - ); - qc_byte_order!( - prop_int_2, - i64, - calc_max!(super::I64_MAX, 2), - 2, - read_int, - write_int - ); - qc_byte_order!( - prop_int_3, - i64, - calc_max!(super::I64_MAX, 3), - 3, - read_int, - write_int - ); - qc_byte_order!( - prop_int_4, - i64, - calc_max!(super::I64_MAX, 4), - 4, - read_int, - write_int - ); - qc_byte_order!( - prop_int_5, - i64, - calc_max!(super::I64_MAX, 5), - 5, - read_int, - write_int - ); - qc_byte_order!( - prop_int_6, - i64, - calc_max!(super::I64_MAX, 6), - 6, - read_int, - write_int - ); - qc_byte_order!( - prop_int_7, - i64, - calc_max!(super::I64_MAX, 7), - 7, - read_int, - write_int - ); - qc_byte_order!( - prop_int_8, - i64, - calc_max!(super::I64_MAX, 8), - 8, - read_int, - write_int - ); - - qc_byte_order!( - prop_int128_1, - Wi128<i128>, - 1, - 1, - read_int128, - write_int128 - ); - qc_byte_order!( - prop_int128_2, - Wi128<i128>, - 2, - 2, - read_int128, - write_int128 - ); - qc_byte_order!( - prop_int128_3, - Wi128<i128>, - 3, - 3, - read_int128, - write_int128 - ); - qc_byte_order!( - prop_int128_4, - Wi128<i128>, - 4, - 4, - read_int128, - write_int128 - ); - qc_byte_order!( - prop_int128_5, - Wi128<i128>, - 5, - 5, - read_int128, - write_int128 - ); - qc_byte_order!( - prop_int128_6, - Wi128<i128>, - 6, - 6, - read_int128, - write_int128 - ); - qc_byte_order!( - prop_int128_7, - Wi128<i128>, - 7, - 7, - read_int128, - write_int128 - ); - qc_byte_order!( - prop_int128_8, - Wi128<i128>, - 8, - 8, - read_int128, - write_int128 - ); - qc_byte_order!( - prop_int128_9, - Wi128<i128>, - 9, - 9, - read_int128, - write_int128 - ); - qc_byte_order!( - prop_int128_10, - Wi128<i128>, - 10, - 10, - read_int128, - write_int128 - ); - qc_byte_order!( - prop_int128_11, - Wi128<i128>, - 11, - 11, - read_int128, - write_int128 - ); - qc_byte_order!( - prop_int128_12, - Wi128<i128>, - 12, - 12, - read_int128, - write_int128 - ); - qc_byte_order!( - prop_int128_13, - Wi128<i128>, - 13, - 13, - read_int128, - write_int128 - ); - qc_byte_order!( - prop_int128_14, - Wi128<i128>, - 14, - 14, - read_int128, - write_int128 - ); - qc_byte_order!( - prop_int128_15, - Wi128<i128>, - 15, - 15, - read_int128, - write_int128 - ); - qc_byte_order!( - prop_int128_16, - Wi128<i128>, - 16, - 16, - read_int128, - write_int128 - ); - - // Test that all of the byte conversion functions panic when given a - // buffer that is too small. - // - // These tests are critical to ensure safety, otherwise we might end up - // with a buffer overflow. - macro_rules! too_small { - ($name:ident, $maximally_small:expr, $zero:expr, - $read:ident, $write:ident) => { - mod $name { - use crate::{ - BigEndian, ByteOrder, LittleEndian, NativeEndian, - }; - - #[test] - #[should_panic] - fn read_big_endian() { - let buf = [0; $maximally_small]; - BigEndian::$read(&buf); - } - - #[test] - #[should_panic] - fn read_little_endian() { - let buf = [0; $maximally_small]; - LittleEndian::$read(&buf); - } - - #[test] - #[should_panic] - fn read_native_endian() { - let buf = [0; $maximally_small]; - NativeEndian::$read(&buf); - } - - #[test] - #[should_panic] - fn write_big_endian() { - let mut buf = [0; $maximally_small]; - BigEndian::$write(&mut buf, $zero); - } - - #[test] - #[should_panic] - fn write_little_endian() { - let mut buf = [0; $maximally_small]; - LittleEndian::$write(&mut buf, $zero); - } - - #[test] - #[should_panic] - fn write_native_endian() { - let mut buf = [0; $maximally_small]; - NativeEndian::$write(&mut buf, $zero); - } - } - }; - ($name:ident, $maximally_small:expr, $read:ident) => { - mod $name { - use crate::{ - BigEndian, ByteOrder, LittleEndian, NativeEndian, - }; - - #[test] - #[should_panic] - fn read_big_endian() { - let buf = [0; $maximally_small]; - BigEndian::$read(&buf, $maximally_small + 1); - } - - #[test] - #[should_panic] - fn read_little_endian() { - let buf = [0; $maximally_small]; - LittleEndian::$read(&buf, $maximally_small + 1); - } - - #[test] - #[should_panic] - fn read_native_endian() { - let buf = [0; $maximally_small]; - NativeEndian::$read(&buf, $maximally_small + 1); - } - } - }; - } - - too_small!(small_u16, 1, 0, read_u16, write_u16); - too_small!(small_i16, 1, 0, read_i16, write_i16); - too_small!(small_u32, 3, 0, read_u32, write_u32); - too_small!(small_i32, 3, 0, read_i32, write_i32); - too_small!(small_u64, 7, 0, read_u64, write_u64); - too_small!(small_i64, 7, 0, read_i64, write_i64); - too_small!(small_f32, 3, 0.0, read_f32, write_f32); - too_small!(small_f64, 7, 0.0, read_f64, write_f64); - too_small!(small_u128, 15, 0, read_u128, write_u128); - too_small!(small_i128, 15, 0, read_i128, write_i128); - - too_small!(small_uint_1, 1, read_uint); - too_small!(small_uint_2, 2, read_uint); - too_small!(small_uint_3, 3, read_uint); - too_small!(small_uint_4, 4, read_uint); - too_small!(small_uint_5, 5, read_uint); - too_small!(small_uint_6, 6, read_uint); - too_small!(small_uint_7, 7, read_uint); - - too_small!(small_uint128_1, 1, read_uint128); - too_small!(small_uint128_2, 2, read_uint128); - too_small!(small_uint128_3, 3, read_uint128); - too_small!(small_uint128_4, 4, read_uint128); - too_small!(small_uint128_5, 5, read_uint128); - too_small!(small_uint128_6, 6, read_uint128); - too_small!(small_uint128_7, 7, read_uint128); - too_small!(small_uint128_8, 8, read_uint128); - too_small!(small_uint128_9, 9, read_uint128); - too_small!(small_uint128_10, 10, read_uint128); - too_small!(small_uint128_11, 11, read_uint128); - too_small!(small_uint128_12, 12, read_uint128); - too_small!(small_uint128_13, 13, read_uint128); - too_small!(small_uint128_14, 14, read_uint128); - too_small!(small_uint128_15, 15, read_uint128); - - too_small!(small_int_1, 1, read_int); - too_small!(small_int_2, 2, read_int); - too_small!(small_int_3, 3, read_int); - too_small!(small_int_4, 4, read_int); - too_small!(small_int_5, 5, read_int); - too_small!(small_int_6, 6, read_int); - too_small!(small_int_7, 7, read_int); - - too_small!(small_int128_1, 1, read_int128); - too_small!(small_int128_2, 2, read_int128); - too_small!(small_int128_3, 3, read_int128); - too_small!(small_int128_4, 4, read_int128); - too_small!(small_int128_5, 5, read_int128); - too_small!(small_int128_6, 6, read_int128); - too_small!(small_int128_7, 7, read_int128); - too_small!(small_int128_8, 8, read_int128); - too_small!(small_int128_9, 9, read_int128); - too_small!(small_int128_10, 10, read_int128); - too_small!(small_int128_11, 11, read_int128); - too_small!(small_int128_12, 12, read_int128); - too_small!(small_int128_13, 13, read_int128); - too_small!(small_int128_14, 14, read_int128); - too_small!(small_int128_15, 15, read_int128); - - // Test that reading/writing slices enforces the correct lengths. - macro_rules! slice_lengths { - ($name:ident, $read:ident, $write:ident, - $num_bytes:expr, $numbers:expr) => { - mod $name { - use crate::{ - BigEndian, ByteOrder, LittleEndian, NativeEndian, - }; - - #[test] - #[should_panic] - fn read_big_endian() { - let bytes = [0; $num_bytes]; - let mut numbers = $numbers; - BigEndian::$read(&bytes, &mut numbers); - } - - #[test] - #[should_panic] - fn read_little_endian() { - let bytes = [0; $num_bytes]; - let mut numbers = $numbers; - LittleEndian::$read(&bytes, &mut numbers); - } - - #[test] - #[should_panic] - fn read_native_endian() { - let bytes = [0; $num_bytes]; - let mut numbers = $numbers; - NativeEndian::$read(&bytes, &mut numbers); - } - - #[test] - #[should_panic] - fn write_big_endian() { - let mut bytes = [0; $num_bytes]; - let numbers = $numbers; - BigEndian::$write(&numbers, &mut bytes); - } - - #[test] - #[should_panic] - fn write_little_endian() { - let mut bytes = [0; $num_bytes]; - let numbers = $numbers; - LittleEndian::$write(&numbers, &mut bytes); - } - - #[test] - #[should_panic] - fn write_native_endian() { - let mut bytes = [0; $num_bytes]; - let numbers = $numbers; - NativeEndian::$write(&numbers, &mut bytes); - } - } - }; - } - - slice_lengths!( - slice_len_too_small_u16, - read_u16_into, - write_u16_into, - 3, - [0, 0] - ); - slice_lengths!( - slice_len_too_big_u16, - read_u16_into, - write_u16_into, - 5, - [0, 0] - ); - slice_lengths!( - slice_len_too_small_i16, - read_i16_into, - write_i16_into, - 3, - [0, 0] - ); - slice_lengths!( - slice_len_too_big_i16, - read_i16_into, - write_i16_into, - 5, - [0, 0] - ); - - slice_lengths!( - slice_len_too_small_u32, - read_u32_into, - write_u32_into, - 7, - [0, 0] - ); - slice_lengths!( - slice_len_too_big_u32, - read_u32_into, - write_u32_into, - 9, - [0, 0] - ); - slice_lengths!( - slice_len_too_small_i32, - read_i32_into, - write_i32_into, - 7, - [0, 0] - ); - slice_lengths!( - slice_len_too_big_i32, - read_i32_into, - write_i32_into, - 9, - [0, 0] - ); - - slice_lengths!( - slice_len_too_small_u64, - read_u64_into, - write_u64_into, - 15, - [0, 0] - ); - slice_lengths!( - slice_len_too_big_u64, - read_u64_into, - write_u64_into, - 17, - [0, 0] - ); - slice_lengths!( - slice_len_too_small_i64, - read_i64_into, - write_i64_into, - 15, - [0, 0] - ); - slice_lengths!( - slice_len_too_big_i64, - read_i64_into, - write_i64_into, - 17, - [0, 0] - ); - - slice_lengths!( - slice_len_too_small_u128, - read_u128_into, - write_u128_into, - 31, - [0, 0] - ); - slice_lengths!( - slice_len_too_big_u128, - read_u128_into, - write_u128_into, - 33, - [0, 0] - ); - slice_lengths!( - slice_len_too_small_i128, - read_i128_into, - write_i128_into, - 31, - [0, 0] - ); - slice_lengths!( - slice_len_too_big_i128, - read_i128_into, - write_i128_into, - 33, - [0, 0] - ); - - #[test] - fn uint_bigger_buffer() { - use crate::{ByteOrder, LittleEndian}; - let n = LittleEndian::read_uint(&[1, 2, 3, 4, 5, 6, 7, 8], 5); - assert_eq!(n, 0x05_0403_0201); - } - - #[test] - fn regression173_array_impl() { - use crate::{BigEndian, ByteOrder, LittleEndian}; - - let xs = [0; 100]; - - let x = BigEndian::read_u16(&xs); - assert_eq!(x, 0); - let x = BigEndian::read_u32(&xs); - assert_eq!(x, 0); - let x = BigEndian::read_u64(&xs); - assert_eq!(x, 0); - let x = BigEndian::read_u128(&xs); - assert_eq!(x, 0); - let x = BigEndian::read_i16(&xs); - assert_eq!(x, 0); - let x = BigEndian::read_i32(&xs); - assert_eq!(x, 0); - let x = BigEndian::read_i64(&xs); - assert_eq!(x, 0); - let x = BigEndian::read_i128(&xs); - assert_eq!(x, 0); - - let x = LittleEndian::read_u16(&xs); - assert_eq!(x, 0); - let x = LittleEndian::read_u32(&xs); - assert_eq!(x, 0); - let x = LittleEndian::read_u64(&xs); - assert_eq!(x, 0); - let x = LittleEndian::read_u128(&xs); - assert_eq!(x, 0); - let x = LittleEndian::read_i16(&xs); - assert_eq!(x, 0); - let x = LittleEndian::read_i32(&xs); - assert_eq!(x, 0); - let x = LittleEndian::read_i64(&xs); - assert_eq!(x, 0); - let x = LittleEndian::read_i128(&xs); - assert_eq!(x, 0); - } -} - -#[cfg(test)] -#[cfg(feature = "std")] -mod stdtests { - extern crate quickcheck; - extern crate rand; - - use self::quickcheck::{QuickCheck, StdGen, Testable}; - use self::rand::thread_rng; - - fn qc_unsized<A: Testable>(f: A) { - QuickCheck::new() - .gen(StdGen::new(thread_rng(), 16)) - .tests(1_00) - .max_tests(10_000) - .quickcheck(f); - } - - macro_rules! calc_max { - ($max:expr, $bytes:expr) => { - ($max - 1) >> (8 * (8 - $bytes)) - }; - } - - macro_rules! qc_bytes_ext { - ($name:ident, $ty_int:ty, $max:expr, - $bytes:expr, $read:ident, $write:ident) => { - #[cfg(not(miri))] - mod $name { - #[allow(unused_imports)] - use crate::test::{qc_sized, Wi128}; - use crate::{ - BigEndian, LittleEndian, NativeEndian, ReadBytesExt, - WriteBytesExt, - }; - use std::io::Cursor; - - #[test] - fn big_endian() { - fn prop(n: $ty_int) -> bool { - let mut wtr = vec![]; - wtr.$write::<BigEndian>(n.clone()).unwrap(); - let offset = wtr.len() - $bytes; - let mut rdr = Cursor::new(&mut wtr[offset..]); - n == rdr.$read::<BigEndian>($bytes).unwrap() - } - qc_sized(prop as fn($ty_int) -> bool, $max); - } - - #[test] - fn little_endian() { - fn prop(n: $ty_int) -> bool { - let mut wtr = vec![]; - wtr.$write::<LittleEndian>(n.clone()).unwrap(); - let mut rdr = Cursor::new(wtr); - n == rdr.$read::<LittleEndian>($bytes).unwrap() - } - qc_sized(prop as fn($ty_int) -> bool, $max); - } - - #[test] - fn native_endian() { - fn prop(n: $ty_int) -> bool { - let mut wtr = vec![]; - wtr.$write::<NativeEndian>(n.clone()).unwrap(); - let offset = if cfg!(target_endian = "big") { - wtr.len() - $bytes - } else { - 0 - }; - let mut rdr = Cursor::new(&mut wtr[offset..]); - n == rdr.$read::<NativeEndian>($bytes).unwrap() - } - qc_sized(prop as fn($ty_int) -> bool, $max); - } - } - }; - ($name:ident, $ty_int:ty, $max:expr, $read:ident, $write:ident) => { - #[cfg(not(miri))] - mod $name { - #[allow(unused_imports)] - use crate::test::{qc_sized, Wi128}; - use crate::{ - BigEndian, LittleEndian, NativeEndian, ReadBytesExt, - WriteBytesExt, - }; - use std::io::Cursor; - - #[test] - fn big_endian() { - fn prop(n: $ty_int) -> bool { - let mut wtr = vec![]; - wtr.$write::<BigEndian>(n.clone()).unwrap(); - let mut rdr = Cursor::new(wtr); - n == rdr.$read::<BigEndian>().unwrap() - } - qc_sized(prop as fn($ty_int) -> bool, $max - 1); - } - - #[test] - fn little_endian() { - fn prop(n: $ty_int) -> bool { - let mut wtr = vec![]; - wtr.$write::<LittleEndian>(n.clone()).unwrap(); - let mut rdr = Cursor::new(wtr); - n == rdr.$read::<LittleEndian>().unwrap() - } - qc_sized(prop as fn($ty_int) -> bool, $max - 1); - } - - #[test] - fn native_endian() { - fn prop(n: $ty_int) -> bool { - let mut wtr = vec![]; - wtr.$write::<NativeEndian>(n.clone()).unwrap(); - let mut rdr = Cursor::new(wtr); - n == rdr.$read::<NativeEndian>().unwrap() - } - qc_sized(prop as fn($ty_int) -> bool, $max - 1); - } - } - }; - } - - qc_bytes_ext!( - prop_ext_u16, - u16, - ::std::u16::MAX as u64, - read_u16, - write_u16 - ); - qc_bytes_ext!( - prop_ext_i16, - i16, - ::std::i16::MAX as u64, - read_i16, - write_i16 - ); - qc_bytes_ext!( - prop_ext_u32, - u32, - ::std::u32::MAX as u64, - read_u32, - write_u32 - ); - qc_bytes_ext!( - prop_ext_i32, - i32, - ::std::i32::MAX as u64, - read_i32, - write_i32 - ); - qc_bytes_ext!( - prop_ext_u64, - u64, - ::std::u64::MAX as u64, - read_u64, - write_u64 - ); - qc_bytes_ext!( - prop_ext_i64, - i64, - ::std::i64::MAX as u64, - read_i64, - write_i64 - ); - qc_bytes_ext!( - prop_ext_f32, - f32, - ::std::u64::MAX as u64, - read_f32, - write_f32 - ); - qc_bytes_ext!( - prop_ext_f64, - f64, - ::std::i64::MAX as u64, - read_f64, - write_f64 - ); - - qc_bytes_ext!(prop_ext_u128, Wi128<u128>, 16 + 1, read_u128, write_u128); - qc_bytes_ext!(prop_ext_i128, Wi128<i128>, 16 + 1, read_i128, write_i128); - - qc_bytes_ext!( - prop_ext_uint_1, - u64, - calc_max!(crate::test::U64_MAX, 1), - 1, - read_uint, - write_u64 - ); - qc_bytes_ext!( - prop_ext_uint_2, - u64, - calc_max!(crate::test::U64_MAX, 2), - 2, - read_uint, - write_u64 - ); - qc_bytes_ext!( - prop_ext_uint_3, - u64, - calc_max!(crate::test::U64_MAX, 3), - 3, - read_uint, - write_u64 - ); - qc_bytes_ext!( - prop_ext_uint_4, - u64, - calc_max!(crate::test::U64_MAX, 4), - 4, - read_uint, - write_u64 - ); - qc_bytes_ext!( - prop_ext_uint_5, - u64, - calc_max!(crate::test::U64_MAX, 5), - 5, - read_uint, - write_u64 - ); - qc_bytes_ext!( - prop_ext_uint_6, - u64, - calc_max!(crate::test::U64_MAX, 6), - 6, - read_uint, - write_u64 - ); - qc_bytes_ext!( - prop_ext_uint_7, - u64, - calc_max!(crate::test::U64_MAX, 7), - 7, - read_uint, - write_u64 - ); - qc_bytes_ext!( - prop_ext_uint_8, - u64, - calc_max!(crate::test::U64_MAX, 8), - 8, - read_uint, - write_u64 - ); - - qc_bytes_ext!( - prop_ext_uint128_1, - Wi128<u128>, - 1, - 1, - read_uint128, - write_u128 - ); - qc_bytes_ext!( - prop_ext_uint128_2, - Wi128<u128>, - 2, - 2, - read_uint128, - write_u128 - ); - qc_bytes_ext!( - prop_ext_uint128_3, - Wi128<u128>, - 3, - 3, - read_uint128, - write_u128 - ); - qc_bytes_ext!( - prop_ext_uint128_4, - Wi128<u128>, - 4, - 4, - read_uint128, - write_u128 - ); - qc_bytes_ext!( - prop_ext_uint128_5, - Wi128<u128>, - 5, - 5, - read_uint128, - write_u128 - ); - qc_bytes_ext!( - prop_ext_uint128_6, - Wi128<u128>, - 6, - 6, - read_uint128, - write_u128 - ); - qc_bytes_ext!( - prop_ext_uint128_7, - Wi128<u128>, - 7, - 7, - read_uint128, - write_u128 - ); - qc_bytes_ext!( - prop_ext_uint128_8, - Wi128<u128>, - 8, - 8, - read_uint128, - write_u128 - ); - qc_bytes_ext!( - prop_ext_uint128_9, - Wi128<u128>, - 9, - 9, - read_uint128, - write_u128 - ); - qc_bytes_ext!( - prop_ext_uint128_10, - Wi128<u128>, - 10, - 10, - read_uint128, - write_u128 - ); - qc_bytes_ext!( - prop_ext_uint128_11, - Wi128<u128>, - 11, - 11, - read_uint128, - write_u128 - ); - qc_bytes_ext!( - prop_ext_uint128_12, - Wi128<u128>, - 12, - 12, - read_uint128, - write_u128 - ); - qc_bytes_ext!( - prop_ext_uint128_13, - Wi128<u128>, - 13, - 13, - read_uint128, - write_u128 - ); - qc_bytes_ext!( - prop_ext_uint128_14, - Wi128<u128>, - 14, - 14, - read_uint128, - write_u128 - ); - qc_bytes_ext!( - prop_ext_uint128_15, - Wi128<u128>, - 15, - 15, - read_uint128, - write_u128 - ); - qc_bytes_ext!( - prop_ext_uint128_16, - Wi128<u128>, - 16, - 16, - read_uint128, - write_u128 - ); - - qc_bytes_ext!( - prop_ext_int_1, - i64, - calc_max!(crate::test::I64_MAX, 1), - 1, - read_int, - write_i64 - ); - qc_bytes_ext!( - prop_ext_int_2, - i64, - calc_max!(crate::test::I64_MAX, 2), - 2, - read_int, - write_i64 - ); - qc_bytes_ext!( - prop_ext_int_3, - i64, - calc_max!(crate::test::I64_MAX, 3), - 3, - read_int, - write_i64 - ); - qc_bytes_ext!( - prop_ext_int_4, - i64, - calc_max!(crate::test::I64_MAX, 4), - 4, - read_int, - write_i64 - ); - qc_bytes_ext!( - prop_ext_int_5, - i64, - calc_max!(crate::test::I64_MAX, 5), - 5, - read_int, - write_i64 - ); - qc_bytes_ext!( - prop_ext_int_6, - i64, - calc_max!(crate::test::I64_MAX, 6), - 6, - read_int, - write_i64 - ); - qc_bytes_ext!( - prop_ext_int_7, - i64, - calc_max!(crate::test::I64_MAX, 1), - 7, - read_int, - write_i64 - ); - qc_bytes_ext!( - prop_ext_int_8, - i64, - calc_max!(crate::test::I64_MAX, 8), - 8, - read_int, - write_i64 - ); - - qc_bytes_ext!( - prop_ext_int128_1, - Wi128<i128>, - 1, - 1, - read_int128, - write_i128 - ); - qc_bytes_ext!( - prop_ext_int128_2, - Wi128<i128>, - 2, - 2, - read_int128, - write_i128 - ); - qc_bytes_ext!( - prop_ext_int128_3, - Wi128<i128>, - 3, - 3, - read_int128, - write_i128 - ); - qc_bytes_ext!( - prop_ext_int128_4, - Wi128<i128>, - 4, - 4, - read_int128, - write_i128 - ); - qc_bytes_ext!( - prop_ext_int128_5, - Wi128<i128>, - 5, - 5, - read_int128, - write_i128 - ); - qc_bytes_ext!( - prop_ext_int128_6, - Wi128<i128>, - 6, - 6, - read_int128, - write_i128 - ); - qc_bytes_ext!( - prop_ext_int128_7, - Wi128<i128>, - 7, - 7, - read_int128, - write_i128 - ); - qc_bytes_ext!( - prop_ext_int128_8, - Wi128<i128>, - 8, - 8, - read_int128, - write_i128 - ); - qc_bytes_ext!( - prop_ext_int128_9, - Wi128<i128>, - 9, - 9, - read_int128, - write_i128 - ); - qc_bytes_ext!( - prop_ext_int128_10, - Wi128<i128>, - 10, - 10, - read_int128, - write_i128 - ); - qc_bytes_ext!( - prop_ext_int128_11, - Wi128<i128>, - 11, - 11, - read_int128, - write_i128 - ); - qc_bytes_ext!( - prop_ext_int128_12, - Wi128<i128>, - 12, - 12, - read_int128, - write_i128 - ); - qc_bytes_ext!( - prop_ext_int128_13, - Wi128<i128>, - 13, - 13, - read_int128, - write_i128 - ); - qc_bytes_ext!( - prop_ext_int128_14, - Wi128<i128>, - 14, - 14, - read_int128, - write_i128 - ); - qc_bytes_ext!( - prop_ext_int128_15, - Wi128<i128>, - 15, - 15, - read_int128, - write_i128 - ); - qc_bytes_ext!( - prop_ext_int128_16, - Wi128<i128>, - 16, - 16, - read_int128, - write_i128 - ); - - // Test slice serialization/deserialization. - macro_rules! qc_slice { - ($name:ident, $ty_int:ty, $read:ident, $write:ident, $zero:expr) => { - #[cfg(not(miri))] - mod $name { - use super::qc_unsized; - #[allow(unused_imports)] - use crate::test::Wi128; - use crate::{ - BigEndian, ByteOrder, LittleEndian, NativeEndian, - }; - use core::mem::size_of; - - #[test] - fn big_endian() { - #[allow(unused_unsafe)] - fn prop(numbers: Vec<$ty_int>) -> bool { - let numbers: Vec<_> = - numbers.into_iter().map(|x| x.clone()).collect(); - let num_bytes = size_of::<$ty_int>() * numbers.len(); - let mut bytes = vec![0; num_bytes]; - - BigEndian::$write(&numbers, &mut bytes); - - let mut got = vec![$zero; numbers.len()]; - unsafe { - BigEndian::$read(&bytes, &mut got); - } - - numbers == got - } - qc_unsized(prop as fn(_) -> bool); - } - - #[test] - fn little_endian() { - #[allow(unused_unsafe)] - fn prop(numbers: Vec<$ty_int>) -> bool { - let numbers: Vec<_> = - numbers.into_iter().map(|x| x.clone()).collect(); - let num_bytes = size_of::<$ty_int>() * numbers.len(); - let mut bytes = vec![0; num_bytes]; - - LittleEndian::$write(&numbers, &mut bytes); - - let mut got = vec![$zero; numbers.len()]; - unsafe { - LittleEndian::$read(&bytes, &mut got); - } - - numbers == got - } - qc_unsized(prop as fn(_) -> bool); - } - - #[test] - fn native_endian() { - #[allow(unused_unsafe)] - fn prop(numbers: Vec<$ty_int>) -> bool { - let numbers: Vec<_> = - numbers.into_iter().map(|x| x.clone()).collect(); - let num_bytes = size_of::<$ty_int>() * numbers.len(); - let mut bytes = vec![0; num_bytes]; - - NativeEndian::$write(&numbers, &mut bytes); - - let mut got = vec![$zero; numbers.len()]; - unsafe { - NativeEndian::$read(&bytes, &mut got); - } - - numbers == got - } - qc_unsized(prop as fn(_) -> bool); - } - } - }; - } - - qc_slice!(prop_slice_u16, u16, read_u16_into, write_u16_into, 0); - qc_slice!(prop_slice_i16, i16, read_i16_into, write_i16_into, 0); - qc_slice!(prop_slice_u32, u32, read_u32_into, write_u32_into, 0); - qc_slice!(prop_slice_i32, i32, read_i32_into, write_i32_into, 0); - qc_slice!(prop_slice_u64, u64, read_u64_into, write_u64_into, 0); - qc_slice!(prop_slice_i64, i64, read_i64_into, write_i64_into, 0); - qc_slice!( - prop_slice_u128, - Wi128<u128>, - read_u128_into, - write_u128_into, - 0 - ); - qc_slice!( - prop_slice_i128, - Wi128<i128>, - read_i128_into, - write_i128_into, - 0 - ); - - qc_slice!(prop_slice_f32, f32, read_f32_into, write_f32_into, 0.0); - qc_slice!(prop_slice_f64, f64, read_f64_into, write_f64_into, 0.0); -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/.cargo-checksum.json b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/.cargo-checksum.json deleted file mode 100644 index 697c9ce..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/.cargo-checksum.json +++ /dev/null
@@ -1 +0,0 @@ -{"files":{}}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/.cargo_vcs_info.json b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/.cargo_vcs_info.json deleted file mode 100644 index f04fc1cf..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/.cargo_vcs_info.json +++ /dev/null
@@ -1,6 +0,0 @@ -{ - "git": { - "sha1": "727de668608f2d16e151c42e344d172c0931b1e9" - }, - "path_in_vcs": "" -} \ No newline at end of file
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/CONTRIBUTING.md b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/CONTRIBUTING.md deleted file mode 100644 index 929e8099..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/CONTRIBUTING.md +++ /dev/null
@@ -1,215 +0,0 @@ -<!-- Copyright 2022 The Fuchsia Authors - -Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -<LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -This file may not be copied, modified, or distributed except according to -those terms. --> - -# How to Contribute - -We'd love to accept your patches and contributions to zerocopy. There are just a -few small guidelines you need to follow. - -Once you've read the rest of this doc, check out our [good-first-issue -label][good-first-issue] for some good issues you can use to get your toes wet! - -## Contributor License Agreement - -Contributions to this project must be accompanied by a Contributor License -Agreement. You (or your employer) retain the copyright to your contribution; -this simply gives us permission to use and redistribute your contributions as -part of the project. Head over to <https://cla.developers.google.com/> to see -your current agreements on file or to sign a new one. - -You generally only need to submit a CLA once, so if you've already submitted one -(even if it was for a different project), you probably don't need to do it -again. - -## Code Reviews - -All submissions, including submissions by project members, require review. We -use GitHub pull requests for this purpose. Consult [GitHub -Help][about_pull_requests] for more information on using pull requests. - -## Code Guidelines - -### Philosophy - -This section is inspired by [Flutter's style guide][flutter_philosophy], which -contains many general principles that you should apply to all your programming -work. Read it. The below calls out specific aspects that we feel are -particularly important. - -#### Dogfood Your Features - -In non-library code, it's often advised to only implement features you need. -After all, it's hard to correctly design code without a concrete use case to -guide its design. Since zerocopy is a library, this advice is not as applicable; -we want our API surface to be featureful and complete even if not every feature -or method has a known use case. However, the observation that unused code is -hard to design still holds. - -Thus, when designing external-facing features, try to make use of them somehow. -This could be by using them to implement other features, or it could be by -writing prototype code which won't actually be checked in anywhere. If you're -feeling ambitious, you could even add (and check in) a [Cargo -example][cargo_example] that exercises the new feature. - -#### Go Down the Rabbit Hole - -You will occasionally encounter behavior that surprises you or seems wrong. It -probably is! Invest the time to find the root cause - you will either learn -something, or fix something, and both are worth your time. Do not work around -behavior you don't understand. - -### Avoid Duplication - -Avoid duplicating code whenever possible. In cases where existing code is not -exposed in a manner suitable to your needs, prefer to extract the necessary -parts into a common dependency. - -### Comments - -When writing comments, take a moment to consider the future reader of your -comment. Ensure that your comments are complete sentences with proper grammar -and punctuation. Note that adding more comments or more verbose comments is not -always better; for example, avoid comments that repeat the code they're anchored -on. - -Documentation comments should be self-contained; in other words, do not assume -that the reader is aware of documentation in adjacent files or on adjacent -structures. Avoid documentation comments on types which describe _instances_ of -the type; for example, `AddressSet is a set of client addresses.` is a comment -that describes a field of type `AddressSet`, but the type may be used to hold -any kind of `Address`, not just a client's. - -Phrase your comments to avoid references that might become stale; for example: -do not mention a variable or type by name when possible (certain doc comments -are necessary exceptions). Also avoid references to past or future versions of -or past or future work surrounding the item being documented; explain things -from first principles rather than making external references (including past -revisions). - -When writing TODOs: - -1. Include an issue reference using the format `TODO(#123):` -1. Phrase the text as an action that is to be taken; it should be possible for - another contributor to pick up the TODO without consulting any external - sources, including the referenced issue. - -### Tests - -Much of the code in zerocopy has the property that, if it is buggy, those bugs -may not cause user code to fail. This makes it extra important to write thorough -tests, but it also makes it harder to write those tests correctly. Here are some -guidelines on how to test code in zerocopy: -1. All code added to zerocopy must include tests that exercise it completely. -1. Tests must be deterministic. Threaded or time-dependent code, random number - generators (RNGs), and communication with external processes are common - sources of nondeterminism. See [Write reproducible, deterministic - tests][determinism] for tips. -1. Avoid [change detector tests][change_detector_tests]; tests that are - unnecessarily sensitive to changes, especially ones external to the code - under test, can hamper feature development and refactoring. -1. Since we run tests in [Miri][miri], make sure that tests exist which exercise - any potential [undefined behavior][undefined_behavior] so that Miri can catch - it. -1. If there's some user code that should be impossible to compile, add a - [trybuild test][trybuild] to ensure that it's properly rejected. - -### Source Control Best Practices - -Commits should be arranged for ease of reading; that is, incidental changes -such as code movement or formatting changes should be committed separately from -actual code changes. - -Commits should always be focused. For example, a commit could add a feature, -fix a bug, or refactor code, but not a mixture. - -Commits should be thoughtfully sized; avoid overly large or complex commits -which can be logically separated, but also avoid overly separated commits that -require code reviews to load multiple commits into their mental working memory -in order to properly understand how the various pieces fit together. - -#### Commit Messages - -Commit messages should be _concise_ but self-contained (avoid relying on issue -references as explanations for changes) and written such that they are helpful -to people reading in the future (include rationale and any necessary context). - -Avoid superfluous details or narrative. - -Commit messages should consist of a brief subject line and a separate -explanatory paragraph in accordance with the following: - -1. [Separate subject from body with a blank line](https://chris.beams.io/posts/git-commit/#separate) -1. [Limit the subject line to 50 characters](https://chris.beams.io/posts/git-commit/#limit-50) -1. [Capitalize the subject line](https://chris.beams.io/posts/git-commit/#capitalize) -1. [Do not end the subject line with a period](https://chris.beams.io/posts/git-commit/#end) -1. [Use the imperative mood in the subject line](https://chris.beams.io/posts/git-commit/#imperative) -1. [Wrap the body at 72 characters](https://chris.beams.io/posts/git-commit/#wrap-72) -1. [Use the body to explain what and why vs. how](https://chris.beams.io/posts/git-commit/#why-not-how) - -If the code affects a particular subsystem, prefix the subject line with the -name of that subsystem in square brackets, omitting any "zerocopy" prefix -(that's implicit). For example, for a commit adding a feature to the -zerocopy-derive crate: - -```text -[derive] Support AsBytes on types with parameters -``` - -The body may be omitted if the subject is self-explanatory; e.g. when fixing a -typo. The git book contains a [Commit Guidelines][commit_guidelines] section -with much of the same advice, and the list above is part of a [blog -post][beams_git_commit] by [Chris Beams][chris_beams]. - -Commit messages should make use of issue integration. Including an issue -reference like `#123` will cause the GitHub UI to link the text of that -reference to the referenced issue, and will also make it so that the referenced -issue back-links to the commit. Use "Closes", "Fixes", or "Resolves" on its own -line to automatically close an issue when your commit is merged: - -```text -Closes #123 -Fixes #123 -Resolves #123 -``` - -When using issue integration, don't omit necessary context that may also be -included in the relevant issue (see "Commit messages should be _concise_ but -self-contained" above). Git history is more likely to be retained indefinitely -than issue history (for example, if this repository is migrated away from GitHub -at some point in the future). - -Commit messages should never contain references to any of: - -1. Relative moments in time -1. Non-public URLs -1. Individuals -1. Hosted code reviews (such as on https://github.com/google/zerocopy/pulls) - + Refer to commits in this repository by their SHA-1 hash - + Refer to commits in other repositories by public web address (such as - https://github.com/google/zerocopy/commit/789b3deb) -1. Other entities which may not make sense to arbitrary future readers - -## Community Guidelines - -This project follows [Google's Open Source Community -Guidelines][google_open_source_guidelines]. - -[about_pull_requests]: https://help.github.com/articles/about-pull-requests/ -[beams_git_commit]: https://chris.beams.io/posts/git-commit/ -[cargo_example]: http://xion.io/post/code/rust-examples.html -[change_detector_tests]: https://testing.googleblog.com/2015/01/testing-on-toilet-change-detector-tests.html -[chris_beams]: https://chris.beams.io/ -[commit_guidelines]: https://www.git-scm.com/book/en/v2/Distributed-Git-Contributing-to-a-Project#_commit_guidelines -[determinism]: https://fuchsia.dev/fuchsia-src/contribute/testing/best-practices#write_reproducible_deterministic_tests -[flutter_philosophy]: https://github.com/flutter/flutter/wiki/Style-guide-for-Flutter-repo#philosophy -[good-first-issue]: https://github.com/google/zerocopy/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22 -[google_open_source_guidelines]: https://opensource.google/conduct/ -[magic_number]: https://en.wikipedia.org/wiki/Magic_number_(programming) -[miri]: https://github.com/rust-lang/miri -[trybuild]: https://crates.io/crates/trybuild -[undefined_behavior]: https://raphlinus.github.io/programming/rust/2018/08/17/undefined-behavior.html
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/Cargo.toml b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/Cargo.toml deleted file mode 100644 index 3d3907cb8..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/Cargo.toml +++ /dev/null
@@ -1,101 +0,0 @@ -# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO -# -# When uploading crates to the registry Cargo will automatically -# "normalize" Cargo.toml files for maximal compatibility -# with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g., crates.io) dependencies. -# -# If you are reading this file be aware that the original Cargo.toml -# will likely look very different (and much more reasonable). -# See Cargo.toml.orig for the original contents. - -[package] -edition = "2018" -rust-version = "1.60.0" -name = "zerocopy" -version = "0.7.35" -authors = ["Joshua Liebow-Feeser <joshlf@google.com>"] -exclude = [".*"] -description = "Utilities for zero-copy parsing and serialization" -readme = "README.md" -keywords = [ - "cast", - "convert", - "transmute", - "transmutation", - "type-punning", -] -categories = [ - "embedded", - "encoding", - "no-std::no-alloc", - "parsing", - "rust-patterns", -] -license = "BSD-2-Clause OR Apache-2.0 OR MIT" -repository = "https://github.com/google/zerocopy" - -[package.metadata.ci] -pinned-nightly = "nightly-2024-06-19" -pinned-stable = "1.79.0" - -[package.metadata.docs.rs] -all-features = true -rustdoc-args = [ - "--cfg", - "doc_cfg", - "--generate-link-to-definition", -] - -[package.metadata.playground] -features = ["__internal_use_only_features_that_work_on_stable"] - -[dependencies.byteorder] -version = "1.3" -optional = true -default-features = false - -[dependencies.zerocopy-derive] -version = "=0.7.35" -optional = true - -[dev-dependencies.assert_matches] -version = "1.5" - -[dev-dependencies.elain] -version = "0.3.0" - -[dev-dependencies.itertools] -version = "0.11" - -[dev-dependencies.rand] -version = "0.8.5" -features = ["small_rng"] - -[dev-dependencies.rustversion] -version = "1.0" - -[dev-dependencies.static_assertions] -version = "1.1" - -[dev-dependencies.trybuild] -version = "=1.0.85" -features = ["diff"] - -[dev-dependencies.zerocopy-derive] -version = "=0.7.35" - -[features] -__internal_use_only_features_that_work_on_stable = [ - "alloc", - "derive", - "simd", -] -alloc = [] -default = ["byteorder"] -derive = ["zerocopy-derive"] -simd = [] -simd-nightly = ["simd"] - -[target."cfg(any())".dependencies.zerocopy-derive] -version = "=0.7.35"
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/Cargo.toml.orig b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/Cargo.toml.orig deleted file mode 100644 index 6ac966a7d..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/Cargo.toml.orig +++ /dev/null
@@ -1,82 +0,0 @@ -# Copyright 2018 The Fuchsia Authors -# -# Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -# <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -# license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -# This file may not be copied, modified, or distributed except according to -# those terms. - -# Put both crates in a single workspace so that `trybuild` compiler errors have -# paths that are stable regardless of the path to the repository root. This -# avoids issues like: -# https://github.com/dtolnay/trybuild/issues/207#issuecomment-131227.594 -[workspace] - -[package] -edition = "2018" -name = "zerocopy" -version = "0.7.35" -authors = ["Joshua Liebow-Feeser <joshlf@google.com>"] -description = "Utilities for zero-copy parsing and serialization" -categories = ["embedded", "encoding", "no-std::no-alloc", "parsing", "rust-patterns"] -keywords = ["cast", "convert", "transmute", "transmutation", "type-punning"] -license = "BSD-2-Clause OR Apache-2.0 OR MIT" -repository = "https://github.com/google/zerocopy" -rust-version = "1.60.0" - -exclude = [".*"] - -[package.metadata.docs.rs] -all-features = true -rustdoc-args = ["--cfg", "doc_cfg", "--generate-link-to-definition"] - -[package.metadata.ci] -# The versions of the stable and nightly compiler toolchains to use in CI. -pinned-stable = "1.79.0" -pinned-nightly = "nightly-2024-06-19" - -[package.metadata.playground] -features = ["__internal_use_only_features_that_work_on_stable"] - -[features] -default = ["byteorder"] - -alloc = [] -derive = ["zerocopy-derive"] -simd = [] -simd-nightly = ["simd"] -# This feature depends on all other features that work on the stable compiler. -# We make no stability guarantees about this feature; it may be modified or -# removed at any time. -__internal_use_only_features_that_work_on_stable = ["alloc", "derive", "simd"] - -[dependencies] -zerocopy-derive = { version = "=0.7.35", path = "zerocopy-derive", optional = true } - -[dependencies.byteorder] -version = "1.3" -default-features = false -optional = true - -# The "associated proc macro pattern" ensures that the versions of zerocopy and -# zerocopy-derive remain equal, even if the 'derive' feature isn't used. -# See: https://github.com/matklad/macro-dep-test -[target.'cfg(any())'.dependencies] -zerocopy-derive = { version = "=0.7.35", path = "zerocopy-derive" } - -[dev-dependencies] -assert_matches = "1.5" -itertools = "0.11" -rand = { version = "0.8.5", features = ["small_rng"] } -rustversion = "1.0" -static_assertions = "1.1" -testutil = { path = "testutil" } -# Pinned to a specific version so that the version used for local development -# and the version used in CI are guaranteed to be the same. Future versions -# sometimes change the output format slightly, so a version mismatch can cause -# CI test failures. -trybuild = { version = "=1.0.85", features = ["diff"] } -# In tests, unlike in production, zerocopy-derive is not optional -zerocopy-derive = { version = "=0.7.35", path = "zerocopy-derive" } -# TODO(#381) Remove this dependency once we have our own layout gadgets. -elain = "0.3.0"
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/INTERNAL.md b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/INTERNAL.md deleted file mode 100644 index 4e7f440..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/INTERNAL.md +++ /dev/null
@@ -1,44 +0,0 @@ -<!-- Copyright 2022 The Fuchsia Authors - -Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -<LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -This file may not be copied, modified, or distributed except according to -those terms. --> - -# Internal details - -This file documents various internal details of zerocopy and its infrastructure -that consumers don't need to be concerned about. It focuses on details that -affect multiple files, and allows each affected code location to reference this -document rather than requiring us to repeat the same explanation in multiple -locations. - -## CI and toolchain versions - -In CI (`.github/workflows/ci.yml`), we pin to specific versions or dates of the -stable and nightly toolchains. The reason is twofold: First, our UI tests (see -`tests/trybuild.rs` and `zerocopy-derive/tests/trybuild.rs`) depend on the -format of rustc's error messages, and that format can change between toolchain -versions (we also maintain multiple copies of our UI tests - one for each -toolchain version pinned in CI - for this reason). Second, not all nightlies -have a working Miri, so we need to pin to one that does (see -https://rust-lang.github.io/rustup-components-history/). - -Updating the versions pinned in CI may cause the UI tests to break. In order to -fix UI tests after a version update, run: - -``` -$ TRYBUILD=overwrite ./cargo.sh +all test -``` - -## Crate versions - -We ensure that the crate versions of zerocopy and zerocopy-derive are always the -same in-tree, and that zerocopy depends upon zerocopy-derive using an exact -version match to the current version in-tree. This has the result that, even -when published on crates.io, both crates effectively constitute a single atomic -version. So long as the code in zerocopy is compatible with the code in -zerocopy-derive in the same Git commit, then publishing them both is fine. This -frees us from the normal task of reasoning about compatibility with a range of -semver-compatible versions of different crates.
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/LICENSE-APACHE b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/LICENSE-APACHE deleted file mode 100644 index 2dc22c1..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/LICENSE-APACHE +++ /dev/null
@@ -1,202 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright 2023 The Fuchsia Authors - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/LICENSE-BSD b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/LICENSE-BSD deleted file mode 100644 index 7ed244f..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/LICENSE-BSD +++ /dev/null
@@ -1,24 +0,0 @@ -Copyright 2019 The Fuchsia Authors. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/LICENSE-MIT b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/LICENSE-MIT deleted file mode 100644 index 26e1521..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/LICENSE-MIT +++ /dev/null
@@ -1,26 +0,0 @@ -Copyright 2023 The Fuchsia Authors - -Permission is hereby granted, free of charge, to any -person obtaining a copy of this software and associated -documentation files (the "Software"), to deal in the -Software without restriction, including without -limitation the rights to use, copy, modify, merge, -publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software -is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice -shall be included in all copies or substantial portions -of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF -ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED -TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT -SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR -IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. -
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/POLICIES.md b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/POLICIES.md deleted file mode 100644 index 7f6e148..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/POLICIES.md +++ /dev/null
@@ -1,114 +0,0 @@ -<!-- Copyright 2023 The Fuchsia Authors - -Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -<LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -This file may not be copied, modified, or distributed except according to -those terms. --> - -# Zerocopy's Policies - -## Soundness - -Zerocopy is expressly designed for use in security-critical contexts. It is used -in hardware security firmware, cryptographic implementations, hypervisors, and -more. We understand that software in these contexts has a very high bar for -correctness, and we take our responsibility to meet that bar very seriously. - -This section describes policies which are designed to ensure the correctness and -soundness of our code and prevent regressions. - -### Forwards-compatibility - -Rust does not currently have a formal memory model. As such, while Rust provides -guarantees about the semantics of some operations, the semantics of many -operations is up in the air and subject to change. - -Zerocopy strives to ensure that our code - and code emitted by our custom -derives - is sound under any version of Rust as early as our MSRV, and will -continue to be sound under any future version of Rust. The policies in this -section are designed to help ensure that we live up to this goal. - -### Safety comments - -Each non-test `unsafe` block must be annotated with a "safety comment" which -provides a rationale for its soundness. In order to ensure that our soundness is -forwards-compatible, safety comments must satisfy the following criteria: -- Safety comments must constitute a (possibly informal) proof that all of Rust's - soundness rules are upheld. -- Safety comments must only rely for their correctness on statements which - appear in the stable versions of the [Rust Reference] or standard library - documentation (ie, the docs for [core], [alloc], and [std]); arguments which - rely on text from the beta or nightly versions of these documents are not - considered complete. -- All statements from the Reference or standard library documentation which are - relied upon for soundness must be quoted in the safety comment. This ensures - that there is no ambiguity as to what aspect of the text is being cited. This - is especially important in cases where the text of these documents changes in - the future. Such changes are of course required to be backwards-compatible, - but may change the manner in which a particular guarantee is explained. - -We use the [`clippy::undocumented_unsafe_blocks`] lint to ensure that `unsafe` -blocks cannot be added without a safety comment. Note that there are a few -outstanding uncommented `unsafe` blocks which are tracked in [#429]. Our goal is -to reach 100% safety comment coverage and not regress once we've reached it. - -[Rust Reference]: https://doc.rust-lang.org/reference/ -[core]: https://doc.rust-lang.org/stable/core/ -[alloc]: https://doc.rust-lang.org/stable/alloc/ -[std]: https://doc.rust-lang.org/stable/std/ -[`clippy::undocumented_unsafe_blocks`]: https://rust-lang.github.io/rust-clippy/master/index.html#/undocumented_unsafe_blocks -[#429]: https://github.com/google/zerocopy/issues/429 - -#### Exceptions to our safety comment policy - -In rare circumstances, the soundness of an `unsafe` block may depend upon -semantics which are widely agreed upon but not formally guaranteed. In order to -avoid slowing down zerocopy's development to an unreasonable degree, a safety -comment may violate our safety comment policy so long as all of the following -hold: -- The safety comment's correctness may rely on semantics which are not - guaranteed in official Rust documentation *so long as* a member of the Rust - team has articulated in an official communication (e.g. a comment on a Rust - GitHub repo) that Rust intends to guarantee particular semantics. -- There exists an active effort to formalize the guarantee in Rust's official - documentation. - -### Target architecture support - -Zerocopy bases its soundness on guarantees made about the semantics of Rust -which appear in the Rust Reference or standard library documentation; zerocopy -is sound so long as these guarantees hold. There are known cases in which these -guarantees do not hold on certain target architectures (see -[rust-lang/unsafe-code-guidelines#461]); on such target architectures, zerocopy -may be unsound. We consider it outside of zerocopy's scope to reason about these -cases. Zerocopy makes no effort maintain soundness in cases where Rust's -documented guarantees do not hold. - -[rust-lang/unsafe-code-guidelines#461]: https://github.com/rust-lang/unsafe-code-guidelines/issues/461 - -## MSRV - -<!-- Our policy used to be simply that MSRV was a breaking change in all -circumstances. This implicitly relied on syn having the same MSRV policy, which -it does not. See #1085 and #1088. --> - -Without the `derive` feature enabled, zerocopy's minimum supported Rust version -(MSRV) is encoded the `package.rust-version` field in its `Cargo.toml` file. For -zerocopy, we consider an increase in MSRV to be a semver-breaking change, and -will only increase our MSRV during semver-breaking version changes (e.g., 0.1 -> -0.2, 1.0 -> 2.0, etc). - -For zerocopy with the `derive` feature enabled, and for the zerocopy-derive -crate, we inherit the MSRV of our sole external dependency, syn. As of this -writing (2024-07-02), syn does *not* consider MSRV increases to be -semver-breaking changes. Thus, using the `derive` feature may result in the -effective MSRV increasing within a semver version train. - -## Yanking - -Whenever a bug or regression is identified, we will yank any affected versions -which are part of the current version train. For example, if the most recent -version is 0.10.20 and a bug is uncovered, we will release a fix in 0.10.21 and -yank all 0.10.X versions which are affected. We *may* also yank versions in previous -version trains on a case-by-case basis, but we don't guarantee it.
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/README.md b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/README.md deleted file mode 100644 index ec09c45..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/README.md +++ /dev/null
@@ -1,154 +0,0 @@ -<!-- Copyright 2022 The Fuchsia Authors - -Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -<LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -This file may not be copied, modified, or distributed except according to -those terms. - -WARNING: DO NOT EDIT THIS FILE. It is generated automatically. Edits should be -made in the doc comment on `src/lib.rs` or in `generate-readme.sh`. ---> - -# zerocopy - -*<span style="font-size: 100%; color:grey;">Want to help improve zerocopy? -Fill out our [user survey][user-survey]!</span>* - -***<span style="font-size: 140%">Fast, safe, <span -style="color:red;">compile error</span>. Pick two.</span>*** - -Zerocopy makes zero-cost memory manipulation effortless. We write `unsafe` -so you don't have to. - -## Overview - -Zerocopy provides four core marker traits, each of which can be derived -(e.g., `#[derive(FromZeroes)]`): -- `FromZeroes` indicates that a sequence of zero bytes represents a valid - instance of a type -- `FromBytes` indicates that a type may safely be converted from an - arbitrary byte sequence -- `AsBytes` indicates that a type may safely be converted *to* a byte - sequence -- `Unaligned` indicates that a type's alignment requirement is 1 - -Types which implement a subset of these traits can then be converted to/from -byte sequences with little to no runtime overhead. - -Zerocopy also provides byte-order aware integer types that support these -conversions; see the `byteorder` module. These types are especially useful -for network parsing. - -[user-survey]: https://docs.google.com/forms/d/e/1FAIpQLSdzBNTN9tzwsmtyZxRFNL02K36IWCdHWW2ZBckyQS2xiO3i8Q/viewform?usp=published_options - -## Cargo Features - -- **`alloc`** - By default, `zerocopy` is `no_std`. When the `alloc` feature is enabled, - the `alloc` crate is added as a dependency, and some allocation-related - functionality is added. - -- **`byteorder`** (enabled by default) - Adds the `byteorder` module and a dependency on the `byteorder` crate. - The `byteorder` module provides byte order-aware equivalents of the - multi-byte primitive numerical types. Unlike their primitive equivalents, - the types in this module have no alignment requirement and support byte - order conversions. This can be useful in handling file formats, network - packet layouts, etc which don't provide alignment guarantees and which may - use a byte order different from that of the execution platform. - -- **`derive`** - Provides derives for the core marker traits via the `zerocopy-derive` - crate. These derives are re-exported from `zerocopy`, so it is not - necessary to depend on `zerocopy-derive` directly. - - However, you may experience better compile times if you instead directly - depend on both `zerocopy` and `zerocopy-derive` in your `Cargo.toml`, - since doing so will allow Rust to compile these crates in parallel. To do - so, do *not* enable the `derive` feature, and list both dependencies in - your `Cargo.toml` with the same leading non-zero version number; e.g: - - ```toml - [dependencies] - zerocopy = "0.X" - zerocopy-derive = "0.X" - ``` - -- **`simd`** - When the `simd` feature is enabled, `FromZeroes`, `FromBytes`, and - `AsBytes` impls are emitted for all stable SIMD types which exist on the - target platform. Note that the layout of SIMD types is not yet stabilized, - so these impls may be removed in the future if layout changes make them - invalid. For more information, see the Unsafe Code Guidelines Reference - page on the [layout of packed SIMD vectors][simd-layout]. - -- **`simd-nightly`** - Enables the `simd` feature and adds support for SIMD types which are only - available on nightly. Since these types are unstable, support for any type - may be removed at any point in the future. - -[simd-layout]: https://rust-lang.github.io/unsafe-code-guidelines/layout/packed-simd-vectors.html - -## Security Ethos - -Zerocopy is expressly designed for use in security-critical contexts. We -strive to ensure that that zerocopy code is sound under Rust's current -memory model, and *any future memory model*. We ensure this by: -- **...not 'guessing' about Rust's semantics.** - We annotate `unsafe` code with a precise rationale for its soundness that - cites a relevant section of Rust's official documentation. When Rust's - documented semantics are unclear, we work with the Rust Operational - Semantics Team to clarify Rust's documentation. -- **...rigorously testing our implementation.** - We run tests using [Miri], ensuring that zerocopy is sound across a wide - array of supported target platforms of varying endianness and pointer - width, and across both current and experimental memory models of Rust. -- **...formally proving the correctness of our implementation.** - We apply formal verification tools like [Kani][kani] to prove zerocopy's - correctness. - -For more information, see our full [soundness policy]. - -[Miri]: https://github.com/rust-lang/miri -[Kani]: https://github.com/model-checking/kani -[soundness policy]: https://github.com/google/zerocopy/blob/main/POLICIES.md#soundness - -## Relationship to Project Safe Transmute - -[Project Safe Transmute] is an official initiative of the Rust Project to -develop language-level support for safer transmutation. The Project consults -with crates like zerocopy to identify aspects of safer transmutation that -would benefit from compiler support, and has developed an [experimental, -compiler-supported analysis][mcp-transmutability] which determines whether, -for a given type, any value of that type may be soundly transmuted into -another type. Once this functionality is sufficiently mature, zerocopy -intends to replace its internal transmutability analysis (implemented by our -custom derives) with the compiler-supported one. This change will likely be -an implementation detail that is invisible to zerocopy's users. - -Project Safe Transmute will not replace the need for most of zerocopy's -higher-level abstractions. The experimental compiler analysis is a tool for -checking the soundness of `unsafe` code, not a tool to avoid writing -`unsafe` code altogether. For the foreseeable future, crates like zerocopy -will still be required in order to provide higher-level abstractions on top -of the building block provided by Project Safe Transmute. - -[Project Safe Transmute]: https://rust-lang.github.io/rfcs/2835-project-safe-transmute.html -[mcp-transmutability]: https://github.com/rust-lang/compiler-team/issues/411 - -## MSRV - -See our [MSRV policy]. - -[MSRV policy]: https://github.com/google/zerocopy/blob/main/POLICIES.md#msrv - -## Changelog - -Zerocopy uses [GitHub Releases]. - -[GitHub Releases]: https://github.com/google/zerocopy/releases - -## Disclaimer - -Disclaimer: Zerocopy is not an officially supported Google product.
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/cargo.sh b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/cargo.sh deleted file mode 100755 index f72e898..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/cargo.sh +++ /dev/null
@@ -1,120 +0,0 @@ -#!/bin/bash -# -# Copyright 2023 The Fuchsia Authors -# -# Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -# <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -# license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -# This file may not be copied, modified, or distributed except according to -# those terms. - -# This script is a thin wrapper around Cargo that provides human-friendly -# toolchain names which are automatically translated to the toolchain versions -# we have pinned in CI. -# -# cargo.sh --version <toolchain-name> # looks up the version for the named toolchain -# cargo.sh +<toolchain-name> [...] # runs cargo commands with the named toolchain -# cargo.sh +all [...] # runs cargo commands with each toolchain -# -# The meta-toolchain "all" instructs this script to run the provided command -# once for each toolchain (msrv, stable, nightly). -# -# A common task that is especially annoying to perform by hand is to update -# trybuild's stderr files. Using this script: -# -# TRYBUILD=overwrite ./cargo.sh +all test --workspace - -set -eo pipefail - -function print-usage-and-exit { - echo "Usage:" >&2 - echo " $0 --version <toolchain-name>" >&2 - echo " $0 +<toolchain-name> [...]" >&2 - echo " $0 +all [...]" >&2 - exit 1 -} - -[[ $# -gt 0 ]] || print-usage-and-exit - -function pkg-meta { - # NOTE(#547): We set `CARGO_TARGET_DIR` here because `cargo metadata` - # sometimes causes the `cargo-metadata` crate to be rebuilt from source using - # the default toolchain. This has the effect of clobbering any existing build - # artifacts from whatever toolchain the user has specified (e.g., `+nightly`), - # causing the subsequent `cargo` invocation to rebuild unnecessarily. By - # specifying a separate build directory here, we ensure that this never - # clobbers the build artifacts used by the later `cargo` invocation. - CARGO_TARGET_DIR=target/cargo-sh cargo metadata --format-version 1 | jq -r ".packages[] | select(.name == \"zerocopy\").$1" -} - -function lookup-version { - VERSION="$1" - case "$VERSION" in - msrv) - pkg-meta rust_version - ;; - stable) - pkg-meta 'metadata.ci."pinned-stable"' - ;; - nightly) - pkg-meta 'metadata.ci."pinned-nightly"' - ;; - *) - echo "Unrecognized toolchain name: '$VERSION' (options are 'msrv', 'stable', 'nightly')" >&2 - return 1 - ;; - esac -} - -function get-rustflags { - [ "$1" == nightly ] && echo "--cfg __INTERNAL_USE_ONLY_NIGHLTY_FEATURES_IN_TESTS" -} - -function prompt { - PROMPT="$1" - YES="$2" - while true; do - read -p "$PROMPT " yn - case "$yn" in - [Yy]) $YES; return $?; ;; - [Nn]) return 1; ;; - *) break; ;; - esac - done -} - -case "$1" in - # cargo.sh --version <toolchain-name> - --version) - [[ $# -eq 2 ]] || print-usage-and-exit - lookup-version "$2" - ;; - # cargo.sh +all [...] - +all) - echo "[cargo.sh] warning: running the same command for each toolchain (msrv, stable, nightly)" >&2 - for toolchain in msrv stable nightly; do - echo "[cargo.sh] running with toolchain: $toolchain" >&2 - $0 "+$toolchain" ${@:2} - done - exit 0 - ;; - # cargo.sh +<toolchain-name> [...] - +*) - TOOLCHAIN="$(lookup-version ${1:1})" - - cargo "+$TOOLCHAIN" version &>/dev/null && \ - rustup "+$TOOLCHAIN" component list | grep '^rust-src (installed)$' >/dev/null || { - echo "[cargo.sh] missing either toolchain '$TOOLCHAIN' or component 'rust-src'" >&2 - # If we're running in a GitHub action, then it's better to bail than to - # hang waiting for input we're never going to get. - [ -z ${GITHUB_RUN_ID+x} ] || exit 1 - prompt "[cargo.sh] would you like to install toolchain '$TOOLCHAIN' and component 'rust-src' via 'rustup'?" \ - "rustup toolchain install $TOOLCHAIN -c rust-src" - } || exit 1 - - RUSTFLAGS="$(get-rustflags ${1:1}) $RUSTFLAGS" cargo "+$TOOLCHAIN" ${@:2} - ;; - *) - print-usage-and-exit - ;; -esac
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/clippy.toml b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/clippy.toml deleted file mode 100644 index 9c1140643..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/clippy.toml +++ /dev/null
@@ -1,10 +0,0 @@ -# Copyright 2023 The Fuchsia Authors -# -# Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -# <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -# license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -# This file may not be copied, modified, or distributed except according to -# those terms. - -accept-comment-above-statement = true -accept-comment-above-attributes = true
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/generate-readme.sh b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/generate-readme.sh deleted file mode 100755 index be0dc92..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/generate-readme.sh +++ /dev/null
@@ -1,50 +0,0 @@ -#!/bin/bash -# -# Copyright 2022 The Fuchsia Authors -# -# Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -# <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -# license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -# This file may not be copied, modified, or distributed except according to -# those terms. - -set -eo pipefail - -COPYRIGHT_HEADER=$(mktemp) -BODY=$(mktemp) -DISCLAIMER_FOOTER=$(mktemp) - -cat > $COPYRIGHT_HEADER <<'EOF' -<!-- Copyright 2022 The Fuchsia Authors - -Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -<LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -This file may not be copied, modified, or distributed except according to -those terms. - -WARNING: DO NOT EDIT THIS FILE. It is generated automatically. Edits should be -made in the doc comment on `src/lib.rs` or in `generate-readme.sh`. ---> - -EOF - -# This uses the `cargo readme` tool, which you can install via `cargo install -# cargo-readme --version 3.2.0`. -# -# The `sed` command is used to strip code links like: -# -# /// Here is a link to [`Vec`]. -# -# These links don't work in a Markdown file, and so we remove the `[` and `]` -# characters to convert them to non-link code snippets. -cargo readme --no-license | sed 's/\[\(`[^`]*`\)]/\1/g' > $BODY - -cat > $DISCLAIMER_FOOTER <<'EOF' - -## Disclaimer - -Disclaimer: Zerocopy is not an officially supported Google product. -EOF - -cat $COPYRIGHT_HEADER $BODY $DISCLAIMER_FOOTER
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/rustfmt.toml b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/rustfmt.toml deleted file mode 100644 index c967afe..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/rustfmt.toml +++ /dev/null
@@ -1,19 +0,0 @@ -# Copyright 2022 The Fuchsia Authors -# -# Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -# <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -# license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -# This file may not be copied, modified, or distributed except according to -# those terms. - -edition = "2021" - -# The "Default" setting has a heuristic which splits lines too aggresively. -# We are willing to revisit this setting in future versions of rustfmt. -# Bugs: -# * https://github.com/rust-lang/rustfmt/issues/3119 -# * https://github.com/rust-lang/rustfmt/issues/3120 -use_small_heuristics = "Max" - -# Prevent carriage returns -newline_style = "Unix"
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/src/byteorder.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/src/byteorder.rs deleted file mode 100644 index 376c981..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/src/byteorder.rs +++ /dev/null
@@ -1,1071 +0,0 @@ -// Copyright 2019 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -//! Byte order-aware numeric primitives. -//! -//! This module contains equivalents of the native multi-byte integer types with -//! no alignment requirement and supporting byte order conversions. -//! -//! For each native multi-byte integer type - `u16`, `i16`, `u32`, etc - and -//! floating point type - `f32` and `f64` - an equivalent type is defined by -//! this module - [`U16`], [`I16`], [`U32`], [`F64`], etc. Unlike their native -//! counterparts, these types have alignment 1, and take a type parameter -//! specifying the byte order in which the bytes are stored in memory. Each type -//! implements the [`FromBytes`], [`AsBytes`], and [`Unaligned`] traits. -//! -//! These two properties, taken together, make these types useful for defining -//! data structures whose memory layout matches a wire format such as that of a -//! network protocol or a file format. Such formats often have multi-byte values -//! at offsets that do not respect the alignment requirements of the equivalent -//! native types, and stored in a byte order not necessarily the same as that of -//! the target platform. -//! -//! Type aliases are provided for common byte orders in the [`big_endian`], -//! [`little_endian`], [`network_endian`], and [`native_endian`] submodules. -//! -//! # Example -//! -//! One use of these types is for representing network packet formats, such as -//! UDP: -//! -//! ```rust,edition2021 -//! # #[cfg(feature = "derive")] { // This example uses derives, and won't compile without them -//! use zerocopy::{AsBytes, ByteSlice, FromBytes, FromZeroes, Ref, Unaligned}; -//! use zerocopy::byteorder::network_endian::U16; -//! -//! #[derive(FromZeroes, FromBytes, AsBytes, Unaligned)] -//! #[repr(C)] -//! struct UdpHeader { -//! src_port: U16, -//! dst_port: U16, -//! length: U16, -//! checksum: U16, -//! } -//! -//! struct UdpPacket<B: ByteSlice> { -//! header: Ref<B, UdpHeader>, -//! body: B, -//! } -//! -//! impl<B: ByteSlice> UdpPacket<B> { -//! fn parse(bytes: B) -> Option<UdpPacket<B>> { -//! let (header, body) = Ref::new_from_prefix(bytes)?; -//! Some(UdpPacket { header, body }) -//! } -//! -//! fn src_port(&self) -> u16 { -//! self.header.src_port.get() -//! } -//! -//! // more getters... -//! } -//! # } -//! ``` - -use core::{ - convert::{TryFrom, TryInto}, - fmt::{self, Binary, Debug, Display, Formatter, LowerHex, Octal, UpperHex}, - marker::PhantomData, - num::TryFromIntError, -}; - -// We don't reexport `WriteBytesExt` or `ReadBytesExt` because those are only -// available with the `std` feature enabled, and zerocopy is `no_std` by -// default. -pub use ::byteorder::{BigEndian, ByteOrder, LittleEndian, NativeEndian, NetworkEndian, BE, LE}; - -use super::*; - -macro_rules! impl_fmt_trait { - ($name:ident, $native:ident, $trait:ident) => { - impl<O: ByteOrder> $trait for $name<O> { - #[inline(always)] - fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { - $trait::fmt(&self.get(), f) - } - } - }; -} - -macro_rules! impl_fmt_traits { - ($name:ident, $native:ident, "floating point number") => { - impl_fmt_trait!($name, $native, Display); - }; - ($name:ident, $native:ident, "unsigned integer") => { - impl_fmt_traits!($name, $native, @all_types); - }; - ($name:ident, $native:ident, "signed integer") => { - impl_fmt_traits!($name, $native, @all_types); - }; - ($name:ident, $native:ident, @all_types) => { - impl_fmt_trait!($name, $native, Display); - impl_fmt_trait!($name, $native, Octal); - impl_fmt_trait!($name, $native, LowerHex); - impl_fmt_trait!($name, $native, UpperHex); - impl_fmt_trait!($name, $native, Binary); - }; -} - -macro_rules! impl_ops_traits { - ($name:ident, $native:ident, "floating point number") => { - impl_ops_traits!($name, $native, @all_types); - impl_ops_traits!($name, $native, @signed_integer_floating_point); - }; - ($name:ident, $native:ident, "unsigned integer") => { - impl_ops_traits!($name, $native, @signed_unsigned_integer); - impl_ops_traits!($name, $native, @all_types); - }; - ($name:ident, $native:ident, "signed integer") => { - impl_ops_traits!($name, $native, @signed_unsigned_integer); - impl_ops_traits!($name, $native, @signed_integer_floating_point); - impl_ops_traits!($name, $native, @all_types); - }; - ($name:ident, $native:ident, @signed_unsigned_integer) => { - impl_ops_traits!(@without_byteorder_swap $name, $native, BitAnd, bitand, BitAndAssign, bitand_assign); - impl_ops_traits!(@without_byteorder_swap $name, $native, BitOr, bitor, BitOrAssign, bitor_assign); - impl_ops_traits!(@without_byteorder_swap $name, $native, BitXor, bitxor, BitXorAssign, bitxor_assign); - impl_ops_traits!(@with_byteorder_swap $name, $native, Shl, shl, ShlAssign, shl_assign); - impl_ops_traits!(@with_byteorder_swap $name, $native, Shr, shr, ShrAssign, shr_assign); - - impl<O> core::ops::Not for $name<O> { - type Output = $name<O>; - - #[inline(always)] - fn not(self) -> $name<O> { - let self_native = $native::from_ne_bytes(self.0); - $name((!self_native).to_ne_bytes(), PhantomData) - } - } - }; - ($name:ident, $native:ident, @signed_integer_floating_point) => { - impl<O: ByteOrder> core::ops::Neg for $name<O> { - type Output = $name<O>; - - #[inline(always)] - fn neg(self) -> $name<O> { - let self_native: $native = self.get(); - #[allow(clippy::arithmetic_side_effects)] - $name::<O>::new(-self_native) - } - } - }; - ($name:ident, $native:ident, @all_types) => { - impl_ops_traits!(@with_byteorder_swap $name, $native, Add, add, AddAssign, add_assign); - impl_ops_traits!(@with_byteorder_swap $name, $native, Div, div, DivAssign, div_assign); - impl_ops_traits!(@with_byteorder_swap $name, $native, Mul, mul, MulAssign, mul_assign); - impl_ops_traits!(@with_byteorder_swap $name, $native, Rem, rem, RemAssign, rem_assign); - impl_ops_traits!(@with_byteorder_swap $name, $native, Sub, sub, SubAssign, sub_assign); - }; - (@with_byteorder_swap $name:ident, $native:ident, $trait:ident, $method:ident, $trait_assign:ident, $method_assign:ident) => { - impl<O: ByteOrder> core::ops::$trait for $name<O> { - type Output = $name<O>; - - #[inline(always)] - fn $method(self, rhs: $name<O>) -> $name<O> { - let self_native: $native = self.get(); - let rhs_native: $native = rhs.get(); - let result_native = core::ops::$trait::$method(self_native, rhs_native); - $name::<O>::new(result_native) - } - } - - impl<O: ByteOrder> core::ops::$trait_assign for $name<O> { - #[inline(always)] - fn $method_assign(&mut self, rhs: $name<O>) { - *self = core::ops::$trait::$method(*self, rhs); - } - } - }; - // Implement traits in terms of the same trait on the native type, but - // without performing a byte order swap. This only works for bitwise - // operations like `&`, `|`, etc. - (@without_byteorder_swap $name:ident, $native:ident, $trait:ident, $method:ident, $trait_assign:ident, $method_assign:ident) => { - impl<O: ByteOrder> core::ops::$trait for $name<O> { - type Output = $name<O>; - - #[inline(always)] - fn $method(self, rhs: $name<O>) -> $name<O> { - let self_native = $native::from_ne_bytes(self.0); - let rhs_native = $native::from_ne_bytes(rhs.0); - let result_native = core::ops::$trait::$method(self_native, rhs_native); - $name(result_native.to_ne_bytes(), PhantomData) - } - } - - impl<O: ByteOrder> core::ops::$trait_assign for $name<O> { - #[inline(always)] - fn $method_assign(&mut self, rhs: $name<O>) { - *self = core::ops::$trait::$method(*self, rhs); - } - } - }; -} - -macro_rules! doc_comment { - ($x:expr, $($tt:tt)*) => { - #[doc = $x] - $($tt)* - }; -} - -macro_rules! define_max_value_constant { - ($name:ident, $bytes:expr, "unsigned integer") => { - /// The maximum value. - /// - /// This constant should be preferred to constructing a new value using - /// `new`, as `new` may perform an endianness swap depending on the - /// endianness `O` and the endianness of the platform. - pub const MAX_VALUE: $name<O> = $name([0xFFu8; $bytes], PhantomData); - }; - // We don't provide maximum and minimum value constants for signed values - // and floats because there's no way to do it generically - it would require - // a different value depending on the value of the `ByteOrder` type - // parameter. Currently, one workaround would be to provide implementations - // for concrete implementations of that trait. In the long term, if we are - // ever able to make the `new` constructor a const fn, we could use that - // instead. - ($name:ident, $bytes:expr, "signed integer") => {}; - ($name:ident, $bytes:expr, "floating point number") => {}; -} - -macro_rules! define_type { - ($article:ident, - $name:ident, - $native:ident, - $bits:expr, - $bytes:expr, - $read_method:ident, - $write_method:ident, - $number_kind:tt, - [$($larger_native:ty),*], - [$($larger_native_try:ty),*], - [$($larger_byteorder:ident),*], - [$($larger_byteorder_try:ident),*]) => { - doc_comment! { - concat!("A ", stringify!($bits), "-bit ", $number_kind, - " stored in a given byte order. - -`", stringify!($name), "` is like the native `", stringify!($native), "` type with -two major differences: First, it has no alignment requirement (its alignment is 1). -Second, the endianness of its memory layout is given by the type parameter `O`, -which can be any type which implements [`ByteOrder`]. In particular, this refers -to [`BigEndian`], [`LittleEndian`], [`NativeEndian`], and [`NetworkEndian`]. - -", stringify!($article), " `", stringify!($name), "` can be constructed using -the [`new`] method, and its contained value can be obtained as a native -`",stringify!($native), "` using the [`get`] method, or updated in place with -the [`set`] method. In all cases, if the endianness `O` is not the same as the -endianness of the current platform, an endianness swap will be performed in -order to uphold the invariants that a) the layout of `", stringify!($name), "` -has endianness `O` and that, b) the layout of `", stringify!($native), "` has -the platform's native endianness. - -`", stringify!($name), "` implements [`FromBytes`], [`AsBytes`], and [`Unaligned`], -making it useful for parsing and serialization. See the module documentation for an -example of how it can be used for parsing UDP packets. - -[`new`]: crate::byteorder::", stringify!($name), "::new -[`get`]: crate::byteorder::", stringify!($name), "::get -[`set`]: crate::byteorder::", stringify!($name), "::set -[`FromBytes`]: crate::FromBytes -[`AsBytes`]: crate::AsBytes -[`Unaligned`]: crate::Unaligned"), - #[derive(Copy, Clone, Eq, PartialEq, Hash)] - #[cfg_attr(any(feature = "derive", test), derive(KnownLayout, FromZeroes, FromBytes, AsBytes, Unaligned))] - #[repr(transparent)] - pub struct $name<O>([u8; $bytes], PhantomData<O>); - } - - #[cfg(not(any(feature = "derive", test)))] - impl_known_layout!(O => $name<O>); - - safety_comment! { - /// SAFETY: - /// `$name<O>` is `repr(transparent)`, and so it has the same layout - /// as its only non-zero field, which is a `u8` array. `u8` arrays - /// are `FromZeroes`, `FromBytes`, `AsBytes`, and `Unaligned`. - impl_or_verify!(O => FromZeroes for $name<O>); - impl_or_verify!(O => FromBytes for $name<O>); - impl_or_verify!(O => AsBytes for $name<O>); - impl_or_verify!(O => Unaligned for $name<O>); - } - - impl<O> Default for $name<O> { - #[inline(always)] - fn default() -> $name<O> { - $name::ZERO - } - } - - impl<O> $name<O> { - /// The value zero. - /// - /// This constant should be preferred to constructing a new value - /// using `new`, as `new` may perform an endianness swap depending - /// on the endianness and platform. - pub const ZERO: $name<O> = $name([0u8; $bytes], PhantomData); - - define_max_value_constant!($name, $bytes, $number_kind); - - /// Constructs a new value from bytes which are already in the - /// endianness `O`. - #[inline(always)] - pub const fn from_bytes(bytes: [u8; $bytes]) -> $name<O> { - $name(bytes, PhantomData) - } - } - - impl<O: ByteOrder> $name<O> { - // TODO(joshlf): Make these const fns if the `ByteOrder` methods - // ever become const fns. - - /// Constructs a new value, possibly performing an endianness swap - /// to guarantee that the returned value has endianness `O`. - #[inline(always)] - pub fn new(n: $native) -> $name<O> { - let mut out = $name::default(); - O::$write_method(&mut out.0[..], n); - out - } - - /// Returns the value as a primitive type, possibly performing an - /// endianness swap to guarantee that the return value has the - /// endianness of the native platform. - #[inline(always)] - pub fn get(self) -> $native { - O::$read_method(&self.0[..]) - } - - /// Updates the value in place as a primitive type, possibly - /// performing an endianness swap to guarantee that the stored value - /// has the endianness `O`. - #[inline(always)] - pub fn set(&mut self, n: $native) { - O::$write_method(&mut self.0[..], n); - } - } - - // The reasoning behind which traits to implement here is to only - // implement traits which won't cause inference issues. Notably, - // comparison traits like PartialEq and PartialOrd tend to cause - // inference issues. - - impl<O: ByteOrder> From<$name<O>> for [u8; $bytes] { - #[inline(always)] - fn from(x: $name<O>) -> [u8; $bytes] { - x.0 - } - } - - impl<O: ByteOrder> From<[u8; $bytes]> for $name<O> { - #[inline(always)] - fn from(bytes: [u8; $bytes]) -> $name<O> { - $name(bytes, PhantomData) - } - } - - impl<O: ByteOrder> From<$name<O>> for $native { - #[inline(always)] - fn from(x: $name<O>) -> $native { - x.get() - } - } - - impl<O: ByteOrder> From<$native> for $name<O> { - #[inline(always)] - fn from(x: $native) -> $name<O> { - $name::new(x) - } - } - - $( - impl<O: ByteOrder> From<$name<O>> for $larger_native { - #[inline(always)] - fn from(x: $name<O>) -> $larger_native { - x.get().into() - } - } - )* - - $( - impl<O: ByteOrder> TryFrom<$larger_native_try> for $name<O> { - type Error = TryFromIntError; - #[inline(always)] - fn try_from(x: $larger_native_try) -> Result<$name<O>, TryFromIntError> { - $native::try_from(x).map($name::new) - } - } - )* - - $( - impl<O: ByteOrder, P: ByteOrder> From<$name<O>> for $larger_byteorder<P> { - #[inline(always)] - fn from(x: $name<O>) -> $larger_byteorder<P> { - $larger_byteorder::new(x.get().into()) - } - } - )* - - $( - impl<O: ByteOrder, P: ByteOrder> TryFrom<$larger_byteorder_try<P>> for $name<O> { - type Error = TryFromIntError; - #[inline(always)] - fn try_from(x: $larger_byteorder_try<P>) -> Result<$name<O>, TryFromIntError> { - x.get().try_into().map($name::new) - } - } - )* - - impl<O: ByteOrder> AsRef<[u8; $bytes]> for $name<O> { - #[inline(always)] - fn as_ref(&self) -> &[u8; $bytes] { - &self.0 - } - } - - impl<O: ByteOrder> AsMut<[u8; $bytes]> for $name<O> { - #[inline(always)] - fn as_mut(&mut self) -> &mut [u8; $bytes] { - &mut self.0 - } - } - - impl<O: ByteOrder> PartialEq<$name<O>> for [u8; $bytes] { - #[inline(always)] - fn eq(&self, other: &$name<O>) -> bool { - self.eq(&other.0) - } - } - - impl<O: ByteOrder> PartialEq<[u8; $bytes]> for $name<O> { - #[inline(always)] - fn eq(&self, other: &[u8; $bytes]) -> bool { - self.0.eq(other) - } - } - - impl_fmt_traits!($name, $native, $number_kind); - impl_ops_traits!($name, $native, $number_kind); - - impl<O: ByteOrder> Debug for $name<O> { - #[inline] - fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { - // This results in a format like "U16(42)". - f.debug_tuple(stringify!($name)).field(&self.get()).finish() - } - } - }; -} - -define_type!( - A, - U16, - u16, - 16, - 2, - read_u16, - write_u16, - "unsigned integer", - [u32, u64, u128, usize], - [u32, u64, u128, usize], - [U32, U64, U128], - [U32, U64, U128] -); -define_type!( - A, - U32, - u32, - 32, - 4, - read_u32, - write_u32, - "unsigned integer", - [u64, u128], - [u64, u128], - [U64, U128], - [U64, U128] -); -define_type!( - A, - U64, - u64, - 64, - 8, - read_u64, - write_u64, - "unsigned integer", - [u128], - [u128], - [U128], - [U128] -); -define_type!(A, U128, u128, 128, 16, read_u128, write_u128, "unsigned integer", [], [], [], []); -define_type!( - An, - I16, - i16, - 16, - 2, - read_i16, - write_i16, - "signed integer", - [i32, i64, i128, isize], - [i32, i64, i128, isize], - [I32, I64, I128], - [I32, I64, I128] -); -define_type!( - An, - I32, - i32, - 32, - 4, - read_i32, - write_i32, - "signed integer", - [i64, i128], - [i64, i128], - [I64, I128], - [I64, I128] -); -define_type!( - An, - I64, - i64, - 64, - 8, - read_i64, - write_i64, - "signed integer", - [i128], - [i128], - [I128], - [I128] -); -define_type!(An, I128, i128, 128, 16, read_i128, write_i128, "signed integer", [], [], [], []); -define_type!( - An, - F32, - f32, - 32, - 4, - read_f32, - write_f32, - "floating point number", - [f64], - [], - [F64], - [] -); -define_type!(An, F64, f64, 64, 8, read_f64, write_f64, "floating point number", [], [], [], []); - -macro_rules! module { - ($name:ident, $trait:ident, $endianness_str:expr) => { - /// Numeric primitives stored in - #[doc = $endianness_str] - /// byte order. - pub mod $name { - use byteorder::$trait; - - module!(@ty U16, $trait, "16-bit unsigned integer", $endianness_str); - module!(@ty U32, $trait, "32-bit unsigned integer", $endianness_str); - module!(@ty U64, $trait, "64-bit unsigned integer", $endianness_str); - module!(@ty U128, $trait, "128-bit unsigned integer", $endianness_str); - module!(@ty I16, $trait, "16-bit signed integer", $endianness_str); - module!(@ty I32, $trait, "32-bit signed integer", $endianness_str); - module!(@ty I64, $trait, "64-bit signed integer", $endianness_str); - module!(@ty I128, $trait, "128-bit signed integer", $endianness_str); - module!(@ty F32, $trait, "32-bit floating point number", $endianness_str); - module!(@ty F64, $trait, "64-bit floating point number", $endianness_str); - } - }; - (@ty $ty:ident, $trait:ident, $desc_str:expr, $endianness_str:expr) => { - /// A - #[doc = $desc_str] - /// stored in - #[doc = $endianness_str] - /// byte order. - pub type $ty = crate::byteorder::$ty<$trait>; - }; -} - -module!(big_endian, BigEndian, "big-endian"); -module!(little_endian, LittleEndian, "little-endian"); -module!(network_endian, NetworkEndian, "network-endian"); -module!(native_endian, NativeEndian, "native-endian"); - -#[cfg(any(test, kani))] -mod tests { - use ::byteorder::NativeEndian; - - use { - super::*, - crate::{AsBytes, FromBytes, Unaligned}, - }; - - #[cfg(not(kani))] - mod compatibility { - pub(super) use rand::{ - distributions::{Distribution, Standard}, - rngs::SmallRng, - Rng, SeedableRng, - }; - - pub(crate) trait Arbitrary {} - - impl<T> Arbitrary for T {} - } - - #[cfg(kani)] - mod compatibility { - pub(crate) use kani::Arbitrary; - - pub(crate) struct SmallRng; - - impl SmallRng { - pub(crate) fn seed_from_u64(_state: u64) -> Self { - Self - } - } - - pub(crate) trait Rng { - fn sample<T, D: Distribution<T>>(&mut self, _distr: D) -> T - where - T: Arbitrary, - { - kani::any() - } - } - - impl Rng for SmallRng {} - - pub(crate) trait Distribution<T> {} - impl<T, U> Distribution<T> for U {} - - pub(crate) struct Standard; - } - - use compatibility::*; - - // A native integer type (u16, i32, etc). - #[cfg_attr(kani, allow(dead_code))] - trait Native: Arbitrary + FromBytes + AsBytes + Copy + PartialEq + Debug { - const ZERO: Self; - const MAX_VALUE: Self; - - type Distribution: Distribution<Self>; - const DIST: Self::Distribution; - - fn rand<R: Rng>(rng: &mut R) -> Self { - rng.sample(Self::DIST) - } - - fn checked_add(self, rhs: Self) -> Option<Self>; - fn checked_div(self, rhs: Self) -> Option<Self>; - fn checked_mul(self, rhs: Self) -> Option<Self>; - fn checked_rem(self, rhs: Self) -> Option<Self>; - fn checked_sub(self, rhs: Self) -> Option<Self>; - fn checked_shl(self, rhs: Self) -> Option<Self>; - fn checked_shr(self, rhs: Self) -> Option<Self>; - - fn is_nan(self) -> bool; - - /// For `f32` and `f64`, NaN values are not considered equal to - /// themselves. This method is like `assert_eq!`, but it treats NaN - /// values as equal. - fn assert_eq_or_nan(self, other: Self) { - let slf = (!self.is_nan()).then(|| self); - let other = (!other.is_nan()).then(|| other); - assert_eq!(slf, other); - } - } - - trait ByteArray: - FromBytes + AsBytes + Copy + AsRef<[u8]> + AsMut<[u8]> + Debug + Default + Eq - { - /// Invert the order of the bytes in the array. - fn invert(self) -> Self; - } - - trait ByteOrderType: FromBytes + AsBytes + Unaligned + Copy + Eq + Debug { - type Native: Native; - type ByteArray: ByteArray; - - const ZERO: Self; - - fn new(native: Self::Native) -> Self; - fn get(self) -> Self::Native; - fn set(&mut self, native: Self::Native); - fn from_bytes(bytes: Self::ByteArray) -> Self; - fn into_bytes(self) -> Self::ByteArray; - - /// For `f32` and `f64`, NaN values are not considered equal to - /// themselves. This method is like `assert_eq!`, but it treats NaN - /// values as equal. - fn assert_eq_or_nan(self, other: Self) { - let slf = (!self.get().is_nan()).then(|| self); - let other = (!other.get().is_nan()).then(|| other); - assert_eq!(slf, other); - } - } - - trait ByteOrderTypeUnsigned: ByteOrderType { - const MAX_VALUE: Self; - } - - macro_rules! impl_byte_array { - ($bytes:expr) => { - impl ByteArray for [u8; $bytes] { - fn invert(mut self) -> [u8; $bytes] { - self.reverse(); - self - } - } - }; - } - - impl_byte_array!(2); - impl_byte_array!(4); - impl_byte_array!(8); - impl_byte_array!(16); - - macro_rules! impl_byte_order_type_unsigned { - ($name:ident, unsigned) => { - impl<O: ByteOrder> ByteOrderTypeUnsigned for $name<O> { - const MAX_VALUE: $name<O> = $name::MAX_VALUE; - } - }; - ($name:ident, signed) => {}; - } - - macro_rules! impl_traits { - ($name:ident, $native:ident, $bytes:expr, $sign:ident $(, @$float:ident)?) => { - impl Native for $native { - // For some types, `0 as $native` is required (for example, when - // `$native` is a floating-point type; `0` is an integer), but - // for other types, it's a trivial cast. In all cases, Clippy - // thinks it's dangerous. - #[allow(trivial_numeric_casts, clippy::as_conversions)] - const ZERO: $native = 0 as $native; - const MAX_VALUE: $native = $native::MAX; - - type Distribution = Standard; - const DIST: Standard = Standard; - - impl_traits!(@float_dependent_methods $(@$float)?); - } - - impl<O: ByteOrder> ByteOrderType for $name<O> { - type Native = $native; - type ByteArray = [u8; $bytes]; - - const ZERO: $name<O> = $name::ZERO; - - fn new(native: $native) -> $name<O> { - $name::new(native) - } - - fn get(self) -> $native { - $name::get(self) - } - - fn set(&mut self, native: $native) { - $name::set(self, native) - } - - fn from_bytes(bytes: [u8; $bytes]) -> $name<O> { - $name::from(bytes) - } - - fn into_bytes(self) -> [u8; $bytes] { - <[u8; $bytes]>::from(self) - } - } - - impl_byte_order_type_unsigned!($name, $sign); - }; - (@float_dependent_methods) => { - fn checked_add(self, rhs: Self) -> Option<Self> { self.checked_add(rhs) } - fn checked_div(self, rhs: Self) -> Option<Self> { self.checked_div(rhs) } - fn checked_mul(self, rhs: Self) -> Option<Self> { self.checked_mul(rhs) } - fn checked_rem(self, rhs: Self) -> Option<Self> { self.checked_rem(rhs) } - fn checked_sub(self, rhs: Self) -> Option<Self> { self.checked_sub(rhs) } - fn checked_shl(self, rhs: Self) -> Option<Self> { self.checked_shl(rhs.try_into().unwrap_or(u32::MAX)) } - fn checked_shr(self, rhs: Self) -> Option<Self> { self.checked_shr(rhs.try_into().unwrap_or(u32::MAX)) } - fn is_nan(self) -> bool { false } - }; - (@float_dependent_methods @float) => { - fn checked_add(self, rhs: Self) -> Option<Self> { Some(self + rhs) } - fn checked_div(self, rhs: Self) -> Option<Self> { Some(self / rhs) } - fn checked_mul(self, rhs: Self) -> Option<Self> { Some(self * rhs) } - fn checked_rem(self, rhs: Self) -> Option<Self> { Some(self % rhs) } - fn checked_sub(self, rhs: Self) -> Option<Self> { Some(self - rhs) } - fn checked_shl(self, _rhs: Self) -> Option<Self> { unimplemented!() } - fn checked_shr(self, _rhs: Self) -> Option<Self> { unimplemented!() } - fn is_nan(self) -> bool { self.is_nan() } - }; - } - - impl_traits!(U16, u16, 2, unsigned); - impl_traits!(U32, u32, 4, unsigned); - impl_traits!(U64, u64, 8, unsigned); - impl_traits!(U128, u128, 16, unsigned); - impl_traits!(I16, i16, 2, signed); - impl_traits!(I32, i32, 4, signed); - impl_traits!(I64, i64, 8, signed); - impl_traits!(I128, i128, 16, signed); - impl_traits!(F32, f32, 4, signed, @float); - impl_traits!(F64, f64, 8, signed, @float); - - macro_rules! call_for_unsigned_types { - ($fn:ident, $byteorder:ident) => { - $fn::<U16<$byteorder>>(); - $fn::<U32<$byteorder>>(); - $fn::<U64<$byteorder>>(); - $fn::<U128<$byteorder>>(); - }; - } - - macro_rules! call_for_signed_types { - ($fn:ident, $byteorder:ident) => { - $fn::<I16<$byteorder>>(); - $fn::<I32<$byteorder>>(); - $fn::<I64<$byteorder>>(); - $fn::<I128<$byteorder>>(); - }; - } - - macro_rules! call_for_float_types { - ($fn:ident, $byteorder:ident) => { - $fn::<F32<$byteorder>>(); - $fn::<F64<$byteorder>>(); - }; - } - - macro_rules! call_for_all_types { - ($fn:ident, $byteorder:ident) => { - call_for_unsigned_types!($fn, $byteorder); - call_for_signed_types!($fn, $byteorder); - call_for_float_types!($fn, $byteorder); - }; - } - - #[cfg(target_endian = "big")] - type NonNativeEndian = LittleEndian; - #[cfg(target_endian = "little")] - type NonNativeEndian = BigEndian; - - // We use a `u64` seed so that we can use `SeedableRng::seed_from_u64`. - // `SmallRng`'s `SeedableRng::Seed` differs by platform, so if we wanted to - // call `SeedableRng::from_seed`, which takes a `Seed`, we would need - // conditional compilation by `target_pointer_width`. - const RNG_SEED: u64 = 0x7A03CAE2F32B5B8F; - - const RAND_ITERS: usize = if cfg!(any(miri, kani)) { - // The tests below which use this constant used to take a very long time - // on Miri, which slows down local development and CI jobs. We're not - // using Miri to check for the correctness of our code, but rather its - // soundness, and at least in the context of these particular tests, a - // single loop iteration is just as good for surfacing UB as multiple - // iterations are. - // - // As of the writing of this comment, here's one set of measurements: - // - // $ # RAND_ITERS == 1 - // $ cargo miri test -- -Z unstable-options --report-time endian - // test byteorder::tests::test_native_endian ... ok <0.049s> - // test byteorder::tests::test_non_native_endian ... ok <0.061s> - // - // $ # RAND_ITERS == 1024 - // $ cargo miri test -- -Z unstable-options --report-time endian - // test byteorder::tests::test_native_endian ... ok <25.716s> - // test byteorder::tests::test_non_native_endian ... ok <38.127s> - 1 - } else { - 1024 - }; - - #[cfg_attr(test, test)] - #[cfg_attr(kani, kani::proof)] - fn test_zero() { - fn test_zero<T: ByteOrderType>() { - assert_eq!(T::ZERO.get(), T::Native::ZERO); - } - - call_for_all_types!(test_zero, NativeEndian); - call_for_all_types!(test_zero, NonNativeEndian); - } - - #[cfg_attr(test, test)] - #[cfg_attr(kani, kani::proof)] - fn test_max_value() { - fn test_max_value<T: ByteOrderTypeUnsigned>() { - assert_eq!(T::MAX_VALUE.get(), T::Native::MAX_VALUE); - } - - call_for_unsigned_types!(test_max_value, NativeEndian); - call_for_unsigned_types!(test_max_value, NonNativeEndian); - } - - #[cfg_attr(test, test)] - #[cfg_attr(kani, kani::proof)] - fn test_endian() { - fn test<T: ByteOrderType>(invert: bool) { - let mut r = SmallRng::seed_from_u64(RNG_SEED); - for _ in 0..RAND_ITERS { - let native = T::Native::rand(&mut r); - let mut bytes = T::ByteArray::default(); - bytes.as_bytes_mut().copy_from_slice(native.as_bytes()); - if invert { - bytes = bytes.invert(); - } - let mut from_native = T::new(native); - let from_bytes = T::from_bytes(bytes); - - from_native.assert_eq_or_nan(from_bytes); - from_native.get().assert_eq_or_nan(native); - from_bytes.get().assert_eq_or_nan(native); - - assert_eq!(from_native.into_bytes(), bytes); - assert_eq!(from_bytes.into_bytes(), bytes); - - let updated = T::Native::rand(&mut r); - from_native.set(updated); - from_native.get().assert_eq_or_nan(updated); - } - } - - fn test_native<T: ByteOrderType>() { - test::<T>(false); - } - - fn test_non_native<T: ByteOrderType>() { - test::<T>(true); - } - - call_for_all_types!(test_native, NativeEndian); - call_for_all_types!(test_non_native, NonNativeEndian); - } - - #[test] - fn test_ops_impls() { - // Test implementations of traits in `core::ops`. Some of these are - // fairly banal, but some are optimized to perform the operation without - // swapping byte order (namely, bit-wise operations which are identical - // regardless of byte order). These are important to test, and while - // we're testing those anyway, it's trivial to test all of the impls. - - fn test<T, F, G, H>(op: F, op_native: G, op_native_checked: Option<H>) - where - T: ByteOrderType, - F: Fn(T, T) -> T, - G: Fn(T::Native, T::Native) -> T::Native, - H: Fn(T::Native, T::Native) -> Option<T::Native>, - { - let mut r = SmallRng::seed_from_u64(RNG_SEED); - for _ in 0..RAND_ITERS { - let n0 = T::Native::rand(&mut r); - let n1 = T::Native::rand(&mut r); - let t0 = T::new(n0); - let t1 = T::new(n1); - - // If this operation would overflow/underflow, skip it rather - // than attempt to catch and recover from panics. - if matches!(&op_native_checked, Some(checked) if checked(n0, n1).is_none()) { - continue; - } - - let n_res = op_native(n0, n1); - let t_res = op(t0, t1); - - // For `f32` and `f64`, NaN values are not considered equal to - // themselves. We store `Option<f32>`/`Option<f64>` and store - // NaN as `None` so they can still be compared. - let n_res = (!T::Native::is_nan(n_res)).then(|| n_res); - let t_res = (!T::Native::is_nan(t_res.get())).then(|| t_res.get()); - assert_eq!(n_res, t_res); - } - } - - macro_rules! test { - (@binary $trait:ident, $method:ident $([$checked_method:ident])?, $($call_for_macros:ident),*) => {{ - test!( - @inner $trait, - core::ops::$trait::$method, - core::ops::$trait::$method, - { - #[allow(unused_mut, unused_assignments)] - let mut op_native_checked = None::<fn(T::Native, T::Native) -> Option<T::Native>>; - $( - op_native_checked = Some(T::Native::$checked_method); - )? - op_native_checked - }, - $($call_for_macros),* - ); - }}; - (@unary $trait:ident, $method:ident $([$checked_method:ident])?, $($call_for_macros:ident),*) => {{ - test!( - @inner $trait, - |slf, _rhs| core::ops::$trait::$method(slf), - |slf, _rhs| core::ops::$trait::$method(slf), - { - #[allow(unused_mut, unused_assignments)] - let mut op_native_checked = None::<fn(T::Native, T::Native) -> Option<T::Native>>; - $( - op_native_checked = Some(|slf, _rhs| T::Native::$checked_method(slf)); - )? - op_native_checked - }, - $($call_for_macros),* - ); - }}; - (@inner $trait:ident, $op:expr, $op_native:expr, $op_native_checked:expr, $($call_for_macros:ident),*) => {{ - fn t<T: ByteOrderType + core::ops::$trait<Output = T>>() - where - T::Native: core::ops::$trait<Output = T::Native>, - { - test::<T, _, _, _>( - $op, - $op_native, - $op_native_checked, - ); - } - - $( - $call_for_macros!(t, NativeEndian); - $call_for_macros!(t, NonNativeEndian); - )* - }}; - } - - test!(@binary Add, add[checked_add], call_for_all_types); - test!(@binary Div, div[checked_div], call_for_all_types); - test!(@binary Mul, mul[checked_mul], call_for_all_types); - test!(@binary Rem, rem[checked_rem], call_for_all_types); - test!(@binary Sub, sub[checked_sub], call_for_all_types); - - test!(@binary BitAnd, bitand, call_for_unsigned_types, call_for_signed_types); - test!(@binary BitOr, bitor, call_for_unsigned_types, call_for_signed_types); - test!(@binary BitXor, bitxor, call_for_unsigned_types, call_for_signed_types); - test!(@binary Shl, shl[checked_shl], call_for_unsigned_types, call_for_signed_types); - test!(@binary Shr, shr[checked_shr], call_for_unsigned_types, call_for_signed_types); - - test!(@unary Not, not, call_for_signed_types, call_for_unsigned_types); - test!(@unary Neg, neg, call_for_signed_types, call_for_float_types); - } - - #[test] - fn test_debug_impl() { - // Ensure that Debug applies format options to the inner value. - let val = U16::<LE>::new(10); - assert_eq!(format!("{:?}", val), "U16(10)"); - assert_eq!(format!("{:03?}", val), "U16(010)"); - assert_eq!(format!("{:x?}", val), "U16(a)"); - } -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/src/lib.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/src/lib.rs deleted file mode 100644 index c221de2..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/src/lib.rs +++ /dev/null
@@ -1,8284 +0,0 @@ -// Copyright 2018 The Fuchsia Authors -// -// Licensed under the 2-Clause BSD License <LICENSE-BSD or -// https://opensource.org/license/bsd-2-clause>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -// After updating the following doc comment, make sure to run the following -// command to update `README.md` based on its contents: -// -// ./generate-readme.sh > README.md - -//! *<span style="font-size: 100%; color:grey;">Want to help improve zerocopy? -//! Fill out our [user survey][user-survey]!</span>* -//! -//! ***<span style="font-size: 140%">Fast, safe, <span -//! style="color:red;">compile error</span>. Pick two.</span>*** -//! -//! Zerocopy makes zero-cost memory manipulation effortless. We write `unsafe` -//! so you don't have to. -//! -//! # Overview -//! -//! Zerocopy provides four core marker traits, each of which can be derived -//! (e.g., `#[derive(FromZeroes)]`): -//! - [`FromZeroes`] indicates that a sequence of zero bytes represents a valid -//! instance of a type -//! - [`FromBytes`] indicates that a type may safely be converted from an -//! arbitrary byte sequence -//! - [`AsBytes`] indicates that a type may safely be converted *to* a byte -//! sequence -//! - [`Unaligned`] indicates that a type's alignment requirement is 1 -//! -//! Types which implement a subset of these traits can then be converted to/from -//! byte sequences with little to no runtime overhead. -//! -//! Zerocopy also provides byte-order aware integer types that support these -//! conversions; see the [`byteorder`] module. These types are especially useful -//! for network parsing. -//! -//! [user-survey]: https://docs.google.com/forms/d/e/1FAIpQLSdzBNTN9tzwsmtyZxRFNL02K36IWCdHWW2ZBckyQS2xiO3i8Q/viewform?usp=published_options -//! -//! # Cargo Features -//! -//! - **`alloc`** -//! By default, `zerocopy` is `no_std`. When the `alloc` feature is enabled, -//! the `alloc` crate is added as a dependency, and some allocation-related -//! functionality is added. -//! -//! - **`byteorder`** (enabled by default) -//! Adds the [`byteorder`] module and a dependency on the `byteorder` crate. -//! The `byteorder` module provides byte order-aware equivalents of the -//! multi-byte primitive numerical types. Unlike their primitive equivalents, -//! the types in this module have no alignment requirement and support byte -//! order conversions. This can be useful in handling file formats, network -//! packet layouts, etc which don't provide alignment guarantees and which may -//! use a byte order different from that of the execution platform. -//! -//! - **`derive`** -//! Provides derives for the core marker traits via the `zerocopy-derive` -//! crate. These derives are re-exported from `zerocopy`, so it is not -//! necessary to depend on `zerocopy-derive` directly. -//! -//! However, you may experience better compile times if you instead directly -//! depend on both `zerocopy` and `zerocopy-derive` in your `Cargo.toml`, -//! since doing so will allow Rust to compile these crates in parallel. To do -//! so, do *not* enable the `derive` feature, and list both dependencies in -//! your `Cargo.toml` with the same leading non-zero version number; e.g: -//! -//! ```toml -//! [dependencies] -//! zerocopy = "0.X" -//! zerocopy-derive = "0.X" -//! ``` -//! -//! - **`simd`** -//! When the `simd` feature is enabled, `FromZeroes`, `FromBytes`, and -//! `AsBytes` impls are emitted for all stable SIMD types which exist on the -//! target platform. Note that the layout of SIMD types is not yet stabilized, -//! so these impls may be removed in the future if layout changes make them -//! invalid. For more information, see the Unsafe Code Guidelines Reference -//! page on the [layout of packed SIMD vectors][simd-layout]. -//! -//! - **`simd-nightly`** -//! Enables the `simd` feature and adds support for SIMD types which are only -//! available on nightly. Since these types are unstable, support for any type -//! may be removed at any point in the future. -//! -//! [simd-layout]: https://rust-lang.github.io/unsafe-code-guidelines/layout/packed-simd-vectors.html -//! -//! # Security Ethos -//! -//! Zerocopy is expressly designed for use in security-critical contexts. We -//! strive to ensure that that zerocopy code is sound under Rust's current -//! memory model, and *any future memory model*. We ensure this by: -//! - **...not 'guessing' about Rust's semantics.** -//! We annotate `unsafe` code with a precise rationale for its soundness that -//! cites a relevant section of Rust's official documentation. When Rust's -//! documented semantics are unclear, we work with the Rust Operational -//! Semantics Team to clarify Rust's documentation. -//! - **...rigorously testing our implementation.** -//! We run tests using [Miri], ensuring that zerocopy is sound across a wide -//! array of supported target platforms of varying endianness and pointer -//! width, and across both current and experimental memory models of Rust. -//! - **...formally proving the correctness of our implementation.** -//! We apply formal verification tools like [Kani][kani] to prove zerocopy's -//! correctness. -//! -//! For more information, see our full [soundness policy]. -//! -//! [Miri]: https://github.com/rust-lang/miri -//! [Kani]: https://github.com/model-checking/kani -//! [soundness policy]: https://github.com/google/zerocopy/blob/main/POLICIES.md#soundness -//! -//! # Relationship to Project Safe Transmute -//! -//! [Project Safe Transmute] is an official initiative of the Rust Project to -//! develop language-level support for safer transmutation. The Project consults -//! with crates like zerocopy to identify aspects of safer transmutation that -//! would benefit from compiler support, and has developed an [experimental, -//! compiler-supported analysis][mcp-transmutability] which determines whether, -//! for a given type, any value of that type may be soundly transmuted into -//! another type. Once this functionality is sufficiently mature, zerocopy -//! intends to replace its internal transmutability analysis (implemented by our -//! custom derives) with the compiler-supported one. This change will likely be -//! an implementation detail that is invisible to zerocopy's users. -//! -//! Project Safe Transmute will not replace the need for most of zerocopy's -//! higher-level abstractions. The experimental compiler analysis is a tool for -//! checking the soundness of `unsafe` code, not a tool to avoid writing -//! `unsafe` code altogether. For the foreseeable future, crates like zerocopy -//! will still be required in order to provide higher-level abstractions on top -//! of the building block provided by Project Safe Transmute. -//! -//! [Project Safe Transmute]: https://rust-lang.github.io/rfcs/2835-project-safe-transmute.html -//! [mcp-transmutability]: https://github.com/rust-lang/compiler-team/issues/411 -//! -//! # MSRV -//! -//! See our [MSRV policy]. -//! -//! [MSRV policy]: https://github.com/google/zerocopy/blob/main/POLICIES.md#msrv -//! -//! # Changelog -//! -//! Zerocopy uses [GitHub Releases]. -//! -//! [GitHub Releases]: https://github.com/google/zerocopy/releases - -// Sometimes we want to use lints which were added after our MSRV. -// `unknown_lints` is `warn` by default and we deny warnings in CI, so without -// this attribute, any unknown lint would cause a CI failure when testing with -// our MSRV. -// -// TODO(#1201): Remove `unexpected_cfgs` -#![allow(unknown_lints, non_local_definitions, unexpected_cfgs)] -#![deny(renamed_and_removed_lints)] -#![deny( - anonymous_parameters, - deprecated_in_future, - late_bound_lifetime_arguments, - missing_copy_implementations, - missing_debug_implementations, - missing_docs, - path_statements, - patterns_in_fns_without_body, - rust_2018_idioms, - trivial_numeric_casts, - unreachable_pub, - unsafe_op_in_unsafe_fn, - unused_extern_crates, - // We intentionally choose not to deny `unused_qualifications`. When items - // are added to the prelude (e.g., `core::mem::size_of`), this has the - // consequence of making some uses trigger this lint on the latest toolchain - // (e.g., `mem::size_of`), but fixing it (e.g. by replacing with `size_of`) - // does not work on older toolchains. - // - // We tested a more complicated fix in #1413, but ultimately decided that, - // since this lint is just a minor style lint, the complexity isn't worth it - // - it's fine to occasionally have unused qualifications slip through, - // especially since these do not affect our user-facing API in any way. - variant_size_differences -)] -#![cfg_attr( - __INTERNAL_USE_ONLY_NIGHLTY_FEATURES_IN_TESTS, - deny(fuzzy_provenance_casts, lossy_provenance_casts) -)] -#![deny( - clippy::all, - clippy::alloc_instead_of_core, - clippy::arithmetic_side_effects, - clippy::as_underscore, - clippy::assertions_on_result_states, - clippy::as_conversions, - clippy::correctness, - clippy::dbg_macro, - clippy::decimal_literal_representation, - clippy::get_unwrap, - clippy::indexing_slicing, - clippy::missing_inline_in_public_items, - clippy::missing_safety_doc, - clippy::obfuscated_if_else, - clippy::perf, - clippy::print_stdout, - clippy::std_instead_of_core, - clippy::style, - clippy::suspicious, - clippy::todo, - clippy::undocumented_unsafe_blocks, - clippy::unimplemented, - clippy::unnested_or_patterns, - clippy::unwrap_used, - clippy::use_debug -)] -#![deny( - rustdoc::bare_urls, - rustdoc::broken_intra_doc_links, - rustdoc::invalid_codeblock_attributes, - rustdoc::invalid_html_tags, - rustdoc::invalid_rust_codeblocks, - rustdoc::missing_crate_level_docs, - rustdoc::private_intra_doc_links -)] -// In test code, it makes sense to weight more heavily towards concise, readable -// code over correct or debuggable code. -#![cfg_attr(any(test, kani), allow( - // In tests, you get line numbers and have access to source code, so panic - // messages are less important. You also often unwrap a lot, which would - // make expect'ing instead very verbose. - clippy::unwrap_used, - // In tests, there's no harm to "panic risks" - the worst that can happen is - // that your test will fail, and you'll fix it. By contrast, panic risks in - // production code introduce the possibly of code panicking unexpectedly "in - // the field". - clippy::arithmetic_side_effects, - clippy::indexing_slicing, -))] -#![cfg_attr(not(test), no_std)] -#![cfg_attr( - all(feature = "simd-nightly", any(target_arch = "x86", target_arch = "x86_64")), - feature(stdarch_x86_avx512) -)] -#![cfg_attr( - all(feature = "simd-nightly", target_arch = "arm"), - feature(stdarch_arm_dsp, stdarch_arm_neon_intrinsics) -)] -#![cfg_attr( - all(feature = "simd-nightly", any(target_arch = "powerpc", target_arch = "powerpc64")), - feature(stdarch_powerpc) -)] -#![cfg_attr(doc_cfg, feature(doc_cfg))] -#![cfg_attr( - __INTERNAL_USE_ONLY_NIGHLTY_FEATURES_IN_TESTS, - feature(layout_for_ptr, strict_provenance) -)] - -// This is a hack to allow zerocopy-derive derives to work in this crate. They -// assume that zerocopy is linked as an extern crate, so they access items from -// it as `zerocopy::Xxx`. This makes that still work. -#[cfg(any(feature = "derive", test))] -extern crate self as zerocopy; - -#[macro_use] -mod macros; - -#[cfg(feature = "byteorder")] -#[cfg_attr(doc_cfg, doc(cfg(feature = "byteorder")))] -pub mod byteorder; -#[doc(hidden)] -pub mod macro_util; -mod post_monomorphization_compile_fail_tests; -mod util; -// TODO(#252): If we make this pub, come up with a better name. -mod wrappers; - -#[cfg(feature = "byteorder")] -#[cfg_attr(doc_cfg, doc(cfg(feature = "byteorder")))] -pub use crate::byteorder::*; -pub use crate::wrappers::*; - -#[cfg(any(feature = "derive", test))] -#[cfg_attr(doc_cfg, doc(cfg(feature = "derive")))] -pub use zerocopy_derive::Unaligned; - -// `pub use` separately here so that we can mark it `#[doc(hidden)]`. -// -// TODO(#29): Remove this or add a doc comment. -#[cfg(any(feature = "derive", test))] -#[cfg_attr(doc_cfg, doc(cfg(feature = "derive")))] -#[doc(hidden)] -pub use zerocopy_derive::KnownLayout; - -use core::{ - cell::{self, RefMut}, - cmp::Ordering, - fmt::{self, Debug, Display, Formatter}, - hash::Hasher, - marker::PhantomData, - mem::{self, ManuallyDrop, MaybeUninit}, - num::{ - NonZeroI128, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI8, NonZeroIsize, NonZeroU128, - NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU8, NonZeroUsize, Wrapping, - }, - ops::{Deref, DerefMut}, - ptr::{self, NonNull}, - slice, -}; - -#[cfg(feature = "alloc")] -extern crate alloc; -#[cfg(feature = "alloc")] -use alloc::{boxed::Box, vec::Vec}; - -#[cfg(any(feature = "alloc", kani))] -use core::alloc::Layout; - -// Used by `TryFromBytes::is_bit_valid`. -#[doc(hidden)] -pub use crate::util::ptr::Ptr; - -// For each polyfill, as soon as the corresponding feature is stable, the -// polyfill import will be unused because method/function resolution will prefer -// the inherent method/function over a trait method/function. Thus, we suppress -// the `unused_imports` warning. -// -// See the documentation on `util::polyfills` for more information. -#[allow(unused_imports)] -use crate::util::polyfills::NonNullExt as _; - -#[rustversion::nightly] -#[cfg(all(test, not(__INTERNAL_USE_ONLY_NIGHLTY_FEATURES_IN_TESTS)))] -const _: () = { - #[deprecated = "some tests may be skipped due to missing RUSTFLAGS=\"--cfg __INTERNAL_USE_ONLY_NIGHLTY_FEATURES_IN_TESTS\""] - const _WARNING: () = (); - #[warn(deprecated)] - _WARNING -}; - -/// The target pointer width, counted in bits. -const POINTER_WIDTH_BITS: usize = mem::size_of::<usize>() * 8; - -/// The layout of a type which might be dynamically-sized. -/// -/// `DstLayout` describes the layout of sized types, slice types, and "slice -/// DSTs" - ie, those that are known by the type system to have a trailing slice -/// (as distinguished from `dyn Trait` types - such types *might* have a -/// trailing slice type, but the type system isn't aware of it). -/// -/// # Safety -/// -/// Unlike [`core::alloc::Layout`], `DstLayout` is only used to describe full -/// Rust types - ie, those that satisfy the layout requirements outlined by -/// [the reference]. Callers may assume that an instance of `DstLayout` -/// satisfies any conditions imposed on Rust types by the reference. -/// -/// If `layout: DstLayout` describes a type, `T`, then it is guaranteed that: -/// - `layout.align` is equal to `T`'s alignment -/// - If `layout.size_info` is `SizeInfo::Sized { size }`, then `T: Sized` and -/// `size_of::<T>() == size` -/// - If `layout.size_info` is `SizeInfo::SliceDst(slice_layout)`, then -/// - `T` is a slice DST -/// - The `size` of an instance of `T` with `elems` trailing slice elements is -/// equal to `slice_layout.offset + slice_layout.elem_size * elems` rounded up -/// to the nearest multiple of `layout.align`. Any bytes in the range -/// `[slice_layout.offset + slice_layout.elem_size * elems, size)` are padding -/// and must not be assumed to be initialized. -/// -/// [the reference]: https://doc.rust-lang.org/reference/type-layout.html -#[doc(hidden)] -#[allow(missing_debug_implementations, missing_copy_implementations)] -#[cfg_attr(any(kani, test), derive(Copy, Clone, Debug, PartialEq, Eq))] -pub struct DstLayout { - align: NonZeroUsize, - size_info: SizeInfo, -} - -#[cfg_attr(any(kani, test), derive(Copy, Clone, Debug, PartialEq, Eq))] -enum SizeInfo<E = usize> { - Sized { _size: usize }, - SliceDst(TrailingSliceLayout<E>), -} - -#[cfg_attr(any(kani, test), derive(Copy, Clone, Debug, PartialEq, Eq))] -struct TrailingSliceLayout<E = usize> { - // The offset of the first byte of the trailing slice field. Note that this - // is NOT the same as the minimum size of the type. For example, consider - // the following type: - // - // struct Foo { - // a: u16, - // b: u8, - // c: [u8], - // } - // - // In `Foo`, `c` is at byte offset 3. When `c.len() == 0`, `c` is followed - // by a padding byte. - _offset: usize, - // The size of the element type of the trailing slice field. - _elem_size: E, -} - -impl SizeInfo { - /// Attempts to create a `SizeInfo` from `Self` in which `elem_size` is a - /// `NonZeroUsize`. If `elem_size` is 0, returns `None`. - #[allow(unused)] - const fn try_to_nonzero_elem_size(&self) -> Option<SizeInfo<NonZeroUsize>> { - Some(match *self { - SizeInfo::Sized { _size } => SizeInfo::Sized { _size }, - SizeInfo::SliceDst(TrailingSliceLayout { _offset, _elem_size }) => { - if let Some(_elem_size) = NonZeroUsize::new(_elem_size) { - SizeInfo::SliceDst(TrailingSliceLayout { _offset, _elem_size }) - } else { - return None; - } - } - }) - } -} - -#[doc(hidden)] -#[derive(Copy, Clone)] -#[cfg_attr(test, derive(Debug))] -#[allow(missing_debug_implementations)] -pub enum _CastType { - _Prefix, - _Suffix, -} - -impl DstLayout { - /// The minimum possible alignment of a type. - const MIN_ALIGN: NonZeroUsize = match NonZeroUsize::new(1) { - Some(min_align) => min_align, - None => unreachable!(), - }; - - /// The maximum theoretic possible alignment of a type. - /// - /// For compatibility with future Rust versions, this is defined as the - /// maximum power-of-two that fits into a `usize`. See also - /// [`DstLayout::CURRENT_MAX_ALIGN`]. - const THEORETICAL_MAX_ALIGN: NonZeroUsize = - match NonZeroUsize::new(1 << (POINTER_WIDTH_BITS - 1)) { - Some(max_align) => max_align, - None => unreachable!(), - }; - - /// The current, documented max alignment of a type \[1\]. - /// - /// \[1\] Per <https://doc.rust-lang.org/reference/type-layout.html#the-alignment-modifiers>: - /// - /// The alignment value must be a power of two from 1 up to - /// 2<sup>29</sup>. - #[cfg(not(kani))] - const CURRENT_MAX_ALIGN: NonZeroUsize = match NonZeroUsize::new(1 << 28) { - Some(max_align) => max_align, - None => unreachable!(), - }; - - /// Constructs a `DstLayout` for a zero-sized type with `repr_align` - /// alignment (or 1). If `repr_align` is provided, then it must be a power - /// of two. - /// - /// # Panics - /// - /// This function panics if the supplied `repr_align` is not a power of two. - /// - /// # Safety - /// - /// Unsafe code may assume that the contract of this function is satisfied. - #[doc(hidden)] - #[inline] - pub const fn new_zst(repr_align: Option<NonZeroUsize>) -> DstLayout { - let align = match repr_align { - Some(align) => align, - None => Self::MIN_ALIGN, - }; - - assert!(align.is_power_of_two()); - - DstLayout { align, size_info: SizeInfo::Sized { _size: 0 } } - } - - /// Constructs a `DstLayout` which describes `T`. - /// - /// # Safety - /// - /// Unsafe code may assume that `DstLayout` is the correct layout for `T`. - #[doc(hidden)] - #[inline] - pub const fn for_type<T>() -> DstLayout { - // SAFETY: `align` is correct by construction. `T: Sized`, and so it is - // sound to initialize `size_info` to `SizeInfo::Sized { size }`; the - // `size` field is also correct by construction. - DstLayout { - align: match NonZeroUsize::new(mem::align_of::<T>()) { - Some(align) => align, - None => unreachable!(), - }, - size_info: SizeInfo::Sized { _size: mem::size_of::<T>() }, - } - } - - /// Constructs a `DstLayout` which describes `[T]`. - /// - /// # Safety - /// - /// Unsafe code may assume that `DstLayout` is the correct layout for `[T]`. - const fn for_slice<T>() -> DstLayout { - // SAFETY: The alignment of a slice is equal to the alignment of its - // element type, and so `align` is initialized correctly. - // - // Since this is just a slice type, there is no offset between the - // beginning of the type and the beginning of the slice, so it is - // correct to set `offset: 0`. The `elem_size` is correct by - // construction. Since `[T]` is a (degenerate case of a) slice DST, it - // is correct to initialize `size_info` to `SizeInfo::SliceDst`. - DstLayout { - align: match NonZeroUsize::new(mem::align_of::<T>()) { - Some(align) => align, - None => unreachable!(), - }, - size_info: SizeInfo::SliceDst(TrailingSliceLayout { - _offset: 0, - _elem_size: mem::size_of::<T>(), - }), - } - } - - /// Like `Layout::extend`, this creates a layout that describes a record - /// whose layout consists of `self` followed by `next` that includes the - /// necessary inter-field padding, but not any trailing padding. - /// - /// In order to match the layout of a `#[repr(C)]` struct, this method - /// should be invoked for each field in declaration order. To add trailing - /// padding, call `DstLayout::pad_to_align` after extending the layout for - /// all fields. If `self` corresponds to a type marked with - /// `repr(packed(N))`, then `repr_packed` should be set to `Some(N)`, - /// otherwise `None`. - /// - /// This method cannot be used to match the layout of a record with the - /// default representation, as that representation is mostly unspecified. - /// - /// # Safety - /// - /// If a (potentially hypothetical) valid `repr(C)` Rust type begins with - /// fields whose layout are `self`, and those fields are immediately - /// followed by a field whose layout is `field`, then unsafe code may rely - /// on `self.extend(field, repr_packed)` producing a layout that correctly - /// encompasses those two components. - /// - /// We make no guarantees to the behavior of this method if these fragments - /// cannot appear in a valid Rust type (e.g., the concatenation of the - /// layouts would lead to a size larger than `isize::MAX`). - #[doc(hidden)] - #[inline] - pub const fn extend(self, field: DstLayout, repr_packed: Option<NonZeroUsize>) -> Self { - use util::{core_layout::padding_needed_for, max, min}; - - // If `repr_packed` is `None`, there are no alignment constraints, and - // the value can be defaulted to `THEORETICAL_MAX_ALIGN`. - let max_align = match repr_packed { - Some(max_align) => max_align, - None => Self::THEORETICAL_MAX_ALIGN, - }; - - assert!(max_align.is_power_of_two()); - - // We use Kani to prove that this method is robust to future increases - // in Rust's maximum allowed alignment. However, if such a change ever - // actually occurs, we'd like to be notified via assertion failures. - #[cfg(not(kani))] - { - debug_assert!(self.align.get() <= DstLayout::CURRENT_MAX_ALIGN.get()); - debug_assert!(field.align.get() <= DstLayout::CURRENT_MAX_ALIGN.get()); - if let Some(repr_packed) = repr_packed { - debug_assert!(repr_packed.get() <= DstLayout::CURRENT_MAX_ALIGN.get()); - } - } - - // The field's alignment is clamped by `repr_packed` (i.e., the - // `repr(packed(N))` attribute, if any) [1]. - // - // [1] Per https://doc.rust-lang.org/reference/type-layout.html#the-alignment-modifiers: - // - // The alignments of each field, for the purpose of positioning - // fields, is the smaller of the specified alignment and the alignment - // of the field's type. - let field_align = min(field.align, max_align); - - // The struct's alignment is the maximum of its previous alignment and - // `field_align`. - let align = max(self.align, field_align); - - let size_info = match self.size_info { - // If the layout is already a DST, we panic; DSTs cannot be extended - // with additional fields. - SizeInfo::SliceDst(..) => panic!("Cannot extend a DST with additional fields."), - - SizeInfo::Sized { _size: preceding_size } => { - // Compute the minimum amount of inter-field padding needed to - // satisfy the field's alignment, and offset of the trailing - // field. [1] - // - // [1] Per https://doc.rust-lang.org/reference/type-layout.html#the-alignment-modifiers: - // - // Inter-field padding is guaranteed to be the minimum - // required in order to satisfy each field's (possibly - // altered) alignment. - let padding = padding_needed_for(preceding_size, field_align); - - // This will not panic (and is proven to not panic, with Kani) - // if the layout components can correspond to a leading layout - // fragment of a valid Rust type, but may panic otherwise (e.g., - // combining or aligning the components would create a size - // exceeding `isize::MAX`). - let offset = match preceding_size.checked_add(padding) { - Some(offset) => offset, - None => panic!("Adding padding to `self`'s size overflows `usize`."), - }; - - match field.size_info { - SizeInfo::Sized { _size: field_size } => { - // If the trailing field is sized, the resulting layout - // will be sized. Its size will be the sum of the - // preceeding layout, the size of the new field, and the - // size of inter-field padding between the two. - // - // This will not panic (and is proven with Kani to not - // panic) if the layout components can correspond to a - // leading layout fragment of a valid Rust type, but may - // panic otherwise (e.g., combining or aligning the - // components would create a size exceeding - // `usize::MAX`). - let size = match offset.checked_add(field_size) { - Some(size) => size, - None => panic!("`field` cannot be appended without the total size overflowing `usize`"), - }; - SizeInfo::Sized { _size: size } - } - SizeInfo::SliceDst(TrailingSliceLayout { - _offset: trailing_offset, - _elem_size, - }) => { - // If the trailing field is dynamically sized, so too - // will the resulting layout. The offset of the trailing - // slice component is the sum of the offset of the - // trailing field and the trailing slice offset within - // that field. - // - // This will not panic (and is proven with Kani to not - // panic) if the layout components can correspond to a - // leading layout fragment of a valid Rust type, but may - // panic otherwise (e.g., combining or aligning the - // components would create a size exceeding - // `usize::MAX`). - let offset = match offset.checked_add(trailing_offset) { - Some(offset) => offset, - None => panic!("`field` cannot be appended without the total size overflowing `usize`"), - }; - SizeInfo::SliceDst(TrailingSliceLayout { _offset: offset, _elem_size }) - } - } - } - }; - - DstLayout { align, size_info } - } - - /// Like `Layout::pad_to_align`, this routine rounds the size of this layout - /// up to the nearest multiple of this type's alignment or `repr_packed` - /// (whichever is less). This method leaves DST layouts unchanged, since the - /// trailing padding of DSTs is computed at runtime. - /// - /// In order to match the layout of a `#[repr(C)]` struct, this method - /// should be invoked after the invocations of [`DstLayout::extend`]. If - /// `self` corresponds to a type marked with `repr(packed(N))`, then - /// `repr_packed` should be set to `Some(N)`, otherwise `None`. - /// - /// This method cannot be used to match the layout of a record with the - /// default representation, as that representation is mostly unspecified. - /// - /// # Safety - /// - /// If a (potentially hypothetical) valid `repr(C)` type begins with fields - /// whose layout are `self` followed only by zero or more bytes of trailing - /// padding (not included in `self`), then unsafe code may rely on - /// `self.pad_to_align(repr_packed)` producing a layout that correctly - /// encapsulates the layout of that type. - /// - /// We make no guarantees to the behavior of this method if `self` cannot - /// appear in a valid Rust type (e.g., because the addition of trailing - /// padding would lead to a size larger than `isize::MAX`). - #[doc(hidden)] - #[inline] - pub const fn pad_to_align(self) -> Self { - use util::core_layout::padding_needed_for; - - let size_info = match self.size_info { - // For sized layouts, we add the minimum amount of trailing padding - // needed to satisfy alignment. - SizeInfo::Sized { _size: unpadded_size } => { - let padding = padding_needed_for(unpadded_size, self.align); - let size = match unpadded_size.checked_add(padding) { - Some(size) => size, - None => panic!("Adding padding caused size to overflow `usize`."), - }; - SizeInfo::Sized { _size: size } - } - // For DST layouts, trailing padding depends on the length of the - // trailing DST and is computed at runtime. This does not alter the - // offset or element size of the layout, so we leave `size_info` - // unchanged. - size_info @ SizeInfo::SliceDst(_) => size_info, - }; - - DstLayout { align: self.align, size_info } - } - - /// Validates that a cast is sound from a layout perspective. - /// - /// Validates that the size and alignment requirements of a type with the - /// layout described in `self` would not be violated by performing a - /// `cast_type` cast from a pointer with address `addr` which refers to a - /// memory region of size `bytes_len`. - /// - /// If the cast is valid, `validate_cast_and_convert_metadata` returns - /// `(elems, split_at)`. If `self` describes a dynamically-sized type, then - /// `elems` is the maximum number of trailing slice elements for which a - /// cast would be valid (for sized types, `elem` is meaningless and should - /// be ignored). `split_at` is the index at which to split the memory region - /// in order for the prefix (suffix) to contain the result of the cast, and - /// in order for the remaining suffix (prefix) to contain the leftover - /// bytes. - /// - /// There are three conditions under which a cast can fail: - /// - The smallest possible value for the type is larger than the provided - /// memory region - /// - A prefix cast is requested, and `addr` does not satisfy `self`'s - /// alignment requirement - /// - A suffix cast is requested, and `addr + bytes_len` does not satisfy - /// `self`'s alignment requirement (as a consequence, since all instances - /// of the type are a multiple of its alignment, no size for the type will - /// result in a starting address which is properly aligned) - /// - /// # Safety - /// - /// The caller may assume that this implementation is correct, and may rely - /// on that assumption for the soundness of their code. In particular, the - /// caller may assume that, if `validate_cast_and_convert_metadata` returns - /// `Some((elems, split_at))`, then: - /// - A pointer to the type (for dynamically sized types, this includes - /// `elems` as its pointer metadata) describes an object of size `size <= - /// bytes_len` - /// - If this is a prefix cast: - /// - `addr` satisfies `self`'s alignment - /// - `size == split_at` - /// - If this is a suffix cast: - /// - `split_at == bytes_len - size` - /// - `addr + split_at` satisfies `self`'s alignment - /// - /// Note that this method does *not* ensure that a pointer constructed from - /// its return values will be a valid pointer. In particular, this method - /// does not reason about `isize` overflow, which is a requirement of many - /// Rust pointer APIs, and may at some point be determined to be a validity - /// invariant of pointer types themselves. This should never be a problem so - /// long as the arguments to this method are derived from a known-valid - /// pointer (e.g., one derived from a safe Rust reference), but it is - /// nonetheless the caller's responsibility to justify that pointer - /// arithmetic will not overflow based on a safety argument *other than* the - /// mere fact that this method returned successfully. - /// - /// # Panics - /// - /// `validate_cast_and_convert_metadata` will panic if `self` describes a - /// DST whose trailing slice element is zero-sized. - /// - /// If `addr + bytes_len` overflows `usize`, - /// `validate_cast_and_convert_metadata` may panic, or it may return - /// incorrect results. No guarantees are made about when - /// `validate_cast_and_convert_metadata` will panic. The caller should not - /// rely on `validate_cast_and_convert_metadata` panicking in any particular - /// condition, even if `debug_assertions` are enabled. - #[allow(unused)] - const fn validate_cast_and_convert_metadata( - &self, - addr: usize, - bytes_len: usize, - cast_type: _CastType, - ) -> Option<(usize, usize)> { - // `debug_assert!`, but with `#[allow(clippy::arithmetic_side_effects)]`. - macro_rules! __debug_assert { - ($e:expr $(, $msg:expr)?) => { - debug_assert!({ - #[allow(clippy::arithmetic_side_effects)] - let e = $e; - e - } $(, $msg)?); - }; - } - - // Note that, in practice, `self` is always a compile-time constant. We - // do this check earlier than needed to ensure that we always panic as a - // result of bugs in the program (such as calling this function on an - // invalid type) instead of allowing this panic to be hidden if the cast - // would have failed anyway for runtime reasons (such as a too-small - // memory region). - // - // TODO(#67): Once our MSRV is 1.65, use let-else: - // https://blog.rust-lang.org/2022/11/03/Rust-1.65.0.html#let-else-statements - let size_info = match self.size_info.try_to_nonzero_elem_size() { - Some(size_info) => size_info, - None => panic!("attempted to cast to slice type with zero-sized element"), - }; - - // Precondition - __debug_assert!(addr.checked_add(bytes_len).is_some(), "`addr` + `bytes_len` > usize::MAX"); - - // Alignment checks go in their own block to avoid introducing variables - // into the top-level scope. - { - // We check alignment for `addr` (for prefix casts) or `addr + - // bytes_len` (for suffix casts). For a prefix cast, the correctness - // of this check is trivial - `addr` is the address the object will - // live at. - // - // For a suffix cast, we know that all valid sizes for the type are - // a multiple of the alignment (and by safety precondition, we know - // `DstLayout` may only describe valid Rust types). Thus, a - // validly-sized instance which lives at a validly-aligned address - // must also end at a validly-aligned address. Thus, if the end - // address for a suffix cast (`addr + bytes_len`) is not aligned, - // then no valid start address will be aligned either. - let offset = match cast_type { - _CastType::_Prefix => 0, - _CastType::_Suffix => bytes_len, - }; - - // Addition is guaranteed not to overflow because `offset <= - // bytes_len`, and `addr + bytes_len <= usize::MAX` is a - // precondition of this method. Modulus is guaranteed not to divide - // by 0 because `align` is non-zero. - #[allow(clippy::arithmetic_side_effects)] - if (addr + offset) % self.align.get() != 0 { - return None; - } - } - - let (elems, self_bytes) = match size_info { - SizeInfo::Sized { _size: size } => { - if size > bytes_len { - return None; - } - (0, size) - } - SizeInfo::SliceDst(TrailingSliceLayout { _offset: offset, _elem_size: elem_size }) => { - // Calculate the maximum number of bytes that could be consumed - // - any number of bytes larger than this will either not be a - // multiple of the alignment, or will be larger than - // `bytes_len`. - let max_total_bytes = - util::round_down_to_next_multiple_of_alignment(bytes_len, self.align); - // Calculate the maximum number of bytes that could be consumed - // by the trailing slice. - // - // TODO(#67): Once our MSRV is 1.65, use let-else: - // https://blog.rust-lang.org/2022/11/03/Rust-1.65.0.html#let-else-statements - let max_slice_and_padding_bytes = match max_total_bytes.checked_sub(offset) { - Some(max) => max, - // `bytes_len` too small even for 0 trailing slice elements. - None => return None, - }; - - // Calculate the number of elements that fit in - // `max_slice_and_padding_bytes`; any remaining bytes will be - // considered padding. - // - // Guaranteed not to divide by zero: `elem_size` is non-zero. - #[allow(clippy::arithmetic_side_effects)] - let elems = max_slice_and_padding_bytes / elem_size.get(); - // Guaranteed not to overflow on multiplication: `usize::MAX >= - // max_slice_and_padding_bytes >= (max_slice_and_padding_bytes / - // elem_size) * elem_size`. - // - // Guaranteed not to overflow on addition: - // - max_slice_and_padding_bytes == max_total_bytes - offset - // - elems * elem_size <= max_slice_and_padding_bytes == max_total_bytes - offset - // - elems * elem_size + offset <= max_total_bytes <= usize::MAX - #[allow(clippy::arithmetic_side_effects)] - let without_padding = offset + elems * elem_size.get(); - // `self_bytes` is equal to the offset bytes plus the bytes - // consumed by the trailing slice plus any padding bytes - // required to satisfy the alignment. Note that we have computed - // the maximum number of trailing slice elements that could fit - // in `self_bytes`, so any padding is guaranteed to be less than - // the size of an extra element. - // - // Guaranteed not to overflow: - // - By previous comment: without_padding == elems * elem_size + - // offset <= max_total_bytes - // - By construction, `max_total_bytes` is a multiple of - // `self.align`. - // - At most, adding padding needed to round `without_padding` - // up to the next multiple of the alignment will bring - // `self_bytes` up to `max_total_bytes`. - #[allow(clippy::arithmetic_side_effects)] - let self_bytes = without_padding - + util::core_layout::padding_needed_for(without_padding, self.align); - (elems, self_bytes) - } - }; - - __debug_assert!(self_bytes <= bytes_len); - - let split_at = match cast_type { - _CastType::_Prefix => self_bytes, - // Guaranteed not to underflow: - // - In the `Sized` branch, only returns `size` if `size <= - // bytes_len`. - // - In the `SliceDst` branch, calculates `self_bytes <= - // max_toatl_bytes`, which is upper-bounded by `bytes_len`. - #[allow(clippy::arithmetic_side_effects)] - _CastType::_Suffix => bytes_len - self_bytes, - }; - - Some((elems, split_at)) - } -} - -/// A trait which carries information about a type's layout that is used by the -/// internals of this crate. -/// -/// This trait is not meant for consumption by code outside of this crate. While -/// the normal semver stability guarantees apply with respect to which types -/// implement this trait and which trait implementations are implied by this -/// trait, no semver stability guarantees are made regarding its internals; they -/// may change at any time, and code which makes use of them may break. -/// -/// # Safety -/// -/// This trait does not convey any safety guarantees to code outside this crate. -#[doc(hidden)] // TODO: Remove this once KnownLayout is used by other APIs -pub unsafe trait KnownLayout { - // The `Self: Sized` bound makes it so that `KnownLayout` can still be - // object safe. It's not currently object safe thanks to `const LAYOUT`, and - // it likely won't be in the future, but there's no reason not to be - // forwards-compatible with object safety. - #[doc(hidden)] - fn only_derive_is_allowed_to_implement_this_trait() - where - Self: Sized; - - #[doc(hidden)] - const LAYOUT: DstLayout; - - /// SAFETY: The returned pointer has the same address and provenance as - /// `bytes`. If `Self` is a DST, the returned pointer's referent has `elems` - /// elements in its trailing slice. If `Self` is sized, `elems` is ignored. - #[doc(hidden)] - fn raw_from_ptr_len(bytes: NonNull<u8>, elems: usize) -> NonNull<Self>; -} - -// SAFETY: Delegates safety to `DstLayout::for_slice`. -unsafe impl<T: KnownLayout> KnownLayout for [T] { - #[allow(clippy::missing_inline_in_public_items)] - fn only_derive_is_allowed_to_implement_this_trait() - where - Self: Sized, - { - } - const LAYOUT: DstLayout = DstLayout::for_slice::<T>(); - - // SAFETY: `.cast` preserves address and provenance. The returned pointer - // refers to an object with `elems` elements by construction. - #[inline(always)] - fn raw_from_ptr_len(data: NonNull<u8>, elems: usize) -> NonNull<Self> { - // TODO(#67): Remove this allow. See NonNullExt for more details. - #[allow(unstable_name_collisions)] - NonNull::slice_from_raw_parts(data.cast::<T>(), elems) - } -} - -#[rustfmt::skip] -impl_known_layout!( - (), - u8, i8, u16, i16, u32, i32, u64, i64, u128, i128, usize, isize, f32, f64, - bool, char, - NonZeroU8, NonZeroI8, NonZeroU16, NonZeroI16, NonZeroU32, NonZeroI32, - NonZeroU64, NonZeroI64, NonZeroU128, NonZeroI128, NonZeroUsize, NonZeroIsize -); -#[rustfmt::skip] -impl_known_layout!( - T => Option<T>, - T: ?Sized => PhantomData<T>, - T => Wrapping<T>, - T => MaybeUninit<T>, - T: ?Sized => *const T, - T: ?Sized => *mut T, -); -impl_known_layout!(const N: usize, T => [T; N]); - -safety_comment! { - /// SAFETY: - /// `str` and `ManuallyDrop<[T]>` [1] have the same representations as - /// `[u8]` and `[T]` repsectively. `str` has different bit validity than - /// `[u8]`, but that doesn't affect the soundness of this impl. - /// - /// [1] Per https://doc.rust-lang.org/nightly/core/mem/struct.ManuallyDrop.html: - /// - /// `ManuallyDrop<T>` is guaranteed to have the same layout and bit - /// validity as `T` - /// - /// TODO(#429): - /// - Add quotes from docs. - /// - Once [1] (added in - /// https://github.com/rust-lang/rust/pull/115522) is available on stable, - /// quote the stable docs instead of the nightly docs. - unsafe_impl_known_layout!(#[repr([u8])] str); - unsafe_impl_known_layout!(T: ?Sized + KnownLayout => #[repr(T)] ManuallyDrop<T>); -} - -/// Analyzes whether a type is [`FromZeroes`]. -/// -/// This derive analyzes, at compile time, whether the annotated type satisfies -/// the [safety conditions] of `FromZeroes` and implements `FromZeroes` if it is -/// sound to do so. This derive can be applied to structs, enums, and unions; -/// e.g.: -/// -/// ``` -/// # use zerocopy_derive::FromZeroes; -/// #[derive(FromZeroes)] -/// struct MyStruct { -/// # /* -/// ... -/// # */ -/// } -/// -/// #[derive(FromZeroes)] -/// #[repr(u8)] -/// enum MyEnum { -/// # Variant0, -/// # /* -/// ... -/// # */ -/// } -/// -/// #[derive(FromZeroes)] -/// union MyUnion { -/// # variant: u8, -/// # /* -/// ... -/// # */ -/// } -/// ``` -/// -/// [safety conditions]: trait@FromZeroes#safety -/// -/// # Analysis -/// -/// *This section describes, roughly, the analysis performed by this derive to -/// determine whether it is sound to implement `FromZeroes` for a given type. -/// Unless you are modifying the implementation of this derive, or attempting to -/// manually implement `FromZeroes` for a type yourself, you don't need to read -/// this section.* -/// -/// If a type has the following properties, then this derive can implement -/// `FromZeroes` for that type: -/// -/// - If the type is a struct, all of its fields must be `FromZeroes`. -/// - If the type is an enum, it must be C-like (meaning that all variants have -/// no fields) and it must have a variant with a discriminant of `0`. See [the -/// reference] for a description of how discriminant values are chosen. -/// - The type must not contain any [`UnsafeCell`]s (this is required in order -/// for it to be sound to construct a `&[u8]` and a `&T` to the same region of -/// memory). The type may contain references or pointers to `UnsafeCell`s so -/// long as those values can themselves be initialized from zeroes -/// (`FromZeroes` is not currently implemented for, e.g., -/// `Option<&UnsafeCell<_>>`, but it could be one day). -/// -/// This analysis is subject to change. Unsafe code may *only* rely on the -/// documented [safety conditions] of `FromZeroes`, and must *not* rely on the -/// implementation details of this derive. -/// -/// [the reference]: https://doc.rust-lang.org/reference/items/enumerations.html#custom-discriminant-values-for-fieldless-enumerations -/// [`UnsafeCell`]: core::cell::UnsafeCell -/// -/// ## Why isn't an explicit representation required for structs? -/// -/// Neither this derive, nor the [safety conditions] of `FromZeroes`, requires -/// that structs are marked with `#[repr(C)]`. -/// -/// Per the [Rust reference](reference), -/// -/// > The representation of a type can change the padding between fields, but -/// > does not change the layout of the fields themselves. -/// -/// [reference]: https://doc.rust-lang.org/reference/type-layout.html#representations -/// -/// Since the layout of structs only consists of padding bytes and field bytes, -/// a struct is soundly `FromZeroes` if: -/// 1. its padding is soundly `FromZeroes`, and -/// 2. its fields are soundly `FromZeroes`. -/// -/// The answer to the first question is always yes: padding bytes do not have -/// any validity constraints. A [discussion] of this question in the Unsafe Code -/// Guidelines Working Group concluded that it would be virtually unimaginable -/// for future versions of rustc to add validity constraints to padding bytes. -/// -/// [discussion]: https://github.com/rust-lang/unsafe-code-guidelines/issues/174 -/// -/// Whether a struct is soundly `FromZeroes` therefore solely depends on whether -/// its fields are `FromZeroes`. -// TODO(#146): Document why we don't require an enum to have an explicit `repr` -// attribute. -#[cfg(any(feature = "derive", test))] -#[cfg_attr(doc_cfg, doc(cfg(feature = "derive")))] -pub use zerocopy_derive::FromZeroes; - -/// Types whose validity can be checked at runtime, allowing them to be -/// conditionally converted from byte slices. -/// -/// WARNING: Do not implement this trait yourself! Instead, use -/// `#[derive(TryFromBytes)]`. -/// -/// `TryFromBytes` types can safely be deserialized from an untrusted sequence -/// of bytes by performing a runtime check that the byte sequence contains a -/// valid instance of `Self`. -/// -/// `TryFromBytes` is ignorant of byte order. For byte order-aware types, see -/// the [`byteorder`] module. -/// -/// # What is a "valid instance"? -/// -/// In Rust, each type has *bit validity*, which refers to the set of bit -/// patterns which may appear in an instance of that type. It is impossible for -/// safe Rust code to produce values which violate bit validity (ie, values -/// outside of the "valid" set of bit patterns). If `unsafe` code produces an -/// invalid value, this is considered [undefined behavior]. -/// -/// Rust's bit validity rules are currently being decided, which means that some -/// types have three classes of bit patterns: those which are definitely valid, -/// and whose validity is documented in the language; those which may or may not -/// be considered valid at some point in the future; and those which are -/// definitely invalid. -/// -/// Zerocopy takes a conservative approach, and only considers a bit pattern to -/// be valid if its validity is a documenteed guarantee provided by the -/// language. -/// -/// For most use cases, Rust's current guarantees align with programmers' -/// intuitions about what ought to be valid. As a result, zerocopy's -/// conservatism should not affect most users. One notable exception is unions, -/// whose bit validity is very up in the air; zerocopy does not permit -/// implementing `TryFromBytes` for any union type. -/// -/// If you are negatively affected by lack of support for a particular type, -/// we encourage you to let us know by [filing an issue][github-repo]. -/// -/// # Safety -/// -/// On its own, `T: TryFromBytes` does not make any guarantees about the layout -/// or representation of `T`. It merely provides the ability to perform a -/// validity check at runtime via methods like [`try_from_ref`]. -/// -/// Currently, it is not possible to stably implement `TryFromBytes` other than -/// by using `#[derive(TryFromBytes)]`. While there are `#[doc(hidden)]` items -/// on this trait that provide well-defined safety invariants, no stability -/// guarantees are made with respect to these items. In particular, future -/// releases of zerocopy may make backwards-breaking changes to these items, -/// including changes that only affect soundness, which may cause code which -/// uses those items to silently become unsound. -/// -/// [undefined behavior]: https://raphlinus.github.io/programming/rust/2018/08/17/undefined-behavior.html -/// [github-repo]: https://github.com/google/zerocopy -/// [`try_from_ref`]: TryFromBytes::try_from_ref -// TODO(#5): Update `try_from_ref` doc link once it exists -#[doc(hidden)] -pub unsafe trait TryFromBytes { - /// Does a given memory range contain a valid instance of `Self`? - /// - /// # Safety - /// - /// ## Preconditions - /// - /// The memory referenced by `candidate` may only be accessed via reads for - /// the duration of this method call. This prohibits writes through mutable - /// references and through [`UnsafeCell`]s. There may exist immutable - /// references to the same memory which contain `UnsafeCell`s so long as: - /// - Those `UnsafeCell`s exist at the same byte ranges as `UnsafeCell`s in - /// `Self`. This is a bidirectional property: `Self` may not contain - /// `UnsafeCell`s where other references to the same memory do not, and - /// vice-versa. - /// - Those `UnsafeCell`s are never used to perform mutation for the - /// duration of this method call. - /// - /// The memory referenced by `candidate` may not be referenced by any - /// mutable references even if these references are not used to perform - /// mutation. - /// - /// `candidate` is not required to refer to a valid `Self`. However, it must - /// satisfy the requirement that uninitialized bytes may only be present - /// where it is possible for them to be present in `Self`. This is a dynamic - /// property: if, at a particular byte offset, a valid enum discriminant is - /// set, the subsequent bytes may only have uninitialized bytes as - /// specificed by the corresponding enum. - /// - /// Formally, given `len = size_of_val_raw(candidate)`, at every byte - /// offset, `b`, in the range `[0, len)`: - /// - If, in all instances `s: Self` of length `len`, the byte at offset `b` - /// in `s` is initialized, then the byte at offset `b` within `*candidate` - /// must be initialized. - /// - Let `c` be the contents of the byte range `[0, b)` in `*candidate`. - /// Let `S` be the subset of valid instances of `Self` of length `len` - /// which contain `c` in the offset range `[0, b)`. If, for all instances - /// of `s: Self` in `S`, the byte at offset `b` in `s` is initialized, - /// then the byte at offset `b` in `*candidate` must be initialized. - /// - /// Pragmatically, this means that if `*candidate` is guaranteed to - /// contain an enum type at a particular offset, and the enum discriminant - /// stored in `*candidate` corresponds to a valid variant of that enum - /// type, then it is guaranteed that the appropriate bytes of `*candidate` - /// are initialized as defined by that variant's bit validity (although - /// note that the variant may contain another enum type, in which case the - /// same rules apply depending on the state of its discriminant, and so on - /// recursively). - /// - /// ## Postconditions - /// - /// Unsafe code may assume that, if `is_bit_valid(candidate)` returns true, - /// `*candidate` contains a valid `Self`. - /// - /// # Panics - /// - /// `is_bit_valid` may panic. Callers are responsible for ensuring that any - /// `unsafe` code remains sound even in the face of `is_bit_valid` - /// panicking. (We support user-defined validation routines; so long as - /// these routines are not required to be `unsafe`, there is no way to - /// ensure that these do not generate panics.) - /// - /// [`UnsafeCell`]: core::cell::UnsafeCell - #[doc(hidden)] - unsafe fn is_bit_valid(candidate: Ptr<'_, Self>) -> bool; - - /// Attempts to interpret a byte slice as a `Self`. - /// - /// `try_from_ref` validates that `bytes` contains a valid `Self`, and that - /// it satisfies `Self`'s alignment requirement. If it does, then `bytes` is - /// reinterpreted as a `Self`. - /// - /// Note that Rust's bit validity rules are still being decided. As such, - /// there exist types whose bit validity is ambiguous. See the - /// `TryFromBytes` docs for a discussion of how these cases are handled. - // TODO(#251): In a future in which we distinguish between `FromBytes` and - // `RefFromBytes`, this requires `where Self: RefFromBytes` to disallow - // interior mutability. - #[inline] - #[doc(hidden)] // TODO(#5): Finalize name before remove this attribute. - fn try_from_ref(bytes: &[u8]) -> Option<&Self> - where - Self: KnownLayout, - { - let maybe_self = Ptr::from(bytes).try_cast_into_no_leftover::<Self>()?; - - // SAFETY: - // - Since `bytes` is an immutable reference, we know that no mutable - // references exist to this memory region. - // - Since `[u8]` contains no `UnsafeCell`s, we know there are no - // `&UnsafeCell` references to this memory region. - // - Since we don't permit implementing `TryFromBytes` for types which - // contain `UnsafeCell`s, there are no `UnsafeCell`s in `Self`, and so - // the requirement that all references contain `UnsafeCell`s at the - // same offsets is trivially satisfied. - // - All bytes of `bytes` are initialized. - // - // This call may panic. If that happens, it doesn't cause any soundness - // issues, as we have not generated any invalid state which we need to - // fix before returning. - if unsafe { !Self::is_bit_valid(maybe_self) } { - return None; - } - - // SAFETY: - // - Preconditions for `as_ref`: - // - `is_bit_valid` guarantees that `*maybe_self` contains a valid - // `Self`. Since `&[u8]` does not permit interior mutation, this - // cannot be invalidated after this method returns. - // - Since the argument and return types are immutable references, - // Rust will prevent the caller from producing any mutable - // references to the same memory region. - // - Since `Self` is not allowed to contain any `UnsafeCell`s and the - // same is true of `[u8]`, interior mutation is not possible. Thus, - // no mutation is possible. For the same reason, there is no - // mismatch between the two types in terms of which byte ranges are - // referenced as `UnsafeCell`s. - // - Since interior mutation isn't possible within `Self`, there's no - // way for the returned reference to be used to modify the byte range, - // and thus there's no way for the returned reference to be used to - // write an invalid `[u8]` which would be observable via the original - // `&[u8]`. - Some(unsafe { maybe_self.as_ref() }) - } -} - -/// Types for which a sequence of bytes all set to zero represents a valid -/// instance of the type. -/// -/// Any memory region of the appropriate length which is guaranteed to contain -/// only zero bytes can be viewed as any `FromZeroes` type with no runtime -/// overhead. This is useful whenever memory is known to be in a zeroed state, -/// such memory returned from some allocation routines. -/// -/// # Implementation -/// -/// **Do not implement this trait yourself!** Instead, use -/// [`#[derive(FromZeroes)]`][derive] (requires the `derive` Cargo feature); -/// e.g.: -/// -/// ``` -/// # use zerocopy_derive::FromZeroes; -/// #[derive(FromZeroes)] -/// struct MyStruct { -/// # /* -/// ... -/// # */ -/// } -/// -/// #[derive(FromZeroes)] -/// #[repr(u8)] -/// enum MyEnum { -/// # Variant0, -/// # /* -/// ... -/// # */ -/// } -/// -/// #[derive(FromZeroes)] -/// union MyUnion { -/// # variant: u8, -/// # /* -/// ... -/// # */ -/// } -/// ``` -/// -/// This derive performs a sophisticated, compile-time safety analysis to -/// determine whether a type is `FromZeroes`. -/// -/// # Safety -/// -/// *This section describes what is required in order for `T: FromZeroes`, and -/// what unsafe code may assume of such types. If you don't plan on implementing -/// `FromZeroes` manually, and you don't plan on writing unsafe code that -/// operates on `FromZeroes` types, then you don't need to read this section.* -/// -/// If `T: FromZeroes`, then unsafe code may assume that: -/// - It is sound to treat any initialized sequence of zero bytes of length -/// `size_of::<T>()` as a `T`. -/// - Given `b: &[u8]` where `b.len() == size_of::<T>()`, `b` is aligned to -/// `align_of::<T>()`, and `b` contains only zero bytes, it is sound to -/// construct a `t: &T` at the same address as `b`, and it is sound for both -/// `b` and `t` to be live at the same time. -/// -/// If a type is marked as `FromZeroes` which violates this contract, it may -/// cause undefined behavior. -/// -/// `#[derive(FromZeroes)]` only permits [types which satisfy these -/// requirements][derive-analysis]. -/// -#[cfg_attr( - feature = "derive", - doc = "[derive]: zerocopy_derive::FromZeroes", - doc = "[derive-analysis]: zerocopy_derive::FromZeroes#analysis" -)] -#[cfg_attr( - not(feature = "derive"), - doc = concat!("[derive]: https://docs.rs/zerocopy/", env!("CARGO_PKG_VERSION"), "/zerocopy/derive.FromZeroes.html"), - doc = concat!("[derive-analysis]: https://docs.rs/zerocopy/", env!("CARGO_PKG_VERSION"), "/zerocopy/derive.FromZeroes.html#analysis"), -)] -pub unsafe trait FromZeroes { - // The `Self: Sized` bound makes it so that `FromZeroes` is still object - // safe. - #[doc(hidden)] - fn only_derive_is_allowed_to_implement_this_trait() - where - Self: Sized; - - /// Overwrites `self` with zeroes. - /// - /// Sets every byte in `self` to 0. While this is similar to doing `*self = - /// Self::new_zeroed()`, it differs in that `zero` does not semantically - /// drop the current value and replace it with a new one - it simply - /// modifies the bytes of the existing value. - /// - /// # Examples - /// - /// ``` - /// # use zerocopy::FromZeroes; - /// # use zerocopy_derive::*; - /// # - /// #[derive(FromZeroes)] - /// #[repr(C)] - /// struct PacketHeader { - /// src_port: [u8; 2], - /// dst_port: [u8; 2], - /// length: [u8; 2], - /// checksum: [u8; 2], - /// } - /// - /// let mut header = PacketHeader { - /// src_port: 100u16.to_be_bytes(), - /// dst_port: 200u16.to_be_bytes(), - /// length: 300u16.to_be_bytes(), - /// checksum: 400u16.to_be_bytes(), - /// }; - /// - /// header.zero(); - /// - /// assert_eq!(header.src_port, [0, 0]); - /// assert_eq!(header.dst_port, [0, 0]); - /// assert_eq!(header.length, [0, 0]); - /// assert_eq!(header.checksum, [0, 0]); - /// ``` - #[inline(always)] - fn zero(&mut self) { - let slf: *mut Self = self; - let len = mem::size_of_val(self); - // SAFETY: - // - `self` is guaranteed by the type system to be valid for writes of - // size `size_of_val(self)`. - // - `u8`'s alignment is 1, and thus `self` is guaranteed to be aligned - // as required by `u8`. - // - Since `Self: FromZeroes`, the all-zeroes instance is a valid - // instance of `Self.` - // - // TODO(#429): Add references to docs and quotes. - unsafe { ptr::write_bytes(slf.cast::<u8>(), 0, len) }; - } - - /// Creates an instance of `Self` from zeroed bytes. - /// - /// # Examples - /// - /// ``` - /// # use zerocopy::FromZeroes; - /// # use zerocopy_derive::*; - /// # - /// #[derive(FromZeroes)] - /// #[repr(C)] - /// struct PacketHeader { - /// src_port: [u8; 2], - /// dst_port: [u8; 2], - /// length: [u8; 2], - /// checksum: [u8; 2], - /// } - /// - /// let header: PacketHeader = FromZeroes::new_zeroed(); - /// - /// assert_eq!(header.src_port, [0, 0]); - /// assert_eq!(header.dst_port, [0, 0]); - /// assert_eq!(header.length, [0, 0]); - /// assert_eq!(header.checksum, [0, 0]); - /// ``` - #[inline(always)] - fn new_zeroed() -> Self - where - Self: Sized, - { - // SAFETY: `FromZeroes` says that the all-zeroes bit pattern is legal. - unsafe { mem::zeroed() } - } - - /// Creates a `Box<Self>` from zeroed bytes. - /// - /// This function is useful for allocating large values on the heap and - /// zero-initializing them, without ever creating a temporary instance of - /// `Self` on the stack. For example, `<[u8; 1048576]>::new_box_zeroed()` - /// will allocate `[u8; 1048576]` directly on the heap; it does not require - /// storing `[u8; 1048576]` in a temporary variable on the stack. - /// - /// On systems that use a heap implementation that supports allocating from - /// pre-zeroed memory, using `new_box_zeroed` (or related functions) may - /// have performance benefits. - /// - /// Note that `Box<Self>` can be converted to `Arc<Self>` and other - /// container types without reallocation. - /// - /// # Panics - /// - /// Panics if allocation of `size_of::<Self>()` bytes fails. - #[cfg(feature = "alloc")] - #[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))] - #[inline] - fn new_box_zeroed() -> Box<Self> - where - Self: Sized, - { - // If `T` is a ZST, then return a proper boxed instance of it. There is - // no allocation, but `Box` does require a correct dangling pointer. - let layout = Layout::new::<Self>(); - if layout.size() == 0 { - return Box::new(Self::new_zeroed()); - } - - // TODO(#429): Add a "SAFETY" comment and remove this `allow`. - #[allow(clippy::undocumented_unsafe_blocks)] - let ptr = unsafe { alloc::alloc::alloc_zeroed(layout).cast::<Self>() }; - if ptr.is_null() { - alloc::alloc::handle_alloc_error(layout); - } - // TODO(#429): Add a "SAFETY" comment and remove this `allow`. - #[allow(clippy::undocumented_unsafe_blocks)] - unsafe { - Box::from_raw(ptr) - } - } - - /// Creates a `Box<[Self]>` (a boxed slice) from zeroed bytes. - /// - /// This function is useful for allocating large values of `[Self]` on the - /// heap and zero-initializing them, without ever creating a temporary - /// instance of `[Self; _]` on the stack. For example, - /// `u8::new_box_slice_zeroed(1048576)` will allocate the slice directly on - /// the heap; it does not require storing the slice on the stack. - /// - /// On systems that use a heap implementation that supports allocating from - /// pre-zeroed memory, using `new_box_slice_zeroed` may have performance - /// benefits. - /// - /// If `Self` is a zero-sized type, then this function will return a - /// `Box<[Self]>` that has the correct `len`. Such a box cannot contain any - /// actual information, but its `len()` property will report the correct - /// value. - /// - /// # Panics - /// - /// * Panics if `size_of::<Self>() * len` overflows. - /// * Panics if allocation of `size_of::<Self>() * len` bytes fails. - #[cfg(feature = "alloc")] - #[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))] - #[inline] - fn new_box_slice_zeroed(len: usize) -> Box<[Self]> - where - Self: Sized, - { - let size = mem::size_of::<Self>() - .checked_mul(len) - .expect("mem::size_of::<Self>() * len overflows `usize`"); - let align = mem::align_of::<Self>(); - // On stable Rust versions <= 1.64.0, `Layout::from_size_align` has a - // bug in which sufficiently-large allocations (those which, when - // rounded up to the alignment, overflow `isize`) are not rejected, - // which can cause undefined behavior. See #64 for details. - // - // TODO(#67): Once our MSRV is > 1.64.0, remove this assertion. - #[allow(clippy::as_conversions)] - let max_alloc = (isize::MAX as usize).saturating_sub(align); - assert!(size <= max_alloc); - // TODO(https://github.com/rust-lang/rust/issues/55724): Use - // `Layout::repeat` once it's stabilized. - let layout = - Layout::from_size_align(size, align).expect("total allocation size overflows `isize`"); - - let ptr = if layout.size() != 0 { - // TODO(#429): Add a "SAFETY" comment and remove this `allow`. - #[allow(clippy::undocumented_unsafe_blocks)] - let ptr = unsafe { alloc::alloc::alloc_zeroed(layout).cast::<Self>() }; - if ptr.is_null() { - alloc::alloc::handle_alloc_error(layout); - } - ptr - } else { - // `Box<[T]>` does not allocate when `T` is zero-sized or when `len` - // is zero, but it does require a non-null dangling pointer for its - // allocation. - NonNull::<Self>::dangling().as_ptr() - }; - - // TODO(#429): Add a "SAFETY" comment and remove this `allow`. - #[allow(clippy::undocumented_unsafe_blocks)] - unsafe { - Box::from_raw(slice::from_raw_parts_mut(ptr, len)) - } - } - - /// Creates a `Vec<Self>` from zeroed bytes. - /// - /// This function is useful for allocating large values of `Vec`s and - /// zero-initializing them, without ever creating a temporary instance of - /// `[Self; _]` (or many temporary instances of `Self`) on the stack. For - /// example, `u8::new_vec_zeroed(1048576)` will allocate directly on the - /// heap; it does not require storing intermediate values on the stack. - /// - /// On systems that use a heap implementation that supports allocating from - /// pre-zeroed memory, using `new_vec_zeroed` may have performance benefits. - /// - /// If `Self` is a zero-sized type, then this function will return a - /// `Vec<Self>` that has the correct `len`. Such a `Vec` cannot contain any - /// actual information, but its `len()` property will report the correct - /// value. - /// - /// # Panics - /// - /// * Panics if `size_of::<Self>() * len` overflows. - /// * Panics if allocation of `size_of::<Self>() * len` bytes fails. - #[cfg(feature = "alloc")] - #[cfg_attr(doc_cfg, doc(cfg(feature = "new_vec_zeroed")))] - #[inline(always)] - fn new_vec_zeroed(len: usize) -> Vec<Self> - where - Self: Sized, - { - Self::new_box_slice_zeroed(len).into() - } -} - -/// Analyzes whether a type is [`FromBytes`]. -/// -/// This derive analyzes, at compile time, whether the annotated type satisfies -/// the [safety conditions] of `FromBytes` and implements `FromBytes` if it is -/// sound to do so. This derive can be applied to structs, enums, and unions; -/// e.g.: -/// -/// ``` -/// # use zerocopy_derive::{FromBytes, FromZeroes}; -/// #[derive(FromZeroes, FromBytes)] -/// struct MyStruct { -/// # /* -/// ... -/// # */ -/// } -/// -/// #[derive(FromZeroes, FromBytes)] -/// #[repr(u8)] -/// enum MyEnum { -/// # V00, V01, V02, V03, V04, V05, V06, V07, V08, V09, V0A, V0B, V0C, V0D, V0E, -/// # V0F, V10, V11, V12, V13, V14, V15, V16, V17, V18, V19, V1A, V1B, V1C, V1D, -/// # V1E, V1F, V20, V21, V22, V23, V24, V25, V26, V27, V28, V29, V2A, V2B, V2C, -/// # V2D, V2E, V2F, V30, V31, V32, V33, V34, V35, V36, V37, V38, V39, V3A, V3B, -/// # V3C, V3D, V3E, V3F, V40, V41, V42, V43, V44, V45, V46, V47, V48, V49, V4A, -/// # V4B, V4C, V4D, V4E, V4F, V50, V51, V52, V53, V54, V55, V56, V57, V58, V59, -/// # V5A, V5B, V5C, V5D, V5E, V5F, V60, V61, V62, V63, V64, V65, V66, V67, V68, -/// # V69, V6A, V6B, V6C, V6D, V6E, V6F, V70, V71, V72, V73, V74, V75, V76, V77, -/// # V78, V79, V7A, V7B, V7C, V7D, V7E, V7F, V80, V81, V82, V83, V84, V85, V86, -/// # V87, V88, V89, V8A, V8B, V8C, V8D, V8E, V8F, V90, V91, V92, V93, V94, V95, -/// # V96, V97, V98, V99, V9A, V9B, V9C, V9D, V9E, V9F, VA0, VA1, VA2, VA3, VA4, -/// # VA5, VA6, VA7, VA8, VA9, VAA, VAB, VAC, VAD, VAE, VAF, VB0, VB1, VB2, VB3, -/// # VB4, VB5, VB6, VB7, VB8, VB9, VBA, VBB, VBC, VBD, VBE, VBF, VC0, VC1, VC2, -/// # VC3, VC4, VC5, VC6, VC7, VC8, VC9, VCA, VCB, VCC, VCD, VCE, VCF, VD0, VD1, -/// # VD2, VD3, VD4, VD5, VD6, VD7, VD8, VD9, VDA, VDB, VDC, VDD, VDE, VDF, VE0, -/// # VE1, VE2, VE3, VE4, VE5, VE6, VE7, VE8, VE9, VEA, VEB, VEC, VED, VEE, VEF, -/// # VF0, VF1, VF2, VF3, VF4, VF5, VF6, VF7, VF8, VF9, VFA, VFB, VFC, VFD, VFE, -/// # VFF, -/// # /* -/// ... -/// # */ -/// } -/// -/// #[derive(FromZeroes, FromBytes)] -/// union MyUnion { -/// # variant: u8, -/// # /* -/// ... -/// # */ -/// } -/// ``` -/// -/// [safety conditions]: trait@FromBytes#safety -/// -/// # Analysis -/// -/// *This section describes, roughly, the analysis performed by this derive to -/// determine whether it is sound to implement `FromBytes` for a given type. -/// Unless you are modifying the implementation of this derive, or attempting to -/// manually implement `FromBytes` for a type yourself, you don't need to read -/// this section.* -/// -/// If a type has the following properties, then this derive can implement -/// `FromBytes` for that type: -/// -/// - If the type is a struct, all of its fields must be `FromBytes`. -/// - If the type is an enum: -/// - It must be a C-like enum (meaning that all variants have no fields). -/// - It must have a defined representation (`repr`s `C`, `u8`, `u16`, `u32`, -/// `u64`, `usize`, `i8`, `i16`, `i32`, `i64`, or `isize`). -/// - The maximum number of discriminants must be used (so that every possible -/// bit pattern is a valid one). Be very careful when using the `C`, -/// `usize`, or `isize` representations, as their size is -/// platform-dependent. -/// - The type must not contain any [`UnsafeCell`]s (this is required in order -/// for it to be sound to construct a `&[u8]` and a `&T` to the same region of -/// memory). The type may contain references or pointers to `UnsafeCell`s so -/// long as those values can themselves be initialized from zeroes -/// (`FromBytes` is not currently implemented for, e.g., `Option<*const -/// UnsafeCell<_>>`, but it could be one day). -/// -/// [`UnsafeCell`]: core::cell::UnsafeCell -/// -/// This analysis is subject to change. Unsafe code may *only* rely on the -/// documented [safety conditions] of `FromBytes`, and must *not* rely on the -/// implementation details of this derive. -/// -/// ## Why isn't an explicit representation required for structs? -/// -/// Neither this derive, nor the [safety conditions] of `FromBytes`, requires -/// that structs are marked with `#[repr(C)]`. -/// -/// Per the [Rust reference](reference), -/// -/// > The representation of a type can change the padding between fields, but -/// > does not change the layout of the fields themselves. -/// -/// [reference]: https://doc.rust-lang.org/reference/type-layout.html#representations -/// -/// Since the layout of structs only consists of padding bytes and field bytes, -/// a struct is soundly `FromBytes` if: -/// 1. its padding is soundly `FromBytes`, and -/// 2. its fields are soundly `FromBytes`. -/// -/// The answer to the first question is always yes: padding bytes do not have -/// any validity constraints. A [discussion] of this question in the Unsafe Code -/// Guidelines Working Group concluded that it would be virtually unimaginable -/// for future versions of rustc to add validity constraints to padding bytes. -/// -/// [discussion]: https://github.com/rust-lang/unsafe-code-guidelines/issues/174 -/// -/// Whether a struct is soundly `FromBytes` therefore solely depends on whether -/// its fields are `FromBytes`. -// TODO(#146): Document why we don't require an enum to have an explicit `repr` -// attribute. -#[cfg(any(feature = "derive", test))] -#[cfg_attr(doc_cfg, doc(cfg(feature = "derive")))] -pub use zerocopy_derive::FromBytes; - -/// Types for which any bit pattern is valid. -/// -/// Any memory region of the appropriate length which contains initialized bytes -/// can be viewed as any `FromBytes` type with no runtime overhead. This is -/// useful for efficiently parsing bytes as structured data. -/// -/// # Implementation -/// -/// **Do not implement this trait yourself!** Instead, use -/// [`#[derive(FromBytes)]`][derive] (requires the `derive` Cargo feature); -/// e.g.: -/// -/// ``` -/// # use zerocopy_derive::{FromBytes, FromZeroes}; -/// #[derive(FromZeroes, FromBytes)] -/// struct MyStruct { -/// # /* -/// ... -/// # */ -/// } -/// -/// #[derive(FromZeroes, FromBytes)] -/// #[repr(u8)] -/// enum MyEnum { -/// # V00, V01, V02, V03, V04, V05, V06, V07, V08, V09, V0A, V0B, V0C, V0D, V0E, -/// # V0F, V10, V11, V12, V13, V14, V15, V16, V17, V18, V19, V1A, V1B, V1C, V1D, -/// # V1E, V1F, V20, V21, V22, V23, V24, V25, V26, V27, V28, V29, V2A, V2B, V2C, -/// # V2D, V2E, V2F, V30, V31, V32, V33, V34, V35, V36, V37, V38, V39, V3A, V3B, -/// # V3C, V3D, V3E, V3F, V40, V41, V42, V43, V44, V45, V46, V47, V48, V49, V4A, -/// # V4B, V4C, V4D, V4E, V4F, V50, V51, V52, V53, V54, V55, V56, V57, V58, V59, -/// # V5A, V5B, V5C, V5D, V5E, V5F, V60, V61, V62, V63, V64, V65, V66, V67, V68, -/// # V69, V6A, V6B, V6C, V6D, V6E, V6F, V70, V71, V72, V73, V74, V75, V76, V77, -/// # V78, V79, V7A, V7B, V7C, V7D, V7E, V7F, V80, V81, V82, V83, V84, V85, V86, -/// # V87, V88, V89, V8A, V8B, V8C, V8D, V8E, V8F, V90, V91, V92, V93, V94, V95, -/// # V96, V97, V98, V99, V9A, V9B, V9C, V9D, V9E, V9F, VA0, VA1, VA2, VA3, VA4, -/// # VA5, VA6, VA7, VA8, VA9, VAA, VAB, VAC, VAD, VAE, VAF, VB0, VB1, VB2, VB3, -/// # VB4, VB5, VB6, VB7, VB8, VB9, VBA, VBB, VBC, VBD, VBE, VBF, VC0, VC1, VC2, -/// # VC3, VC4, VC5, VC6, VC7, VC8, VC9, VCA, VCB, VCC, VCD, VCE, VCF, VD0, VD1, -/// # VD2, VD3, VD4, VD5, VD6, VD7, VD8, VD9, VDA, VDB, VDC, VDD, VDE, VDF, VE0, -/// # VE1, VE2, VE3, VE4, VE5, VE6, VE7, VE8, VE9, VEA, VEB, VEC, VED, VEE, VEF, -/// # VF0, VF1, VF2, VF3, VF4, VF5, VF6, VF7, VF8, VF9, VFA, VFB, VFC, VFD, VFE, -/// # VFF, -/// # /* -/// ... -/// # */ -/// } -/// -/// #[derive(FromZeroes, FromBytes)] -/// union MyUnion { -/// # variant: u8, -/// # /* -/// ... -/// # */ -/// } -/// ``` -/// -/// This derive performs a sophisticated, compile-time safety analysis to -/// determine whether a type is `FromBytes`. -/// -/// # Safety -/// -/// *This section describes what is required in order for `T: FromBytes`, and -/// what unsafe code may assume of such types. If you don't plan on implementing -/// `FromBytes` manually, and you don't plan on writing unsafe code that -/// operates on `FromBytes` types, then you don't need to read this section.* -/// -/// If `T: FromBytes`, then unsafe code may assume that: -/// - It is sound to treat any initialized sequence of bytes of length -/// `size_of::<T>()` as a `T`. -/// - Given `b: &[u8]` where `b.len() == size_of::<T>()`, `b` is aligned to -/// `align_of::<T>()` it is sound to construct a `t: &T` at the same address -/// as `b`, and it is sound for both `b` and `t` to be live at the same time. -/// -/// If a type is marked as `FromBytes` which violates this contract, it may -/// cause undefined behavior. -/// -/// `#[derive(FromBytes)]` only permits [types which satisfy these -/// requirements][derive-analysis]. -/// -#[cfg_attr( - feature = "derive", - doc = "[derive]: zerocopy_derive::FromBytes", - doc = "[derive-analysis]: zerocopy_derive::FromBytes#analysis" -)] -#[cfg_attr( - not(feature = "derive"), - doc = concat!("[derive]: https://docs.rs/zerocopy/", env!("CARGO_PKG_VERSION"), "/zerocopy/derive.FromBytes.html"), - doc = concat!("[derive-analysis]: https://docs.rs/zerocopy/", env!("CARGO_PKG_VERSION"), "/zerocopy/derive.FromBytes.html#analysis"), -)] -pub unsafe trait FromBytes: FromZeroes { - // The `Self: Sized` bound makes it so that `FromBytes` is still object - // safe. - #[doc(hidden)] - fn only_derive_is_allowed_to_implement_this_trait() - where - Self: Sized; - - /// Interprets the given `bytes` as a `&Self` without copying. - /// - /// If `bytes.len() != size_of::<Self>()` or `bytes` is not aligned to - /// `align_of::<Self>()`, this returns `None`. - /// - /// # Examples - /// - /// ``` - /// use zerocopy::FromBytes; - /// # use zerocopy_derive::*; - /// - /// #[derive(FromZeroes, FromBytes)] - /// #[repr(C)] - /// struct PacketHeader { - /// src_port: [u8; 2], - /// dst_port: [u8; 2], - /// length: [u8; 2], - /// checksum: [u8; 2], - /// } - /// - /// // These bytes encode a `PacketHeader`. - /// let bytes = [0, 1, 2, 3, 4, 5, 6, 7].as_slice(); - /// - /// let header = PacketHeader::ref_from(bytes).unwrap(); - /// - /// assert_eq!(header.src_port, [0, 1]); - /// assert_eq!(header.dst_port, [2, 3]); - /// assert_eq!(header.length, [4, 5]); - /// assert_eq!(header.checksum, [6, 7]); - /// ``` - #[inline] - fn ref_from(bytes: &[u8]) -> Option<&Self> - where - Self: Sized, - { - Ref::<&[u8], Self>::new(bytes).map(Ref::into_ref) - } - - /// Interprets the prefix of the given `bytes` as a `&Self` without copying. - /// - /// `ref_from_prefix` returns a reference to the first `size_of::<Self>()` - /// bytes of `bytes`. If `bytes.len() < size_of::<Self>()` or `bytes` is not - /// aligned to `align_of::<Self>()`, this returns `None`. - /// - /// To also access the prefix bytes, use [`Ref::new_from_prefix`]. Then, use - /// [`Ref::into_ref`] to get a `&Self` with the same lifetime. - /// - /// # Examples - /// - /// ``` - /// use zerocopy::FromBytes; - /// # use zerocopy_derive::*; - /// - /// #[derive(FromZeroes, FromBytes)] - /// #[repr(C)] - /// struct PacketHeader { - /// src_port: [u8; 2], - /// dst_port: [u8; 2], - /// length: [u8; 2], - /// checksum: [u8; 2], - /// } - /// - /// // These are more bytes than are needed to encode a `PacketHeader`. - /// let bytes = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].as_slice(); - /// - /// let header = PacketHeader::ref_from_prefix(bytes).unwrap(); - /// - /// assert_eq!(header.src_port, [0, 1]); - /// assert_eq!(header.dst_port, [2, 3]); - /// assert_eq!(header.length, [4, 5]); - /// assert_eq!(header.checksum, [6, 7]); - /// ``` - #[inline] - fn ref_from_prefix(bytes: &[u8]) -> Option<&Self> - where - Self: Sized, - { - Ref::<&[u8], Self>::new_from_prefix(bytes).map(|(r, _)| r.into_ref()) - } - - /// Interprets the suffix of the given `bytes` as a `&Self` without copying. - /// - /// `ref_from_suffix` returns a reference to the last `size_of::<Self>()` - /// bytes of `bytes`. If `bytes.len() < size_of::<Self>()` or the suffix of - /// `bytes` is not aligned to `align_of::<Self>()`, this returns `None`. - /// - /// To also access the suffix bytes, use [`Ref::new_from_suffix`]. Then, use - /// [`Ref::into_ref`] to get a `&Self` with the same lifetime. - /// - /// # Examples - /// - /// ``` - /// use zerocopy::FromBytes; - /// # use zerocopy_derive::*; - /// - /// #[derive(FromZeroes, FromBytes)] - /// #[repr(C)] - /// struct PacketTrailer { - /// frame_check_sequence: [u8; 4], - /// } - /// - /// // These are more bytes than are needed to encode a `PacketTrailer`. - /// let bytes = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].as_slice(); - /// - /// let trailer = PacketTrailer::ref_from_suffix(bytes).unwrap(); - /// - /// assert_eq!(trailer.frame_check_sequence, [6, 7, 8, 9]); - /// ``` - #[inline] - fn ref_from_suffix(bytes: &[u8]) -> Option<&Self> - where - Self: Sized, - { - Ref::<&[u8], Self>::new_from_suffix(bytes).map(|(_, r)| r.into_ref()) - } - - /// Interprets the given `bytes` as a `&mut Self` without copying. - /// - /// If `bytes.len() != size_of::<Self>()` or `bytes` is not aligned to - /// `align_of::<Self>()`, this returns `None`. - /// - /// # Examples - /// - /// ``` - /// use zerocopy::FromBytes; - /// # use zerocopy_derive::*; - /// - /// #[derive(AsBytes, FromZeroes, FromBytes)] - /// #[repr(C)] - /// struct PacketHeader { - /// src_port: [u8; 2], - /// dst_port: [u8; 2], - /// length: [u8; 2], - /// checksum: [u8; 2], - /// } - /// - /// // These bytes encode a `PacketHeader`. - /// let bytes = &mut [0, 1, 2, 3, 4, 5, 6, 7][..]; - /// - /// let header = PacketHeader::mut_from(bytes).unwrap(); - /// - /// assert_eq!(header.src_port, [0, 1]); - /// assert_eq!(header.dst_port, [2, 3]); - /// assert_eq!(header.length, [4, 5]); - /// assert_eq!(header.checksum, [6, 7]); - /// - /// header.checksum = [0, 0]; - /// - /// assert_eq!(bytes, [0, 1, 2, 3, 4, 5, 0, 0]); - /// ``` - #[inline] - fn mut_from(bytes: &mut [u8]) -> Option<&mut Self> - where - Self: Sized + AsBytes, - { - Ref::<&mut [u8], Self>::new(bytes).map(Ref::into_mut) - } - - /// Interprets the prefix of the given `bytes` as a `&mut Self` without - /// copying. - /// - /// `mut_from_prefix` returns a reference to the first `size_of::<Self>()` - /// bytes of `bytes`. If `bytes.len() < size_of::<Self>()` or `bytes` is not - /// aligned to `align_of::<Self>()`, this returns `None`. - /// - /// To also access the prefix bytes, use [`Ref::new_from_prefix`]. Then, use - /// [`Ref::into_mut`] to get a `&mut Self` with the same lifetime. - /// - /// # Examples - /// - /// ``` - /// use zerocopy::FromBytes; - /// # use zerocopy_derive::*; - /// - /// #[derive(AsBytes, FromZeroes, FromBytes)] - /// #[repr(C)] - /// struct PacketHeader { - /// src_port: [u8; 2], - /// dst_port: [u8; 2], - /// length: [u8; 2], - /// checksum: [u8; 2], - /// } - /// - /// // These are more bytes than are needed to encode a `PacketHeader`. - /// let bytes = &mut [0, 1, 2, 3, 4, 5, 6, 7, 8, 9][..]; - /// - /// let header = PacketHeader::mut_from_prefix(bytes).unwrap(); - /// - /// assert_eq!(header.src_port, [0, 1]); - /// assert_eq!(header.dst_port, [2, 3]); - /// assert_eq!(header.length, [4, 5]); - /// assert_eq!(header.checksum, [6, 7]); - /// - /// header.checksum = [0, 0]; - /// - /// assert_eq!(bytes, [0, 1, 2, 3, 4, 5, 0, 0, 8, 9]); - /// ``` - #[inline] - fn mut_from_prefix(bytes: &mut [u8]) -> Option<&mut Self> - where - Self: Sized + AsBytes, - { - Ref::<&mut [u8], Self>::new_from_prefix(bytes).map(|(r, _)| r.into_mut()) - } - - /// Interprets the suffix of the given `bytes` as a `&mut Self` without copying. - /// - /// `mut_from_suffix` returns a reference to the last `size_of::<Self>()` - /// bytes of `bytes`. If `bytes.len() < size_of::<Self>()` or the suffix of - /// `bytes` is not aligned to `align_of::<Self>()`, this returns `None`. - /// - /// To also access the suffix bytes, use [`Ref::new_from_suffix`]. Then, - /// use [`Ref::into_mut`] to get a `&mut Self` with the same lifetime. - /// - /// # Examples - /// - /// ``` - /// use zerocopy::FromBytes; - /// # use zerocopy_derive::*; - /// - /// #[derive(AsBytes, FromZeroes, FromBytes)] - /// #[repr(C)] - /// struct PacketTrailer { - /// frame_check_sequence: [u8; 4], - /// } - /// - /// // These are more bytes than are needed to encode a `PacketTrailer`. - /// let bytes = &mut [0, 1, 2, 3, 4, 5, 6, 7, 8, 9][..]; - /// - /// let trailer = PacketTrailer::mut_from_suffix(bytes).unwrap(); - /// - /// assert_eq!(trailer.frame_check_sequence, [6, 7, 8, 9]); - /// - /// trailer.frame_check_sequence = [0, 0, 0, 0]; - /// - /// assert_eq!(bytes, [0, 1, 2, 3, 4, 5, 0, 0, 0, 0]); - /// ``` - #[inline] - fn mut_from_suffix(bytes: &mut [u8]) -> Option<&mut Self> - where - Self: Sized + AsBytes, - { - Ref::<&mut [u8], Self>::new_from_suffix(bytes).map(|(_, r)| r.into_mut()) - } - - /// Interprets the given `bytes` as a `&[Self]` without copying. - /// - /// If `bytes.len() % size_of::<Self>() != 0` or `bytes` is not aligned to - /// `align_of::<Self>()`, this returns `None`. - /// - /// If you need to convert a specific number of slice elements, see - /// [`slice_from_prefix`](FromBytes::slice_from_prefix) or - /// [`slice_from_suffix`](FromBytes::slice_from_suffix). - /// - /// # Panics - /// - /// If `Self` is a zero-sized type. - /// - /// # Examples - /// - /// ``` - /// use zerocopy::FromBytes; - /// # use zerocopy_derive::*; - /// - /// # #[derive(Debug, PartialEq, Eq)] - /// #[derive(FromZeroes, FromBytes)] - /// #[repr(C)] - /// struct Pixel { - /// r: u8, - /// g: u8, - /// b: u8, - /// a: u8, - /// } - /// - /// // These bytes encode two `Pixel`s. - /// let bytes = [0, 1, 2, 3, 4, 5, 6, 7].as_slice(); - /// - /// let pixels = Pixel::slice_from(bytes).unwrap(); - /// - /// assert_eq!(pixels, &[ - /// Pixel { r: 0, g: 1, b: 2, a: 3 }, - /// Pixel { r: 4, g: 5, b: 6, a: 7 }, - /// ]); - /// ``` - #[inline] - fn slice_from(bytes: &[u8]) -> Option<&[Self]> - where - Self: Sized, - { - Ref::<_, [Self]>::new_slice(bytes).map(|r| r.into_slice()) - } - - /// Interprets the prefix of the given `bytes` as a `&[Self]` with length - /// equal to `count` without copying. - /// - /// This method verifies that `bytes.len() >= size_of::<T>() * count` - /// and that `bytes` is aligned to `align_of::<T>()`. It consumes the - /// first `size_of::<T>() * count` bytes from `bytes` to construct a - /// `&[Self]`, and returns the remaining bytes to the caller. It also - /// ensures that `sizeof::<T>() * count` does not overflow a `usize`. - /// If any of the length, alignment, or overflow checks fail, it returns - /// `None`. - /// - /// # Panics - /// - /// If `T` is a zero-sized type. - /// - /// # Examples - /// - /// ``` - /// use zerocopy::FromBytes; - /// # use zerocopy_derive::*; - /// - /// # #[derive(Debug, PartialEq, Eq)] - /// #[derive(FromZeroes, FromBytes)] - /// #[repr(C)] - /// struct Pixel { - /// r: u8, - /// g: u8, - /// b: u8, - /// a: u8, - /// } - /// - /// // These are more bytes than are needed to encode two `Pixel`s. - /// let bytes = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].as_slice(); - /// - /// let (pixels, rest) = Pixel::slice_from_prefix(bytes, 2).unwrap(); - /// - /// assert_eq!(pixels, &[ - /// Pixel { r: 0, g: 1, b: 2, a: 3 }, - /// Pixel { r: 4, g: 5, b: 6, a: 7 }, - /// ]); - /// - /// assert_eq!(rest, &[8, 9]); - /// ``` - #[inline] - fn slice_from_prefix(bytes: &[u8], count: usize) -> Option<(&[Self], &[u8])> - where - Self: Sized, - { - Ref::<_, [Self]>::new_slice_from_prefix(bytes, count).map(|(r, b)| (r.into_slice(), b)) - } - - /// Interprets the suffix of the given `bytes` as a `&[Self]` with length - /// equal to `count` without copying. - /// - /// This method verifies that `bytes.len() >= size_of::<T>() * count` - /// and that `bytes` is aligned to `align_of::<T>()`. It consumes the - /// last `size_of::<T>() * count` bytes from `bytes` to construct a - /// `&[Self]`, and returns the preceding bytes to the caller. It also - /// ensures that `sizeof::<T>() * count` does not overflow a `usize`. - /// If any of the length, alignment, or overflow checks fail, it returns - /// `None`. - /// - /// # Panics - /// - /// If `T` is a zero-sized type. - /// - /// # Examples - /// - /// ``` - /// use zerocopy::FromBytes; - /// # use zerocopy_derive::*; - /// - /// # #[derive(Debug, PartialEq, Eq)] - /// #[derive(FromZeroes, FromBytes)] - /// #[repr(C)] - /// struct Pixel { - /// r: u8, - /// g: u8, - /// b: u8, - /// a: u8, - /// } - /// - /// // These are more bytes than are needed to encode two `Pixel`s. - /// let bytes = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].as_slice(); - /// - /// let (rest, pixels) = Pixel::slice_from_suffix(bytes, 2).unwrap(); - /// - /// assert_eq!(rest, &[0, 1]); - /// - /// assert_eq!(pixels, &[ - /// Pixel { r: 2, g: 3, b: 4, a: 5 }, - /// Pixel { r: 6, g: 7, b: 8, a: 9 }, - /// ]); - /// ``` - #[inline] - fn slice_from_suffix(bytes: &[u8], count: usize) -> Option<(&[u8], &[Self])> - where - Self: Sized, - { - Ref::<_, [Self]>::new_slice_from_suffix(bytes, count).map(|(b, r)| (b, r.into_slice())) - } - - /// Interprets the given `bytes` as a `&mut [Self]` without copying. - /// - /// If `bytes.len() % size_of::<T>() != 0` or `bytes` is not aligned to - /// `align_of::<T>()`, this returns `None`. - /// - /// If you need to convert a specific number of slice elements, see - /// [`mut_slice_from_prefix`](FromBytes::mut_slice_from_prefix) or - /// [`mut_slice_from_suffix`](FromBytes::mut_slice_from_suffix). - /// - /// # Panics - /// - /// If `T` is a zero-sized type. - /// - /// # Examples - /// - /// ``` - /// use zerocopy::FromBytes; - /// # use zerocopy_derive::*; - /// - /// # #[derive(Debug, PartialEq, Eq)] - /// #[derive(AsBytes, FromZeroes, FromBytes)] - /// #[repr(C)] - /// struct Pixel { - /// r: u8, - /// g: u8, - /// b: u8, - /// a: u8, - /// } - /// - /// // These bytes encode two `Pixel`s. - /// let bytes = &mut [0, 1, 2, 3, 4, 5, 6, 7][..]; - /// - /// let pixels = Pixel::mut_slice_from(bytes).unwrap(); - /// - /// assert_eq!(pixels, &[ - /// Pixel { r: 0, g: 1, b: 2, a: 3 }, - /// Pixel { r: 4, g: 5, b: 6, a: 7 }, - /// ]); - /// - /// pixels[1] = Pixel { r: 0, g: 0, b: 0, a: 0 }; - /// - /// assert_eq!(bytes, [0, 1, 2, 3, 0, 0, 0, 0]); - /// ``` - #[inline] - fn mut_slice_from(bytes: &mut [u8]) -> Option<&mut [Self]> - where - Self: Sized + AsBytes, - { - Ref::<_, [Self]>::new_slice(bytes).map(|r| r.into_mut_slice()) - } - - /// Interprets the prefix of the given `bytes` as a `&mut [Self]` with length - /// equal to `count` without copying. - /// - /// This method verifies that `bytes.len() >= size_of::<T>() * count` - /// and that `bytes` is aligned to `align_of::<T>()`. It consumes the - /// first `size_of::<T>() * count` bytes from `bytes` to construct a - /// `&[Self]`, and returns the remaining bytes to the caller. It also - /// ensures that `sizeof::<T>() * count` does not overflow a `usize`. - /// If any of the length, alignment, or overflow checks fail, it returns - /// `None`. - /// - /// # Panics - /// - /// If `T` is a zero-sized type. - /// - /// # Examples - /// - /// ``` - /// use zerocopy::FromBytes; - /// # use zerocopy_derive::*; - /// - /// # #[derive(Debug, PartialEq, Eq)] - /// #[derive(AsBytes, FromZeroes, FromBytes)] - /// #[repr(C)] - /// struct Pixel { - /// r: u8, - /// g: u8, - /// b: u8, - /// a: u8, - /// } - /// - /// // These are more bytes than are needed to encode two `Pixel`s. - /// let bytes = &mut [0, 1, 2, 3, 4, 5, 6, 7, 8, 9][..]; - /// - /// let (pixels, rest) = Pixel::mut_slice_from_prefix(bytes, 2).unwrap(); - /// - /// assert_eq!(pixels, &[ - /// Pixel { r: 0, g: 1, b: 2, a: 3 }, - /// Pixel { r: 4, g: 5, b: 6, a: 7 }, - /// ]); - /// - /// assert_eq!(rest, &[8, 9]); - /// - /// pixels[1] = Pixel { r: 0, g: 0, b: 0, a: 0 }; - /// - /// assert_eq!(bytes, [0, 1, 2, 3, 0, 0, 0, 0, 8, 9]); - /// ``` - #[inline] - fn mut_slice_from_prefix(bytes: &mut [u8], count: usize) -> Option<(&mut [Self], &mut [u8])> - where - Self: Sized + AsBytes, - { - Ref::<_, [Self]>::new_slice_from_prefix(bytes, count).map(|(r, b)| (r.into_mut_slice(), b)) - } - - /// Interprets the suffix of the given `bytes` as a `&mut [Self]` with length - /// equal to `count` without copying. - /// - /// This method verifies that `bytes.len() >= size_of::<T>() * count` - /// and that `bytes` is aligned to `align_of::<T>()`. It consumes the - /// last `size_of::<T>() * count` bytes from `bytes` to construct a - /// `&[Self]`, and returns the preceding bytes to the caller. It also - /// ensures that `sizeof::<T>() * count` does not overflow a `usize`. - /// If any of the length, alignment, or overflow checks fail, it returns - /// `None`. - /// - /// # Panics - /// - /// If `T` is a zero-sized type. - /// - /// # Examples - /// - /// ``` - /// use zerocopy::FromBytes; - /// # use zerocopy_derive::*; - /// - /// # #[derive(Debug, PartialEq, Eq)] - /// #[derive(AsBytes, FromZeroes, FromBytes)] - /// #[repr(C)] - /// struct Pixel { - /// r: u8, - /// g: u8, - /// b: u8, - /// a: u8, - /// } - /// - /// // These are more bytes than are needed to encode two `Pixel`s. - /// let bytes = &mut [0, 1, 2, 3, 4, 5, 6, 7, 8, 9][..]; - /// - /// let (rest, pixels) = Pixel::mut_slice_from_suffix(bytes, 2).unwrap(); - /// - /// assert_eq!(rest, &[0, 1]); - /// - /// assert_eq!(pixels, &[ - /// Pixel { r: 2, g: 3, b: 4, a: 5 }, - /// Pixel { r: 6, g: 7, b: 8, a: 9 }, - /// ]); - /// - /// pixels[1] = Pixel { r: 0, g: 0, b: 0, a: 0 }; - /// - /// assert_eq!(bytes, [0, 1, 2, 3, 4, 5, 0, 0, 0, 0]); - /// ``` - #[inline] - fn mut_slice_from_suffix(bytes: &mut [u8], count: usize) -> Option<(&mut [u8], &mut [Self])> - where - Self: Sized + AsBytes, - { - Ref::<_, [Self]>::new_slice_from_suffix(bytes, count).map(|(b, r)| (b, r.into_mut_slice())) - } - - /// Reads a copy of `Self` from `bytes`. - /// - /// If `bytes.len() != size_of::<Self>()`, `read_from` returns `None`. - /// - /// # Examples - /// - /// ``` - /// use zerocopy::FromBytes; - /// # use zerocopy_derive::*; - /// - /// #[derive(FromZeroes, FromBytes)] - /// #[repr(C)] - /// struct PacketHeader { - /// src_port: [u8; 2], - /// dst_port: [u8; 2], - /// length: [u8; 2], - /// checksum: [u8; 2], - /// } - /// - /// // These bytes encode a `PacketHeader`. - /// let bytes = [0, 1, 2, 3, 4, 5, 6, 7].as_slice(); - /// - /// let header = PacketHeader::read_from(bytes).unwrap(); - /// - /// assert_eq!(header.src_port, [0, 1]); - /// assert_eq!(header.dst_port, [2, 3]); - /// assert_eq!(header.length, [4, 5]); - /// assert_eq!(header.checksum, [6, 7]); - /// ``` - #[inline] - fn read_from(bytes: &[u8]) -> Option<Self> - where - Self: Sized, - { - Ref::<_, Unalign<Self>>::new_unaligned(bytes).map(|r| r.read().into_inner()) - } - - /// Reads a copy of `Self` from the prefix of `bytes`. - /// - /// `read_from_prefix` reads a `Self` from the first `size_of::<Self>()` - /// bytes of `bytes`. If `bytes.len() < size_of::<Self>()`, it returns - /// `None`. - /// - /// # Examples - /// - /// ``` - /// use zerocopy::FromBytes; - /// # use zerocopy_derive::*; - /// - /// #[derive(FromZeroes, FromBytes)] - /// #[repr(C)] - /// struct PacketHeader { - /// src_port: [u8; 2], - /// dst_port: [u8; 2], - /// length: [u8; 2], - /// checksum: [u8; 2], - /// } - /// - /// // These are more bytes than are needed to encode a `PacketHeader`. - /// let bytes = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].as_slice(); - /// - /// let header = PacketHeader::read_from_prefix(bytes).unwrap(); - /// - /// assert_eq!(header.src_port, [0, 1]); - /// assert_eq!(header.dst_port, [2, 3]); - /// assert_eq!(header.length, [4, 5]); - /// assert_eq!(header.checksum, [6, 7]); - /// ``` - #[inline] - fn read_from_prefix(bytes: &[u8]) -> Option<Self> - where - Self: Sized, - { - Ref::<_, Unalign<Self>>::new_unaligned_from_prefix(bytes) - .map(|(r, _)| r.read().into_inner()) - } - - /// Reads a copy of `Self` from the suffix of `bytes`. - /// - /// `read_from_suffix` reads a `Self` from the last `size_of::<Self>()` - /// bytes of `bytes`. If `bytes.len() < size_of::<Self>()`, it returns - /// `None`. - /// - /// # Examples - /// - /// ``` - /// use zerocopy::FromBytes; - /// # use zerocopy_derive::*; - /// - /// #[derive(FromZeroes, FromBytes)] - /// #[repr(C)] - /// struct PacketTrailer { - /// frame_check_sequence: [u8; 4], - /// } - /// - /// // These are more bytes than are needed to encode a `PacketTrailer`. - /// let bytes = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].as_slice(); - /// - /// let trailer = PacketTrailer::read_from_suffix(bytes).unwrap(); - /// - /// assert_eq!(trailer.frame_check_sequence, [6, 7, 8, 9]); - /// ``` - #[inline] - fn read_from_suffix(bytes: &[u8]) -> Option<Self> - where - Self: Sized, - { - Ref::<_, Unalign<Self>>::new_unaligned_from_suffix(bytes) - .map(|(_, r)| r.read().into_inner()) - } -} - -/// Analyzes whether a type is [`AsBytes`]. -/// -/// This derive analyzes, at compile time, whether the annotated type satisfies -/// the [safety conditions] of `AsBytes` and implements `AsBytes` if it is -/// sound to do so. This derive can be applied to structs, enums, and unions; -/// e.g.: -/// -/// ``` -/// # use zerocopy_derive::{AsBytes}; -/// #[derive(AsBytes)] -/// #[repr(C)] -/// struct MyStruct { -/// # /* -/// ... -/// # */ -/// } -/// -/// #[derive(AsBytes)] -/// #[repr(u8)] -/// enum MyEnum { -/// # Variant, -/// # /* -/// ... -/// # */ -/// } -/// -/// #[derive(AsBytes)] -/// #[repr(C)] -/// union MyUnion { -/// # variant: u8, -/// # /* -/// ... -/// # */ -/// } -/// ``` -/// -/// [safety conditions]: trait@AsBytes#safety -/// -/// # Error Messages -/// -/// Due to the way that the custom derive for `AsBytes` is implemented, you may -/// get an error like this: -/// -/// ```text -/// error[E0277]: the trait bound `HasPadding<Foo, true>: ShouldBe<false>` is not satisfied -/// --> lib.rs:23:10 -/// | -/// 1 | #[derive(AsBytes)] -/// | ^^^^^^^ the trait `ShouldBe<false>` is not implemented for `HasPadding<Foo, true>` -/// | -/// = help: the trait `ShouldBe<VALUE>` is implemented for `HasPadding<T, VALUE>` -/// ``` -/// -/// This error indicates that the type being annotated has padding bytes, which -/// is illegal for `AsBytes` types. Consider reducing the alignment of some -/// fields by using types in the [`byteorder`] module, adding explicit struct -/// fields where those padding bytes would be, or using `#[repr(packed)]`. See -/// the Rust Reference's page on [type layout] for more information -/// about type layout and padding. -/// -/// [type layout]: https://doc.rust-lang.org/reference/type-layout.html -/// -/// # Analysis -/// -/// *This section describes, roughly, the analysis performed by this derive to -/// determine whether it is sound to implement `AsBytes` for a given type. -/// Unless you are modifying the implementation of this derive, or attempting to -/// manually implement `AsBytes` for a type yourself, you don't need to read -/// this section.* -/// -/// If a type has the following properties, then this derive can implement -/// `AsBytes` for that type: -/// -/// - If the type is a struct: -/// - It must have a defined representation (`repr(C)`, `repr(transparent)`, -/// or `repr(packed)`). -/// - All of its fields must be `AsBytes`. -/// - Its layout must have no padding. This is always true for -/// `repr(transparent)` and `repr(packed)`. For `repr(C)`, see the layout -/// algorithm described in the [Rust Reference]. -/// - If the type is an enum: -/// - It must be a C-like enum (meaning that all variants have no fields). -/// - It must have a defined representation (`repr`s `C`, `u8`, `u16`, `u32`, -/// `u64`, `usize`, `i8`, `i16`, `i32`, `i64`, or `isize`). -/// - The type must not contain any [`UnsafeCell`]s (this is required in order -/// for it to be sound to construct a `&[u8]` and a `&T` to the same region of -/// memory). The type may contain references or pointers to `UnsafeCell`s so -/// long as those values can themselves be initialized from zeroes (`AsBytes` -/// is not currently implemented for, e.g., `Option<&UnsafeCell<_>>`, but it -/// could be one day). -/// -/// [`UnsafeCell`]: core::cell::UnsafeCell -/// -/// This analysis is subject to change. Unsafe code may *only* rely on the -/// documented [safety conditions] of `FromBytes`, and must *not* rely on the -/// implementation details of this derive. -/// -/// [Rust Reference]: https://doc.rust-lang.org/reference/type-layout.html -#[cfg(any(feature = "derive", test))] -#[cfg_attr(doc_cfg, doc(cfg(feature = "derive")))] -pub use zerocopy_derive::AsBytes; - -/// Types that can be viewed as an immutable slice of initialized bytes. -/// -/// Any `AsBytes` type can be viewed as a slice of initialized bytes of the same -/// size. This is useful for efficiently serializing structured data as raw -/// bytes. -/// -/// # Implementation -/// -/// **Do not implement this trait yourself!** Instead, use -/// [`#[derive(AsBytes)]`][derive] (requires the `derive` Cargo feature); e.g.: -/// -/// ``` -/// # use zerocopy_derive::AsBytes; -/// #[derive(AsBytes)] -/// #[repr(C)] -/// struct MyStruct { -/// # /* -/// ... -/// # */ -/// } -/// -/// #[derive(AsBytes)] -/// #[repr(u8)] -/// enum MyEnum { -/// # Variant0, -/// # /* -/// ... -/// # */ -/// } -/// -/// #[derive(AsBytes)] -/// #[repr(C)] -/// union MyUnion { -/// # variant: u8, -/// # /* -/// ... -/// # */ -/// } -/// ``` -/// -/// This derive performs a sophisticated, compile-time safety analysis to -/// determine whether a type is `AsBytes`. See the [derive -/// documentation][derive] for guidance on how to interpret error messages -/// produced by the derive's analysis. -/// -/// # Safety -/// -/// *This section describes what is required in order for `T: AsBytes`, and -/// what unsafe code may assume of such types. If you don't plan on implementing -/// `AsBytes` manually, and you don't plan on writing unsafe code that -/// operates on `AsBytes` types, then you don't need to read this section.* -/// -/// If `T: AsBytes`, then unsafe code may assume that: -/// - It is sound to treat any `t: T` as an immutable `[u8]` of length -/// `size_of_val(t)`. -/// - Given `t: &T`, it is sound to construct a `b: &[u8]` where `b.len() == -/// size_of_val(t)` at the same address as `t`, and it is sound for both `b` -/// and `t` to be live at the same time. -/// -/// If a type is marked as `AsBytes` which violates this contract, it may cause -/// undefined behavior. -/// -/// `#[derive(AsBytes)]` only permits [types which satisfy these -/// requirements][derive-analysis]. -/// -#[cfg_attr( - feature = "derive", - doc = "[derive]: zerocopy_derive::AsBytes", - doc = "[derive-analysis]: zerocopy_derive::AsBytes#analysis" -)] -#[cfg_attr( - not(feature = "derive"), - doc = concat!("[derive]: https://docs.rs/zerocopy/", env!("CARGO_PKG_VERSION"), "/zerocopy/derive.AsBytes.html"), - doc = concat!("[derive-analysis]: https://docs.rs/zerocopy/", env!("CARGO_PKG_VERSION"), "/zerocopy/derive.AsBytes.html#analysis"), -)] -pub unsafe trait AsBytes { - // The `Self: Sized` bound makes it so that this function doesn't prevent - // `AsBytes` from being object safe. Note that other `AsBytes` methods - // prevent object safety, but those provide a benefit in exchange for object - // safety. If at some point we remove those methods, change their type - // signatures, or move them out of this trait so that `AsBytes` is object - // safe again, it's important that this function not prevent object safety. - #[doc(hidden)] - fn only_derive_is_allowed_to_implement_this_trait() - where - Self: Sized; - - /// Gets the bytes of this value. - /// - /// `as_bytes` provides access to the bytes of this value as an immutable - /// byte slice. - /// - /// # Examples - /// - /// ``` - /// use zerocopy::AsBytes; - /// # use zerocopy_derive::*; - /// - /// #[derive(AsBytes)] - /// #[repr(C)] - /// struct PacketHeader { - /// src_port: [u8; 2], - /// dst_port: [u8; 2], - /// length: [u8; 2], - /// checksum: [u8; 2], - /// } - /// - /// let header = PacketHeader { - /// src_port: [0, 1], - /// dst_port: [2, 3], - /// length: [4, 5], - /// checksum: [6, 7], - /// }; - /// - /// let bytes = header.as_bytes(); - /// - /// assert_eq!(bytes, [0, 1, 2, 3, 4, 5, 6, 7]); - /// ``` - #[inline(always)] - fn as_bytes(&self) -> &[u8] { - // Note that this method does not have a `Self: Sized` bound; - // `size_of_val` works for unsized values too. - let len = mem::size_of_val(self); - let slf: *const Self = self; - - // SAFETY: - // - `slf.cast::<u8>()` is valid for reads for `len * - // mem::size_of::<u8>()` many bytes because... - // - `slf` is the same pointer as `self`, and `self` is a reference - // which points to an object whose size is `len`. Thus... - // - The entire region of `len` bytes starting at `slf` is contained - // within a single allocation. - // - `slf` is non-null. - // - `slf` is trivially aligned to `align_of::<u8>() == 1`. - // - `Self: AsBytes` ensures that all of the bytes of `slf` are - // initialized. - // - Since `slf` is derived from `self`, and `self` is an immutable - // reference, the only other references to this memory region that - // could exist are other immutable references, and those don't allow - // mutation. `AsBytes` prohibits types which contain `UnsafeCell`s, - // which are the only types for which this rule wouldn't be sufficient. - // - The total size of the resulting slice is no larger than - // `isize::MAX` because no allocation produced by safe code can be - // larger than `isize::MAX`. - // - // TODO(#429): Add references to docs and quotes. - unsafe { slice::from_raw_parts(slf.cast::<u8>(), len) } - } - - /// Gets the bytes of this value mutably. - /// - /// `as_bytes_mut` provides access to the bytes of this value as a mutable - /// byte slice. - /// - /// # Examples - /// - /// ``` - /// use zerocopy::AsBytes; - /// # use zerocopy_derive::*; - /// - /// # #[derive(Eq, PartialEq, Debug)] - /// #[derive(AsBytes, FromZeroes, FromBytes)] - /// #[repr(C)] - /// struct PacketHeader { - /// src_port: [u8; 2], - /// dst_port: [u8; 2], - /// length: [u8; 2], - /// checksum: [u8; 2], - /// } - /// - /// let mut header = PacketHeader { - /// src_port: [0, 1], - /// dst_port: [2, 3], - /// length: [4, 5], - /// checksum: [6, 7], - /// }; - /// - /// let bytes = header.as_bytes_mut(); - /// - /// assert_eq!(bytes, [0, 1, 2, 3, 4, 5, 6, 7]); - /// - /// bytes.reverse(); - /// - /// assert_eq!(header, PacketHeader { - /// src_port: [7, 6], - /// dst_port: [5, 4], - /// length: [3, 2], - /// checksum: [1, 0], - /// }); - /// ``` - #[inline(always)] - fn as_bytes_mut(&mut self) -> &mut [u8] - where - Self: FromBytes, - { - // Note that this method does not have a `Self: Sized` bound; - // `size_of_val` works for unsized values too. - let len = mem::size_of_val(self); - let slf: *mut Self = self; - - // SAFETY: - // - `slf.cast::<u8>()` is valid for reads and writes for `len * - // mem::size_of::<u8>()` many bytes because... - // - `slf` is the same pointer as `self`, and `self` is a reference - // which points to an object whose size is `len`. Thus... - // - The entire region of `len` bytes starting at `slf` is contained - // within a single allocation. - // - `slf` is non-null. - // - `slf` is trivially aligned to `align_of::<u8>() == 1`. - // - `Self: AsBytes` ensures that all of the bytes of `slf` are - // initialized. - // - `Self: FromBytes` ensures that no write to this memory region - // could result in it containing an invalid `Self`. - // - Since `slf` is derived from `self`, and `self` is a mutable - // reference, no other references to this memory region can exist. - // - The total size of the resulting slice is no larger than - // `isize::MAX` because no allocation produced by safe code can be - // larger than `isize::MAX`. - // - // TODO(#429): Add references to docs and quotes. - unsafe { slice::from_raw_parts_mut(slf.cast::<u8>(), len) } - } - - /// Writes a copy of `self` to `bytes`. - /// - /// If `bytes.len() != size_of_val(self)`, `write_to` returns `None`. - /// - /// # Examples - /// - /// ``` - /// use zerocopy::AsBytes; - /// # use zerocopy_derive::*; - /// - /// #[derive(AsBytes)] - /// #[repr(C)] - /// struct PacketHeader { - /// src_port: [u8; 2], - /// dst_port: [u8; 2], - /// length: [u8; 2], - /// checksum: [u8; 2], - /// } - /// - /// let header = PacketHeader { - /// src_port: [0, 1], - /// dst_port: [2, 3], - /// length: [4, 5], - /// checksum: [6, 7], - /// }; - /// - /// let mut bytes = [0, 0, 0, 0, 0, 0, 0, 0]; - /// - /// header.write_to(&mut bytes[..]); - /// - /// assert_eq!(bytes, [0, 1, 2, 3, 4, 5, 6, 7]); - /// ``` - /// - /// If too many or too few target bytes are provided, `write_to` returns - /// `None` and leaves the target bytes unmodified: - /// - /// ``` - /// # use zerocopy::AsBytes; - /// # let header = u128::MAX; - /// let mut excessive_bytes = &mut [0u8; 128][..]; - /// - /// let write_result = header.write_to(excessive_bytes); - /// - /// assert!(write_result.is_none()); - /// assert_eq!(excessive_bytes, [0u8; 128]); - /// ``` - #[inline] - fn write_to(&self, bytes: &mut [u8]) -> Option<()> { - if bytes.len() != mem::size_of_val(self) { - return None; - } - - bytes.copy_from_slice(self.as_bytes()); - Some(()) - } - - /// Writes a copy of `self` to the prefix of `bytes`. - /// - /// `write_to_prefix` writes `self` to the first `size_of_val(self)` bytes - /// of `bytes`. If `bytes.len() < size_of_val(self)`, it returns `None`. - /// - /// # Examples - /// - /// ``` - /// use zerocopy::AsBytes; - /// # use zerocopy_derive::*; - /// - /// #[derive(AsBytes)] - /// #[repr(C)] - /// struct PacketHeader { - /// src_port: [u8; 2], - /// dst_port: [u8; 2], - /// length: [u8; 2], - /// checksum: [u8; 2], - /// } - /// - /// let header = PacketHeader { - /// src_port: [0, 1], - /// dst_port: [2, 3], - /// length: [4, 5], - /// checksum: [6, 7], - /// }; - /// - /// let mut bytes = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; - /// - /// header.write_to_prefix(&mut bytes[..]); - /// - /// assert_eq!(bytes, [0, 1, 2, 3, 4, 5, 6, 7, 0, 0]); - /// ``` - /// - /// If insufficient target bytes are provided, `write_to_prefix` returns - /// `None` and leaves the target bytes unmodified: - /// - /// ``` - /// # use zerocopy::AsBytes; - /// # let header = u128::MAX; - /// let mut insufficent_bytes = &mut [0, 0][..]; - /// - /// let write_result = header.write_to_suffix(insufficent_bytes); - /// - /// assert!(write_result.is_none()); - /// assert_eq!(insufficent_bytes, [0, 0]); - /// ``` - #[inline] - fn write_to_prefix(&self, bytes: &mut [u8]) -> Option<()> { - let size = mem::size_of_val(self); - bytes.get_mut(..size)?.copy_from_slice(self.as_bytes()); - Some(()) - } - - /// Writes a copy of `self` to the suffix of `bytes`. - /// - /// `write_to_suffix` writes `self` to the last `size_of_val(self)` bytes of - /// `bytes`. If `bytes.len() < size_of_val(self)`, it returns `None`. - /// - /// # Examples - /// - /// ``` - /// use zerocopy::AsBytes; - /// # use zerocopy_derive::*; - /// - /// #[derive(AsBytes)] - /// #[repr(C)] - /// struct PacketHeader { - /// src_port: [u8; 2], - /// dst_port: [u8; 2], - /// length: [u8; 2], - /// checksum: [u8; 2], - /// } - /// - /// let header = PacketHeader { - /// src_port: [0, 1], - /// dst_port: [2, 3], - /// length: [4, 5], - /// checksum: [6, 7], - /// }; - /// - /// let mut bytes = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; - /// - /// header.write_to_suffix(&mut bytes[..]); - /// - /// assert_eq!(bytes, [0, 0, 0, 1, 2, 3, 4, 5, 6, 7]); - /// - /// let mut insufficent_bytes = &mut [0, 0][..]; - /// - /// let write_result = header.write_to_suffix(insufficent_bytes); - /// - /// assert!(write_result.is_none()); - /// assert_eq!(insufficent_bytes, [0, 0]); - /// ``` - /// - /// If insufficient target bytes are provided, `write_to_suffix` returns - /// `None` and leaves the target bytes unmodified: - /// - /// ``` - /// # use zerocopy::AsBytes; - /// # let header = u128::MAX; - /// let mut insufficent_bytes = &mut [0, 0][..]; - /// - /// let write_result = header.write_to_suffix(insufficent_bytes); - /// - /// assert!(write_result.is_none()); - /// assert_eq!(insufficent_bytes, [0, 0]); - /// ``` - #[inline] - fn write_to_suffix(&self, bytes: &mut [u8]) -> Option<()> { - let start = bytes.len().checked_sub(mem::size_of_val(self))?; - bytes - .get_mut(start..) - .expect("`start` should be in-bounds of `bytes`") - .copy_from_slice(self.as_bytes()); - Some(()) - } -} - -/// Types with no alignment requirement. -/// -/// WARNING: Do not implement this trait yourself! Instead, use -/// `#[derive(Unaligned)]` (requires the `derive` Cargo feature). -/// -/// If `T: Unaligned`, then `align_of::<T>() == 1`. -/// -/// # Safety -/// -/// *This section describes what is required in order for `T: Unaligned`, and -/// what unsafe code may assume of such types. `#[derive(Unaligned)]` only -/// permits types which satisfy these requirements. If you don't plan on -/// implementing `Unaligned` manually, and you don't plan on writing unsafe code -/// that operates on `Unaligned` types, then you don't need to read this -/// section.* -/// -/// If `T: Unaligned`, then unsafe code may assume that it is sound to produce a -/// reference to `T` at any memory location regardless of alignment. If a type -/// is marked as `Unaligned` which violates this contract, it may cause -/// undefined behavior. -pub unsafe trait Unaligned { - // The `Self: Sized` bound makes it so that `Unaligned` is still object - // safe. - #[doc(hidden)] - fn only_derive_is_allowed_to_implement_this_trait() - where - Self: Sized; -} - -safety_comment! { - /// SAFETY: - /// Per the reference [1], "the unit tuple (`()`) ... is guaranteed as a - /// zero-sized type to have a size of 0 and an alignment of 1." - /// - `TryFromBytes` (with no validator), `FromZeroes`, `FromBytes`: There - /// is only one possible sequence of 0 bytes, and `()` is inhabited. - /// - `AsBytes`: Since `()` has size 0, it contains no padding bytes. - /// - `Unaligned`: `()` has alignment 1. - /// - /// [1] https://doc.rust-lang.org/reference/type-layout.html#tuple-layout - unsafe_impl!((): TryFromBytes, FromZeroes, FromBytes, AsBytes, Unaligned); - assert_unaligned!(()); -} - -safety_comment! { - /// SAFETY: - /// - `TryFromBytes` (with no validator), `FromZeroes`, `FromBytes`: all bit - /// patterns are valid for numeric types [1] - /// - `AsBytes`: numeric types have no padding bytes [1] - /// - `Unaligned` (`u8` and `i8` only): The reference [2] specifies the size - /// of `u8` and `i8` as 1 byte. We also know that: - /// - Alignment is >= 1 [3] - /// - Size is an integer multiple of alignment [4] - /// - The only value >= 1 for which 1 is an integer multiple is 1 - /// Therefore, the only possible alignment for `u8` and `i8` is 1. - /// - /// [1] Per https://doc.rust-lang.org/beta/reference/types/numeric.html#bit-validity: - /// - /// For every numeric type, `T`, the bit validity of `T` is equivalent to - /// the bit validity of `[u8; size_of::<T>()]`. An uninitialized byte is - /// not a valid `u8`. - /// - /// TODO(https://github.com/rust-lang/reference/pull/1392): Once this text - /// is available on the Stable docs, cite those instead. - /// - /// [2] https://doc.rust-lang.org/reference/type-layout.html#primitive-data-layout - /// - /// [3] Per https://doc.rust-lang.org/reference/type-layout.html#size-and-alignment: - /// - /// Alignment is measured in bytes, and must be at least 1. - /// - /// [4] Per https://doc.rust-lang.org/reference/type-layout.html#size-and-alignment: - /// - /// The size of a value is always a multiple of its alignment. - /// - /// TODO(#278): Once we've updated the trait docs to refer to `u8`s rather - /// than bits or bytes, update this comment, especially the reference to - /// [1]. - unsafe_impl!(u8: TryFromBytes, FromZeroes, FromBytes, AsBytes, Unaligned); - unsafe_impl!(i8: TryFromBytes, FromZeroes, FromBytes, AsBytes, Unaligned); - assert_unaligned!(u8, i8); - unsafe_impl!(u16: TryFromBytes, FromZeroes, FromBytes, AsBytes); - unsafe_impl!(i16: TryFromBytes, FromZeroes, FromBytes, AsBytes); - unsafe_impl!(u32: TryFromBytes, FromZeroes, FromBytes, AsBytes); - unsafe_impl!(i32: TryFromBytes, FromZeroes, FromBytes, AsBytes); - unsafe_impl!(u64: TryFromBytes, FromZeroes, FromBytes, AsBytes); - unsafe_impl!(i64: TryFromBytes, FromZeroes, FromBytes, AsBytes); - unsafe_impl!(u128: TryFromBytes, FromZeroes, FromBytes, AsBytes); - unsafe_impl!(i128: TryFromBytes, FromZeroes, FromBytes, AsBytes); - unsafe_impl!(usize: TryFromBytes, FromZeroes, FromBytes, AsBytes); - unsafe_impl!(isize: TryFromBytes, FromZeroes, FromBytes, AsBytes); - unsafe_impl!(f32: TryFromBytes, FromZeroes, FromBytes, AsBytes); - unsafe_impl!(f64: TryFromBytes, FromZeroes, FromBytes, AsBytes); -} - -safety_comment! { - /// SAFETY: - /// - `FromZeroes`: Valid since "[t]he value false has the bit pattern - /// 0x00" [1]. - /// - `AsBytes`: Since "the boolean type has a size and alignment of 1 each" - /// and "The value false has the bit pattern 0x00 and the value true has - /// the bit pattern 0x01" [1]. Thus, the only byte of the bool is always - /// initialized. - /// - `Unaligned`: Per the reference [1], "[a]n object with the boolean type - /// has a size and alignment of 1 each." - /// - /// [1] https://doc.rust-lang.org/reference/types/boolean.html - unsafe_impl!(bool: FromZeroes, AsBytes, Unaligned); - assert_unaligned!(bool); - /// SAFETY: - /// - The safety requirements for `unsafe_impl!` with an `is_bit_valid` - /// closure: - /// - Given `t: *mut bool` and `let r = *mut u8`, `r` refers to an object - /// of the same size as that referred to by `t`. This is true because - /// `bool` and `u8` have the same size (1 byte) [1]. - /// - Since the closure takes a `&u8` argument, given a `Ptr<'a, bool>` - /// which satisfies the preconditions of - /// `TryFromBytes::<bool>::is_bit_valid`, it must be guaranteed that the - /// memory referenced by that `Ptr` always contains a valid `u8`. Since - /// `bool`'s single byte is always initialized, `is_bit_valid`'s - /// precondition requires that the same is true of its argument. Since - /// `u8`'s only bit validity invariant is that its single byte must be - /// initialized, this memory is guaranteed to contain a valid `u8`. - /// - The alignment of `bool` is equal to the alignment of `u8`. [1] [2] - /// - The impl must only return `true` for its argument if the original - /// `Ptr<bool>` refers to a valid `bool`. We only return true if the - /// `u8` value is 0 or 1, and both of these are valid values for `bool`. - /// [3] - /// - /// [1] Per https://doc.rust-lang.org/reference/type-layout.html#primitive-data-layout: - /// - /// The size of most primitives is given in this table. - /// - /// | Type | `size_of::<Type>() ` | - /// |-----------|----------------------| - /// | `bool` | 1 | - /// | `u8`/`i8` | 1 | - /// - /// [2] Per https://doc.rust-lang.org/reference/type-layout.html#size-and-alignment: - /// - /// The size of a value is always a multiple of its alignment. - /// - /// [3] Per https://doc.rust-lang.org/reference/types/boolean.html: - /// - /// The value false has the bit pattern 0x00 and the value true has the - /// bit pattern 0x01. - unsafe_impl!(bool: TryFromBytes; |byte: &u8| *byte < 2); -} -safety_comment! { - /// SAFETY: - /// - `FromZeroes`: Per reference [1], "[a] value of type char is a Unicode - /// scalar value (i.e. a code point that is not a surrogate), represented - /// as a 32-bit unsigned word in the 0x0000 to 0xD7FF or 0xE000 to - /// 0x10FFFF range" which contains 0x0000. - /// - `AsBytes`: `char` is per reference [1] "represented as a 32-bit - /// unsigned word" (`u32`) which is `AsBytes`. Note that unlike `u32`, not - /// all bit patterns are valid for `char`. - /// - /// [1] https://doc.rust-lang.org/reference/types/textual.html - unsafe_impl!(char: FromZeroes, AsBytes); - /// SAFETY: - /// - The safety requirements for `unsafe_impl!` with an `is_bit_valid` - /// closure: - /// - Given `t: *mut char` and `let r = *mut u32`, `r` refers to an object - /// of the same size as that referred to by `t`. This is true because - /// `char` and `u32` have the same size [1]. - /// - Since the closure takes a `&u32` argument, given a `Ptr<'a, char>` - /// which satisfies the preconditions of - /// `TryFromBytes::<char>::is_bit_valid`, it must be guaranteed that the - /// memory referenced by that `Ptr` always contains a valid `u32`. Since - /// `char`'s bytes are always initialized [2], `is_bit_valid`'s - /// precondition requires that the same is true of its argument. Since - /// `u32`'s only bit validity invariant is that its bytes must be - /// initialized, this memory is guaranteed to contain a valid `u32`. - /// - The alignment of `char` is equal to the alignment of `u32`. [1] - /// - The impl must only return `true` for its argument if the original - /// `Ptr<char>` refers to a valid `char`. `char::from_u32` guarantees - /// that it returns `None` if its input is not a valid `char`. [3] - /// - /// [1] Per https://doc.rust-lang.org/nightly/reference/types/textual.html#layout-and-bit-validity: - /// - /// `char` is guaranteed to have the same size and alignment as `u32` on - /// all platforms. - /// - /// [2] Per https://doc.rust-lang.org/core/primitive.char.html#method.from_u32: - /// - /// Every byte of a `char` is guaranteed to be initialized. - /// - /// [3] Per https://doc.rust-lang.org/core/primitive.char.html#method.from_u32: - /// - /// `from_u32()` will return `None` if the input is not a valid value for - /// a `char`. - unsafe_impl!(char: TryFromBytes; |candidate: &u32| char::from_u32(*candidate).is_some()); -} -safety_comment! { - /// SAFETY: - /// - `FromZeroes`, `AsBytes`, `Unaligned`: Per the reference [1], `str` - /// has the same layout as `[u8]`, and `[u8]` is `FromZeroes`, `AsBytes`, - /// and `Unaligned`. - /// - /// Note that we don't `assert_unaligned!(str)` because `assert_unaligned!` - /// uses `align_of`, which only works for `Sized` types. - /// - /// TODO(#429): Add quotes from documentation. - /// - /// [1] https://doc.rust-lang.org/reference/type-layout.html#str-layout - unsafe_impl!(str: FromZeroes, AsBytes, Unaligned); - /// SAFETY: - /// - The safety requirements for `unsafe_impl!` with an `is_bit_valid` - /// closure: - /// - Given `t: *mut str` and `let r = *mut [u8]`, `r` refers to an object - /// of the same size as that referred to by `t`. This is true because - /// `str` and `[u8]` have the same representation. [1] - /// - Since the closure takes a `&[u8]` argument, given a `Ptr<'a, str>` - /// which satisfies the preconditions of - /// `TryFromBytes::<str>::is_bit_valid`, it must be guaranteed that the - /// memory referenced by that `Ptr` always contains a valid `[u8]`. - /// Since `str`'s bytes are always initialized [1], `is_bit_valid`'s - /// precondition requires that the same is true of its argument. Since - /// `[u8]`'s only bit validity invariant is that its bytes must be - /// initialized, this memory is guaranteed to contain a valid `[u8]`. - /// - The alignment of `str` is equal to the alignment of `[u8]`. [1] - /// - The impl must only return `true` for its argument if the original - /// `Ptr<str>` refers to a valid `str`. `str::from_utf8` guarantees that - /// it returns `Err` if its input is not a valid `str`. [2] - /// - /// [1] Per https://doc.rust-lang.org/reference/types/textual.html: - /// - /// A value of type `str` is represented the same was as `[u8]`. - /// - /// [2] Per https://doc.rust-lang.org/core/str/fn.from_utf8.html#errors: - /// - /// Returns `Err` if the slice is not UTF-8. - unsafe_impl!(str: TryFromBytes; |candidate: &[u8]| core::str::from_utf8(candidate).is_ok()); -} - -safety_comment! { - // `NonZeroXxx` is `AsBytes`, but not `FromZeroes` or `FromBytes`. - // - /// SAFETY: - /// - `AsBytes`: `NonZeroXxx` has the same layout as its associated - /// primitive. Since it is the same size, this guarantees it has no - /// padding - integers have no padding, and there's no room for padding - /// if it can represent all of the same values except 0. - /// - `Unaligned`: `NonZeroU8` and `NonZeroI8` document that - /// `Option<NonZeroU8>` and `Option<NonZeroI8>` both have size 1. [1] [2] - /// This is worded in a way that makes it unclear whether it's meant as a - /// guarantee, but given the purpose of those types, it's virtually - /// unthinkable that that would ever change. `Option` cannot be smaller - /// than its contained type, which implies that, and `NonZeroX8` are of - /// size 1 or 0. `NonZeroX8` can represent multiple states, so they cannot - /// be 0 bytes, which means that they must be 1 byte. The only valid - /// alignment for a 1-byte type is 1. - /// - /// TODO(#429): Add quotes from documentation. - /// - /// [1] https://doc.rust-lang.org/stable/std/num/struct.NonZeroU8.html - /// [2] https://doc.rust-lang.org/stable/std/num/struct.NonZeroI8.html - /// TODO(https://github.com/rust-lang/rust/pull/104082): Cite documentation - /// that layout is the same as primitive layout. - unsafe_impl!(NonZeroU8: AsBytes, Unaligned); - unsafe_impl!(NonZeroI8: AsBytes, Unaligned); - assert_unaligned!(NonZeroU8, NonZeroI8); - unsafe_impl!(NonZeroU16: AsBytes); - unsafe_impl!(NonZeroI16: AsBytes); - unsafe_impl!(NonZeroU32: AsBytes); - unsafe_impl!(NonZeroI32: AsBytes); - unsafe_impl!(NonZeroU64: AsBytes); - unsafe_impl!(NonZeroI64: AsBytes); - unsafe_impl!(NonZeroU128: AsBytes); - unsafe_impl!(NonZeroI128: AsBytes); - unsafe_impl!(NonZeroUsize: AsBytes); - unsafe_impl!(NonZeroIsize: AsBytes); - /// SAFETY: - /// - The safety requirements for `unsafe_impl!` with an `is_bit_valid` - /// closure: - /// - Given `t: *mut NonZeroXxx` and `let r = *mut xxx`, `r` refers to an - /// object of the same size as that referred to by `t`. This is true - /// because `NonZeroXxx` and `xxx` have the same size. [1] - /// - Since the closure takes a `&xxx` argument, given a `Ptr<'a, - /// NonZeroXxx>` which satisfies the preconditions of - /// `TryFromBytes::<NonZeroXxx>::is_bit_valid`, it must be guaranteed - /// that the memory referenced by that `Ptr` always contains a valid - /// `xxx`. Since `NonZeroXxx`'s bytes are always initialized [1], - /// `is_bit_valid`'s precondition requires that the same is true of its - /// argument. Since `xxx`'s only bit validity invariant is that its - /// bytes must be initialized, this memory is guaranteed to contain a - /// valid `xxx`. - /// - The alignment of `NonZeroXxx` is equal to the alignment of `xxx`. - /// [1] - /// - The impl must only return `true` for its argument if the original - /// `Ptr<NonZeroXxx>` refers to a valid `NonZeroXxx`. The only `xxx` - /// which is not also a valid `NonZeroXxx` is 0. [1] - /// - /// [1] Per https://doc.rust-lang.org/core/num/struct.NonZeroU16.html: - /// - /// `NonZeroU16` is guaranteed to have the same layout and bit validity as - /// `u16` with the exception that `0` is not a valid instance. - unsafe_impl!(NonZeroU8: TryFromBytes; |n: &u8| *n != 0); - unsafe_impl!(NonZeroI8: TryFromBytes; |n: &i8| *n != 0); - unsafe_impl!(NonZeroU16: TryFromBytes; |n: &u16| *n != 0); - unsafe_impl!(NonZeroI16: TryFromBytes; |n: &i16| *n != 0); - unsafe_impl!(NonZeroU32: TryFromBytes; |n: &u32| *n != 0); - unsafe_impl!(NonZeroI32: TryFromBytes; |n: &i32| *n != 0); - unsafe_impl!(NonZeroU64: TryFromBytes; |n: &u64| *n != 0); - unsafe_impl!(NonZeroI64: TryFromBytes; |n: &i64| *n != 0); - unsafe_impl!(NonZeroU128: TryFromBytes; |n: &u128| *n != 0); - unsafe_impl!(NonZeroI128: TryFromBytes; |n: &i128| *n != 0); - unsafe_impl!(NonZeroUsize: TryFromBytes; |n: &usize| *n != 0); - unsafe_impl!(NonZeroIsize: TryFromBytes; |n: &isize| *n != 0); -} -safety_comment! { - /// SAFETY: - /// - `TryFromBytes` (with no validator), `FromZeroes`, `FromBytes`, - /// `AsBytes`: The Rust compiler reuses `0` value to represent `None`, so - /// `size_of::<Option<NonZeroXxx>>() == size_of::<xxx>()`; see - /// `NonZeroXxx` documentation. - /// - `Unaligned`: `NonZeroU8` and `NonZeroI8` document that - /// `Option<NonZeroU8>` and `Option<NonZeroI8>` both have size 1. [1] [2] - /// This is worded in a way that makes it unclear whether it's meant as a - /// guarantee, but given the purpose of those types, it's virtually - /// unthinkable that that would ever change. The only valid alignment for - /// a 1-byte type is 1. - /// - /// TODO(#429): Add quotes from documentation. - /// - /// [1] https://doc.rust-lang.org/stable/std/num/struct.NonZeroU8.html - /// [2] https://doc.rust-lang.org/stable/std/num/struct.NonZeroI8.html - /// - /// TODO(https://github.com/rust-lang/rust/pull/104082): Cite documentation - /// for layout guarantees. - unsafe_impl!(Option<NonZeroU8>: TryFromBytes, FromZeroes, FromBytes, AsBytes, Unaligned); - unsafe_impl!(Option<NonZeroI8>: TryFromBytes, FromZeroes, FromBytes, AsBytes, Unaligned); - assert_unaligned!(Option<NonZeroU8>, Option<NonZeroI8>); - unsafe_impl!(Option<NonZeroU16>: TryFromBytes, FromZeroes, FromBytes, AsBytes); - unsafe_impl!(Option<NonZeroI16>: TryFromBytes, FromZeroes, FromBytes, AsBytes); - unsafe_impl!(Option<NonZeroU32>: TryFromBytes, FromZeroes, FromBytes, AsBytes); - unsafe_impl!(Option<NonZeroI32>: TryFromBytes, FromZeroes, FromBytes, AsBytes); - unsafe_impl!(Option<NonZeroU64>: TryFromBytes, FromZeroes, FromBytes, AsBytes); - unsafe_impl!(Option<NonZeroI64>: TryFromBytes, FromZeroes, FromBytes, AsBytes); - unsafe_impl!(Option<NonZeroU128>: TryFromBytes, FromZeroes, FromBytes, AsBytes); - unsafe_impl!(Option<NonZeroI128>: TryFromBytes, FromZeroes, FromBytes, AsBytes); - unsafe_impl!(Option<NonZeroUsize>: TryFromBytes, FromZeroes, FromBytes, AsBytes); - unsafe_impl!(Option<NonZeroIsize>: TryFromBytes, FromZeroes, FromBytes, AsBytes); -} - -safety_comment! { - /// SAFETY: - /// The following types can be transmuted from `[0u8; size_of::<T>()]`. [1] - /// None of them contain `UnsafeCell`s, and so they all soundly implement - /// `FromZeroes`. - /// - /// [1] Per - /// https://doc.rust-lang.org/nightly/core/option/index.html#representation: - /// - /// Rust guarantees to optimize the following types `T` such that - /// [`Option<T>`] has the same size and alignment as `T`. In some of these - /// cases, Rust further guarantees that `transmute::<_, Option<T>>([0u8; - /// size_of::<T>()])` is sound and produces `Option::<T>::None`. These - /// cases are identified by the second column: - /// - /// | `T` | `transmute::<_, Option<T>>([0u8; size_of::<T>()])` sound? | - /// |-----------------------|-----------------------------------------------------------| - /// | [`Box<U>`] | when `U: Sized` | - /// | `&U` | when `U: Sized` | - /// | `&mut U` | when `U: Sized` | - /// | [`ptr::NonNull<U>`] | when `U: Sized` | - /// | `fn`, `extern "C" fn` | always | - /// - /// TODO(#429), TODO(https://github.com/rust-lang/rust/pull/115333): Cite - /// the Stable docs once they're available. - #[cfg(feature = "alloc")] - unsafe_impl!( - #[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))] - T => FromZeroes for Option<Box<T>> - ); - unsafe_impl!(T => FromZeroes for Option<&'_ T>); - unsafe_impl!(T => FromZeroes for Option<&'_ mut T>); - unsafe_impl!(T => FromZeroes for Option<NonNull<T>>); - unsafe_impl_for_power_set!(A, B, C, D, E, F, G, H, I, J, K, L -> M => FromZeroes for opt_fn!(...)); - unsafe_impl_for_power_set!(A, B, C, D, E, F, G, H, I, J, K, L -> M => FromZeroes for opt_extern_c_fn!(...)); -} - -safety_comment! { - /// SAFETY: - /// Per reference [1]: - /// "For all T, the following are guaranteed: - /// size_of::<PhantomData<T>>() == 0 - /// align_of::<PhantomData<T>>() == 1". - /// This gives: - /// - `TryFromBytes` (with no validator), `FromZeroes`, `FromBytes`: There - /// is only one possible sequence of 0 bytes, and `PhantomData` is - /// inhabited. - /// - `AsBytes`: Since `PhantomData` has size 0, it contains no padding - /// bytes. - /// - `Unaligned`: Per the preceding reference, `PhantomData` has alignment - /// 1. - /// - /// [1] https://doc.rust-lang.org/std/marker/struct.PhantomData.html#layout-1 - unsafe_impl!(T: ?Sized => TryFromBytes for PhantomData<T>); - unsafe_impl!(T: ?Sized => FromZeroes for PhantomData<T>); - unsafe_impl!(T: ?Sized => FromBytes for PhantomData<T>); - unsafe_impl!(T: ?Sized => AsBytes for PhantomData<T>); - unsafe_impl!(T: ?Sized => Unaligned for PhantomData<T>); - assert_unaligned!(PhantomData<()>, PhantomData<u8>, PhantomData<u64>); -} -safety_comment! { - /// SAFETY: - /// `Wrapping<T>` is guaranteed by its docs [1] to have the same layout and - /// bit validity as `T`. Also, `Wrapping<T>` is `#[repr(transparent)]`, and - /// has a single field, which is `pub`. Per the reference [2], this means - /// that the `#[repr(transparent)]` attribute is "considered part of the - /// public ABI". - /// - /// - `TryFromBytes`: The safety requirements for `unsafe_impl!` with an - /// `is_bit_valid` closure: - /// - Given `t: *mut Wrapping<T>` and `let r = *mut T`, `r` refers to an - /// object of the same size as that referred to by `t`. This is true - /// because `Wrapping<T>` and `T` have the same layout - /// - The alignment of `Wrapping<T>` is equal to the alignment of `T`. - /// - The impl must only return `true` for its argument if the original - /// `Ptr<Wrapping<T>>` refers to a valid `Wrapping<T>`. Since - /// `Wrapping<T>` has the same bit validity as `T`, and since our impl - /// just calls `T::is_bit_valid`, our impl returns `true` exactly when - /// its argument contains a valid `Wrapping<T>`. - /// - `FromBytes`: Since `Wrapping<T>` has the same bit validity as `T`, if - /// `T: FromBytes`, then all initialized byte sequences are valid - /// instances of `Wrapping<T>`. Similarly, if `T: FromBytes`, then - /// `Wrapping<T>` doesn't contain any `UnsafeCell`s. Thus, `impl FromBytes - /// for Wrapping<T> where T: FromBytes` is a sound impl. - /// - `AsBytes`: Since `Wrapping<T>` has the same bit validity as `T`, if - /// `T: AsBytes`, then all valid instances of `Wrapping<T>` have all of - /// their bytes initialized. Similarly, if `T: AsBytes`, then - /// `Wrapping<T>` doesn't contain any `UnsafeCell`s. Thus, `impl AsBytes - /// for Wrapping<T> where T: AsBytes` is a valid impl. - /// - `Unaligned`: Since `Wrapping<T>` has the same layout as `T`, - /// `Wrapping<T>` has alignment 1 exactly when `T` does. - /// - /// [1] Per https://doc.rust-lang.org/core/num/struct.NonZeroU16.html: - /// - /// `NonZeroU16` is guaranteed to have the same layout and bit validity as - /// `u16` with the exception that `0` is not a valid instance. - /// - /// TODO(#429): Add quotes from documentation. - /// - /// [1] TODO(https://doc.rust-lang.org/nightly/core/num/struct.Wrapping.html#layout-1): - /// Reference this documentation once it's available on stable. - /// - /// [2] https://doc.rust-lang.org/nomicon/other-reprs.html#reprtransparent - unsafe_impl!(T: TryFromBytes => TryFromBytes for Wrapping<T>; |candidate: Ptr<T>| { - // SAFETY: - // - Since `T` and `Wrapping<T>` have the same layout and bit validity - // and contain the same fields, `T` contains `UnsafeCell`s exactly - // where `Wrapping<T>` does. Thus, all memory and `UnsafeCell` - // preconditions of `T::is_bit_valid` hold exactly when the same - // preconditions for `Wrapping<T>::is_bit_valid` hold. - // - By the same token, since `candidate` is guaranteed to have its - // bytes initialized where there are always initialized bytes in - // `Wrapping<T>`, the same is true for `T`. - unsafe { T::is_bit_valid(candidate) } - }); - unsafe_impl!(T: FromZeroes => FromZeroes for Wrapping<T>); - unsafe_impl!(T: FromBytes => FromBytes for Wrapping<T>); - unsafe_impl!(T: AsBytes => AsBytes for Wrapping<T>); - unsafe_impl!(T: Unaligned => Unaligned for Wrapping<T>); - assert_unaligned!(Wrapping<()>, Wrapping<u8>); -} -safety_comment! { - // `MaybeUninit<T>` is `FromZeroes` and `FromBytes`, but never `AsBytes` - // since it may contain uninitialized bytes. - // - /// SAFETY: - /// - `TryFromBytes` (with no validator), `FromZeroes`, `FromBytes`: - /// `MaybeUninit<T>` has no restrictions on its contents. Unfortunately, - /// in addition to bit validity, `TryFromBytes`, `FromZeroes` and - /// `FromBytes` also require that implementers contain no `UnsafeCell`s. - /// Thus, we require `T: Trait` in order to ensure that `T` - and thus - /// `MaybeUninit<T>` - contains to `UnsafeCell`s. Thus, requiring that `T` - /// implement each of these traits is sufficient. - /// - `Unaligned`: "MaybeUninit<T> is guaranteed to have the same size, - /// alignment, and ABI as T" [1] - /// - /// [1] https://doc.rust-lang.org/stable/core/mem/union.MaybeUninit.html#layout-1 - /// - /// TODO(https://github.com/google/zerocopy/issues/251): If we split - /// `FromBytes` and `RefFromBytes`, or if we introduce a separate - /// `NoCell`/`Freeze` trait, we can relax the trait bounds for `FromZeroes` - /// and `FromBytes`. - unsafe_impl!(T: TryFromBytes => TryFromBytes for MaybeUninit<T>); - unsafe_impl!(T: FromZeroes => FromZeroes for MaybeUninit<T>); - unsafe_impl!(T: FromBytes => FromBytes for MaybeUninit<T>); - unsafe_impl!(T: Unaligned => Unaligned for MaybeUninit<T>); - assert_unaligned!(MaybeUninit<()>, MaybeUninit<u8>); -} -safety_comment! { - /// SAFETY: - /// `ManuallyDrop` has the same layout and bit validity as `T` [1], and - /// accessing the inner value is safe (meaning that it's unsound to leave - /// the inner value uninitialized while exposing the `ManuallyDrop` to safe - /// code). - /// - `FromZeroes`, `FromBytes`: Since it has the same layout as `T`, any - /// valid `T` is a valid `ManuallyDrop<T>`. If `T: FromZeroes`, a sequence - /// of zero bytes is a valid `T`, and thus a valid `ManuallyDrop<T>`. If - /// `T: FromBytes`, any sequence of bytes is a valid `T`, and thus a valid - /// `ManuallyDrop<T>`. - /// - `AsBytes`: Since it has the same layout as `T`, and since it's unsound - /// to let safe code access a `ManuallyDrop` whose inner value is - /// uninitialized, safe code can only ever access a `ManuallyDrop` whose - /// contents are a valid `T`. Since `T: AsBytes`, this means that safe - /// code can only ever access a `ManuallyDrop` with all initialized bytes. - /// - `Unaligned`: `ManuallyDrop` has the same layout (and thus alignment) - /// as `T`, and `T: Unaligned` guarantees that that alignment is 1. - /// - /// `ManuallyDrop<T>` is guaranteed to have the same layout and bit - /// validity as `T` - /// - /// [1] Per https://doc.rust-lang.org/nightly/core/mem/struct.ManuallyDrop.html: - /// - /// TODO(#429): - /// - Add quotes from docs. - /// - Once [1] (added in - /// https://github.com/rust-lang/rust/pull/115522) is available on stable, - /// quote the stable docs instead of the nightly docs. - unsafe_impl!(T: ?Sized + FromZeroes => FromZeroes for ManuallyDrop<T>); - unsafe_impl!(T: ?Sized + FromBytes => FromBytes for ManuallyDrop<T>); - unsafe_impl!(T: ?Sized + AsBytes => AsBytes for ManuallyDrop<T>); - unsafe_impl!(T: ?Sized + Unaligned => Unaligned for ManuallyDrop<T>); - assert_unaligned!(ManuallyDrop<()>, ManuallyDrop<u8>); -} -safety_comment! { - /// SAFETY: - /// Per the reference [1]: - /// - /// An array of `[T; N]` has a size of `size_of::<T>() * N` and the same - /// alignment of `T`. Arrays are laid out so that the zero-based `nth` - /// element of the array is offset from the start of the array by `n * - /// size_of::<T>()` bytes. - /// - /// ... - /// - /// Slices have the same layout as the section of the array they slice. - /// - /// In other words, the layout of a `[T]` or `[T; N]` is a sequence of `T`s - /// laid out back-to-back with no bytes in between. Therefore, `[T]` or `[T; - /// N]` are `TryFromBytes`, `FromZeroes`, `FromBytes`, and `AsBytes` if `T` - /// is (respectively). Furthermore, since an array/slice has "the same - /// alignment of `T`", `[T]` and `[T; N]` are `Unaligned` if `T` is. - /// - /// Note that we don't `assert_unaligned!` for slice types because - /// `assert_unaligned!` uses `align_of`, which only works for `Sized` types. - /// - /// [1] https://doc.rust-lang.org/reference/type-layout.html#array-layout - unsafe_impl!(const N: usize, T: FromZeroes => FromZeroes for [T; N]); - unsafe_impl!(const N: usize, T: FromBytes => FromBytes for [T; N]); - unsafe_impl!(const N: usize, T: AsBytes => AsBytes for [T; N]); - unsafe_impl!(const N: usize, T: Unaligned => Unaligned for [T; N]); - assert_unaligned!([(); 0], [(); 1], [u8; 0], [u8; 1]); - unsafe_impl!(T: TryFromBytes => TryFromBytes for [T]; |c: Ptr<[T]>| { - // SAFETY: Assuming the preconditions of `is_bit_valid` are satisfied, - // so too will the postcondition: that, if `is_bit_valid(candidate)` - // returns true, `*candidate` contains a valid `Self`. Per the reference - // [1]: - // - // An array of `[T; N]` has a size of `size_of::<T>() * N` and the - // same alignment of `T`. Arrays are laid out so that the zero-based - // `nth` element of the array is offset from the start of the array by - // `n * size_of::<T>()` bytes. - // - // ... - // - // Slices have the same layout as the section of the array they slice. - // - // In other words, the layout of a `[T] is a sequence of `T`s laid out - // back-to-back with no bytes in between. If all elements in `candidate` - // are `is_bit_valid`, so too is `candidate`. - // - // Note that any of the below calls may panic, but it would still be - // sound even if it did. `is_bit_valid` does not promise that it will - // not panic (in fact, it explicitly warns that it's a possibility), and - // we have not violated any safety invariants that we must fix before - // returning. - c.iter().all(|elem| - // SAFETY: We uphold the safety contract of `is_bit_valid(elem)`, by - // precondition on the surrounding call to `is_bit_valid`. The - // memory referenced by `elem` is contained entirely within `c`, and - // satisfies the preconditions satisfied by `c`. By axiom, we assume - // that `Iterator:all` does not invalidate these preconditions - // (e.g., by writing to `elem`.) Since `elem` is derived from `c`, - // it is only possible for uninitialized bytes to occur in `elem` at - // the same bytes they occur within `c`. - unsafe { <T as TryFromBytes>::is_bit_valid(elem) } - ) - }); - unsafe_impl!(T: FromZeroes => FromZeroes for [T]); - unsafe_impl!(T: FromBytes => FromBytes for [T]); - unsafe_impl!(T: AsBytes => AsBytes for [T]); - unsafe_impl!(T: Unaligned => Unaligned for [T]); -} -safety_comment! { - /// SAFETY: - /// - `FromZeroes`: For thin pointers (note that `T: Sized`), the zero - /// pointer is considered "null". [1] No operations which require - /// provenance are legal on null pointers, so this is not a footgun. - /// - /// NOTE(#170): Implementing `FromBytes` and `AsBytes` for raw pointers - /// would be sound, but carries provenance footguns. We want to support - /// `FromBytes` and `AsBytes` for raw pointers eventually, but we are - /// holding off until we can figure out how to address those footguns. - /// - /// [1] TODO(https://github.com/rust-lang/rust/pull/116988): Cite the - /// documentation once this PR lands. - unsafe_impl!(T => FromZeroes for *const T); - unsafe_impl!(T => FromZeroes for *mut T); -} - -// SIMD support -// -// Per the Unsafe Code Guidelines Reference [1]: -// -// Packed SIMD vector types are `repr(simd)` homogeneous tuple-structs -// containing `N` elements of type `T` where `N` is a power-of-two and the -// size and alignment requirements of `T` are equal: -// -// ```rust -// #[repr(simd)] -// struct Vector<T, N>(T_0, ..., T_(N - 1)); -// ``` -// -// ... -// -// The size of `Vector` is `N * size_of::<T>()` and its alignment is an -// implementation-defined function of `T` and `N` greater than or equal to -// `align_of::<T>()`. -// -// ... -// -// Vector elements are laid out in source field order, enabling random access -// to vector elements by reinterpreting the vector as an array: -// -// ```rust -// union U { -// vec: Vector<T, N>, -// arr: [T; N] -// } -// -// assert_eq!(size_of::<Vector<T, N>>(), size_of::<[T; N]>()); -// assert!(align_of::<Vector<T, N>>() >= align_of::<[T; N]>()); -// -// unsafe { -// let u = U { vec: Vector<T, N>(t_0, ..., t_(N - 1)) }; -// -// assert_eq!(u.vec.0, u.arr[0]); -// // ... -// assert_eq!(u.vec.(N - 1), u.arr[N - 1]); -// } -// ``` -// -// Given this background, we can observe that: -// - The size and bit pattern requirements of a SIMD type are equivalent to the -// equivalent array type. Thus, for any SIMD type whose primitive `T` is -// `TryFromBytes`, `FromZeroes`, `FromBytes`, or `AsBytes`, that SIMD type is -// also `TryFromBytes`, `FromZeroes`, `FromBytes`, or `AsBytes` respectively. -// - Since no upper bound is placed on the alignment, no SIMD type can be -// guaranteed to be `Unaligned`. -// -// Also per [1]: -// -// This chapter represents the consensus from issue #38. The statements in -// here are not (yet) "guaranteed" not to change until an RFC ratifies them. -// -// See issue #38 [2]. While this behavior is not technically guaranteed, the -// likelihood that the behavior will change such that SIMD types are no longer -// `TryFromBytes`, `FromZeroes`, `FromBytes`, or `AsBytes` is next to zero, as -// that would defeat the entire purpose of SIMD types. Nonetheless, we put this -// behavior behind the `simd` Cargo feature, which requires consumers to opt -// into this stability hazard. -// -// [1] https://rust-lang.github.io/unsafe-code-guidelines/layout/packed-simd-vectors.html -// [2] https://github.com/rust-lang/unsafe-code-guidelines/issues/38 -#[cfg(feature = "simd")] -#[cfg_attr(doc_cfg, doc(cfg(feature = "simd")))] -mod simd { - /// Defines a module which implements `TryFromBytes`, `FromZeroes`, - /// `FromBytes`, and `AsBytes` for a set of types from a module in - /// `core::arch`. - /// - /// `$arch` is both the name of the defined module and the name of the - /// module in `core::arch`, and `$typ` is the list of items from that module - /// to implement `FromZeroes`, `FromBytes`, and `AsBytes` for. - #[allow(unused_macros)] // `allow(unused_macros)` is needed because some - // target/feature combinations don't emit any impls - // and thus don't use this macro. - macro_rules! simd_arch_mod { - (#[cfg $cfg:tt] $arch:ident, $mod:ident, $($typ:ident),*) => { - #[cfg $cfg] - #[cfg_attr(doc_cfg, doc(cfg $cfg))] - mod $mod { - use core::arch::$arch::{$($typ),*}; - - use crate::*; - impl_known_layout!($($typ),*); - safety_comment! { - /// SAFETY: - /// See comment on module definition for justification. - $( unsafe_impl!($typ: TryFromBytes, FromZeroes, FromBytes, AsBytes); )* - } - } - }; - } - - #[rustfmt::skip] - const _: () = { - simd_arch_mod!( - #[cfg(target_arch = "x86")] - x86, x86, __m128, __m128d, __m128i, __m256, __m256d, __m256i - ); - simd_arch_mod!( - #[cfg(all(feature = "simd-nightly", target_arch = "x86"))] - x86, x86_nightly, __m512bh, __m512, __m512d, __m512i - ); - simd_arch_mod!( - #[cfg(target_arch = "x86_64")] - x86_64, x86_64, __m128, __m128d, __m128i, __m256, __m256d, __m256i - ); - simd_arch_mod!( - #[cfg(all(feature = "simd-nightly", target_arch = "x86_64"))] - x86_64, x86_64_nightly, __m512bh, __m512, __m512d, __m512i - ); - simd_arch_mod!( - #[cfg(target_arch = "wasm32")] - wasm32, wasm32, v128 - ); - simd_arch_mod!( - #[cfg(all(feature = "simd-nightly", target_arch = "powerpc"))] - powerpc, powerpc, vector_bool_long, vector_double, vector_signed_long, vector_unsigned_long - ); - simd_arch_mod!( - #[cfg(all(feature = "simd-nightly", target_arch = "powerpc64"))] - powerpc64, powerpc64, vector_bool_long, vector_double, vector_signed_long, vector_unsigned_long - ); - simd_arch_mod!( - #[cfg(target_arch = "aarch64")] - aarch64, aarch64, float32x2_t, float32x4_t, float64x1_t, float64x2_t, int8x8_t, int8x8x2_t, - int8x8x3_t, int8x8x4_t, int8x16_t, int8x16x2_t, int8x16x3_t, int8x16x4_t, int16x4_t, - int16x8_t, int32x2_t, int32x4_t, int64x1_t, int64x2_t, poly8x8_t, poly8x8x2_t, poly8x8x3_t, - poly8x8x4_t, poly8x16_t, poly8x16x2_t, poly8x16x3_t, poly8x16x4_t, poly16x4_t, poly16x8_t, - poly64x1_t, poly64x2_t, uint8x8_t, uint8x8x2_t, uint8x8x3_t, uint8x8x4_t, uint8x16_t, - uint8x16x2_t, uint8x16x3_t, uint8x16x4_t, uint16x4_t, uint16x8_t, uint32x2_t, uint32x4_t, - uint64x1_t, uint64x2_t - ); - simd_arch_mod!( - #[cfg(all(feature = "simd-nightly", target_arch = "arm"))] - arm, arm, int8x4_t, uint8x4_t - ); - }; -} - -/// Safely transmutes a value of one type to a value of another type of the same -/// size. -/// -/// The expression `$e` must have a concrete type, `T`, which implements -/// `AsBytes`. The `transmute!` expression must also have a concrete type, `U` -/// (`U` is inferred from the calling context), and `U` must implement -/// `FromBytes`. -/// -/// Note that the `T` produced by the expression `$e` will *not* be dropped. -/// Semantically, its bits will be copied into a new value of type `U`, the -/// original `T` will be forgotten, and the value of type `U` will be returned. -/// -/// # Examples -/// -/// ``` -/// # use zerocopy::transmute; -/// let one_dimensional: [u8; 8] = [0, 1, 2, 3, 4, 5, 6, 7]; -/// -/// let two_dimensional: [[u8; 4]; 2] = transmute!(one_dimensional); -/// -/// assert_eq!(two_dimensional, [[0, 1, 2, 3], [4, 5, 6, 7]]); -/// ``` -#[macro_export] -macro_rules! transmute { - ($e:expr) => {{ - // NOTE: This must be a macro (rather than a function with trait bounds) - // because there's no way, in a generic context, to enforce that two - // types have the same size. `core::mem::transmute` uses compiler magic - // to enforce this so long as the types are concrete. - - let e = $e; - if false { - // This branch, though never taken, ensures that the type of `e` is - // `AsBytes` and that the type of this macro invocation expression - // is `FromBytes`. - - struct AssertIsAsBytes<T: $crate::AsBytes>(T); - let _ = AssertIsAsBytes(e); - - struct AssertIsFromBytes<U: $crate::FromBytes>(U); - #[allow(unused, unreachable_code)] - let u = AssertIsFromBytes(loop {}); - u.0 - } else { - // SAFETY: `core::mem::transmute` ensures that the type of `e` and - // the type of this macro invocation expression have the same size. - // We know this transmute is safe thanks to the `AsBytes` and - // `FromBytes` bounds enforced by the `false` branch. - // - // We use this reexport of `core::mem::transmute` because we know it - // will always be available for crates which are using the 2015 - // edition of Rust. By contrast, if we were to use - // `std::mem::transmute`, this macro would not work for such crates - // in `no_std` contexts, and if we were to use - // `core::mem::transmute`, this macro would not work in `std` - // contexts in which `core` was not manually imported. This is not a - // problem for 2018 edition crates. - unsafe { - // Clippy: It's okay to transmute a type to itself. - #[allow(clippy::useless_transmute, clippy::missing_transmute_annotations)] - $crate::macro_util::core_reexport::mem::transmute(e) - } - } - }} -} - -/// Safely transmutes a mutable or immutable reference of one type to an -/// immutable reference of another type of the same size. -/// -/// The expression `$e` must have a concrete type, `&T` or `&mut T`, where `T: -/// Sized + AsBytes`. The `transmute_ref!` expression must also have a concrete -/// type, `&U` (`U` is inferred from the calling context), where `U: Sized + -/// FromBytes`. It must be the case that `align_of::<T>() >= align_of::<U>()`. -/// -/// The lifetime of the input type, `&T` or `&mut T`, must be the same as or -/// outlive the lifetime of the output type, `&U`. -/// -/// # Examples -/// -/// ``` -/// # use zerocopy::transmute_ref; -/// let one_dimensional: [u8; 8] = [0, 1, 2, 3, 4, 5, 6, 7]; -/// -/// let two_dimensional: &[[u8; 4]; 2] = transmute_ref!(&one_dimensional); -/// -/// assert_eq!(two_dimensional, &[[0, 1, 2, 3], [4, 5, 6, 7]]); -/// ``` -/// -/// # Alignment increase error message -/// -/// Because of limitations on macros, the error message generated when -/// `transmute_ref!` is used to transmute from a type of lower alignment to a -/// type of higher alignment is somewhat confusing. For example, the following -/// code: -/// -/// ```compile_fail -/// const INCREASE_ALIGNMENT: &u16 = zerocopy::transmute_ref!(&[0u8; 2]); -/// ``` -/// -/// ...generates the following error: -/// -/// ```text -/// error[E0512]: cannot transmute between types of different sizes, or dependently-sized types -/// --> src/lib.rs:1524:34 -/// | -/// 5 | const INCREASE_ALIGNMENT: &u16 = zerocopy::transmute_ref!(&[0u8; 2]); -/// | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -/// | -/// = note: source type: `AlignOf<[u8; 2]>` (8 bits) -/// = note: target type: `MaxAlignsOf<[u8; 2], u16>` (16 bits) -/// = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) -/// ``` -/// -/// This is saying that `max(align_of::<T>(), align_of::<U>()) != -/// align_of::<T>()`, which is equivalent to `align_of::<T>() < -/// align_of::<U>()`. -#[macro_export] -macro_rules! transmute_ref { - ($e:expr) => {{ - // NOTE: This must be a macro (rather than a function with trait bounds) - // because there's no way, in a generic context, to enforce that two - // types have the same size or alignment. - - // Ensure that the source type is a reference or a mutable reference - // (note that mutable references are implicitly reborrowed here). - let e: &_ = $e; - - #[allow(unused, clippy::diverging_sub_expression)] - if false { - // This branch, though never taken, ensures that the type of `e` is - // `&T` where `T: 't + Sized + AsBytes`, that the type of this macro - // expression is `&U` where `U: 'u + Sized + FromBytes`, and that - // `'t` outlives `'u`. - - struct AssertIsAsBytes<'a, T: ::core::marker::Sized + $crate::AsBytes>(&'a T); - let _ = AssertIsAsBytes(e); - - struct AssertIsFromBytes<'a, U: ::core::marker::Sized + $crate::FromBytes>(&'a U); - #[allow(unused, unreachable_code)] - let u = AssertIsFromBytes(loop {}); - u.0 - } else if false { - // This branch, though never taken, ensures that `size_of::<T>() == - // size_of::<U>()` and that that `align_of::<T>() >= - // align_of::<U>()`. - - // `t` is inferred to have type `T` because it's assigned to `e` (of - // type `&T`) as `&t`. - let mut t = unreachable!(); - e = &t; - - // `u` is inferred to have type `U` because it's used as `&u` as the - // value returned from this branch. - let u; - - $crate::assert_size_eq!(t, u); - $crate::assert_align_gt_eq!(t, u); - - &u - } else { - // SAFETY: For source type `Src` and destination type `Dst`: - // - We know that `Src: AsBytes` and `Dst: FromBytes` thanks to the - // uses of `AssertIsAsBytes` and `AssertIsFromBytes` above. - // - We know that `size_of::<Src>() == size_of::<Dst>()` thanks to - // the use of `assert_size_eq!` above. - // - We know that `align_of::<Src>() >= align_of::<Dst>()` thanks to - // the use of `assert_align_gt_eq!` above. - unsafe { $crate::macro_util::transmute_ref(e) } - } - }} -} - -/// Safely transmutes a mutable reference of one type to an mutable reference of -/// another type of the same size. -/// -/// The expression `$e` must have a concrete type, `&mut T`, where `T: Sized + -/// AsBytes`. The `transmute_mut!` expression must also have a concrete type, -/// `&mut U` (`U` is inferred from the calling context), where `U: Sized + -/// FromBytes`. It must be the case that `align_of::<T>() >= align_of::<U>()`. -/// -/// The lifetime of the input type, `&mut T`, must be the same as or outlive the -/// lifetime of the output type, `&mut U`. -/// -/// # Examples -/// -/// ``` -/// # use zerocopy::transmute_mut; -/// let mut one_dimensional: [u8; 8] = [0, 1, 2, 3, 4, 5, 6, 7]; -/// -/// let two_dimensional: &mut [[u8; 4]; 2] = transmute_mut!(&mut one_dimensional); -/// -/// assert_eq!(two_dimensional, &[[0, 1, 2, 3], [4, 5, 6, 7]]); -/// -/// two_dimensional.reverse(); -/// -/// assert_eq!(one_dimensional, [4, 5, 6, 7, 0, 1, 2, 3]); -/// ``` -/// -/// # Alignment increase error message -/// -/// Because of limitations on macros, the error message generated when -/// `transmute_mut!` is used to transmute from a type of lower alignment to a -/// type of higher alignment is somewhat confusing. For example, the following -/// code: -/// -/// ```compile_fail -/// const INCREASE_ALIGNMENT: &mut u16 = zerocopy::transmute_mut!(&mut [0u8; 2]); -/// ``` -/// -/// ...generates the following error: -/// -/// ```text -/// error[E0512]: cannot transmute between types of different sizes, or dependently-sized types -/// --> src/lib.rs:1524:34 -/// | -/// 5 | const INCREASE_ALIGNMENT: &mut u16 = zerocopy::transmute_mut!(&mut [0u8; 2]); -/// | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -/// | -/// = note: source type: `AlignOf<[u8; 2]>` (8 bits) -/// = note: target type: `MaxAlignsOf<[u8; 2], u16>` (16 bits) -/// = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) -/// ``` -/// -/// This is saying that `max(align_of::<T>(), align_of::<U>()) != -/// align_of::<T>()`, which is equivalent to `align_of::<T>() < -/// align_of::<U>()`. -#[macro_export] -macro_rules! transmute_mut { - ($e:expr) => {{ - // NOTE: This must be a macro (rather than a function with trait bounds) - // because there's no way, in a generic context, to enforce that two - // types have the same size or alignment. - - // Ensure that the source type is a mutable reference. - let e: &mut _ = $e; - - #[allow(unused, clippy::diverging_sub_expression)] - if false { - // This branch, though never taken, ensures that the type of `e` is - // `&mut T` where `T: 't + Sized + FromBytes + AsBytes`, that the - // type of this macro expression is `&mut U` where `U: 'u + Sized + - // FromBytes + AsBytes`. - - // We use immutable references here rather than mutable so that, if - // this macro is used in a const context (in which, as of this - // writing, mutable references are banned), the error message - // appears to originate in the user's code rather than in the - // internals of this macro. - struct AssertSrcIsFromBytes<'a, T: ::core::marker::Sized + $crate::FromBytes>(&'a T); - struct AssertSrcIsAsBytes<'a, T: ::core::marker::Sized + $crate::AsBytes>(&'a T); - struct AssertDstIsFromBytes<'a, T: ::core::marker::Sized + $crate::FromBytes>(&'a T); - struct AssertDstIsAsBytes<'a, T: ::core::marker::Sized + $crate::AsBytes>(&'a T); - - if true { - let _ = AssertSrcIsFromBytes(&*e); - } else { - let _ = AssertSrcIsAsBytes(&*e); - } - - if true { - #[allow(unused, unreachable_code)] - let u = AssertDstIsFromBytes(loop {}); - &mut *u.0 - } else { - #[allow(unused, unreachable_code)] - let u = AssertDstIsAsBytes(loop {}); - &mut *u.0 - } - } else if false { - // This branch, though never taken, ensures that `size_of::<T>() == - // size_of::<U>()` and that that `align_of::<T>() >= - // align_of::<U>()`. - - // `t` is inferred to have type `T` because it's assigned to `e` (of - // type `&mut T`) as `&mut t`. - let mut t = unreachable!(); - e = &mut t; - - // `u` is inferred to have type `U` because it's used as `&mut u` as - // the value returned from this branch. - let u; - - $crate::assert_size_eq!(t, u); - $crate::assert_align_gt_eq!(t, u); - - &mut u - } else { - // SAFETY: For source type `Src` and destination type `Dst`: - // - We know that `Src: FromBytes + AsBytes` and `Dst: FromBytes + - // AsBytes` thanks to the uses of `AssertSrcIsFromBytes`, - // `AssertSrcIsAsBytes`, `AssertDstIsFromBytes`, and - // `AssertDstIsAsBytes` above. - // - We know that `size_of::<Src>() == size_of::<Dst>()` thanks to - // the use of `assert_size_eq!` above. - // - We know that `align_of::<Src>() >= align_of::<Dst>()` thanks to - // the use of `assert_align_gt_eq!` above. - unsafe { $crate::macro_util::transmute_mut(e) } - } - }} -} - -/// Includes a file and safely transmutes it to a value of an arbitrary type. -/// -/// The file will be included as a byte array, `[u8; N]`, which will be -/// transmuted to another type, `T`. `T` is inferred from the calling context, -/// and must implement [`FromBytes`]. -/// -/// The file is located relative to the current file (similarly to how modules -/// are found). The provided path is interpreted in a platform-specific way at -/// compile time. So, for instance, an invocation with a Windows path containing -/// backslashes `\` would not compile correctly on Unix. -/// -/// `include_value!` is ignorant of byte order. For byte order-aware types, see -/// the [`byteorder`] module. -/// -/// # Examples -/// -/// Assume there are two files in the same directory with the following -/// contents: -/// -/// File `data` (no trailing newline): -/// -/// ```text -/// abcd -/// ``` -/// -/// File `main.rs`: -/// -/// ```rust -/// use zerocopy::include_value; -/// # macro_rules! include_value { -/// # ($file:expr) => { zerocopy::include_value!(concat!("../testdata/include_value/", $file)) }; -/// # } -/// -/// fn main() { -/// let as_u32: u32 = include_value!("data"); -/// assert_eq!(as_u32, u32::from_ne_bytes([b'a', b'b', b'c', b'd'])); -/// let as_i32: i32 = include_value!("data"); -/// assert_eq!(as_i32, i32::from_ne_bytes([b'a', b'b', b'c', b'd'])); -/// } -/// ``` -#[doc(alias("include_bytes", "include_data", "include_type"))] -#[macro_export] -macro_rules! include_value { - ($file:expr $(,)?) => { - $crate::transmute!(*::core::include_bytes!($file)) - }; -} - -/// A typed reference derived from a byte slice. -/// -/// A `Ref<B, T>` is a reference to a `T` which is stored in a byte slice, `B`. -/// Unlike a native reference (`&T` or `&mut T`), `Ref<B, T>` has the same -/// mutability as the byte slice it was constructed from (`B`). -/// -/// # Examples -/// -/// `Ref` can be used to treat a sequence of bytes as a structured type, and to -/// read and write the fields of that type as if the byte slice reference were -/// simply a reference to that type. -/// -/// ```rust -/// # #[cfg(feature = "derive")] { // This example uses derives, and won't compile without them -/// use zerocopy::{AsBytes, ByteSlice, ByteSliceMut, FromBytes, FromZeroes, Ref, Unaligned}; -/// -/// #[derive(FromZeroes, FromBytes, AsBytes, Unaligned)] -/// #[repr(C)] -/// struct UdpHeader { -/// src_port: [u8; 2], -/// dst_port: [u8; 2], -/// length: [u8; 2], -/// checksum: [u8; 2], -/// } -/// -/// struct UdpPacket<B> { -/// header: Ref<B, UdpHeader>, -/// body: B, -/// } -/// -/// impl<B: ByteSlice> UdpPacket<B> { -/// pub fn parse(bytes: B) -> Option<UdpPacket<B>> { -/// let (header, body) = Ref::new_unaligned_from_prefix(bytes)?; -/// Some(UdpPacket { header, body }) -/// } -/// -/// pub fn get_src_port(&self) -> [u8; 2] { -/// self.header.src_port -/// } -/// } -/// -/// impl<B: ByteSliceMut> UdpPacket<B> { -/// pub fn set_src_port(&mut self, src_port: [u8; 2]) { -/// self.header.src_port = src_port; -/// } -/// } -/// # } -/// ``` -pub struct Ref<B, T: ?Sized>(B, PhantomData<T>); - -/// Deprecated: prefer [`Ref`] instead. -#[deprecated(since = "0.7.0", note = "LayoutVerified has been renamed to Ref")] -#[doc(hidden)] -pub type LayoutVerified<B, T> = Ref<B, T>; - -impl<B, T> Ref<B, T> -where - B: ByteSlice, -{ - /// Constructs a new `Ref`. - /// - /// `new` verifies that `bytes.len() == size_of::<T>()` and that `bytes` is - /// aligned to `align_of::<T>()`, and constructs a new `Ref`. If either of - /// these checks fail, it returns `None`. - #[inline] - pub fn new(bytes: B) -> Option<Ref<B, T>> { - if bytes.len() != mem::size_of::<T>() || !util::aligned_to::<_, T>(bytes.deref()) { - return None; - } - Some(Ref(bytes, PhantomData)) - } - - /// Constructs a new `Ref` from the prefix of a byte slice. - /// - /// `new_from_prefix` verifies that `bytes.len() >= size_of::<T>()` and that - /// `bytes` is aligned to `align_of::<T>()`. It consumes the first - /// `size_of::<T>()` bytes from `bytes` to construct a `Ref`, and returns - /// the remaining bytes to the caller. If either the length or alignment - /// checks fail, it returns `None`. - #[inline] - pub fn new_from_prefix(bytes: B) -> Option<(Ref<B, T>, B)> { - if bytes.len() < mem::size_of::<T>() || !util::aligned_to::<_, T>(bytes.deref()) { - return None; - } - let (bytes, suffix) = bytes.split_at(mem::size_of::<T>()); - Some((Ref(bytes, PhantomData), suffix)) - } - - /// Constructs a new `Ref` from the suffix of a byte slice. - /// - /// `new_from_suffix` verifies that `bytes.len() >= size_of::<T>()` and that - /// the last `size_of::<T>()` bytes of `bytes` are aligned to - /// `align_of::<T>()`. It consumes the last `size_of::<T>()` bytes from - /// `bytes` to construct a `Ref`, and returns the preceding bytes to the - /// caller. If either the length or alignment checks fail, it returns - /// `None`. - #[inline] - pub fn new_from_suffix(bytes: B) -> Option<(B, Ref<B, T>)> { - let bytes_len = bytes.len(); - let split_at = bytes_len.checked_sub(mem::size_of::<T>())?; - let (prefix, bytes) = bytes.split_at(split_at); - if !util::aligned_to::<_, T>(bytes.deref()) { - return None; - } - Some((prefix, Ref(bytes, PhantomData))) - } -} - -impl<B, T> Ref<B, [T]> -where - B: ByteSlice, -{ - /// Constructs a new `Ref` of a slice type. - /// - /// `new_slice` verifies that `bytes.len()` is a multiple of - /// `size_of::<T>()` and that `bytes` is aligned to `align_of::<T>()`, and - /// constructs a new `Ref`. If either of these checks fail, it returns - /// `None`. - /// - /// # Panics - /// - /// `new_slice` panics if `T` is a zero-sized type. - #[inline] - pub fn new_slice(bytes: B) -> Option<Ref<B, [T]>> { - let remainder = bytes - .len() - .checked_rem(mem::size_of::<T>()) - .expect("Ref::new_slice called on a zero-sized type"); - if remainder != 0 || !util::aligned_to::<_, T>(bytes.deref()) { - return None; - } - Some(Ref(bytes, PhantomData)) - } - - /// Constructs a new `Ref` of a slice type from the prefix of a byte slice. - /// - /// `new_slice_from_prefix` verifies that `bytes.len() >= size_of::<T>() * - /// count` and that `bytes` is aligned to `align_of::<T>()`. It consumes the - /// first `size_of::<T>() * count` bytes from `bytes` to construct a `Ref`, - /// and returns the remaining bytes to the caller. It also ensures that - /// `sizeof::<T>() * count` does not overflow a `usize`. If any of the - /// length, alignment, or overflow checks fail, it returns `None`. - /// - /// # Panics - /// - /// `new_slice_from_prefix` panics if `T` is a zero-sized type. - #[inline] - pub fn new_slice_from_prefix(bytes: B, count: usize) -> Option<(Ref<B, [T]>, B)> { - let expected_len = match mem::size_of::<T>().checked_mul(count) { - Some(len) => len, - None => return None, - }; - if bytes.len() < expected_len { - return None; - } - let (prefix, bytes) = bytes.split_at(expected_len); - Self::new_slice(prefix).map(move |l| (l, bytes)) - } - - /// Constructs a new `Ref` of a slice type from the suffix of a byte slice. - /// - /// `new_slice_from_suffix` verifies that `bytes.len() >= size_of::<T>() * - /// count` and that `bytes` is aligned to `align_of::<T>()`. It consumes the - /// last `size_of::<T>() * count` bytes from `bytes` to construct a `Ref`, - /// and returns the preceding bytes to the caller. It also ensures that - /// `sizeof::<T>() * count` does not overflow a `usize`. If any of the - /// length, alignment, or overflow checks fail, it returns `None`. - /// - /// # Panics - /// - /// `new_slice_from_suffix` panics if `T` is a zero-sized type. - #[inline] - pub fn new_slice_from_suffix(bytes: B, count: usize) -> Option<(B, Ref<B, [T]>)> { - let expected_len = match mem::size_of::<T>().checked_mul(count) { - Some(len) => len, - None => return None, - }; - let split_at = bytes.len().checked_sub(expected_len)?; - let (bytes, suffix) = bytes.split_at(split_at); - Self::new_slice(suffix).map(move |l| (bytes, l)) - } -} - -fn map_zeroed<B: ByteSliceMut, T: ?Sized>(opt: Option<Ref<B, T>>) -> Option<Ref<B, T>> { - match opt { - Some(mut r) => { - r.0.fill(0); - Some(r) - } - None => None, - } -} - -fn map_prefix_tuple_zeroed<B: ByteSliceMut, T: ?Sized>( - opt: Option<(Ref<B, T>, B)>, -) -> Option<(Ref<B, T>, B)> { - match opt { - Some((mut r, rest)) => { - r.0.fill(0); - Some((r, rest)) - } - None => None, - } -} - -fn map_suffix_tuple_zeroed<B: ByteSliceMut, T: ?Sized>( - opt: Option<(B, Ref<B, T>)>, -) -> Option<(B, Ref<B, T>)> { - map_prefix_tuple_zeroed(opt.map(|(a, b)| (b, a))).map(|(a, b)| (b, a)) -} - -impl<B, T> Ref<B, T> -where - B: ByteSliceMut, -{ - /// Constructs a new `Ref` after zeroing the bytes. - /// - /// `new_zeroed` verifies that `bytes.len() == size_of::<T>()` and that - /// `bytes` is aligned to `align_of::<T>()`, and constructs a new `Ref`. If - /// either of these checks fail, it returns `None`. - /// - /// If the checks succeed, then `bytes` will be initialized to zero. This - /// can be useful when re-using buffers to ensure that sensitive data - /// previously stored in the buffer is not leaked. - #[inline(always)] - pub fn new_zeroed(bytes: B) -> Option<Ref<B, T>> { - map_zeroed(Self::new(bytes)) - } - - /// Constructs a new `Ref` from the prefix of a byte slice, zeroing the - /// prefix. - /// - /// `new_from_prefix_zeroed` verifies that `bytes.len() >= size_of::<T>()` - /// and that `bytes` is aligned to `align_of::<T>()`. It consumes the first - /// `size_of::<T>()` bytes from `bytes` to construct a `Ref`, and returns - /// the remaining bytes to the caller. If either the length or alignment - /// checks fail, it returns `None`. - /// - /// If the checks succeed, then the prefix which is consumed will be - /// initialized to zero. This can be useful when re-using buffers to ensure - /// that sensitive data previously stored in the buffer is not leaked. - #[inline(always)] - pub fn new_from_prefix_zeroed(bytes: B) -> Option<(Ref<B, T>, B)> { - map_prefix_tuple_zeroed(Self::new_from_prefix(bytes)) - } - - /// Constructs a new `Ref` from the suffix of a byte slice, zeroing the - /// suffix. - /// - /// `new_from_suffix_zeroed` verifies that `bytes.len() >= size_of::<T>()` - /// and that the last `size_of::<T>()` bytes of `bytes` are aligned to - /// `align_of::<T>()`. It consumes the last `size_of::<T>()` bytes from - /// `bytes` to construct a `Ref`, and returns the preceding bytes to the - /// caller. If either the length or alignment checks fail, it returns - /// `None`. - /// - /// If the checks succeed, then the suffix which is consumed will be - /// initialized to zero. This can be useful when re-using buffers to ensure - /// that sensitive data previously stored in the buffer is not leaked. - #[inline(always)] - pub fn new_from_suffix_zeroed(bytes: B) -> Option<(B, Ref<B, T>)> { - map_suffix_tuple_zeroed(Self::new_from_suffix(bytes)) - } -} - -impl<B, T> Ref<B, [T]> -where - B: ByteSliceMut, -{ - /// Constructs a new `Ref` of a slice type after zeroing the bytes. - /// - /// `new_slice_zeroed` verifies that `bytes.len()` is a multiple of - /// `size_of::<T>()` and that `bytes` is aligned to `align_of::<T>()`, and - /// constructs a new `Ref`. If either of these checks fail, it returns - /// `None`. - /// - /// If the checks succeed, then `bytes` will be initialized to zero. This - /// can be useful when re-using buffers to ensure that sensitive data - /// previously stored in the buffer is not leaked. - /// - /// # Panics - /// - /// `new_slice` panics if `T` is a zero-sized type. - #[inline(always)] - pub fn new_slice_zeroed(bytes: B) -> Option<Ref<B, [T]>> { - map_zeroed(Self::new_slice(bytes)) - } - - /// Constructs a new `Ref` of a slice type from the prefix of a byte slice, - /// after zeroing the bytes. - /// - /// `new_slice_from_prefix` verifies that `bytes.len() >= size_of::<T>() * - /// count` and that `bytes` is aligned to `align_of::<T>()`. It consumes the - /// first `size_of::<T>() * count` bytes from `bytes` to construct a `Ref`, - /// and returns the remaining bytes to the caller. It also ensures that - /// `sizeof::<T>() * count` does not overflow a `usize`. If any of the - /// length, alignment, or overflow checks fail, it returns `None`. - /// - /// If the checks succeed, then the suffix which is consumed will be - /// initialized to zero. This can be useful when re-using buffers to ensure - /// that sensitive data previously stored in the buffer is not leaked. - /// - /// # Panics - /// - /// `new_slice_from_prefix_zeroed` panics if `T` is a zero-sized type. - #[inline(always)] - pub fn new_slice_from_prefix_zeroed(bytes: B, count: usize) -> Option<(Ref<B, [T]>, B)> { - map_prefix_tuple_zeroed(Self::new_slice_from_prefix(bytes, count)) - } - - /// Constructs a new `Ref` of a slice type from the prefix of a byte slice, - /// after zeroing the bytes. - /// - /// `new_slice_from_suffix` verifies that `bytes.len() >= size_of::<T>() * - /// count` and that `bytes` is aligned to `align_of::<T>()`. It consumes the - /// last `size_of::<T>() * count` bytes from `bytes` to construct a `Ref`, - /// and returns the preceding bytes to the caller. It also ensures that - /// `sizeof::<T>() * count` does not overflow a `usize`. If any of the - /// length, alignment, or overflow checks fail, it returns `None`. - /// - /// If the checks succeed, then the consumed suffix will be initialized to - /// zero. This can be useful when re-using buffers to ensure that sensitive - /// data previously stored in the buffer is not leaked. - /// - /// # Panics - /// - /// `new_slice_from_suffix_zeroed` panics if `T` is a zero-sized type. - #[inline(always)] - pub fn new_slice_from_suffix_zeroed(bytes: B, count: usize) -> Option<(B, Ref<B, [T]>)> { - map_suffix_tuple_zeroed(Self::new_slice_from_suffix(bytes, count)) - } -} - -impl<B, T> Ref<B, T> -where - B: ByteSlice, - T: Unaligned, -{ - /// Constructs a new `Ref` for a type with no alignment requirement. - /// - /// `new_unaligned` verifies that `bytes.len() == size_of::<T>()` and - /// constructs a new `Ref`. If the check fails, it returns `None`. - #[inline(always)] - pub fn new_unaligned(bytes: B) -> Option<Ref<B, T>> { - Ref::new(bytes) - } - - /// Constructs a new `Ref` from the prefix of a byte slice for a type with - /// no alignment requirement. - /// - /// `new_unaligned_from_prefix` verifies that `bytes.len() >= - /// size_of::<T>()`. It consumes the first `size_of::<T>()` bytes from - /// `bytes` to construct a `Ref`, and returns the remaining bytes to the - /// caller. If the length check fails, it returns `None`. - #[inline(always)] - pub fn new_unaligned_from_prefix(bytes: B) -> Option<(Ref<B, T>, B)> { - Ref::new_from_prefix(bytes) - } - - /// Constructs a new `Ref` from the suffix of a byte slice for a type with - /// no alignment requirement. - /// - /// `new_unaligned_from_suffix` verifies that `bytes.len() >= - /// size_of::<T>()`. It consumes the last `size_of::<T>()` bytes from - /// `bytes` to construct a `Ref`, and returns the preceding bytes to the - /// caller. If the length check fails, it returns `None`. - #[inline(always)] - pub fn new_unaligned_from_suffix(bytes: B) -> Option<(B, Ref<B, T>)> { - Ref::new_from_suffix(bytes) - } -} - -impl<B, T> Ref<B, [T]> -where - B: ByteSlice, - T: Unaligned, -{ - /// Constructs a new `Ref` of a slice type with no alignment requirement. - /// - /// `new_slice_unaligned` verifies that `bytes.len()` is a multiple of - /// `size_of::<T>()` and constructs a new `Ref`. If the check fails, it - /// returns `None`. - /// - /// # Panics - /// - /// `new_slice` panics if `T` is a zero-sized type. - #[inline(always)] - pub fn new_slice_unaligned(bytes: B) -> Option<Ref<B, [T]>> { - Ref::new_slice(bytes) - } - - /// Constructs a new `Ref` of a slice type with no alignment requirement - /// from the prefix of a byte slice. - /// - /// `new_slice_from_prefix` verifies that `bytes.len() >= size_of::<T>() * - /// count`. It consumes the first `size_of::<T>() * count` bytes from - /// `bytes` to construct a `Ref`, and returns the remaining bytes to the - /// caller. It also ensures that `sizeof::<T>() * count` does not overflow a - /// `usize`. If either the length, or overflow checks fail, it returns - /// `None`. - /// - /// # Panics - /// - /// `new_slice_unaligned_from_prefix` panics if `T` is a zero-sized type. - #[inline(always)] - pub fn new_slice_unaligned_from_prefix(bytes: B, count: usize) -> Option<(Ref<B, [T]>, B)> { - Ref::new_slice_from_prefix(bytes, count) - } - - /// Constructs a new `Ref` of a slice type with no alignment requirement - /// from the suffix of a byte slice. - /// - /// `new_slice_from_suffix` verifies that `bytes.len() >= size_of::<T>() * - /// count`. It consumes the last `size_of::<T>() * count` bytes from `bytes` - /// to construct a `Ref`, and returns the remaining bytes to the caller. It - /// also ensures that `sizeof::<T>() * count` does not overflow a `usize`. - /// If either the length, or overflow checks fail, it returns `None`. - /// - /// # Panics - /// - /// `new_slice_unaligned_from_suffix` panics if `T` is a zero-sized type. - #[inline(always)] - pub fn new_slice_unaligned_from_suffix(bytes: B, count: usize) -> Option<(B, Ref<B, [T]>)> { - Ref::new_slice_from_suffix(bytes, count) - } -} - -impl<B, T> Ref<B, T> -where - B: ByteSliceMut, - T: Unaligned, -{ - /// Constructs a new `Ref` for a type with no alignment requirement, zeroing - /// the bytes. - /// - /// `new_unaligned_zeroed` verifies that `bytes.len() == size_of::<T>()` and - /// constructs a new `Ref`. If the check fails, it returns `None`. - /// - /// If the check succeeds, then `bytes` will be initialized to zero. This - /// can be useful when re-using buffers to ensure that sensitive data - /// previously stored in the buffer is not leaked. - #[inline(always)] - pub fn new_unaligned_zeroed(bytes: B) -> Option<Ref<B, T>> { - map_zeroed(Self::new_unaligned(bytes)) - } - - /// Constructs a new `Ref` from the prefix of a byte slice for a type with - /// no alignment requirement, zeroing the prefix. - /// - /// `new_unaligned_from_prefix_zeroed` verifies that `bytes.len() >= - /// size_of::<T>()`. It consumes the first `size_of::<T>()` bytes from - /// `bytes` to construct a `Ref`, and returns the remaining bytes to the - /// caller. If the length check fails, it returns `None`. - /// - /// If the check succeeds, then the prefix which is consumed will be - /// initialized to zero. This can be useful when re-using buffers to ensure - /// that sensitive data previously stored in the buffer is not leaked. - #[inline(always)] - pub fn new_unaligned_from_prefix_zeroed(bytes: B) -> Option<(Ref<B, T>, B)> { - map_prefix_tuple_zeroed(Self::new_unaligned_from_prefix(bytes)) - } - - /// Constructs a new `Ref` from the suffix of a byte slice for a type with - /// no alignment requirement, zeroing the suffix. - /// - /// `new_unaligned_from_suffix_zeroed` verifies that `bytes.len() >= - /// size_of::<T>()`. It consumes the last `size_of::<T>()` bytes from - /// `bytes` to construct a `Ref`, and returns the preceding bytes to the - /// caller. If the length check fails, it returns `None`. - /// - /// If the check succeeds, then the suffix which is consumed will be - /// initialized to zero. This can be useful when re-using buffers to ensure - /// that sensitive data previously stored in the buffer is not leaked. - #[inline(always)] - pub fn new_unaligned_from_suffix_zeroed(bytes: B) -> Option<(B, Ref<B, T>)> { - map_suffix_tuple_zeroed(Self::new_unaligned_from_suffix(bytes)) - } -} - -impl<B, T> Ref<B, [T]> -where - B: ByteSliceMut, - T: Unaligned, -{ - /// Constructs a new `Ref` for a slice type with no alignment requirement, - /// zeroing the bytes. - /// - /// `new_slice_unaligned_zeroed` verifies that `bytes.len()` is a multiple - /// of `size_of::<T>()` and constructs a new `Ref`. If the check fails, it - /// returns `None`. - /// - /// If the check succeeds, then `bytes` will be initialized to zero. This - /// can be useful when re-using buffers to ensure that sensitive data - /// previously stored in the buffer is not leaked. - /// - /// # Panics - /// - /// `new_slice` panics if `T` is a zero-sized type. - #[inline(always)] - pub fn new_slice_unaligned_zeroed(bytes: B) -> Option<Ref<B, [T]>> { - map_zeroed(Self::new_slice_unaligned(bytes)) - } - - /// Constructs a new `Ref` of a slice type with no alignment requirement - /// from the prefix of a byte slice, after zeroing the bytes. - /// - /// `new_slice_from_prefix` verifies that `bytes.len() >= size_of::<T>() * - /// count`. It consumes the first `size_of::<T>() * count` bytes from - /// `bytes` to construct a `Ref`, and returns the remaining bytes to the - /// caller. It also ensures that `sizeof::<T>() * count` does not overflow a - /// `usize`. If either the length, or overflow checks fail, it returns - /// `None`. - /// - /// If the checks succeed, then the prefix will be initialized to zero. This - /// can be useful when re-using buffers to ensure that sensitive data - /// previously stored in the buffer is not leaked. - /// - /// # Panics - /// - /// `new_slice_unaligned_from_prefix_zeroed` panics if `T` is a zero-sized - /// type. - #[inline(always)] - pub fn new_slice_unaligned_from_prefix_zeroed( - bytes: B, - count: usize, - ) -> Option<(Ref<B, [T]>, B)> { - map_prefix_tuple_zeroed(Self::new_slice_unaligned_from_prefix(bytes, count)) - } - - /// Constructs a new `Ref` of a slice type with no alignment requirement - /// from the suffix of a byte slice, after zeroing the bytes. - /// - /// `new_slice_from_suffix` verifies that `bytes.len() >= size_of::<T>() * - /// count`. It consumes the last `size_of::<T>() * count` bytes from `bytes` - /// to construct a `Ref`, and returns the remaining bytes to the caller. It - /// also ensures that `sizeof::<T>() * count` does not overflow a `usize`. - /// If either the length, or overflow checks fail, it returns `None`. - /// - /// If the checks succeed, then the suffix will be initialized to zero. This - /// can be useful when re-using buffers to ensure that sensitive data - /// previously stored in the buffer is not leaked. - /// - /// # Panics - /// - /// `new_slice_unaligned_from_suffix_zeroed` panics if `T` is a zero-sized - /// type. - #[inline(always)] - pub fn new_slice_unaligned_from_suffix_zeroed( - bytes: B, - count: usize, - ) -> Option<(B, Ref<B, [T]>)> { - map_suffix_tuple_zeroed(Self::new_slice_unaligned_from_suffix(bytes, count)) - } -} - -impl<'a, B, T> Ref<B, T> -where - B: 'a + ByteSlice, - T: FromBytes, -{ - /// Converts this `Ref` into a reference. - /// - /// `into_ref` consumes the `Ref`, and returns a reference to `T`. - #[inline(always)] - pub fn into_ref(self) -> &'a T { - assert!(B::INTO_REF_INTO_MUT_ARE_SOUND); - - // SAFETY: According to the safety preconditions on - // `ByteSlice::INTO_REF_INTO_MUT_ARE_SOUND`, the preceding assert - // ensures that, given `B: 'a`, it is sound to drop `self` and still - // access the underlying memory using reads for `'a`. - unsafe { self.deref_helper() } - } -} - -impl<'a, B, T> Ref<B, T> -where - B: 'a + ByteSliceMut, - T: FromBytes + AsBytes, -{ - /// Converts this `Ref` into a mutable reference. - /// - /// `into_mut` consumes the `Ref`, and returns a mutable reference to `T`. - #[inline(always)] - pub fn into_mut(mut self) -> &'a mut T { - assert!(B::INTO_REF_INTO_MUT_ARE_SOUND); - - // SAFETY: According to the safety preconditions on - // `ByteSlice::INTO_REF_INTO_MUT_ARE_SOUND`, the preceding assert - // ensures that, given `B: 'a + ByteSliceMut`, it is sound to drop - // `self` and still access the underlying memory using both reads and - // writes for `'a`. - unsafe { self.deref_mut_helper() } - } -} - -impl<'a, B, T> Ref<B, [T]> -where - B: 'a + ByteSlice, - T: FromBytes, -{ - /// Converts this `Ref` into a slice reference. - /// - /// `into_slice` consumes the `Ref`, and returns a reference to `[T]`. - #[inline(always)] - pub fn into_slice(self) -> &'a [T] { - assert!(B::INTO_REF_INTO_MUT_ARE_SOUND); - - // SAFETY: According to the safety preconditions on - // `ByteSlice::INTO_REF_INTO_MUT_ARE_SOUND`, the preceding assert - // ensures that, given `B: 'a`, it is sound to drop `self` and still - // access the underlying memory using reads for `'a`. - unsafe { self.deref_slice_helper() } - } -} - -impl<'a, B, T> Ref<B, [T]> -where - B: 'a + ByteSliceMut, - T: FromBytes + AsBytes, -{ - /// Converts this `Ref` into a mutable slice reference. - /// - /// `into_mut_slice` consumes the `Ref`, and returns a mutable reference to - /// `[T]`. - #[inline(always)] - pub fn into_mut_slice(mut self) -> &'a mut [T] { - assert!(B::INTO_REF_INTO_MUT_ARE_SOUND); - - // SAFETY: According to the safety preconditions on - // `ByteSlice::INTO_REF_INTO_MUT_ARE_SOUND`, the preceding assert - // ensures that, given `B: 'a + ByteSliceMut`, it is sound to drop - // `self` and still access the underlying memory using both reads and - // writes for `'a`. - unsafe { self.deref_mut_slice_helper() } - } -} - -impl<B, T> Ref<B, T> -where - B: ByteSlice, - T: FromBytes, -{ - /// Creates an immutable reference to `T` with a specific lifetime. - /// - /// # Safety - /// - /// The type bounds on this method guarantee that it is safe to create an - /// immutable reference to `T` from `self`. However, since the lifetime `'a` - /// is not required to be shorter than the lifetime of the reference to - /// `self`, the caller must guarantee that the lifetime `'a` is valid for - /// this reference. In particular, the referent must exist for all of `'a`, - /// and no mutable references to the same memory may be constructed during - /// `'a`. - unsafe fn deref_helper<'a>(&self) -> &'a T { - // TODO(#429): Add a "SAFETY" comment and remove this `allow`. - #[allow(clippy::undocumented_unsafe_blocks)] - unsafe { - &*self.0.as_ptr().cast::<T>() - } - } -} - -impl<B, T> Ref<B, T> -where - B: ByteSliceMut, - T: FromBytes + AsBytes, -{ - /// Creates a mutable reference to `T` with a specific lifetime. - /// - /// # Safety - /// - /// The type bounds on this method guarantee that it is safe to create a - /// mutable reference to `T` from `self`. However, since the lifetime `'a` - /// is not required to be shorter than the lifetime of the reference to - /// `self`, the caller must guarantee that the lifetime `'a` is valid for - /// this reference. In particular, the referent must exist for all of `'a`, - /// and no other references - mutable or immutable - to the same memory may - /// be constructed during `'a`. - unsafe fn deref_mut_helper<'a>(&mut self) -> &'a mut T { - // TODO(#429): Add a "SAFETY" comment and remove this `allow`. - #[allow(clippy::undocumented_unsafe_blocks)] - unsafe { - &mut *self.0.as_mut_ptr().cast::<T>() - } - } -} - -impl<B, T> Ref<B, [T]> -where - B: ByteSlice, - T: FromBytes, -{ - /// Creates an immutable reference to `[T]` with a specific lifetime. - /// - /// # Safety - /// - /// `deref_slice_helper` has the same safety requirements as `deref_helper`. - unsafe fn deref_slice_helper<'a>(&self) -> &'a [T] { - let len = self.0.len(); - let elem_size = mem::size_of::<T>(); - debug_assert_ne!(elem_size, 0); - // `Ref<_, [T]>` maintains the invariant that `size_of::<T>() > 0`. - // Thus, neither the mod nor division operations here can panic. - #[allow(clippy::arithmetic_side_effects)] - let elems = { - debug_assert_eq!(len % elem_size, 0); - len / elem_size - }; - // TODO(#429): Add a "SAFETY" comment and remove this `allow`. - #[allow(clippy::undocumented_unsafe_blocks)] - unsafe { - slice::from_raw_parts(self.0.as_ptr().cast::<T>(), elems) - } - } -} - -impl<B, T> Ref<B, [T]> -where - B: ByteSliceMut, - T: FromBytes + AsBytes, -{ - /// Creates a mutable reference to `[T]` with a specific lifetime. - /// - /// # Safety - /// - /// `deref_mut_slice_helper` has the same safety requirements as - /// `deref_mut_helper`. - unsafe fn deref_mut_slice_helper<'a>(&mut self) -> &'a mut [T] { - let len = self.0.len(); - let elem_size = mem::size_of::<T>(); - debug_assert_ne!(elem_size, 0); - // `Ref<_, [T]>` maintains the invariant that `size_of::<T>() > 0`. - // Thus, neither the mod nor division operations here can panic. - #[allow(clippy::arithmetic_side_effects)] - let elems = { - debug_assert_eq!(len % elem_size, 0); - len / elem_size - }; - // TODO(#429): Add a "SAFETY" comment and remove this `allow`. - #[allow(clippy::undocumented_unsafe_blocks)] - unsafe { - slice::from_raw_parts_mut(self.0.as_mut_ptr().cast::<T>(), elems) - } - } -} - -impl<B, T> Ref<B, T> -where - B: ByteSlice, - T: ?Sized, -{ - /// Gets the underlying bytes. - #[inline] - pub fn bytes(&self) -> &[u8] { - &self.0 - } -} - -impl<B, T> Ref<B, T> -where - B: ByteSliceMut, - T: ?Sized, -{ - /// Gets the underlying bytes mutably. - #[inline] - pub fn bytes_mut(&mut self) -> &mut [u8] { - &mut self.0 - } -} - -impl<B, T> Ref<B, T> -where - B: ByteSlice, - T: FromBytes, -{ - /// Reads a copy of `T`. - #[inline] - pub fn read(&self) -> T { - // SAFETY: Because of the invariants on `Ref`, we know that `self.0` is - // at least `size_of::<T>()` bytes long, and that it is at least as - // aligned as `align_of::<T>()`. Because `T: FromBytes`, it is sound to - // interpret these bytes as a `T`. - unsafe { ptr::read(self.0.as_ptr().cast::<T>()) } - } -} - -impl<B, T> Ref<B, T> -where - B: ByteSliceMut, - T: AsBytes, -{ - /// Writes the bytes of `t` and then forgets `t`. - #[inline] - pub fn write(&mut self, t: T) { - // SAFETY: Because of the invariants on `Ref`, we know that `self.0` is - // at least `size_of::<T>()` bytes long, and that it is at least as - // aligned as `align_of::<T>()`. Writing `t` to the buffer will allow - // all of the bytes of `t` to be accessed as a `[u8]`, but because `T: - // AsBytes`, we know this is sound. - unsafe { ptr::write(self.0.as_mut_ptr().cast::<T>(), t) } - } -} - -impl<B, T> Deref for Ref<B, T> -where - B: ByteSlice, - T: FromBytes, -{ - type Target = T; - #[inline] - fn deref(&self) -> &T { - // SAFETY: This is sound because the lifetime of `self` is the same as - // the lifetime of the return value, meaning that a) the returned - // reference cannot outlive `self` and, b) no mutable methods on `self` - // can be called during the lifetime of the returned reference. See the - // documentation on `deref_helper` for what invariants we are required - // to uphold. - unsafe { self.deref_helper() } - } -} - -impl<B, T> DerefMut for Ref<B, T> -where - B: ByteSliceMut, - T: FromBytes + AsBytes, -{ - #[inline] - fn deref_mut(&mut self) -> &mut T { - // SAFETY: This is sound because the lifetime of `self` is the same as - // the lifetime of the return value, meaning that a) the returned - // reference cannot outlive `self` and, b) no other methods on `self` - // can be called during the lifetime of the returned reference. See the - // documentation on `deref_mut_helper` for what invariants we are - // required to uphold. - unsafe { self.deref_mut_helper() } - } -} - -impl<B, T> Deref for Ref<B, [T]> -where - B: ByteSlice, - T: FromBytes, -{ - type Target = [T]; - #[inline] - fn deref(&self) -> &[T] { - // SAFETY: This is sound because the lifetime of `self` is the same as - // the lifetime of the return value, meaning that a) the returned - // reference cannot outlive `self` and, b) no mutable methods on `self` - // can be called during the lifetime of the returned reference. See the - // documentation on `deref_slice_helper` for what invariants we are - // required to uphold. - unsafe { self.deref_slice_helper() } - } -} - -impl<B, T> DerefMut for Ref<B, [T]> -where - B: ByteSliceMut, - T: FromBytes + AsBytes, -{ - #[inline] - fn deref_mut(&mut self) -> &mut [T] { - // SAFETY: This is sound because the lifetime of `self` is the same as - // the lifetime of the return value, meaning that a) the returned - // reference cannot outlive `self` and, b) no other methods on `self` - // can be called during the lifetime of the returned reference. See the - // documentation on `deref_mut_slice_helper` for what invariants we are - // required to uphold. - unsafe { self.deref_mut_slice_helper() } - } -} - -impl<T, B> Display for Ref<B, T> -where - B: ByteSlice, - T: FromBytes + Display, -{ - #[inline] - fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result { - let inner: &T = self; - inner.fmt(fmt) - } -} - -impl<T, B> Display for Ref<B, [T]> -where - B: ByteSlice, - T: FromBytes, - [T]: Display, -{ - #[inline] - fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result { - let inner: &[T] = self; - inner.fmt(fmt) - } -} - -impl<T, B> Debug for Ref<B, T> -where - B: ByteSlice, - T: FromBytes + Debug, -{ - #[inline] - fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result { - let inner: &T = self; - fmt.debug_tuple("Ref").field(&inner).finish() - } -} - -impl<T, B> Debug for Ref<B, [T]> -where - B: ByteSlice, - T: FromBytes + Debug, -{ - #[inline] - fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result { - let inner: &[T] = self; - fmt.debug_tuple("Ref").field(&inner).finish() - } -} - -impl<T, B> Eq for Ref<B, T> -where - B: ByteSlice, - T: FromBytes + Eq, -{ -} - -impl<T, B> Eq for Ref<B, [T]> -where - B: ByteSlice, - T: FromBytes + Eq, -{ -} - -impl<T, B> PartialEq for Ref<B, T> -where - B: ByteSlice, - T: FromBytes + PartialEq, -{ - #[inline] - fn eq(&self, other: &Self) -> bool { - self.deref().eq(other.deref()) - } -} - -impl<T, B> PartialEq for Ref<B, [T]> -where - B: ByteSlice, - T: FromBytes + PartialEq, -{ - #[inline] - fn eq(&self, other: &Self) -> bool { - self.deref().eq(other.deref()) - } -} - -impl<T, B> Ord for Ref<B, T> -where - B: ByteSlice, - T: FromBytes + Ord, -{ - #[inline] - fn cmp(&self, other: &Self) -> Ordering { - let inner: &T = self; - let other_inner: &T = other; - inner.cmp(other_inner) - } -} - -impl<T, B> Ord for Ref<B, [T]> -where - B: ByteSlice, - T: FromBytes + Ord, -{ - #[inline] - fn cmp(&self, other: &Self) -> Ordering { - let inner: &[T] = self; - let other_inner: &[T] = other; - inner.cmp(other_inner) - } -} - -impl<T, B> PartialOrd for Ref<B, T> -where - B: ByteSlice, - T: FromBytes + PartialOrd, -{ - #[inline] - fn partial_cmp(&self, other: &Self) -> Option<Ordering> { - let inner: &T = self; - let other_inner: &T = other; - inner.partial_cmp(other_inner) - } -} - -impl<T, B> PartialOrd for Ref<B, [T]> -where - B: ByteSlice, - T: FromBytes + PartialOrd, -{ - #[inline] - fn partial_cmp(&self, other: &Self) -> Option<Ordering> { - let inner: &[T] = self; - let other_inner: &[T] = other; - inner.partial_cmp(other_inner) - } -} - -mod sealed { - pub trait ByteSliceSealed {} -} - -// ByteSlice and ByteSliceMut abstract over [u8] references (&[u8], &mut [u8], -// Ref<[u8]>, RefMut<[u8]>, etc). We rely on various behaviors of these -// references such as that a given reference will never changes its length -// between calls to deref() or deref_mut(), and that split_at() works as -// expected. If ByteSlice or ByteSliceMut were not sealed, consumers could -// implement them in a way that violated these behaviors, and would break our -// unsafe code. Thus, we seal them and implement it only for known-good -// reference types. For the same reason, they're unsafe traits. - -#[allow(clippy::missing_safety_doc)] // TODO(fxbug.dev/99068) -/// A mutable or immutable reference to a byte slice. -/// -/// `ByteSlice` abstracts over the mutability of a byte slice reference, and is -/// implemented for various special reference types such as `Ref<[u8]>` and -/// `RefMut<[u8]>`. -/// -/// Note that, while it would be technically possible, `ByteSlice` is not -/// implemented for [`Vec<u8>`], as the only way to implement the [`split_at`] -/// method would involve reallocation, and `split_at` must be a very cheap -/// operation in order for the utilities in this crate to perform as designed. -/// -/// [`split_at`]: crate::ByteSlice::split_at -// It may seem overkill to go to this length to ensure that this doc link never -// breaks. We do this because it simplifies CI - it means that generating docs -// always succeeds, so we don't need special logic to only generate docs under -// certain features. -#[cfg_attr(feature = "alloc", doc = "[`Vec<u8>`]: alloc::vec::Vec")] -#[cfg_attr( - not(feature = "alloc"), - doc = "[`Vec<u8>`]: https://doc.rust-lang.org/std/vec/struct.Vec.html" -)] -pub unsafe trait ByteSlice: Deref<Target = [u8]> + Sized + sealed::ByteSliceSealed { - /// Are the [`Ref::into_ref`] and [`Ref::into_mut`] methods sound when used - /// with `Self`? If not, evaluating this constant must panic at compile - /// time. - /// - /// This exists to work around #716 on versions of zerocopy prior to 0.8. - /// - /// # Safety - /// - /// This may only be set to true if the following holds: Given the - /// following: - /// - `Self: 'a` - /// - `bytes: Self` - /// - `let ptr = bytes.as_ptr()` - /// - /// ...then: - /// - Using `ptr` to read the memory previously addressed by `bytes` is - /// sound for `'a` even after `bytes` has been dropped. - /// - If `Self: ByteSliceMut`, using `ptr` to write the memory previously - /// addressed by `bytes` is sound for `'a` even after `bytes` has been - /// dropped. - #[doc(hidden)] - const INTO_REF_INTO_MUT_ARE_SOUND: bool; - - /// Gets a raw pointer to the first byte in the slice. - #[inline] - fn as_ptr(&self) -> *const u8 { - <[u8]>::as_ptr(self) - } - - /// Splits the slice at the midpoint. - /// - /// `x.split_at(mid)` returns `x[..mid]` and `x[mid..]`. - /// - /// # Panics - /// - /// `x.split_at(mid)` panics if `mid > x.len()`. - fn split_at(self, mid: usize) -> (Self, Self); -} - -#[allow(clippy::missing_safety_doc)] // TODO(fxbug.dev/99068) -/// A mutable reference to a byte slice. -/// -/// `ByteSliceMut` abstracts over various ways of storing a mutable reference to -/// a byte slice, and is implemented for various special reference types such as -/// `RefMut<[u8]>`. -pub unsafe trait ByteSliceMut: ByteSlice + DerefMut { - /// Gets a mutable raw pointer to the first byte in the slice. - #[inline] - fn as_mut_ptr(&mut self) -> *mut u8 { - <[u8]>::as_mut_ptr(self) - } -} - -impl<'a> sealed::ByteSliceSealed for &'a [u8] {} -// TODO(#429): Add a "SAFETY" comment and remove this `allow`. -#[allow(clippy::undocumented_unsafe_blocks)] -unsafe impl<'a> ByteSlice for &'a [u8] { - // SAFETY: If `&'b [u8]: 'a`, then the underlying memory is treated as - // borrowed immutably for `'a` even if the slice itself is dropped. - const INTO_REF_INTO_MUT_ARE_SOUND: bool = true; - - #[inline] - fn split_at(self, mid: usize) -> (Self, Self) { - <[u8]>::split_at(self, mid) - } -} - -impl<'a> sealed::ByteSliceSealed for &'a mut [u8] {} -// TODO(#429): Add a "SAFETY" comment and remove this `allow`. -#[allow(clippy::undocumented_unsafe_blocks)] -unsafe impl<'a> ByteSlice for &'a mut [u8] { - // SAFETY: If `&'b mut [u8]: 'a`, then the underlying memory is treated as - // borrowed mutably for `'a` even if the slice itself is dropped. - const INTO_REF_INTO_MUT_ARE_SOUND: bool = true; - - #[inline] - fn split_at(self, mid: usize) -> (Self, Self) { - <[u8]>::split_at_mut(self, mid) - } -} - -impl<'a> sealed::ByteSliceSealed for cell::Ref<'a, [u8]> {} -// TODO(#429): Add a "SAFETY" comment and remove this `allow`. -#[allow(clippy::undocumented_unsafe_blocks)] -unsafe impl<'a> ByteSlice for cell::Ref<'a, [u8]> { - const INTO_REF_INTO_MUT_ARE_SOUND: bool = if !cfg!(doc) { - panic!("Ref::into_ref and Ref::into_mut are unsound when used with core::cell::Ref; see https://github.com/google/zerocopy/issues/716") - } else { - // When compiling documentation, allow the evaluation of this constant - // to succeed. This doesn't represent a soundness hole - it just delays - // any error to runtime. The reason we need this is that, otherwise, - // `rustdoc` will fail when trying to document this item. - false - }; - - #[inline] - fn split_at(self, mid: usize) -> (Self, Self) { - cell::Ref::map_split(self, |slice| <[u8]>::split_at(slice, mid)) - } -} - -impl<'a> sealed::ByteSliceSealed for RefMut<'a, [u8]> {} -// TODO(#429): Add a "SAFETY" comment and remove this `allow`. -#[allow(clippy::undocumented_unsafe_blocks)] -unsafe impl<'a> ByteSlice for RefMut<'a, [u8]> { - const INTO_REF_INTO_MUT_ARE_SOUND: bool = if !cfg!(doc) { - panic!("Ref::into_ref and Ref::into_mut are unsound when used with core::cell::RefMut; see https://github.com/google/zerocopy/issues/716") - } else { - // When compiling documentation, allow the evaluation of this constant - // to succeed. This doesn't represent a soundness hole - it just delays - // any error to runtime. The reason we need this is that, otherwise, - // `rustdoc` will fail when trying to document this item. - false - }; - - #[inline] - fn split_at(self, mid: usize) -> (Self, Self) { - RefMut::map_split(self, |slice| <[u8]>::split_at_mut(slice, mid)) - } -} - -// TODO(#429): Add a "SAFETY" comment and remove this `allow`. -#[allow(clippy::undocumented_unsafe_blocks)] -unsafe impl<'a> ByteSliceMut for &'a mut [u8] {} - -// TODO(#429): Add a "SAFETY" comment and remove this `allow`. -#[allow(clippy::undocumented_unsafe_blocks)] -unsafe impl<'a> ByteSliceMut for RefMut<'a, [u8]> {} - -#[cfg(feature = "alloc")] -#[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))] -mod alloc_support { - use alloc::vec::Vec; - - use super::*; - - /// Extends a `Vec<T>` by pushing `additional` new items onto the end of the - /// vector. The new items are initialized with zeroes. - /// - /// # Panics - /// - /// Panics if `Vec::reserve(additional)` fails to reserve enough memory. - #[inline(always)] - pub fn extend_vec_zeroed<T: FromZeroes>(v: &mut Vec<T>, additional: usize) { - insert_vec_zeroed(v, v.len(), additional); - } - - /// Inserts `additional` new items into `Vec<T>` at `position`. - /// The new items are initialized with zeroes. - /// - /// # Panics - /// - /// * Panics if `position > v.len()`. - /// * Panics if `Vec::reserve(additional)` fails to reserve enough memory. - #[inline] - pub fn insert_vec_zeroed<T: FromZeroes>(v: &mut Vec<T>, position: usize, additional: usize) { - assert!(position <= v.len()); - v.reserve(additional); - // SAFETY: The `reserve` call guarantees that these cannot overflow: - // * `ptr.add(position)` - // * `position + additional` - // * `v.len() + additional` - // - // `v.len() - position` cannot overflow because we asserted that - // `position <= v.len()`. - unsafe { - // This is a potentially overlapping copy. - let ptr = v.as_mut_ptr(); - #[allow(clippy::arithmetic_side_effects)] - ptr.add(position).copy_to(ptr.add(position + additional), v.len() - position); - ptr.add(position).write_bytes(0, additional); - #[allow(clippy::arithmetic_side_effects)] - v.set_len(v.len() + additional); - } - } - - #[cfg(test)] - mod tests { - use core::convert::TryFrom as _; - - use super::*; - - #[test] - fn test_extend_vec_zeroed() { - // Test extending when there is an existing allocation. - let mut v = vec![100u64, 200, 300]; - extend_vec_zeroed(&mut v, 3); - assert_eq!(v.len(), 6); - assert_eq!(&*v, &[100, 200, 300, 0, 0, 0]); - drop(v); - - // Test extending when there is no existing allocation. - let mut v: Vec<u64> = Vec::new(); - extend_vec_zeroed(&mut v, 3); - assert_eq!(v.len(), 3); - assert_eq!(&*v, &[0, 0, 0]); - drop(v); - } - - #[test] - fn test_extend_vec_zeroed_zst() { - // Test extending when there is an existing (fake) allocation. - let mut v = vec![(), (), ()]; - extend_vec_zeroed(&mut v, 3); - assert_eq!(v.len(), 6); - assert_eq!(&*v, &[(), (), (), (), (), ()]); - drop(v); - - // Test extending when there is no existing (fake) allocation. - let mut v: Vec<()> = Vec::new(); - extend_vec_zeroed(&mut v, 3); - assert_eq!(&*v, &[(), (), ()]); - drop(v); - } - - #[test] - fn test_insert_vec_zeroed() { - // Insert at start (no existing allocation). - let mut v: Vec<u64> = Vec::new(); - insert_vec_zeroed(&mut v, 0, 2); - assert_eq!(v.len(), 2); - assert_eq!(&*v, &[0, 0]); - drop(v); - - // Insert at start. - let mut v = vec![100u64, 200, 300]; - insert_vec_zeroed(&mut v, 0, 2); - assert_eq!(v.len(), 5); - assert_eq!(&*v, &[0, 0, 100, 200, 300]); - drop(v); - - // Insert at middle. - let mut v = vec![100u64, 200, 300]; - insert_vec_zeroed(&mut v, 1, 1); - assert_eq!(v.len(), 4); - assert_eq!(&*v, &[100, 0, 200, 300]); - drop(v); - - // Insert at end. - let mut v = vec![100u64, 200, 300]; - insert_vec_zeroed(&mut v, 3, 1); - assert_eq!(v.len(), 4); - assert_eq!(&*v, &[100, 200, 300, 0]); - drop(v); - } - - #[test] - fn test_insert_vec_zeroed_zst() { - // Insert at start (no existing fake allocation). - let mut v: Vec<()> = Vec::new(); - insert_vec_zeroed(&mut v, 0, 2); - assert_eq!(v.len(), 2); - assert_eq!(&*v, &[(), ()]); - drop(v); - - // Insert at start. - let mut v = vec![(), (), ()]; - insert_vec_zeroed(&mut v, 0, 2); - assert_eq!(v.len(), 5); - assert_eq!(&*v, &[(), (), (), (), ()]); - drop(v); - - // Insert at middle. - let mut v = vec![(), (), ()]; - insert_vec_zeroed(&mut v, 1, 1); - assert_eq!(v.len(), 4); - assert_eq!(&*v, &[(), (), (), ()]); - drop(v); - - // Insert at end. - let mut v = vec![(), (), ()]; - insert_vec_zeroed(&mut v, 3, 1); - assert_eq!(v.len(), 4); - assert_eq!(&*v, &[(), (), (), ()]); - drop(v); - } - - #[test] - fn test_new_box_zeroed() { - assert_eq!(*u64::new_box_zeroed(), 0); - } - - #[test] - fn test_new_box_zeroed_array() { - drop(<[u32; 0x1000]>::new_box_zeroed()); - } - - #[test] - fn test_new_box_zeroed_zst() { - // This test exists in order to exercise unsafe code, especially - // when running under Miri. - #[allow(clippy::unit_cmp)] - { - assert_eq!(*<()>::new_box_zeroed(), ()); - } - } - - #[test] - fn test_new_box_slice_zeroed() { - let mut s: Box<[u64]> = u64::new_box_slice_zeroed(3); - assert_eq!(s.len(), 3); - assert_eq!(&*s, &[0, 0, 0]); - s[1] = 3; - assert_eq!(&*s, &[0, 3, 0]); - } - - #[test] - fn test_new_box_slice_zeroed_empty() { - let s: Box<[u64]> = u64::new_box_slice_zeroed(0); - assert_eq!(s.len(), 0); - } - - #[test] - fn test_new_box_slice_zeroed_zst() { - let mut s: Box<[()]> = <()>::new_box_slice_zeroed(3); - assert_eq!(s.len(), 3); - assert!(s.get(10).is_none()); - // This test exists in order to exercise unsafe code, especially - // when running under Miri. - #[allow(clippy::unit_cmp)] - { - assert_eq!(s[1], ()); - } - s[2] = (); - } - - #[test] - fn test_new_box_slice_zeroed_zst_empty() { - let s: Box<[()]> = <()>::new_box_slice_zeroed(0); - assert_eq!(s.len(), 0); - } - - #[test] - #[should_panic(expected = "mem::size_of::<Self>() * len overflows `usize`")] - fn test_new_box_slice_zeroed_panics_mul_overflow() { - let _ = u16::new_box_slice_zeroed(usize::MAX); - } - - #[test] - #[should_panic(expected = "assertion failed: size <= max_alloc")] - fn test_new_box_slice_zeroed_panics_isize_overflow() { - let max = usize::try_from(isize::MAX).unwrap(); - let _ = u16::new_box_slice_zeroed((max / mem::size_of::<u16>()) + 1); - } - } -} - -#[cfg(feature = "alloc")] -#[doc(inline)] -pub use alloc_support::*; - -#[cfg(test)] -mod tests { - #![allow(clippy::unreadable_literal)] - - use core::{cell::UnsafeCell, convert::TryInto as _, ops::Deref}; - - use static_assertions::assert_impl_all; - - use super::*; - use crate::util::testutil::*; - - // An unsized type. - // - // This is used to test the custom derives of our traits. The `[u8]` type - // gets a hand-rolled impl, so it doesn't exercise our custom derives. - #[derive(Debug, Eq, PartialEq, FromZeroes, FromBytes, AsBytes, Unaligned)] - #[repr(transparent)] - struct Unsized([u8]); - - impl Unsized { - fn from_mut_slice(slc: &mut [u8]) -> &mut Unsized { - // SAFETY: This *probably* sound - since the layouts of `[u8]` and - // `Unsized` are the same, so are the layouts of `&mut [u8]` and - // `&mut Unsized`. [1] Even if it turns out that this isn't actually - // guaranteed by the language spec, we can just change this since - // it's in test code. - // - // [1] https://github.com/rust-lang/unsafe-code-guidelines/issues/375 - unsafe { mem::transmute(slc) } - } - } - - /// Tests of when a sized `DstLayout` is extended with a sized field. - #[allow(clippy::decimal_literal_representation)] - #[test] - fn test_dst_layout_extend_sized_with_sized() { - // This macro constructs a layout corresponding to a `u8` and extends it - // with a zero-sized trailing field of given alignment `n`. The macro - // tests that the resulting layout has both size and alignment `min(n, - // P)` for all valid values of `repr(packed(P))`. - macro_rules! test_align_is_size { - ($n:expr) => { - let base = DstLayout::for_type::<u8>(); - let trailing_field = DstLayout::for_type::<elain::Align<$n>>(); - - let packs = - core::iter::once(None).chain((0..29).map(|p| NonZeroUsize::new(2usize.pow(p)))); - - for pack in packs { - let composite = base.extend(trailing_field, pack); - let max_align = pack.unwrap_or(DstLayout::CURRENT_MAX_ALIGN); - let align = $n.min(max_align.get()); - assert_eq!( - composite, - DstLayout { - align: NonZeroUsize::new(align).unwrap(), - size_info: SizeInfo::Sized { _size: align } - } - ) - } - }; - } - - test_align_is_size!(1); - test_align_is_size!(2); - test_align_is_size!(4); - test_align_is_size!(8); - test_align_is_size!(16); - test_align_is_size!(32); - test_align_is_size!(64); - test_align_is_size!(128); - test_align_is_size!(256); - test_align_is_size!(512); - test_align_is_size!(1024); - test_align_is_size!(2048); - test_align_is_size!(4096); - test_align_is_size!(8192); - test_align_is_size!(16384); - test_align_is_size!(32768); - test_align_is_size!(65536); - test_align_is_size!(131072); - test_align_is_size!(262144); - test_align_is_size!(524288); - test_align_is_size!(1048576); - test_align_is_size!(2097152); - test_align_is_size!(4194304); - test_align_is_size!(8388608); - test_align_is_size!(16777216); - test_align_is_size!(33554432); - test_align_is_size!(67108864); - test_align_is_size!(33554432); - test_align_is_size!(134217728); - test_align_is_size!(268435456); - } - - /// Tests of when a sized `DstLayout` is extended with a DST field. - #[test] - fn test_dst_layout_extend_sized_with_dst() { - // Test that for all combinations of real-world alignments and - // `repr_packed` values, that the extension of a sized `DstLayout`` with - // a DST field correctly computes the trailing offset in the composite - // layout. - - let aligns = (0..29).map(|p| NonZeroUsize::new(2usize.pow(p)).unwrap()); - let packs = core::iter::once(None).chain(aligns.clone().map(Some)); - - for align in aligns { - for pack in packs.clone() { - let base = DstLayout::for_type::<u8>(); - let elem_size = 42; - let trailing_field_offset = 11; - - let trailing_field = DstLayout { - align, - size_info: SizeInfo::SliceDst(TrailingSliceLayout { - _elem_size: elem_size, - _offset: 11, - }), - }; - - let composite = base.extend(trailing_field, pack); - - let max_align = pack.unwrap_or(DstLayout::CURRENT_MAX_ALIGN).get(); - - let align = align.get().min(max_align); - - assert_eq!( - composite, - DstLayout { - align: NonZeroUsize::new(align).unwrap(), - size_info: SizeInfo::SliceDst(TrailingSliceLayout { - _elem_size: elem_size, - _offset: align + trailing_field_offset, - }), - } - ) - } - } - } - - /// Tests that calling `pad_to_align` on a sized `DstLayout` adds the - /// expected amount of trailing padding. - #[test] - fn test_dst_layout_pad_to_align_with_sized() { - // For all valid alignments `align`, construct a one-byte layout aligned - // to `align`, call `pad_to_align`, and assert that the size of the - // resulting layout is equal to `align`. - for align in (0..29).map(|p| NonZeroUsize::new(2usize.pow(p)).unwrap()) { - let layout = DstLayout { align, size_info: SizeInfo::Sized { _size: 1 } }; - - assert_eq!( - layout.pad_to_align(), - DstLayout { align, size_info: SizeInfo::Sized { _size: align.get() } } - ); - } - - // Test explicitly-provided combinations of unpadded and padded - // counterparts. - - macro_rules! test { - (unpadded { size: $unpadded_size:expr, align: $unpadded_align:expr } - => padded { size: $padded_size:expr, align: $padded_align:expr }) => { - let unpadded = DstLayout { - align: NonZeroUsize::new($unpadded_align).unwrap(), - size_info: SizeInfo::Sized { _size: $unpadded_size }, - }; - let padded = unpadded.pad_to_align(); - - assert_eq!( - padded, - DstLayout { - align: NonZeroUsize::new($padded_align).unwrap(), - size_info: SizeInfo::Sized { _size: $padded_size }, - } - ); - }; - } - - test!(unpadded { size: 0, align: 4 } => padded { size: 0, align: 4 }); - test!(unpadded { size: 1, align: 4 } => padded { size: 4, align: 4 }); - test!(unpadded { size: 2, align: 4 } => padded { size: 4, align: 4 }); - test!(unpadded { size: 3, align: 4 } => padded { size: 4, align: 4 }); - test!(unpadded { size: 4, align: 4 } => padded { size: 4, align: 4 }); - test!(unpadded { size: 5, align: 4 } => padded { size: 8, align: 4 }); - test!(unpadded { size: 6, align: 4 } => padded { size: 8, align: 4 }); - test!(unpadded { size: 7, align: 4 } => padded { size: 8, align: 4 }); - test!(unpadded { size: 8, align: 4 } => padded { size: 8, align: 4 }); - - let current_max_align = DstLayout::CURRENT_MAX_ALIGN.get(); - - test!(unpadded { size: 1, align: current_max_align } - => padded { size: current_max_align, align: current_max_align }); - - test!(unpadded { size: current_max_align + 1, align: current_max_align } - => padded { size: current_max_align * 2, align: current_max_align }); - } - - /// Tests that calling `pad_to_align` on a DST `DstLayout` is a no-op. - #[test] - fn test_dst_layout_pad_to_align_with_dst() { - for align in (0..29).map(|p| NonZeroUsize::new(2usize.pow(p)).unwrap()) { - for offset in 0..10 { - for elem_size in 0..10 { - let layout = DstLayout { - align, - size_info: SizeInfo::SliceDst(TrailingSliceLayout { - _offset: offset, - _elem_size: elem_size, - }), - }; - assert_eq!(layout.pad_to_align(), layout); - } - } - } - } - - // This test takes a long time when running under Miri, so we skip it in - // that case. This is acceptable because this is a logic test that doesn't - // attempt to expose UB. - #[test] - #[cfg_attr(miri, ignore)] - fn testvalidate_cast_and_convert_metadata() { - impl From<usize> for SizeInfo { - fn from(_size: usize) -> SizeInfo { - SizeInfo::Sized { _size } - } - } - - impl From<(usize, usize)> for SizeInfo { - fn from((_offset, _elem_size): (usize, usize)) -> SizeInfo { - SizeInfo::SliceDst(TrailingSliceLayout { _offset, _elem_size }) - } - } - - fn layout<S: Into<SizeInfo>>(s: S, align: usize) -> DstLayout { - DstLayout { size_info: s.into(), align: NonZeroUsize::new(align).unwrap() } - } - - /// This macro accepts arguments in the form of: - /// - /// layout(_, _, _).validate(_, _, _), Ok(Some((_, _))) - /// | | | | | | | | - /// base_size ----+ | | | | | | | - /// align -----------+ | | | | | | - /// trailing_size ------+ | | | | | - /// addr ---------------------------+ | | | | - /// bytes_len -------------------------+ | | | - /// cast_type ----------------------------+ | | - /// elems ---------------------------------------------+ | - /// split_at ---------------------------------------------+ - /// - /// `.validate` is shorthand for `.validate_cast_and_convert_metadata` - /// for brevity. - /// - /// Each argument can either be an iterator or a wildcard. Each - /// wildcarded variable is implicitly replaced by an iterator over a - /// representative sample of values for that variable. Each `test!` - /// invocation iterates over every combination of values provided by - /// each variable's iterator (ie, the cartesian product) and validates - /// that the results are expected. - /// - /// The final argument uses the same syntax, but it has a different - /// meaning: - /// - If it is `Ok(pat)`, then the pattern `pat` is supplied to - /// `assert_matches!` to validate the computed result for each - /// combination of input values. - /// - If it is `Err(msg)`, then `test!` validates that the call to - /// `validate_cast_and_convert_metadata` panics with the given panic - /// message. - /// - /// Note that the meta-variables that match these variables have the - /// `tt` type, and some valid expressions are not valid `tt`s (such as - /// `a..b`). In this case, wrap the expression in parentheses, and it - /// will become valid `tt`. - macro_rules! test { - ($(:$sizes:expr =>)? - layout($size:tt, $align:tt) - .validate($addr:tt, $bytes_len:tt, $cast_type:tt), $expect:pat $(,)? - ) => { - itertools::iproduct!( - test!(@generate_size $size), - test!(@generate_align $align), - test!(@generate_usize $addr), - test!(@generate_usize $bytes_len), - test!(@generate_cast_type $cast_type) - ).for_each(|(size_info, align, addr, bytes_len, cast_type)| { - // Temporarily disable the panic hook installed by the test - // harness. If we don't do this, all panic messages will be - // kept in an internal log. On its own, this isn't a - // problem, but if a non-caught panic ever happens (ie, in - // code later in this test not in this macro), all of the - // previously-buffered messages will be dumped, hiding the - // real culprit. - let previous_hook = std::panic::take_hook(); - // I don't understand why, but this seems to be required in - // addition to the previous line. - std::panic::set_hook(Box::new(|_| {})); - let actual = std::panic::catch_unwind(|| { - layout(size_info, align).validate_cast_and_convert_metadata(addr, bytes_len, cast_type) - }).map_err(|d| { - *d.downcast::<&'static str>().expect("expected string panic message").as_ref() - }); - std::panic::set_hook(previous_hook); - - assert_matches::assert_matches!( - actual, $expect, - "layout({size_info:?}, {align}).validate_cast_and_convert_metadata({addr}, {bytes_len}, {cast_type:?})", - ); - }); - }; - (@generate_usize _) => { 0..8 }; - // Generate sizes for both Sized and !Sized types. - (@generate_size _) => { - test!(@generate_size (_)).chain(test!(@generate_size (_, _))) - }; - // Generate sizes for both Sized and !Sized types by chaining - // specified iterators for each. - (@generate_size ($sized_sizes:tt | $unsized_sizes:tt)) => { - test!(@generate_size ($sized_sizes)).chain(test!(@generate_size $unsized_sizes)) - }; - // Generate sizes for Sized types. - (@generate_size (_)) => { test!(@generate_size (0..8)) }; - (@generate_size ($sizes:expr)) => { $sizes.into_iter().map(Into::<SizeInfo>::into) }; - // Generate sizes for !Sized types. - (@generate_size ($min_sizes:tt, $elem_sizes:tt)) => { - itertools::iproduct!( - test!(@generate_min_size $min_sizes), - test!(@generate_elem_size $elem_sizes) - ).map(Into::<SizeInfo>::into) - }; - (@generate_fixed_size _) => { (0..8).into_iter().map(Into::<SizeInfo>::into) }; - (@generate_min_size _) => { 0..8 }; - (@generate_elem_size _) => { 1..8 }; - (@generate_align _) => { [1, 2, 4, 8, 16] }; - (@generate_opt_usize _) => { [None].into_iter().chain((0..8).map(Some).into_iter()) }; - (@generate_cast_type _) => { [_CastType::_Prefix, _CastType::_Suffix] }; - (@generate_cast_type $variant:ident) => { [_CastType::$variant] }; - // Some expressions need to be wrapped in parentheses in order to be - // valid `tt`s (required by the top match pattern). See the comment - // below for more details. This arm removes these parentheses to - // avoid generating an `unused_parens` warning. - (@$_:ident ($vals:expr)) => { $vals }; - (@$_:ident $vals:expr) => { $vals }; - } - - const EVENS: [usize; 8] = [0, 2, 4, 6, 8, 10, 12, 14]; - const ODDS: [usize; 8] = [1, 3, 5, 7, 9, 11, 13, 15]; - - // base_size is too big for the memory region. - test!(layout(((1..8) | ((1..8), (1..8))), _).validate(_, [0], _), Ok(None)); - test!(layout(((2..8) | ((2..8), (2..8))), _).validate(_, [1], _), Ok(None)); - - // addr is unaligned for prefix cast - test!(layout(_, [2]).validate(ODDS, _, _Prefix), Ok(None)); - test!(layout(_, [2]).validate(ODDS, _, _Prefix), Ok(None)); - - // addr is aligned, but end of buffer is unaligned for suffix cast - test!(layout(_, [2]).validate(EVENS, ODDS, _Suffix), Ok(None)); - test!(layout(_, [2]).validate(EVENS, ODDS, _Suffix), Ok(None)); - - // Unfortunately, these constants cannot easily be used in the - // implementation of `validate_cast_and_convert_metadata`, since - // `panic!` consumes a string literal, not an expression. - // - // It's important that these messages be in a separate module. If they - // were at the function's top level, we'd pass them to `test!` as, e.g., - // `Err(TRAILING)`, which would run into a subtle Rust footgun - the - // `TRAILING` identifier would be treated as a pattern to match rather - // than a value to check for equality. - mod msgs { - pub(super) const TRAILING: &str = - "attempted to cast to slice type with zero-sized element"; - pub(super) const OVERFLOW: &str = "`addr` + `bytes_len` > usize::MAX"; - } - - // casts with ZST trailing element types are unsupported - test!(layout((_, [0]), _).validate(_, _, _), Err(msgs::TRAILING),); - - // addr + bytes_len must not overflow usize - test!(layout(_, _).validate([usize::MAX], (1..100), _), Err(msgs::OVERFLOW)); - test!(layout(_, _).validate((1..100), [usize::MAX], _), Err(msgs::OVERFLOW)); - test!( - layout(_, _).validate( - [usize::MAX / 2 + 1, usize::MAX], - [usize::MAX / 2 + 1, usize::MAX], - _ - ), - Err(msgs::OVERFLOW) - ); - - // Validates that `validate_cast_and_convert_metadata` satisfies its own - // documented safety postconditions, and also a few other properties - // that aren't documented but we want to guarantee anyway. - fn validate_behavior( - (layout, addr, bytes_len, cast_type): (DstLayout, usize, usize, _CastType), - ) { - if let Some((elems, split_at)) = - layout.validate_cast_and_convert_metadata(addr, bytes_len, cast_type) - { - let (size_info, align) = (layout.size_info, layout.align); - let debug_str = format!( - "layout({size_info:?}, {align}).validate_cast_and_convert_metadata({addr}, {bytes_len}, {cast_type:?}) => ({elems}, {split_at})", - ); - - // If this is a sized type (no trailing slice), then `elems` is - // meaningless, but in practice we set it to 0. Callers are not - // allowed to rely on this, but a lot of math is nicer if - // they're able to, and some callers might accidentally do that. - let sized = matches!(layout.size_info, SizeInfo::Sized { .. }); - assert!(!(sized && elems != 0), "{}", debug_str); - - let resulting_size = match layout.size_info { - SizeInfo::Sized { _size } => _size, - SizeInfo::SliceDst(TrailingSliceLayout { - _offset: offset, - _elem_size: elem_size, - }) => { - let padded_size = |elems| { - let without_padding = offset + elems * elem_size; - without_padding - + util::core_layout::padding_needed_for(without_padding, align) - }; - - let resulting_size = padded_size(elems); - // Test that `validate_cast_and_convert_metadata` - // computed the largest possible value that fits in the - // given range. - assert!(padded_size(elems + 1) > bytes_len, "{}", debug_str); - resulting_size - } - }; - - // Test safety postconditions guaranteed by - // `validate_cast_and_convert_metadata`. - assert!(resulting_size <= bytes_len, "{}", debug_str); - match cast_type { - _CastType::_Prefix => { - assert_eq!(addr % align, 0, "{}", debug_str); - assert_eq!(resulting_size, split_at, "{}", debug_str); - } - _CastType::_Suffix => { - assert_eq!(split_at, bytes_len - resulting_size, "{}", debug_str); - assert_eq!((addr + split_at) % align, 0, "{}", debug_str); - } - } - } else { - let min_size = match layout.size_info { - SizeInfo::Sized { _size } => _size, - SizeInfo::SliceDst(TrailingSliceLayout { _offset, .. }) => { - _offset + util::core_layout::padding_needed_for(_offset, layout.align) - } - }; - - // If a cast is invalid, it is either because... - // 1. there are insufficent bytes at the given region for type: - let insufficient_bytes = bytes_len < min_size; - // 2. performing the cast would misalign type: - let base = match cast_type { - _CastType::_Prefix => 0, - _CastType::_Suffix => bytes_len, - }; - let misaligned = (base + addr) % layout.align != 0; - - assert!(insufficient_bytes || misaligned); - } - } - - let sizes = 0..8; - let elem_sizes = 1..8; - let size_infos = sizes - .clone() - .map(Into::<SizeInfo>::into) - .chain(itertools::iproduct!(sizes, elem_sizes).map(Into::<SizeInfo>::into)); - let layouts = itertools::iproduct!(size_infos, [1, 2, 4, 8, 16, 32]) - .filter(|(size_info, align)| !matches!(size_info, SizeInfo::Sized { _size } if _size % align != 0)) - .map(|(size_info, align)| layout(size_info, align)); - itertools::iproduct!(layouts, 0..8, 0..8, [_CastType::_Prefix, _CastType::_Suffix]) - .for_each(validate_behavior); - } - - #[test] - #[cfg(__INTERNAL_USE_ONLY_NIGHLTY_FEATURES_IN_TESTS)] - fn test_validate_rust_layout() { - use core::ptr::NonNull; - - // This test synthesizes pointers with various metadata and uses Rust's - // built-in APIs to confirm that Rust makes decisions about type layout - // which are consistent with what we believe is guaranteed by the - // language. If this test fails, it doesn't just mean our code is wrong - // - it means we're misunderstanding the language's guarantees. - - #[derive(Debug)] - struct MacroArgs { - offset: usize, - align: NonZeroUsize, - elem_size: Option<usize>, - } - - /// # Safety - /// - /// `test` promises to only call `addr_of_slice_field` on a `NonNull<T>` - /// which points to a valid `T`. - /// - /// `with_elems` must produce a pointer which points to a valid `T`. - fn test<T: ?Sized, W: Fn(usize) -> NonNull<T>>( - args: MacroArgs, - with_elems: W, - addr_of_slice_field: Option<fn(NonNull<T>) -> NonNull<u8>>, - ) { - let dst = args.elem_size.is_some(); - let layout = { - let size_info = match args.elem_size { - Some(elem_size) => SizeInfo::SliceDst(TrailingSliceLayout { - _offset: args.offset, - _elem_size: elem_size, - }), - None => SizeInfo::Sized { - // Rust only supports types whose sizes are a multiple - // of their alignment. If the macro created a type like - // this: - // - // #[repr(C, align(2))] - // struct Foo([u8; 1]); - // - // ...then Rust will automatically round the type's size - // up to 2. - _size: args.offset - + util::core_layout::padding_needed_for(args.offset, args.align), - }, - }; - DstLayout { size_info, align: args.align } - }; - - for elems in 0..128 { - let ptr = with_elems(elems); - - if let Some(addr_of_slice_field) = addr_of_slice_field { - let slc_field_ptr = addr_of_slice_field(ptr).as_ptr(); - // SAFETY: Both `slc_field_ptr` and `ptr` are pointers to - // the same valid Rust object. - let offset: usize = - unsafe { slc_field_ptr.byte_offset_from(ptr.as_ptr()).try_into().unwrap() }; - assert_eq!(offset, args.offset); - } - - // SAFETY: `ptr` points to a valid `T`. - let (size, align) = unsafe { - (mem::size_of_val_raw(ptr.as_ptr()), mem::align_of_val_raw(ptr.as_ptr())) - }; - - // Avoid expensive allocation when running under Miri. - let assert_msg = if !cfg!(miri) { - format!("\n{args:?}\nsize:{size}, align:{align}") - } else { - String::new() - }; - - let without_padding = - args.offset + args.elem_size.map(|elem_size| elems * elem_size).unwrap_or(0); - assert!(size >= without_padding, "{}", assert_msg); - assert_eq!(align, args.align.get(), "{}", assert_msg); - - // This encodes the most important part of the test: our - // understanding of how Rust determines the layout of repr(C) - // types. Sized repr(C) types are trivial, but DST types have - // some subtlety. Note that: - // - For sized types, `without_padding` is just the size of the - // type that we constructed for `Foo`. Since we may have - // requested a larger alignment, `Foo` may actually be larger - // than this, hence `padding_needed_for`. - // - For unsized types, `without_padding` is dynamically - // computed from the offset, the element size, and element - // count. We expect that the size of the object should be - // `offset + elem_size * elems` rounded up to the next - // alignment. - let expected_size = without_padding - + util::core_layout::padding_needed_for(without_padding, args.align); - assert_eq!(expected_size, size, "{}", assert_msg); - - // For zero-sized element types, - // `validate_cast_and_convert_metadata` just panics, so we skip - // testing those types. - if args.elem_size.map(|elem_size| elem_size > 0).unwrap_or(true) { - let addr = ptr.addr().get(); - let (got_elems, got_split_at) = layout - .validate_cast_and_convert_metadata(addr, size, _CastType::_Prefix) - .unwrap(); - // Avoid expensive allocation when running under Miri. - let assert_msg = if !cfg!(miri) { - format!( - "{}\nvalidate_cast_and_convert_metadata({addr}, {size})", - assert_msg - ) - } else { - String::new() - }; - assert_eq!(got_split_at, size, "{}", assert_msg); - if dst { - assert!(got_elems >= elems, "{}", assert_msg); - if got_elems != elems { - // If `validate_cast_and_convert_metadata` - // returned more elements than `elems`, that - // means that `elems` is not the maximum number - // of elements that can fit in `size` - in other - // words, there is enough padding at the end of - // the value to fit at least one more element. - // If we use this metadata to synthesize a - // pointer, despite having a different element - // count, we still expect it to have the same - // size. - let got_ptr = with_elems(got_elems); - // SAFETY: `got_ptr` is a pointer to a valid `T`. - let size_of_got_ptr = unsafe { mem::size_of_val_raw(got_ptr.as_ptr()) }; - assert_eq!(size_of_got_ptr, size, "{}", assert_msg); - } - } else { - // For sized casts, the returned element value is - // technically meaningless, and we don't guarantee any - // particular value. In practice, it's always zero. - assert_eq!(got_elems, 0, "{}", assert_msg) - } - } - } - } - - macro_rules! validate_against_rust { - ($offset:literal, $align:literal $(, $elem_size:literal)?) => {{ - #[repr(C, align($align))] - struct Foo([u8; $offset]$(, [[u8; $elem_size]])?); - - let args = MacroArgs { - offset: $offset, - align: $align.try_into().unwrap(), - elem_size: { - #[allow(unused)] - let ret = None::<usize>; - $(let ret = Some($elem_size);)? - ret - } - }; - - #[repr(C, align($align))] - struct FooAlign; - // Create an aligned buffer to use in order to synthesize - // pointers to `Foo`. We don't ever load values from these - // pointers - we just do arithmetic on them - so having a "real" - // block of memory as opposed to a validly-aligned-but-dangling - // pointer is only necessary to make Miri happy since we run it - // with "strict provenance" checking enabled. - let aligned_buf = Align::<_, FooAlign>::new([0u8; 1024]); - let with_elems = |elems| { - let slc = NonNull::slice_from_raw_parts(NonNull::from(&aligned_buf.t), elems); - #[allow(clippy::as_conversions)] - NonNull::new(slc.as_ptr() as *mut Foo).unwrap() - }; - let addr_of_slice_field = { - #[allow(unused)] - let f = None::<fn(NonNull<Foo>) -> NonNull<u8>>; - $( - // SAFETY: `test` promises to only call `f` with a `ptr` - // to a valid `Foo`. - let f: Option<fn(NonNull<Foo>) -> NonNull<u8>> = Some(|ptr: NonNull<Foo>| unsafe { - NonNull::new(ptr::addr_of_mut!((*ptr.as_ptr()).1)).unwrap().cast::<u8>() - }); - let _ = $elem_size; - )? - f - }; - - test::<Foo, _>(args, with_elems, addr_of_slice_field); - }}; - } - - // Every permutation of: - // - offset in [0, 4] - // - align in [1, 16] - // - elem_size in [0, 4] (plus no elem_size) - validate_against_rust!(0, 1); - validate_against_rust!(0, 1, 0); - validate_against_rust!(0, 1, 1); - validate_against_rust!(0, 1, 2); - validate_against_rust!(0, 1, 3); - validate_against_rust!(0, 1, 4); - validate_against_rust!(0, 2); - validate_against_rust!(0, 2, 0); - validate_against_rust!(0, 2, 1); - validate_against_rust!(0, 2, 2); - validate_against_rust!(0, 2, 3); - validate_against_rust!(0, 2, 4); - validate_against_rust!(0, 4); - validate_against_rust!(0, 4, 0); - validate_against_rust!(0, 4, 1); - validate_against_rust!(0, 4, 2); - validate_against_rust!(0, 4, 3); - validate_against_rust!(0, 4, 4); - validate_against_rust!(0, 8); - validate_against_rust!(0, 8, 0); - validate_against_rust!(0, 8, 1); - validate_against_rust!(0, 8, 2); - validate_against_rust!(0, 8, 3); - validate_against_rust!(0, 8, 4); - validate_against_rust!(0, 16); - validate_against_rust!(0, 16, 0); - validate_against_rust!(0, 16, 1); - validate_against_rust!(0, 16, 2); - validate_against_rust!(0, 16, 3); - validate_against_rust!(0, 16, 4); - validate_against_rust!(1, 1); - validate_against_rust!(1, 1, 0); - validate_against_rust!(1, 1, 1); - validate_against_rust!(1, 1, 2); - validate_against_rust!(1, 1, 3); - validate_against_rust!(1, 1, 4); - validate_against_rust!(1, 2); - validate_against_rust!(1, 2, 0); - validate_against_rust!(1, 2, 1); - validate_against_rust!(1, 2, 2); - validate_against_rust!(1, 2, 3); - validate_against_rust!(1, 2, 4); - validate_against_rust!(1, 4); - validate_against_rust!(1, 4, 0); - validate_against_rust!(1, 4, 1); - validate_against_rust!(1, 4, 2); - validate_against_rust!(1, 4, 3); - validate_against_rust!(1, 4, 4); - validate_against_rust!(1, 8); - validate_against_rust!(1, 8, 0); - validate_against_rust!(1, 8, 1); - validate_against_rust!(1, 8, 2); - validate_against_rust!(1, 8, 3); - validate_against_rust!(1, 8, 4); - validate_against_rust!(1, 16); - validate_against_rust!(1, 16, 0); - validate_against_rust!(1, 16, 1); - validate_against_rust!(1, 16, 2); - validate_against_rust!(1, 16, 3); - validate_against_rust!(1, 16, 4); - validate_against_rust!(2, 1); - validate_against_rust!(2, 1, 0); - validate_against_rust!(2, 1, 1); - validate_against_rust!(2, 1, 2); - validate_against_rust!(2, 1, 3); - validate_against_rust!(2, 1, 4); - validate_against_rust!(2, 2); - validate_against_rust!(2, 2, 0); - validate_against_rust!(2, 2, 1); - validate_against_rust!(2, 2, 2); - validate_against_rust!(2, 2, 3); - validate_against_rust!(2, 2, 4); - validate_against_rust!(2, 4); - validate_against_rust!(2, 4, 0); - validate_against_rust!(2, 4, 1); - validate_against_rust!(2, 4, 2); - validate_against_rust!(2, 4, 3); - validate_against_rust!(2, 4, 4); - validate_against_rust!(2, 8); - validate_against_rust!(2, 8, 0); - validate_against_rust!(2, 8, 1); - validate_against_rust!(2, 8, 2); - validate_against_rust!(2, 8, 3); - validate_against_rust!(2, 8, 4); - validate_against_rust!(2, 16); - validate_against_rust!(2, 16, 0); - validate_against_rust!(2, 16, 1); - validate_against_rust!(2, 16, 2); - validate_against_rust!(2, 16, 3); - validate_against_rust!(2, 16, 4); - validate_against_rust!(3, 1); - validate_against_rust!(3, 1, 0); - validate_against_rust!(3, 1, 1); - validate_against_rust!(3, 1, 2); - validate_against_rust!(3, 1, 3); - validate_against_rust!(3, 1, 4); - validate_against_rust!(3, 2); - validate_against_rust!(3, 2, 0); - validate_against_rust!(3, 2, 1); - validate_against_rust!(3, 2, 2); - validate_against_rust!(3, 2, 3); - validate_against_rust!(3, 2, 4); - validate_against_rust!(3, 4); - validate_against_rust!(3, 4, 0); - validate_against_rust!(3, 4, 1); - validate_against_rust!(3, 4, 2); - validate_against_rust!(3, 4, 3); - validate_against_rust!(3, 4, 4); - validate_against_rust!(3, 8); - validate_against_rust!(3, 8, 0); - validate_against_rust!(3, 8, 1); - validate_against_rust!(3, 8, 2); - validate_against_rust!(3, 8, 3); - validate_against_rust!(3, 8, 4); - validate_against_rust!(3, 16); - validate_against_rust!(3, 16, 0); - validate_against_rust!(3, 16, 1); - validate_against_rust!(3, 16, 2); - validate_against_rust!(3, 16, 3); - validate_against_rust!(3, 16, 4); - validate_against_rust!(4, 1); - validate_against_rust!(4, 1, 0); - validate_against_rust!(4, 1, 1); - validate_against_rust!(4, 1, 2); - validate_against_rust!(4, 1, 3); - validate_against_rust!(4, 1, 4); - validate_against_rust!(4, 2); - validate_against_rust!(4, 2, 0); - validate_against_rust!(4, 2, 1); - validate_against_rust!(4, 2, 2); - validate_against_rust!(4, 2, 3); - validate_against_rust!(4, 2, 4); - validate_against_rust!(4, 4); - validate_against_rust!(4, 4, 0); - validate_against_rust!(4, 4, 1); - validate_against_rust!(4, 4, 2); - validate_against_rust!(4, 4, 3); - validate_against_rust!(4, 4, 4); - validate_against_rust!(4, 8); - validate_against_rust!(4, 8, 0); - validate_against_rust!(4, 8, 1); - validate_against_rust!(4, 8, 2); - validate_against_rust!(4, 8, 3); - validate_against_rust!(4, 8, 4); - validate_against_rust!(4, 16); - validate_against_rust!(4, 16, 0); - validate_against_rust!(4, 16, 1); - validate_against_rust!(4, 16, 2); - validate_against_rust!(4, 16, 3); - validate_against_rust!(4, 16, 4); - } - - #[test] - fn test_known_layout() { - // Test that `$ty` and `ManuallyDrop<$ty>` have the expected layout. - // Test that `PhantomData<$ty>` has the same layout as `()` regardless - // of `$ty`. - macro_rules! test { - ($ty:ty, $expect:expr) => { - let expect = $expect; - assert_eq!(<$ty as KnownLayout>::LAYOUT, expect); - assert_eq!(<ManuallyDrop<$ty> as KnownLayout>::LAYOUT, expect); - assert_eq!(<PhantomData<$ty> as KnownLayout>::LAYOUT, <() as KnownLayout>::LAYOUT); - }; - } - - let layout = |offset, align, _trailing_slice_elem_size| DstLayout { - align: NonZeroUsize::new(align).unwrap(), - size_info: match _trailing_slice_elem_size { - None => SizeInfo::Sized { _size: offset }, - Some(elem_size) => SizeInfo::SliceDst(TrailingSliceLayout { - _offset: offset, - _elem_size: elem_size, - }), - }, - }; - - test!((), layout(0, 1, None)); - test!(u8, layout(1, 1, None)); - // Use `align_of` because `u64` alignment may be smaller than 8 on some - // platforms. - test!(u64, layout(8, mem::align_of::<u64>(), None)); - test!(AU64, layout(8, 8, None)); - - test!(Option<&'static ()>, usize::LAYOUT); - - test!([()], layout(0, 1, Some(0))); - test!([u8], layout(0, 1, Some(1))); - test!(str, layout(0, 1, Some(1))); - } - - #[cfg(feature = "derive")] - #[test] - fn test_known_layout_derive() { - // In this and other files (`late_compile_pass.rs`, - // `mid_compile_pass.rs`, and `struct.rs`), we test success and failure - // modes of `derive(KnownLayout)` for the following combination of - // properties: - // - // +------------+--------------------------------------+-----------+ - // | | trailing field properties | | - // | `repr(C)`? | generic? | `KnownLayout`? | `Sized`? | Type Name | - // |------------+----------+----------------+----------+-----------| - // | N | N | N | N | KL00 | - // | N | N | N | Y | KL01 | - // | N | N | Y | N | KL02 | - // | N | N | Y | Y | KL03 | - // | N | Y | N | N | KL04 | - // | N | Y | N | Y | KL05 | - // | N | Y | Y | N | KL06 | - // | N | Y | Y | Y | KL07 | - // | Y | N | N | N | KL08 | - // | Y | N | N | Y | KL09 | - // | Y | N | Y | N | KL10 | - // | Y | N | Y | Y | KL11 | - // | Y | Y | N | N | KL12 | - // | Y | Y | N | Y | KL13 | - // | Y | Y | Y | N | KL14 | - // | Y | Y | Y | Y | KL15 | - // +------------+----------+----------------+----------+-----------+ - - struct NotKnownLayout<T = ()> { - _t: T, - } - - #[derive(KnownLayout)] - #[repr(C)] - struct AlignSize<const ALIGN: usize, const SIZE: usize> - where - elain::Align<ALIGN>: elain::Alignment, - { - _align: elain::Align<ALIGN>, - _size: [u8; SIZE], - } - - type AU16 = AlignSize<2, 2>; - type AU32 = AlignSize<4, 4>; - - fn _assert_kl<T: ?Sized + KnownLayout>(_: &T) {} - - let sized_layout = |align, size| DstLayout { - align: NonZeroUsize::new(align).unwrap(), - size_info: SizeInfo::Sized { _size: size }, - }; - - let unsized_layout = |align, elem_size, offset| DstLayout { - align: NonZeroUsize::new(align).unwrap(), - size_info: SizeInfo::SliceDst(TrailingSliceLayout { - _offset: offset, - _elem_size: elem_size, - }), - }; - - // | `repr(C)`? | generic? | `KnownLayout`? | `Sized`? | Type Name | - // | N | N | N | Y | KL01 | - #[derive(KnownLayout)] - #[allow(dead_code)] // fields are never read - struct KL01(NotKnownLayout<AU32>, NotKnownLayout<AU16>); - - let expected = DstLayout::for_type::<KL01>(); - - assert_eq!(<KL01 as KnownLayout>::LAYOUT, expected); - assert_eq!(<KL01 as KnownLayout>::LAYOUT, sized_layout(4, 8)); - - // ...with `align(N)`: - #[derive(KnownLayout)] - #[repr(align(64))] - #[allow(dead_code)] // fields are never read - struct KL01Align(NotKnownLayout<AU32>, NotKnownLayout<AU16>); - - let expected = DstLayout::for_type::<KL01Align>(); - - assert_eq!(<KL01Align as KnownLayout>::LAYOUT, expected); - assert_eq!(<KL01Align as KnownLayout>::LAYOUT, sized_layout(64, 64)); - - // ...with `packed`: - #[derive(KnownLayout)] - #[repr(packed)] - #[allow(dead_code)] // fields are never read - struct KL01Packed(NotKnownLayout<AU32>, NotKnownLayout<AU16>); - - let expected = DstLayout::for_type::<KL01Packed>(); - - assert_eq!(<KL01Packed as KnownLayout>::LAYOUT, expected); - assert_eq!(<KL01Packed as KnownLayout>::LAYOUT, sized_layout(1, 6)); - - // ...with `packed(N)`: - #[derive(KnownLayout)] - #[repr(packed(2))] - #[allow(dead_code)] // fields are never read - struct KL01PackedN(NotKnownLayout<AU32>, NotKnownLayout<AU16>); - - assert_impl_all!(KL01PackedN: KnownLayout); - - let expected = DstLayout::for_type::<KL01PackedN>(); - - assert_eq!(<KL01PackedN as KnownLayout>::LAYOUT, expected); - assert_eq!(<KL01PackedN as KnownLayout>::LAYOUT, sized_layout(2, 6)); - - // | `repr(C)`? | generic? | `KnownLayout`? | `Sized`? | Type Name | - // | N | N | Y | Y | KL03 | - #[derive(KnownLayout)] - #[allow(dead_code)] // fields are never read - struct KL03(NotKnownLayout, u8); - - let expected = DstLayout::for_type::<KL03>(); - - assert_eq!(<KL03 as KnownLayout>::LAYOUT, expected); - assert_eq!(<KL03 as KnownLayout>::LAYOUT, sized_layout(1, 1)); - - // ... with `align(N)` - #[derive(KnownLayout)] - #[repr(align(64))] - #[allow(dead_code)] // fields are never read - struct KL03Align(NotKnownLayout<AU32>, u8); - - let expected = DstLayout::for_type::<KL03Align>(); - - assert_eq!(<KL03Align as KnownLayout>::LAYOUT, expected); - assert_eq!(<KL03Align as KnownLayout>::LAYOUT, sized_layout(64, 64)); - - // ... with `packed`: - #[derive(KnownLayout)] - #[repr(packed)] - #[allow(dead_code)] // fields are never read - struct KL03Packed(NotKnownLayout<AU32>, u8); - - let expected = DstLayout::for_type::<KL03Packed>(); - - assert_eq!(<KL03Packed as KnownLayout>::LAYOUT, expected); - assert_eq!(<KL03Packed as KnownLayout>::LAYOUT, sized_layout(1, 5)); - - // ... with `packed(N)` - #[derive(KnownLayout)] - #[repr(packed(2))] - #[allow(dead_code)] // fields are never read - struct KL03PackedN(NotKnownLayout<AU32>, u8); - - assert_impl_all!(KL03PackedN: KnownLayout); - - let expected = DstLayout::for_type::<KL03PackedN>(); - - assert_eq!(<KL03PackedN as KnownLayout>::LAYOUT, expected); - assert_eq!(<KL03PackedN as KnownLayout>::LAYOUT, sized_layout(2, 6)); - - // | `repr(C)`? | generic? | `KnownLayout`? | `Sized`? | Type Name | - // | N | Y | N | Y | KL05 | - #[derive(KnownLayout)] - #[allow(dead_code)] // fields are never read - struct KL05<T>(u8, T); - - fn _test_kl05<T>(t: T) -> impl KnownLayout { - KL05(0u8, t) - } - - // | `repr(C)`? | generic? | `KnownLayout`? | `Sized`? | Type Name | - // | N | Y | Y | Y | KL07 | - #[derive(KnownLayout)] - #[allow(dead_code)] // fields are never read - struct KL07<T: KnownLayout>(u8, T); - - fn _test_kl07<T: KnownLayout>(t: T) -> impl KnownLayout { - let _ = KL07(0u8, t); - } - - // | `repr(C)`? | generic? | `KnownLayout`? | `Sized`? | Type Name | - // | Y | N | Y | N | KL10 | - #[derive(KnownLayout)] - #[repr(C)] - struct KL10(NotKnownLayout<AU32>, [u8]); - - let expected = DstLayout::new_zst(None) - .extend(DstLayout::for_type::<NotKnownLayout<AU32>>(), None) - .extend(<[u8] as KnownLayout>::LAYOUT, None) - .pad_to_align(); - - assert_eq!(<KL10 as KnownLayout>::LAYOUT, expected); - assert_eq!(<KL10 as KnownLayout>::LAYOUT, unsized_layout(4, 1, 4)); - - // ...with `align(N)`: - #[derive(KnownLayout)] - #[repr(C, align(64))] - struct KL10Align(NotKnownLayout<AU32>, [u8]); - - let repr_align = NonZeroUsize::new(64); - - let expected = DstLayout::new_zst(repr_align) - .extend(DstLayout::for_type::<NotKnownLayout<AU32>>(), None) - .extend(<[u8] as KnownLayout>::LAYOUT, None) - .pad_to_align(); - - assert_eq!(<KL10Align as KnownLayout>::LAYOUT, expected); - assert_eq!(<KL10Align as KnownLayout>::LAYOUT, unsized_layout(64, 1, 4)); - - // ...with `packed`: - #[derive(KnownLayout)] - #[repr(C, packed)] - struct KL10Packed(NotKnownLayout<AU32>, [u8]); - - let repr_packed = NonZeroUsize::new(1); - - let expected = DstLayout::new_zst(None) - .extend(DstLayout::for_type::<NotKnownLayout<AU32>>(), repr_packed) - .extend(<[u8] as KnownLayout>::LAYOUT, repr_packed) - .pad_to_align(); - - assert_eq!(<KL10Packed as KnownLayout>::LAYOUT, expected); - assert_eq!(<KL10Packed as KnownLayout>::LAYOUT, unsized_layout(1, 1, 4)); - - // ...with `packed(N)`: - #[derive(KnownLayout)] - #[repr(C, packed(2))] - struct KL10PackedN(NotKnownLayout<AU32>, [u8]); - - let repr_packed = NonZeroUsize::new(2); - - let expected = DstLayout::new_zst(None) - .extend(DstLayout::for_type::<NotKnownLayout<AU32>>(), repr_packed) - .extend(<[u8] as KnownLayout>::LAYOUT, repr_packed) - .pad_to_align(); - - assert_eq!(<KL10PackedN as KnownLayout>::LAYOUT, expected); - assert_eq!(<KL10PackedN as KnownLayout>::LAYOUT, unsized_layout(2, 1, 4)); - - // | `repr(C)`? | generic? | `KnownLayout`? | `Sized`? | Type Name | - // | Y | N | Y | Y | KL11 | - #[derive(KnownLayout)] - #[repr(C)] - struct KL11(NotKnownLayout<AU64>, u8); - - let expected = DstLayout::new_zst(None) - .extend(DstLayout::for_type::<NotKnownLayout<AU64>>(), None) - .extend(<u8 as KnownLayout>::LAYOUT, None) - .pad_to_align(); - - assert_eq!(<KL11 as KnownLayout>::LAYOUT, expected); - assert_eq!(<KL11 as KnownLayout>::LAYOUT, sized_layout(8, 16)); - - // ...with `align(N)`: - #[derive(KnownLayout)] - #[repr(C, align(64))] - struct KL11Align(NotKnownLayout<AU64>, u8); - - let repr_align = NonZeroUsize::new(64); - - let expected = DstLayout::new_zst(repr_align) - .extend(DstLayout::for_type::<NotKnownLayout<AU64>>(), None) - .extend(<u8 as KnownLayout>::LAYOUT, None) - .pad_to_align(); - - assert_eq!(<KL11Align as KnownLayout>::LAYOUT, expected); - assert_eq!(<KL11Align as KnownLayout>::LAYOUT, sized_layout(64, 64)); - - // ...with `packed`: - #[derive(KnownLayout)] - #[repr(C, packed)] - struct KL11Packed(NotKnownLayout<AU64>, u8); - - let repr_packed = NonZeroUsize::new(1); - - let expected = DstLayout::new_zst(None) - .extend(DstLayout::for_type::<NotKnownLayout<AU64>>(), repr_packed) - .extend(<u8 as KnownLayout>::LAYOUT, repr_packed) - .pad_to_align(); - - assert_eq!(<KL11Packed as KnownLayout>::LAYOUT, expected); - assert_eq!(<KL11Packed as KnownLayout>::LAYOUT, sized_layout(1, 9)); - - // ...with `packed(N)`: - #[derive(KnownLayout)] - #[repr(C, packed(2))] - struct KL11PackedN(NotKnownLayout<AU64>, u8); - - let repr_packed = NonZeroUsize::new(2); - - let expected = DstLayout::new_zst(None) - .extend(DstLayout::for_type::<NotKnownLayout<AU64>>(), repr_packed) - .extend(<u8 as KnownLayout>::LAYOUT, repr_packed) - .pad_to_align(); - - assert_eq!(<KL11PackedN as KnownLayout>::LAYOUT, expected); - assert_eq!(<KL11PackedN as KnownLayout>::LAYOUT, sized_layout(2, 10)); - - // | `repr(C)`? | generic? | `KnownLayout`? | `Sized`? | Type Name | - // | Y | Y | Y | N | KL14 | - #[derive(KnownLayout)] - #[repr(C)] - struct KL14<T: ?Sized + KnownLayout>(u8, T); - - fn _test_kl14<T: ?Sized + KnownLayout>(kl: &KL14<T>) { - _assert_kl(kl) - } - - // | `repr(C)`? | generic? | `KnownLayout`? | `Sized`? | Type Name | - // | Y | Y | Y | Y | KL15 | - #[derive(KnownLayout)] - #[repr(C)] - struct KL15<T: KnownLayout>(u8, T); - - fn _test_kl15<T: KnownLayout>(t: T) -> impl KnownLayout { - let _ = KL15(0u8, t); - } - - // Test a variety of combinations of field types: - // - () - // - u8 - // - AU16 - // - [()] - // - [u8] - // - [AU16] - - #[allow(clippy::upper_case_acronyms)] - #[derive(KnownLayout)] - #[repr(C)] - struct KLTU<T, U: ?Sized>(T, U); - - assert_eq!(<KLTU<(), ()> as KnownLayout>::LAYOUT, sized_layout(1, 0)); - - assert_eq!(<KLTU<(), u8> as KnownLayout>::LAYOUT, sized_layout(1, 1)); - - assert_eq!(<KLTU<(), AU16> as KnownLayout>::LAYOUT, sized_layout(2, 2)); - - assert_eq!(<KLTU<(), [()]> as KnownLayout>::LAYOUT, unsized_layout(1, 0, 0)); - - assert_eq!(<KLTU<(), [u8]> as KnownLayout>::LAYOUT, unsized_layout(1, 1, 0)); - - assert_eq!(<KLTU<(), [AU16]> as KnownLayout>::LAYOUT, unsized_layout(2, 2, 0)); - - assert_eq!(<KLTU<u8, ()> as KnownLayout>::LAYOUT, sized_layout(1, 1)); - - assert_eq!(<KLTU<u8, u8> as KnownLayout>::LAYOUT, sized_layout(1, 2)); - - assert_eq!(<KLTU<u8, AU16> as KnownLayout>::LAYOUT, sized_layout(2, 4)); - - assert_eq!(<KLTU<u8, [()]> as KnownLayout>::LAYOUT, unsized_layout(1, 0, 1)); - - assert_eq!(<KLTU<u8, [u8]> as KnownLayout>::LAYOUT, unsized_layout(1, 1, 1)); - - assert_eq!(<KLTU<u8, [AU16]> as KnownLayout>::LAYOUT, unsized_layout(2, 2, 2)); - - assert_eq!(<KLTU<AU16, ()> as KnownLayout>::LAYOUT, sized_layout(2, 2)); - - assert_eq!(<KLTU<AU16, u8> as KnownLayout>::LAYOUT, sized_layout(2, 4)); - - assert_eq!(<KLTU<AU16, AU16> as KnownLayout>::LAYOUT, sized_layout(2, 4)); - - assert_eq!(<KLTU<AU16, [()]> as KnownLayout>::LAYOUT, unsized_layout(2, 0, 2)); - - assert_eq!(<KLTU<AU16, [u8]> as KnownLayout>::LAYOUT, unsized_layout(2, 1, 2)); - - assert_eq!(<KLTU<AU16, [AU16]> as KnownLayout>::LAYOUT, unsized_layout(2, 2, 2)); - - // Test a variety of field counts. - - #[derive(KnownLayout)] - #[repr(C)] - struct KLF0; - - assert_eq!(<KLF0 as KnownLayout>::LAYOUT, sized_layout(1, 0)); - - #[derive(KnownLayout)] - #[repr(C)] - struct KLF1([u8]); - - assert_eq!(<KLF1 as KnownLayout>::LAYOUT, unsized_layout(1, 1, 0)); - - #[derive(KnownLayout)] - #[repr(C)] - struct KLF2(NotKnownLayout<u8>, [u8]); - - assert_eq!(<KLF2 as KnownLayout>::LAYOUT, unsized_layout(1, 1, 1)); - - #[derive(KnownLayout)] - #[repr(C)] - struct KLF3(NotKnownLayout<u8>, NotKnownLayout<AU16>, [u8]); - - assert_eq!(<KLF3 as KnownLayout>::LAYOUT, unsized_layout(2, 1, 4)); - - #[derive(KnownLayout)] - #[repr(C)] - struct KLF4(NotKnownLayout<u8>, NotKnownLayout<AU16>, NotKnownLayout<AU32>, [u8]); - - assert_eq!(<KLF4 as KnownLayout>::LAYOUT, unsized_layout(4, 1, 8)); - } - - #[test] - fn test_object_safety() { - fn _takes_from_zeroes(_: &dyn FromZeroes) {} - fn _takes_from_bytes(_: &dyn FromBytes) {} - fn _takes_unaligned(_: &dyn Unaligned) {} - } - - #[test] - fn test_from_zeroes_only() { - // Test types that implement `FromZeroes` but not `FromBytes`. - - assert!(!bool::new_zeroed()); - assert_eq!(char::new_zeroed(), '\0'); - - #[cfg(feature = "alloc")] - { - assert_eq!(bool::new_box_zeroed(), Box::new(false)); - assert_eq!(char::new_box_zeroed(), Box::new('\0')); - - assert_eq!(bool::new_box_slice_zeroed(3).as_ref(), [false, false, false]); - assert_eq!(char::new_box_slice_zeroed(3).as_ref(), ['\0', '\0', '\0']); - - assert_eq!(bool::new_vec_zeroed(3).as_ref(), [false, false, false]); - assert_eq!(char::new_vec_zeroed(3).as_ref(), ['\0', '\0', '\0']); - } - - let mut string = "hello".to_string(); - let s: &mut str = string.as_mut(); - assert_eq!(s, "hello"); - s.zero(); - assert_eq!(s, "\0\0\0\0\0"); - } - - #[test] - fn test_read_write() { - const VAL: u64 = 0x12345678; - #[cfg(target_endian = "big")] - const VAL_BYTES: [u8; 8] = VAL.to_be_bytes(); - #[cfg(target_endian = "little")] - const VAL_BYTES: [u8; 8] = VAL.to_le_bytes(); - - // Test `FromBytes::{read_from, read_from_prefix, read_from_suffix}`. - - assert_eq!(u64::read_from(&VAL_BYTES[..]), Some(VAL)); - // The first 8 bytes are from `VAL_BYTES` and the second 8 bytes are all - // zeroes. - let bytes_with_prefix: [u8; 16] = transmute!([VAL_BYTES, [0; 8]]); - assert_eq!(u64::read_from_prefix(&bytes_with_prefix[..]), Some(VAL)); - assert_eq!(u64::read_from_suffix(&bytes_with_prefix[..]), Some(0)); - // The first 8 bytes are all zeroes and the second 8 bytes are from - // `VAL_BYTES` - let bytes_with_suffix: [u8; 16] = transmute!([[0; 8], VAL_BYTES]); - assert_eq!(u64::read_from_prefix(&bytes_with_suffix[..]), Some(0)); - assert_eq!(u64::read_from_suffix(&bytes_with_suffix[..]), Some(VAL)); - - // Test `AsBytes::{write_to, write_to_prefix, write_to_suffix}`. - - let mut bytes = [0u8; 8]; - assert_eq!(VAL.write_to(&mut bytes[..]), Some(())); - assert_eq!(bytes, VAL_BYTES); - let mut bytes = [0u8; 16]; - assert_eq!(VAL.write_to_prefix(&mut bytes[..]), Some(())); - let want: [u8; 16] = transmute!([VAL_BYTES, [0; 8]]); - assert_eq!(bytes, want); - let mut bytes = [0u8; 16]; - assert_eq!(VAL.write_to_suffix(&mut bytes[..]), Some(())); - let want: [u8; 16] = transmute!([[0; 8], VAL_BYTES]); - assert_eq!(bytes, want); - } - - #[test] - fn test_transmute() { - // Test that memory is transmuted as expected. - let array_of_u8s = [0u8, 1, 2, 3, 4, 5, 6, 7]; - let array_of_arrays = [[0, 1], [2, 3], [4, 5], [6, 7]]; - let x: [[u8; 2]; 4] = transmute!(array_of_u8s); - assert_eq!(x, array_of_arrays); - let x: [u8; 8] = transmute!(array_of_arrays); - assert_eq!(x, array_of_u8s); - - // Test that the source expression's value is forgotten rather than - // dropped. - #[derive(AsBytes)] - #[repr(transparent)] - struct PanicOnDrop(()); - impl Drop for PanicOnDrop { - fn drop(&mut self) { - panic!("PanicOnDrop::drop"); - } - } - #[allow(clippy::let_unit_value)] - let _: () = transmute!(PanicOnDrop(())); - - // Test that `transmute!` is legal in a const context. - const ARRAY_OF_U8S: [u8; 8] = [0u8, 1, 2, 3, 4, 5, 6, 7]; - const ARRAY_OF_ARRAYS: [[u8; 2]; 4] = [[0, 1], [2, 3], [4, 5], [6, 7]]; - const X: [[u8; 2]; 4] = transmute!(ARRAY_OF_U8S); - assert_eq!(X, ARRAY_OF_ARRAYS); - } - - #[test] - fn test_transmute_ref() { - // Test that memory is transmuted as expected. - let array_of_u8s = [0u8, 1, 2, 3, 4, 5, 6, 7]; - let array_of_arrays = [[0, 1], [2, 3], [4, 5], [6, 7]]; - let x: &[[u8; 2]; 4] = transmute_ref!(&array_of_u8s); - assert_eq!(*x, array_of_arrays); - let x: &[u8; 8] = transmute_ref!(&array_of_arrays); - assert_eq!(*x, array_of_u8s); - - // Test that `transmute_ref!` is legal in a const context. - const ARRAY_OF_U8S: [u8; 8] = [0u8, 1, 2, 3, 4, 5, 6, 7]; - const ARRAY_OF_ARRAYS: [[u8; 2]; 4] = [[0, 1], [2, 3], [4, 5], [6, 7]]; - #[allow(clippy::redundant_static_lifetimes)] - const X: &'static [[u8; 2]; 4] = transmute_ref!(&ARRAY_OF_U8S); - assert_eq!(*X, ARRAY_OF_ARRAYS); - - // Test that it's legal to transmute a reference while shrinking the - // lifetime (note that `X` has the lifetime `'static`). - let x: &[u8; 8] = transmute_ref!(X); - assert_eq!(*x, ARRAY_OF_U8S); - - // Test that `transmute_ref!` supports decreasing alignment. - let u = AU64(0); - let array = [0, 0, 0, 0, 0, 0, 0, 0]; - let x: &[u8; 8] = transmute_ref!(&u); - assert_eq!(*x, array); - - // Test that a mutable reference can be turned into an immutable one. - let mut x = 0u8; - #[allow(clippy::useless_transmute)] - let y: &u8 = transmute_ref!(&mut x); - assert_eq!(*y, 0); - } - - #[test] - fn test_transmute_mut() { - // Test that memory is transmuted as expected. - let mut array_of_u8s = [0u8, 1, 2, 3, 4, 5, 6, 7]; - let mut array_of_arrays = [[0, 1], [2, 3], [4, 5], [6, 7]]; - let x: &mut [[u8; 2]; 4] = transmute_mut!(&mut array_of_u8s); - assert_eq!(*x, array_of_arrays); - let x: &mut [u8; 8] = transmute_mut!(&mut array_of_arrays); - assert_eq!(*x, array_of_u8s); - - { - // Test that it's legal to transmute a reference while shrinking the - // lifetime. - let x: &mut [u8; 8] = transmute_mut!(&mut array_of_arrays); - assert_eq!(*x, array_of_u8s); - } - // Test that `transmute_mut!` supports decreasing alignment. - let mut u = AU64(0); - let array = [0, 0, 0, 0, 0, 0, 0, 0]; - let x: &[u8; 8] = transmute_mut!(&mut u); - assert_eq!(*x, array); - - // Test that a mutable reference can be turned into an immutable one. - let mut x = 0u8; - #[allow(clippy::useless_transmute)] - let y: &u8 = transmute_mut!(&mut x); - assert_eq!(*y, 0); - } - - #[test] - fn test_macros_evaluate_args_once() { - let mut ctr = 0; - let _: usize = transmute!({ - ctr += 1; - 0usize - }); - assert_eq!(ctr, 1); - - let mut ctr = 0; - let _: &usize = transmute_ref!({ - ctr += 1; - &0usize - }); - assert_eq!(ctr, 1); - } - - #[test] - fn test_include_value() { - const AS_U32: u32 = include_value!("../testdata/include_value/data"); - assert_eq!(AS_U32, u32::from_ne_bytes([b'a', b'b', b'c', b'd'])); - const AS_I32: i32 = include_value!("../testdata/include_value/data"); - assert_eq!(AS_I32, i32::from_ne_bytes([b'a', b'b', b'c', b'd'])); - } - - #[test] - fn test_address() { - // Test that the `Deref` and `DerefMut` implementations return a - // reference which points to the right region of memory. - - let buf = [0]; - let r = Ref::<_, u8>::new(&buf[..]).unwrap(); - let buf_ptr = buf.as_ptr(); - let deref_ptr: *const u8 = r.deref(); - assert_eq!(buf_ptr, deref_ptr); - - let buf = [0]; - let r = Ref::<_, [u8]>::new_slice(&buf[..]).unwrap(); - let buf_ptr = buf.as_ptr(); - let deref_ptr = r.deref().as_ptr(); - assert_eq!(buf_ptr, deref_ptr); - } - - // Verify that values written to a `Ref` are properly shared between the - // typed and untyped representations, that reads via `deref` and `read` - // behave the same, and that writes via `deref_mut` and `write` behave the - // same. - fn test_new_helper(mut r: Ref<&mut [u8], AU64>) { - // assert that the value starts at 0 - assert_eq!(*r, AU64(0)); - assert_eq!(r.read(), AU64(0)); - - // Assert that values written to the typed value are reflected in the - // byte slice. - const VAL1: AU64 = AU64(0xFF00FF00FF00FF00); - *r = VAL1; - assert_eq!(r.bytes(), &VAL1.to_bytes()); - *r = AU64(0); - r.write(VAL1); - assert_eq!(r.bytes(), &VAL1.to_bytes()); - - // Assert that values written to the byte slice are reflected in the - // typed value. - const VAL2: AU64 = AU64(!VAL1.0); // different from `VAL1` - r.bytes_mut().copy_from_slice(&VAL2.to_bytes()[..]); - assert_eq!(*r, VAL2); - assert_eq!(r.read(), VAL2); - } - - // Verify that values written to a `Ref` are properly shared between the - // typed and untyped representations; pass a value with `typed_len` `AU64`s - // backed by an array of `typed_len * 8` bytes. - fn test_new_helper_slice(mut r: Ref<&mut [u8], [AU64]>, typed_len: usize) { - // Assert that the value starts out zeroed. - assert_eq!(&*r, vec![AU64(0); typed_len].as_slice()); - - // Check the backing storage is the exact same slice. - let untyped_len = typed_len * 8; - assert_eq!(r.bytes().len(), untyped_len); - assert_eq!(r.bytes().as_ptr(), r.as_ptr().cast::<u8>()); - - // Assert that values written to the typed value are reflected in the - // byte slice. - const VAL1: AU64 = AU64(0xFF00FF00FF00FF00); - for typed in &mut *r { - *typed = VAL1; - } - assert_eq!(r.bytes(), VAL1.0.to_ne_bytes().repeat(typed_len).as_slice()); - - // Assert that values written to the byte slice are reflected in the - // typed value. - const VAL2: AU64 = AU64(!VAL1.0); // different from VAL1 - r.bytes_mut().copy_from_slice(&VAL2.0.to_ne_bytes().repeat(typed_len)); - assert!(r.iter().copied().all(|x| x == VAL2)); - } - - // Verify that values written to a `Ref` are properly shared between the - // typed and untyped representations, that reads via `deref` and `read` - // behave the same, and that writes via `deref_mut` and `write` behave the - // same. - fn test_new_helper_unaligned(mut r: Ref<&mut [u8], [u8; 8]>) { - // assert that the value starts at 0 - assert_eq!(*r, [0; 8]); - assert_eq!(r.read(), [0; 8]); - - // Assert that values written to the typed value are reflected in the - // byte slice. - const VAL1: [u8; 8] = [0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00]; - *r = VAL1; - assert_eq!(r.bytes(), &VAL1); - *r = [0; 8]; - r.write(VAL1); - assert_eq!(r.bytes(), &VAL1); - - // Assert that values written to the byte slice are reflected in the - // typed value. - const VAL2: [u8; 8] = [0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF]; // different from VAL1 - r.bytes_mut().copy_from_slice(&VAL2[..]); - assert_eq!(*r, VAL2); - assert_eq!(r.read(), VAL2); - } - - // Verify that values written to a `Ref` are properly shared between the - // typed and untyped representations; pass a value with `len` `u8`s backed - // by an array of `len` bytes. - fn test_new_helper_slice_unaligned(mut r: Ref<&mut [u8], [u8]>, len: usize) { - // Assert that the value starts out zeroed. - assert_eq!(&*r, vec![0u8; len].as_slice()); - - // Check the backing storage is the exact same slice. - assert_eq!(r.bytes().len(), len); - assert_eq!(r.bytes().as_ptr(), r.as_ptr()); - - // Assert that values written to the typed value are reflected in the - // byte slice. - let mut expected_bytes = [0xFF, 0x00].iter().copied().cycle().take(len).collect::<Vec<_>>(); - r.copy_from_slice(&expected_bytes); - assert_eq!(r.bytes(), expected_bytes.as_slice()); - - // Assert that values written to the byte slice are reflected in the - // typed value. - for byte in &mut expected_bytes { - *byte = !*byte; // different from `expected_len` - } - r.bytes_mut().copy_from_slice(&expected_bytes); - assert_eq!(&*r, expected_bytes.as_slice()); - } - - #[test] - fn test_new_aligned_sized() { - // Test that a properly-aligned, properly-sized buffer works for new, - // new_from_prefix, and new_from_suffix, and that new_from_prefix and - // new_from_suffix return empty slices. Test that a properly-aligned - // buffer whose length is a multiple of the element size works for - // new_slice. Test that xxx_zeroed behaves the same, and zeroes the - // memory. - - // A buffer with an alignment of 8. - let mut buf = Align::<[u8; 8], AU64>::default(); - // `buf.t` should be aligned to 8, so this should always succeed. - test_new_helper(Ref::<_, AU64>::new(&mut buf.t[..]).unwrap()); - let ascending: [u8; 8] = (0..8).collect::<Vec<_>>().try_into().unwrap(); - buf.t = ascending; - test_new_helper(Ref::<_, AU64>::new_zeroed(&mut buf.t[..]).unwrap()); - { - // In a block so that `r` and `suffix` don't live too long. - buf.set_default(); - let (r, suffix) = Ref::<_, AU64>::new_from_prefix(&mut buf.t[..]).unwrap(); - assert!(suffix.is_empty()); - test_new_helper(r); - } - { - buf.t = ascending; - let (r, suffix) = Ref::<_, AU64>::new_from_prefix_zeroed(&mut buf.t[..]).unwrap(); - assert!(suffix.is_empty()); - test_new_helper(r); - } - { - buf.set_default(); - let (prefix, r) = Ref::<_, AU64>::new_from_suffix(&mut buf.t[..]).unwrap(); - assert!(prefix.is_empty()); - test_new_helper(r); - } - { - buf.t = ascending; - let (prefix, r) = Ref::<_, AU64>::new_from_suffix_zeroed(&mut buf.t[..]).unwrap(); - assert!(prefix.is_empty()); - test_new_helper(r); - } - - // A buffer with alignment 8 and length 24. We choose this length very - // intentionally: if we instead used length 16, then the prefix and - // suffix lengths would be identical. In the past, we used length 16, - // which resulted in this test failing to discover the bug uncovered in - // #506. - let mut buf = Align::<[u8; 24], AU64>::default(); - // `buf.t` should be aligned to 8 and have a length which is a multiple - // of `size_of::<AU64>()`, so this should always succeed. - test_new_helper_slice(Ref::<_, [AU64]>::new_slice(&mut buf.t[..]).unwrap(), 3); - let ascending: [u8; 24] = (0..24).collect::<Vec<_>>().try_into().unwrap(); - // 16 ascending bytes followed by 8 zeros. - let mut ascending_prefix = ascending; - ascending_prefix[16..].copy_from_slice(&[0, 0, 0, 0, 0, 0, 0, 0]); - // 8 zeros followed by 16 ascending bytes. - let mut ascending_suffix = ascending; - ascending_suffix[..8].copy_from_slice(&[0, 0, 0, 0, 0, 0, 0, 0]); - test_new_helper_slice(Ref::<_, [AU64]>::new_slice_zeroed(&mut buf.t[..]).unwrap(), 3); - - { - buf.t = ascending_suffix; - let (r, suffix) = Ref::<_, [AU64]>::new_slice_from_prefix(&mut buf.t[..], 1).unwrap(); - assert_eq!(suffix, &ascending[8..]); - test_new_helper_slice(r, 1); - } - { - buf.t = ascending_suffix; - let (r, suffix) = - Ref::<_, [AU64]>::new_slice_from_prefix_zeroed(&mut buf.t[..], 1).unwrap(); - assert_eq!(suffix, &ascending[8..]); - test_new_helper_slice(r, 1); - } - { - buf.t = ascending_prefix; - let (prefix, r) = Ref::<_, [AU64]>::new_slice_from_suffix(&mut buf.t[..], 1).unwrap(); - assert_eq!(prefix, &ascending[..16]); - test_new_helper_slice(r, 1); - } - { - buf.t = ascending_prefix; - let (prefix, r) = - Ref::<_, [AU64]>::new_slice_from_suffix_zeroed(&mut buf.t[..], 1).unwrap(); - assert_eq!(prefix, &ascending[..16]); - test_new_helper_slice(r, 1); - } - } - - #[test] - fn test_new_unaligned_sized() { - // Test that an unaligned, properly-sized buffer works for - // `new_unaligned`, `new_unaligned_from_prefix`, and - // `new_unaligned_from_suffix`, and that `new_unaligned_from_prefix` - // `new_unaligned_from_suffix` return empty slices. Test that an - // unaligned buffer whose length is a multiple of the element size works - // for `new_slice`. Test that `xxx_zeroed` behaves the same, and zeroes - // the memory. - - let mut buf = [0u8; 8]; - test_new_helper_unaligned(Ref::<_, [u8; 8]>::new_unaligned(&mut buf[..]).unwrap()); - buf = [0xFFu8; 8]; - test_new_helper_unaligned(Ref::<_, [u8; 8]>::new_unaligned_zeroed(&mut buf[..]).unwrap()); - { - // In a block so that `r` and `suffix` don't live too long. - buf = [0u8; 8]; - let (r, suffix) = Ref::<_, [u8; 8]>::new_unaligned_from_prefix(&mut buf[..]).unwrap(); - assert!(suffix.is_empty()); - test_new_helper_unaligned(r); - } - { - buf = [0xFFu8; 8]; - let (r, suffix) = - Ref::<_, [u8; 8]>::new_unaligned_from_prefix_zeroed(&mut buf[..]).unwrap(); - assert!(suffix.is_empty()); - test_new_helper_unaligned(r); - } - { - buf = [0u8; 8]; - let (prefix, r) = Ref::<_, [u8; 8]>::new_unaligned_from_suffix(&mut buf[..]).unwrap(); - assert!(prefix.is_empty()); - test_new_helper_unaligned(r); - } - { - buf = [0xFFu8; 8]; - let (prefix, r) = - Ref::<_, [u8; 8]>::new_unaligned_from_suffix_zeroed(&mut buf[..]).unwrap(); - assert!(prefix.is_empty()); - test_new_helper_unaligned(r); - } - - let mut buf = [0u8; 16]; - // `buf.t` should be aligned to 8 and have a length which is a multiple - // of `size_of::AU64>()`, so this should always succeed. - test_new_helper_slice_unaligned( - Ref::<_, [u8]>::new_slice_unaligned(&mut buf[..]).unwrap(), - 16, - ); - buf = [0xFFu8; 16]; - test_new_helper_slice_unaligned( - Ref::<_, [u8]>::new_slice_unaligned_zeroed(&mut buf[..]).unwrap(), - 16, - ); - - { - buf = [0u8; 16]; - let (r, suffix) = - Ref::<_, [u8]>::new_slice_unaligned_from_prefix(&mut buf[..], 8).unwrap(); - assert_eq!(suffix, [0; 8]); - test_new_helper_slice_unaligned(r, 8); - } - { - buf = [0xFFu8; 16]; - let (r, suffix) = - Ref::<_, [u8]>::new_slice_unaligned_from_prefix_zeroed(&mut buf[..], 8).unwrap(); - assert_eq!(suffix, [0xFF; 8]); - test_new_helper_slice_unaligned(r, 8); - } - { - buf = [0u8; 16]; - let (prefix, r) = - Ref::<_, [u8]>::new_slice_unaligned_from_suffix(&mut buf[..], 8).unwrap(); - assert_eq!(prefix, [0; 8]); - test_new_helper_slice_unaligned(r, 8); - } - { - buf = [0xFFu8; 16]; - let (prefix, r) = - Ref::<_, [u8]>::new_slice_unaligned_from_suffix_zeroed(&mut buf[..], 8).unwrap(); - assert_eq!(prefix, [0xFF; 8]); - test_new_helper_slice_unaligned(r, 8); - } - } - - #[test] - fn test_new_oversized() { - // Test that a properly-aligned, overly-sized buffer works for - // `new_from_prefix` and `new_from_suffix`, and that they return the - // remainder and prefix of the slice respectively. Test that - // `xxx_zeroed` behaves the same, and zeroes the memory. - - let mut buf = Align::<[u8; 16], AU64>::default(); - { - // In a block so that `r` and `suffix` don't live too long. `buf.t` - // should be aligned to 8, so this should always succeed. - let (r, suffix) = Ref::<_, AU64>::new_from_prefix(&mut buf.t[..]).unwrap(); - assert_eq!(suffix.len(), 8); - test_new_helper(r); - } - { - buf.t = [0xFFu8; 16]; - // `buf.t` should be aligned to 8, so this should always succeed. - let (r, suffix) = Ref::<_, AU64>::new_from_prefix_zeroed(&mut buf.t[..]).unwrap(); - // Assert that the suffix wasn't zeroed. - assert_eq!(suffix, &[0xFFu8; 8]); - test_new_helper(r); - } - { - buf.set_default(); - // `buf.t` should be aligned to 8, so this should always succeed. - let (prefix, r) = Ref::<_, AU64>::new_from_suffix(&mut buf.t[..]).unwrap(); - assert_eq!(prefix.len(), 8); - test_new_helper(r); - } - { - buf.t = [0xFFu8; 16]; - // `buf.t` should be aligned to 8, so this should always succeed. - let (prefix, r) = Ref::<_, AU64>::new_from_suffix_zeroed(&mut buf.t[..]).unwrap(); - // Assert that the prefix wasn't zeroed. - assert_eq!(prefix, &[0xFFu8; 8]); - test_new_helper(r); - } - } - - #[test] - fn test_new_unaligned_oversized() { - // Test than an unaligned, overly-sized buffer works for - // `new_unaligned_from_prefix` and `new_unaligned_from_suffix`, and that - // they return the remainder and prefix of the slice respectively. Test - // that `xxx_zeroed` behaves the same, and zeroes the memory. - - let mut buf = [0u8; 16]; - { - // In a block so that `r` and `suffix` don't live too long. - let (r, suffix) = Ref::<_, [u8; 8]>::new_unaligned_from_prefix(&mut buf[..]).unwrap(); - assert_eq!(suffix.len(), 8); - test_new_helper_unaligned(r); - } - { - buf = [0xFFu8; 16]; - let (r, suffix) = - Ref::<_, [u8; 8]>::new_unaligned_from_prefix_zeroed(&mut buf[..]).unwrap(); - // Assert that the suffix wasn't zeroed. - assert_eq!(suffix, &[0xFF; 8]); - test_new_helper_unaligned(r); - } - { - buf = [0u8; 16]; - let (prefix, r) = Ref::<_, [u8; 8]>::new_unaligned_from_suffix(&mut buf[..]).unwrap(); - assert_eq!(prefix.len(), 8); - test_new_helper_unaligned(r); - } - { - buf = [0xFFu8; 16]; - let (prefix, r) = - Ref::<_, [u8; 8]>::new_unaligned_from_suffix_zeroed(&mut buf[..]).unwrap(); - // Assert that the prefix wasn't zeroed. - assert_eq!(prefix, &[0xFF; 8]); - test_new_helper_unaligned(r); - } - } - - #[test] - fn test_ref_from_mut_from() { - // Test `FromBytes::{ref_from, mut_from}{,_prefix,_suffix}` success cases - // Exhaustive coverage for these methods is covered by the `Ref` tests above, - // which these helper methods defer to. - - let mut buf = - Align::<[u8; 16], AU64>::new([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]); - - assert_eq!( - AU64::ref_from(&buf.t[8..]).unwrap().0.to_ne_bytes(), - [8, 9, 10, 11, 12, 13, 14, 15] - ); - let suffix = AU64::mut_from(&mut buf.t[8..]).unwrap(); - suffix.0 = 0x0101010101010101; - // The `[u8:9]` is a non-half size of the full buffer, which would catch - // `from_prefix` having the same implementation as `from_suffix` (issues #506, #511). - assert_eq!(<[u8; 9]>::ref_from_suffix(&buf.t[..]).unwrap(), &[7u8, 1, 1, 1, 1, 1, 1, 1, 1]); - let suffix = AU64::mut_from_suffix(&mut buf.t[1..]).unwrap(); - suffix.0 = 0x0202020202020202; - <[u8; 10]>::mut_from_suffix(&mut buf.t[..]).unwrap()[0] = 42; - assert_eq!(<[u8; 9]>::ref_from_prefix(&buf.t[..]).unwrap(), &[0, 1, 2, 3, 4, 5, 42, 7, 2]); - <[u8; 2]>::mut_from_prefix(&mut buf.t[..]).unwrap()[1] = 30; - assert_eq!(buf.t, [0, 30, 2, 3, 4, 5, 42, 7, 2, 2, 2, 2, 2, 2, 2, 2]); - } - - #[test] - fn test_ref_from_mut_from_error() { - // Test `FromBytes::{ref_from, mut_from}{,_prefix,_suffix}` error cases. - - // Fail because the buffer is too large. - let mut buf = Align::<[u8; 16], AU64>::default(); - // `buf.t` should be aligned to 8, so only the length check should fail. - assert!(AU64::ref_from(&buf.t[..]).is_none()); - assert!(AU64::mut_from(&mut buf.t[..]).is_none()); - assert!(<[u8; 8]>::ref_from(&buf.t[..]).is_none()); - assert!(<[u8; 8]>::mut_from(&mut buf.t[..]).is_none()); - - // Fail because the buffer is too small. - let mut buf = Align::<[u8; 4], AU64>::default(); - assert!(AU64::ref_from(&buf.t[..]).is_none()); - assert!(AU64::mut_from(&mut buf.t[..]).is_none()); - assert!(<[u8; 8]>::ref_from(&buf.t[..]).is_none()); - assert!(<[u8; 8]>::mut_from(&mut buf.t[..]).is_none()); - assert!(AU64::ref_from_prefix(&buf.t[..]).is_none()); - assert!(AU64::mut_from_prefix(&mut buf.t[..]).is_none()); - assert!(AU64::ref_from_suffix(&buf.t[..]).is_none()); - assert!(AU64::mut_from_suffix(&mut buf.t[..]).is_none()); - assert!(<[u8; 8]>::ref_from_prefix(&buf.t[..]).is_none()); - assert!(<[u8; 8]>::mut_from_prefix(&mut buf.t[..]).is_none()); - assert!(<[u8; 8]>::ref_from_suffix(&buf.t[..]).is_none()); - assert!(<[u8; 8]>::mut_from_suffix(&mut buf.t[..]).is_none()); - - // Fail because the alignment is insufficient. - let mut buf = Align::<[u8; 13], AU64>::default(); - assert!(AU64::ref_from(&buf.t[1..]).is_none()); - assert!(AU64::mut_from(&mut buf.t[1..]).is_none()); - assert!(AU64::ref_from(&buf.t[1..]).is_none()); - assert!(AU64::mut_from(&mut buf.t[1..]).is_none()); - assert!(AU64::ref_from_prefix(&buf.t[1..]).is_none()); - assert!(AU64::mut_from_prefix(&mut buf.t[1..]).is_none()); - assert!(AU64::ref_from_suffix(&buf.t[..]).is_none()); - assert!(AU64::mut_from_suffix(&mut buf.t[..]).is_none()); - } - - #[test] - #[allow(clippy::cognitive_complexity)] - fn test_new_error() { - // Fail because the buffer is too large. - - // A buffer with an alignment of 8. - let mut buf = Align::<[u8; 16], AU64>::default(); - // `buf.t` should be aligned to 8, so only the length check should fail. - assert!(Ref::<_, AU64>::new(&buf.t[..]).is_none()); - assert!(Ref::<_, AU64>::new_zeroed(&mut buf.t[..]).is_none()); - assert!(Ref::<_, [u8; 8]>::new_unaligned(&buf.t[..]).is_none()); - assert!(Ref::<_, [u8; 8]>::new_unaligned_zeroed(&mut buf.t[..]).is_none()); - - // Fail because the buffer is too small. - - // A buffer with an alignment of 8. - let mut buf = Align::<[u8; 4], AU64>::default(); - // `buf.t` should be aligned to 8, so only the length check should fail. - assert!(Ref::<_, AU64>::new(&buf.t[..]).is_none()); - assert!(Ref::<_, AU64>::new_zeroed(&mut buf.t[..]).is_none()); - assert!(Ref::<_, [u8; 8]>::new_unaligned(&buf.t[..]).is_none()); - assert!(Ref::<_, [u8; 8]>::new_unaligned_zeroed(&mut buf.t[..]).is_none()); - assert!(Ref::<_, AU64>::new_from_prefix(&buf.t[..]).is_none()); - assert!(Ref::<_, AU64>::new_from_prefix_zeroed(&mut buf.t[..]).is_none()); - assert!(Ref::<_, AU64>::new_from_suffix(&buf.t[..]).is_none()); - assert!(Ref::<_, AU64>::new_from_suffix_zeroed(&mut buf.t[..]).is_none()); - assert!(Ref::<_, [u8; 8]>::new_unaligned_from_prefix(&buf.t[..]).is_none()); - assert!(Ref::<_, [u8; 8]>::new_unaligned_from_prefix_zeroed(&mut buf.t[..]).is_none()); - assert!(Ref::<_, [u8; 8]>::new_unaligned_from_suffix(&buf.t[..]).is_none()); - assert!(Ref::<_, [u8; 8]>::new_unaligned_from_suffix_zeroed(&mut buf.t[..]).is_none()); - - // Fail because the length is not a multiple of the element size. - - let mut buf = Align::<[u8; 12], AU64>::default(); - // `buf.t` has length 12, but element size is 8. - assert!(Ref::<_, [AU64]>::new_slice(&buf.t[..]).is_none()); - assert!(Ref::<_, [AU64]>::new_slice_zeroed(&mut buf.t[..]).is_none()); - assert!(Ref::<_, [[u8; 8]]>::new_slice_unaligned(&buf.t[..]).is_none()); - assert!(Ref::<_, [[u8; 8]]>::new_slice_unaligned_zeroed(&mut buf.t[..]).is_none()); - - // Fail because the buffer is too short. - let mut buf = Align::<[u8; 12], AU64>::default(); - // `buf.t` has length 12, but the element size is 8 (and we're expecting - // two of them). - assert!(Ref::<_, [AU64]>::new_slice_from_prefix(&buf.t[..], 2).is_none()); - assert!(Ref::<_, [AU64]>::new_slice_from_prefix_zeroed(&mut buf.t[..], 2).is_none()); - assert!(Ref::<_, [AU64]>::new_slice_from_suffix(&buf.t[..], 2).is_none()); - assert!(Ref::<_, [AU64]>::new_slice_from_suffix_zeroed(&mut buf.t[..], 2).is_none()); - assert!(Ref::<_, [[u8; 8]]>::new_slice_unaligned_from_prefix(&buf.t[..], 2).is_none()); - assert!(Ref::<_, [[u8; 8]]>::new_slice_unaligned_from_prefix_zeroed(&mut buf.t[..], 2) - .is_none()); - assert!(Ref::<_, [[u8; 8]]>::new_slice_unaligned_from_suffix(&buf.t[..], 2).is_none()); - assert!(Ref::<_, [[u8; 8]]>::new_slice_unaligned_from_suffix_zeroed(&mut buf.t[..], 2) - .is_none()); - - // Fail because the alignment is insufficient. - - // A buffer with an alignment of 8. An odd buffer size is chosen so that - // the last byte of the buffer has odd alignment. - let mut buf = Align::<[u8; 13], AU64>::default(); - // Slicing from 1, we get a buffer with size 12 (so the length check - // should succeed) but an alignment of only 1, which is insufficient. - assert!(Ref::<_, AU64>::new(&buf.t[1..]).is_none()); - assert!(Ref::<_, AU64>::new_zeroed(&mut buf.t[1..]).is_none()); - assert!(Ref::<_, AU64>::new_from_prefix(&buf.t[1..]).is_none()); - assert!(Ref::<_, AU64>::new_from_prefix_zeroed(&mut buf.t[1..]).is_none()); - assert!(Ref::<_, [AU64]>::new_slice(&buf.t[1..]).is_none()); - assert!(Ref::<_, [AU64]>::new_slice_zeroed(&mut buf.t[1..]).is_none()); - assert!(Ref::<_, [AU64]>::new_slice_from_prefix(&buf.t[1..], 1).is_none()); - assert!(Ref::<_, [AU64]>::new_slice_from_prefix_zeroed(&mut buf.t[1..], 1).is_none()); - assert!(Ref::<_, [AU64]>::new_slice_from_suffix(&buf.t[1..], 1).is_none()); - assert!(Ref::<_, [AU64]>::new_slice_from_suffix_zeroed(&mut buf.t[1..], 1).is_none()); - // Slicing is unnecessary here because `new_from_suffix[_zeroed]` use - // the suffix of the slice, which has odd alignment. - assert!(Ref::<_, AU64>::new_from_suffix(&buf.t[..]).is_none()); - assert!(Ref::<_, AU64>::new_from_suffix_zeroed(&mut buf.t[..]).is_none()); - - // Fail due to arithmetic overflow. - - let mut buf = Align::<[u8; 16], AU64>::default(); - let unreasonable_len = usize::MAX / mem::size_of::<AU64>() + 1; - assert!(Ref::<_, [AU64]>::new_slice_from_prefix(&buf.t[..], unreasonable_len).is_none()); - assert!(Ref::<_, [AU64]>::new_slice_from_prefix_zeroed(&mut buf.t[..], unreasonable_len) - .is_none()); - assert!(Ref::<_, [AU64]>::new_slice_from_suffix(&buf.t[..], unreasonable_len).is_none()); - assert!(Ref::<_, [AU64]>::new_slice_from_suffix_zeroed(&mut buf.t[..], unreasonable_len) - .is_none()); - assert!(Ref::<_, [[u8; 8]]>::new_slice_unaligned_from_prefix(&buf.t[..], unreasonable_len) - .is_none()); - assert!(Ref::<_, [[u8; 8]]>::new_slice_unaligned_from_prefix_zeroed( - &mut buf.t[..], - unreasonable_len - ) - .is_none()); - assert!(Ref::<_, [[u8; 8]]>::new_slice_unaligned_from_suffix(&buf.t[..], unreasonable_len) - .is_none()); - assert!(Ref::<_, [[u8; 8]]>::new_slice_unaligned_from_suffix_zeroed( - &mut buf.t[..], - unreasonable_len - ) - .is_none()); - } - - // Tests for ensuring that, if a ZST is passed into a slice-like function, - // we always panic. Since these tests need to be separate per-function, and - // they tend to take up a lot of space, we generate them using a macro in a - // submodule instead. The submodule ensures that we can just re-use the name - // of the function under test for the name of the test itself. - mod test_zst_panics { - macro_rules! zst_test { - ($name:ident($($tt:tt)*), $constructor_in_panic_msg:tt) => { - #[test] - #[should_panic = concat!("Ref::", $constructor_in_panic_msg, " called on a zero-sized type")] - fn $name() { - let mut buffer = [0u8]; - let r = $crate::Ref::<_, [()]>::$name(&mut buffer[..], $($tt)*); - unreachable!("should have panicked, got {:?}", r); - } - } - } - zst_test!(new_slice(), "new_slice"); - zst_test!(new_slice_zeroed(), "new_slice"); - zst_test!(new_slice_from_prefix(1), "new_slice"); - zst_test!(new_slice_from_prefix_zeroed(1), "new_slice"); - zst_test!(new_slice_from_suffix(1), "new_slice"); - zst_test!(new_slice_from_suffix_zeroed(1), "new_slice"); - zst_test!(new_slice_unaligned(), "new_slice_unaligned"); - zst_test!(new_slice_unaligned_zeroed(), "new_slice_unaligned"); - zst_test!(new_slice_unaligned_from_prefix(1), "new_slice_unaligned"); - zst_test!(new_slice_unaligned_from_prefix_zeroed(1), "new_slice_unaligned"); - zst_test!(new_slice_unaligned_from_suffix(1), "new_slice_unaligned"); - zst_test!(new_slice_unaligned_from_suffix_zeroed(1), "new_slice_unaligned"); - } - - #[test] - fn test_as_bytes_methods() { - /// Run a series of tests by calling `AsBytes` methods on `t`. - /// - /// `bytes` is the expected byte sequence returned from `t.as_bytes()` - /// before `t` has been modified. `post_mutation` is the expected - /// sequence returned from `t.as_bytes()` after `t.as_bytes_mut()[0]` - /// has had its bits flipped (by applying `^= 0xFF`). - /// - /// `N` is the size of `t` in bytes. - fn test<T: FromBytes + AsBytes + Debug + Eq + ?Sized, const N: usize>( - t: &mut T, - bytes: &[u8], - post_mutation: &T, - ) { - // Test that we can access the underlying bytes, and that we get the - // right bytes and the right number of bytes. - assert_eq!(t.as_bytes(), bytes); - - // Test that changes to the underlying byte slices are reflected in - // the original object. - t.as_bytes_mut()[0] ^= 0xFF; - assert_eq!(t, post_mutation); - t.as_bytes_mut()[0] ^= 0xFF; - - // `write_to` rejects slices that are too small or too large. - assert_eq!(t.write_to(&mut vec![0; N - 1][..]), None); - assert_eq!(t.write_to(&mut vec![0; N + 1][..]), None); - - // `write_to` works as expected. - let mut bytes = [0; N]; - assert_eq!(t.write_to(&mut bytes[..]), Some(())); - assert_eq!(bytes, t.as_bytes()); - - // `write_to_prefix` rejects slices that are too small. - assert_eq!(t.write_to_prefix(&mut vec![0; N - 1][..]), None); - - // `write_to_prefix` works with exact-sized slices. - let mut bytes = [0; N]; - assert_eq!(t.write_to_prefix(&mut bytes[..]), Some(())); - assert_eq!(bytes, t.as_bytes()); - - // `write_to_prefix` works with too-large slices, and any bytes past - // the prefix aren't modified. - let mut too_many_bytes = vec![0; N + 1]; - too_many_bytes[N] = 123; - assert_eq!(t.write_to_prefix(&mut too_many_bytes[..]), Some(())); - assert_eq!(&too_many_bytes[..N], t.as_bytes()); - assert_eq!(too_many_bytes[N], 123); - - // `write_to_suffix` rejects slices that are too small. - assert_eq!(t.write_to_suffix(&mut vec![0; N - 1][..]), None); - - // `write_to_suffix` works with exact-sized slices. - let mut bytes = [0; N]; - assert_eq!(t.write_to_suffix(&mut bytes[..]), Some(())); - assert_eq!(bytes, t.as_bytes()); - - // `write_to_suffix` works with too-large slices, and any bytes - // before the suffix aren't modified. - let mut too_many_bytes = vec![0; N + 1]; - too_many_bytes[0] = 123; - assert_eq!(t.write_to_suffix(&mut too_many_bytes[..]), Some(())); - assert_eq!(&too_many_bytes[1..], t.as_bytes()); - assert_eq!(too_many_bytes[0], 123); - } - - #[derive(Debug, Eq, PartialEq, FromZeroes, FromBytes, AsBytes)] - #[repr(C)] - struct Foo { - a: u32, - b: Wrapping<u32>, - c: Option<NonZeroU32>, - } - - let expected_bytes: Vec<u8> = if cfg!(target_endian = "little") { - vec![1, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0] - } else { - vec![0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 0] - }; - let post_mutation_expected_a = - if cfg!(target_endian = "little") { 0x00_00_00_FE } else { 0xFF_00_00_01 }; - test::<_, 12>( - &mut Foo { a: 1, b: Wrapping(2), c: None }, - expected_bytes.as_bytes(), - &Foo { a: post_mutation_expected_a, b: Wrapping(2), c: None }, - ); - test::<_, 3>( - Unsized::from_mut_slice(&mut [1, 2, 3]), - &[1, 2, 3], - Unsized::from_mut_slice(&mut [0xFE, 2, 3]), - ); - } - - #[test] - fn test_array() { - #[derive(FromZeroes, FromBytes, AsBytes)] - #[repr(C)] - struct Foo { - a: [u16; 33], - } - - let foo = Foo { a: [0xFFFF; 33] }; - let expected = [0xFFu8; 66]; - assert_eq!(foo.as_bytes(), &expected[..]); - } - - #[test] - fn test_display_debug() { - let buf = Align::<[u8; 8], u64>::default(); - let r = Ref::<_, u64>::new(&buf.t[..]).unwrap(); - assert_eq!(format!("{}", r), "0"); - assert_eq!(format!("{:?}", r), "Ref(0)"); - - let buf = Align::<[u8; 8], u64>::default(); - let r = Ref::<_, [u64]>::new_slice(&buf.t[..]).unwrap(); - assert_eq!(format!("{:?}", r), "Ref([0])"); - } - - #[test] - fn test_eq() { - let buf1 = 0_u64; - let r1 = Ref::<_, u64>::new(buf1.as_bytes()).unwrap(); - let buf2 = 0_u64; - let r2 = Ref::<_, u64>::new(buf2.as_bytes()).unwrap(); - assert_eq!(r1, r2); - } - - #[test] - fn test_ne() { - let buf1 = 0_u64; - let r1 = Ref::<_, u64>::new(buf1.as_bytes()).unwrap(); - let buf2 = 1_u64; - let r2 = Ref::<_, u64>::new(buf2.as_bytes()).unwrap(); - assert_ne!(r1, r2); - } - - #[test] - fn test_ord() { - let buf1 = 0_u64; - let r1 = Ref::<_, u64>::new(buf1.as_bytes()).unwrap(); - let buf2 = 1_u64; - let r2 = Ref::<_, u64>::new(buf2.as_bytes()).unwrap(); - assert!(r1 < r2); - } - - #[test] - fn test_new_zeroed() { - assert!(!bool::new_zeroed()); - assert_eq!(u64::new_zeroed(), 0); - // This test exists in order to exercise unsafe code, especially when - // running under Miri. - #[allow(clippy::unit_cmp)] - { - assert_eq!(<()>::new_zeroed(), ()); - } - } - - #[test] - fn test_transparent_packed_generic_struct() { - #[derive(AsBytes, FromZeroes, FromBytes, Unaligned)] - #[repr(transparent)] - #[allow(dead_code)] // for the unused fields - struct Foo<T> { - _t: T, - _phantom: PhantomData<()>, - } - - assert_impl_all!(Foo<u32>: FromZeroes, FromBytes, AsBytes); - assert_impl_all!(Foo<u8>: Unaligned); - - #[derive(AsBytes, FromZeroes, FromBytes, Unaligned)] - #[repr(packed)] - #[allow(dead_code)] // for the unused fields - struct Bar<T, U> { - _t: T, - _u: U, - } - - assert_impl_all!(Bar<u8, AU64>: FromZeroes, FromBytes, AsBytes, Unaligned); - } - - #[test] - fn test_impls() { - use core::borrow::Borrow; - - // A type that can supply test cases for testing - // `TryFromBytes::is_bit_valid`. All types passed to `assert_impls!` - // must implement this trait; that macro uses it to generate runtime - // tests for `TryFromBytes` impls. - // - // All `T: FromBytes` types are provided with a blanket impl. Other - // types must implement `TryFromBytesTestable` directly (ie using - // `impl_try_from_bytes_testable!`). - trait TryFromBytesTestable { - fn with_passing_test_cases<F: Fn(&Self)>(f: F); - fn with_failing_test_cases<F: Fn(&[u8])>(f: F); - } - - impl<T: FromBytes> TryFromBytesTestable for T { - fn with_passing_test_cases<F: Fn(&Self)>(f: F) { - // Test with a zeroed value. - f(&Self::new_zeroed()); - - let ffs = { - let mut t = Self::new_zeroed(); - let ptr: *mut T = &mut t; - // SAFETY: `T: FromBytes` - unsafe { ptr::write_bytes(ptr.cast::<u8>(), 0xFF, mem::size_of::<T>()) }; - t - }; - - // Test with a value initialized with 0xFF. - f(&ffs); - } - - fn with_failing_test_cases<F: Fn(&[u8])>(_f: F) {} - } - - // Implements `TryFromBytesTestable`. - macro_rules! impl_try_from_bytes_testable { - // Base case for recursion (when the list of types has run out). - (=> @success $($success_case:expr),* $(, @failure $($failure_case:expr),*)?) => {}; - // Implements for type(s) with no type parameters. - ($ty:ty $(,$tys:ty)* => @success $($success_case:expr),* $(, @failure $($failure_case:expr),*)?) => { - impl TryFromBytesTestable for $ty { - impl_try_from_bytes_testable!( - @methods @success $($success_case),* - $(, @failure $($failure_case),*)? - ); - } - impl_try_from_bytes_testable!($($tys),* => @success $($success_case),* $(, @failure $($failure_case),*)?); - }; - // Implements for multiple types with no type parameters. - ($($($ty:ty),* => @success $($success_case:expr), * $(, @failure $($failure_case:expr),*)?;)*) => { - $( - impl_try_from_bytes_testable!($($ty),* => @success $($success_case),* $(, @failure $($failure_case),*)*); - )* - }; - // Implements only the methods; caller must invoke this from inside - // an impl block. - (@methods @success $($success_case:expr),* $(, @failure $($failure_case:expr),*)?) => { - fn with_passing_test_cases<F: Fn(&Self)>(_f: F) { - $( - _f($success_case.borrow()); - )* - } - - fn with_failing_test_cases<F: Fn(&[u8])>(_f: F) { - $($( - let case = $failure_case.as_bytes(); - _f(case.as_bytes()); - )*)? - } - }; - } - - // Note that these impls are only for types which are not `FromBytes`. - // `FromBytes` types are covered by a preceding blanket impl. - impl_try_from_bytes_testable!( - bool => @success true, false, - @failure 2u8, 3u8, 0xFFu8; - char => @success '\u{0}', '\u{D7FF}', '\u{E000}', '\u{10FFFF}', - @failure 0xD800u32, 0xDFFFu32, 0x110000u32; - str => @success "", "hello", "❤️🧡💛💚💙💜", - @failure [0, 159, 146, 150]; - [u8] => @success [], [0, 1, 2]; - NonZeroU8, NonZeroI8, NonZeroU16, NonZeroI16, NonZeroU32, - NonZeroI32, NonZeroU64, NonZeroI64, NonZeroU128, NonZeroI128, - NonZeroUsize, NonZeroIsize - => @success Self::new(1).unwrap(), - // Doing this instead of `0` ensures that we always satisfy - // the size and alignment requirements of `Self` (whereas - // `0` may be any integer type with a different size or - // alignment than some `NonZeroXxx` types). - @failure Option::<Self>::None; - [bool] - => @success [true, false], [false, true], - @failure [2u8], [3u8], [0xFFu8], [0u8, 1u8, 2u8]; - ); - - // Asserts that `$ty` implements any `$trait` and doesn't implement any - // `!$trait`. Note that all `$trait`s must come before any `!$trait`s. - // - // For `T: TryFromBytes`, uses `TryFromBytesTestable` to test success - // and failure cases for `TryFromBytes::is_bit_valid`. - macro_rules! assert_impls { - ($ty:ty: TryFromBytes) => { - <$ty as TryFromBytesTestable>::with_passing_test_cases(|val| { - let c = Ptr::from(val); - // SAFETY: - // - Since `val` is a normal reference, `c` is guranteed to - // be aligned, to point to a single allocation, and to - // have a size which doesn't overflow `isize`. - // - Since `val` is a valid `$ty`, `c`'s referent satisfies - // the bit validity constraints of `is_bit_valid`, which - // are a superset of the bit validity constraints of - // `$ty`. - let res = unsafe { <$ty as TryFromBytes>::is_bit_valid(c) }; - assert!(res, "{}::is_bit_valid({:?}): got false, expected true", stringify!($ty), val); - - // TODO(#5): In addition to testing `is_bit_valid`, test the - // methods built on top of it. This would both allow us to - // test their implementations and actually convert the bytes - // to `$ty`, giving Miri a chance to catch if this is - // unsound (ie, if our `is_bit_valid` impl is buggy). - // - // The following code was tried, but it doesn't work because - // a) some types are not `AsBytes` and, b) some types are - // not `Sized`. - // - // let r = <$ty as TryFromBytes>::try_from_ref(val.as_bytes()).unwrap(); - // assert_eq!(r, &val); - // let r = <$ty as TryFromBytes>::try_from_mut(val.as_bytes_mut()).unwrap(); - // assert_eq!(r, &mut val); - // let v = <$ty as TryFromBytes>::try_read_from(val.as_bytes()).unwrap(); - // assert_eq!(v, val); - }); - #[allow(clippy::as_conversions)] - <$ty as TryFromBytesTestable>::with_failing_test_cases(|c| { - let res = <$ty as TryFromBytes>::try_from_ref(c); - assert!(res.is_none(), "{}::is_bit_valid({:?}): got true, expected false", stringify!($ty), c); - }); - - #[allow(dead_code)] - const _: () = { static_assertions::assert_impl_all!($ty: TryFromBytes); }; - }; - ($ty:ty: $trait:ident) => { - #[allow(dead_code)] - const _: () = { static_assertions::assert_impl_all!($ty: $trait); }; - }; - ($ty:ty: !$trait:ident) => { - #[allow(dead_code)] - const _: () = { static_assertions::assert_not_impl_any!($ty: $trait); }; - }; - ($ty:ty: $($trait:ident),* $(,)? $(!$negative_trait:ident),*) => { - $( - assert_impls!($ty: $trait); - )* - - $( - assert_impls!($ty: !$negative_trait); - )* - }; - } - - // NOTE: The negative impl assertions here are not necessarily - // prescriptive. They merely serve as change detectors to make sure - // we're aware of what trait impls are getting added with a given - // change. Of course, some impls would be invalid (e.g., `bool: - // FromBytes`), and so this change detection is very important. - - assert_impls!((): KnownLayout, TryFromBytes, FromZeroes, FromBytes, AsBytes, Unaligned); - assert_impls!(u8: KnownLayout, TryFromBytes, FromZeroes, FromBytes, AsBytes, Unaligned); - assert_impls!(i8: KnownLayout, TryFromBytes, FromZeroes, FromBytes, AsBytes, Unaligned); - assert_impls!(u16: KnownLayout, TryFromBytes, FromZeroes, FromBytes, AsBytes, !Unaligned); - assert_impls!(i16: KnownLayout, TryFromBytes, FromZeroes, FromBytes, AsBytes, !Unaligned); - assert_impls!(u32: KnownLayout, TryFromBytes, FromZeroes, FromBytes, AsBytes, !Unaligned); - assert_impls!(i32: KnownLayout, TryFromBytes, FromZeroes, FromBytes, AsBytes, !Unaligned); - assert_impls!(u64: KnownLayout, TryFromBytes, FromZeroes, FromBytes, AsBytes, !Unaligned); - assert_impls!(i64: KnownLayout, TryFromBytes, FromZeroes, FromBytes, AsBytes, !Unaligned); - assert_impls!(u128: KnownLayout, TryFromBytes, FromZeroes, FromBytes, AsBytes, !Unaligned); - assert_impls!(i128: KnownLayout, TryFromBytes, FromZeroes, FromBytes, AsBytes, !Unaligned); - assert_impls!(usize: KnownLayout, TryFromBytes, FromZeroes, FromBytes, AsBytes, !Unaligned); - assert_impls!(isize: KnownLayout, TryFromBytes, FromZeroes, FromBytes, AsBytes, !Unaligned); - assert_impls!(f32: KnownLayout, TryFromBytes, FromZeroes, FromBytes, AsBytes, !Unaligned); - assert_impls!(f64: KnownLayout, TryFromBytes, FromZeroes, FromBytes, AsBytes, !Unaligned); - - assert_impls!(bool: KnownLayout, TryFromBytes, FromZeroes, AsBytes, Unaligned, !FromBytes); - assert_impls!(char: KnownLayout, TryFromBytes, FromZeroes, AsBytes, !FromBytes, !Unaligned); - assert_impls!(str: KnownLayout, TryFromBytes, FromZeroes, AsBytes, Unaligned, !FromBytes); - - assert_impls!(NonZeroU8: KnownLayout, TryFromBytes, AsBytes, Unaligned, !FromZeroes, !FromBytes); - assert_impls!(NonZeroI8: KnownLayout, TryFromBytes, AsBytes, Unaligned, !FromZeroes, !FromBytes); - assert_impls!(NonZeroU16: KnownLayout, TryFromBytes, AsBytes, !FromBytes, !Unaligned); - assert_impls!(NonZeroI16: KnownLayout, TryFromBytes, AsBytes, !FromBytes, !Unaligned); - assert_impls!(NonZeroU32: KnownLayout, TryFromBytes, AsBytes, !FromBytes, !Unaligned); - assert_impls!(NonZeroI32: KnownLayout, TryFromBytes, AsBytes, !FromBytes, !Unaligned); - assert_impls!(NonZeroU64: KnownLayout, TryFromBytes, AsBytes, !FromBytes, !Unaligned); - assert_impls!(NonZeroI64: KnownLayout, TryFromBytes, AsBytes, !FromBytes, !Unaligned); - assert_impls!(NonZeroU128: KnownLayout, TryFromBytes, AsBytes, !FromBytes, !Unaligned); - assert_impls!(NonZeroI128: KnownLayout, TryFromBytes, AsBytes, !FromBytes, !Unaligned); - assert_impls!(NonZeroUsize: KnownLayout, TryFromBytes, AsBytes, !FromBytes, !Unaligned); - assert_impls!(NonZeroIsize: KnownLayout, TryFromBytes, AsBytes, !FromBytes, !Unaligned); - - assert_impls!(Option<NonZeroU8>: KnownLayout, TryFromBytes, FromZeroes, FromBytes, AsBytes, Unaligned); - assert_impls!(Option<NonZeroI8>: KnownLayout, TryFromBytes, FromZeroes, FromBytes, AsBytes, Unaligned); - assert_impls!(Option<NonZeroU16>: KnownLayout, TryFromBytes, FromZeroes, FromBytes, AsBytes, !Unaligned); - assert_impls!(Option<NonZeroI16>: KnownLayout, TryFromBytes, FromZeroes, FromBytes, AsBytes, !Unaligned); - assert_impls!(Option<NonZeroU32>: KnownLayout, TryFromBytes, FromZeroes, FromBytes, AsBytes, !Unaligned); - assert_impls!(Option<NonZeroI32>: KnownLayout, TryFromBytes, FromZeroes, FromBytes, AsBytes, !Unaligned); - assert_impls!(Option<NonZeroU64>: KnownLayout, TryFromBytes, FromZeroes, FromBytes, AsBytes, !Unaligned); - assert_impls!(Option<NonZeroI64>: KnownLayout, TryFromBytes, FromZeroes, FromBytes, AsBytes, !Unaligned); - assert_impls!(Option<NonZeroU128>: KnownLayout, TryFromBytes, FromZeroes, FromBytes, AsBytes, !Unaligned); - assert_impls!(Option<NonZeroI128>: KnownLayout, TryFromBytes, FromZeroes, FromBytes, AsBytes, !Unaligned); - assert_impls!(Option<NonZeroUsize>: KnownLayout, TryFromBytes, FromZeroes, FromBytes, AsBytes, !Unaligned); - assert_impls!(Option<NonZeroIsize>: KnownLayout, TryFromBytes, FromZeroes, FromBytes, AsBytes, !Unaligned); - - // Implements none of the ZC traits. - struct NotZerocopy; - - #[rustfmt::skip] - type FnManyArgs = fn( - NotZerocopy, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, - ) -> (NotZerocopy, NotZerocopy); - - // Allowed, because we're not actually using this type for FFI. - #[allow(improper_ctypes_definitions)] - #[rustfmt::skip] - type ECFnManyArgs = extern "C" fn( - NotZerocopy, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, - ) -> (NotZerocopy, NotZerocopy); - - #[cfg(feature = "alloc")] - assert_impls!(Option<Box<UnsafeCell<NotZerocopy>>>: KnownLayout, FromZeroes, !TryFromBytes, !FromBytes, !AsBytes, !Unaligned); - assert_impls!(Option<Box<[UnsafeCell<NotZerocopy>]>>: KnownLayout, !TryFromBytes, !FromZeroes, !FromBytes, !AsBytes, !Unaligned); - assert_impls!(Option<&'static UnsafeCell<NotZerocopy>>: KnownLayout, FromZeroes, !TryFromBytes, !FromBytes, !AsBytes, !Unaligned); - assert_impls!(Option<&'static [UnsafeCell<NotZerocopy>]>: KnownLayout, !TryFromBytes, !FromZeroes, !FromBytes, !AsBytes, !Unaligned); - assert_impls!(Option<&'static mut UnsafeCell<NotZerocopy>>: KnownLayout, FromZeroes, !TryFromBytes, !FromBytes, !AsBytes, !Unaligned); - assert_impls!(Option<&'static mut [UnsafeCell<NotZerocopy>]>: KnownLayout, !TryFromBytes, !FromZeroes, !FromBytes, !AsBytes, !Unaligned); - assert_impls!(Option<NonNull<UnsafeCell<NotZerocopy>>>: KnownLayout, FromZeroes, !TryFromBytes, !FromBytes, !AsBytes, !Unaligned); - assert_impls!(Option<NonNull<[UnsafeCell<NotZerocopy>]>>: KnownLayout, !TryFromBytes, !FromZeroes, !FromBytes, !AsBytes, !Unaligned); - assert_impls!(Option<fn()>: KnownLayout, FromZeroes, !TryFromBytes, !FromBytes, !AsBytes, !Unaligned); - assert_impls!(Option<FnManyArgs>: KnownLayout, FromZeroes, !TryFromBytes, !FromBytes, !AsBytes, !Unaligned); - assert_impls!(Option<extern "C" fn()>: KnownLayout, FromZeroes, !TryFromBytes, !FromBytes, !AsBytes, !Unaligned); - assert_impls!(Option<ECFnManyArgs>: KnownLayout, FromZeroes, !TryFromBytes, !FromBytes, !AsBytes, !Unaligned); - - assert_impls!(PhantomData<NotZerocopy>: KnownLayout, TryFromBytes, FromZeroes, FromBytes, AsBytes, Unaligned); - assert_impls!(PhantomData<[u8]>: KnownLayout, TryFromBytes, FromZeroes, FromBytes, AsBytes, Unaligned); - - assert_impls!(ManuallyDrop<u8>: KnownLayout, FromZeroes, FromBytes, AsBytes, Unaligned, !TryFromBytes); - assert_impls!(ManuallyDrop<[u8]>: KnownLayout, FromZeroes, FromBytes, AsBytes, Unaligned, !TryFromBytes); - assert_impls!(ManuallyDrop<NotZerocopy>: !TryFromBytes, !KnownLayout, !FromZeroes, !FromBytes, !AsBytes, !Unaligned); - assert_impls!(ManuallyDrop<[NotZerocopy]>: !TryFromBytes, !KnownLayout, !FromZeroes, !FromBytes, !AsBytes, !Unaligned); - - assert_impls!(MaybeUninit<u8>: KnownLayout, TryFromBytes, FromZeroes, FromBytes, Unaligned, !AsBytes); - assert_impls!(MaybeUninit<NotZerocopy>: KnownLayout, !TryFromBytes, !FromZeroes, !FromBytes, !AsBytes, !Unaligned); - - assert_impls!(Wrapping<u8>: KnownLayout, TryFromBytes, FromZeroes, FromBytes, AsBytes, Unaligned); - assert_impls!(Wrapping<NotZerocopy>: KnownLayout, !TryFromBytes, !FromZeroes, !FromBytes, !AsBytes, !Unaligned); - - assert_impls!(Unalign<u8>: KnownLayout, FromZeroes, FromBytes, AsBytes, Unaligned, !TryFromBytes); - assert_impls!(Unalign<NotZerocopy>: Unaligned, !KnownLayout, !TryFromBytes, !FromZeroes, !FromBytes, !AsBytes); - - assert_impls!([u8]: KnownLayout, TryFromBytes, FromZeroes, FromBytes, AsBytes, Unaligned); - assert_impls!([bool]: KnownLayout, TryFromBytes, FromZeroes, AsBytes, Unaligned, !FromBytes); - assert_impls!([NotZerocopy]: !KnownLayout, !TryFromBytes, !FromZeroes, !FromBytes, !AsBytes, !Unaligned); - assert_impls!([u8; 0]: KnownLayout, FromZeroes, FromBytes, AsBytes, Unaligned, !TryFromBytes); - assert_impls!([NotZerocopy; 0]: KnownLayout, !TryFromBytes, !FromZeroes, !FromBytes, !AsBytes, !Unaligned); - assert_impls!([u8; 1]: KnownLayout, FromZeroes, FromBytes, AsBytes, Unaligned, !TryFromBytes); - assert_impls!([NotZerocopy; 1]: KnownLayout, !TryFromBytes, !FromZeroes, !FromBytes, !AsBytes, !Unaligned); - - assert_impls!(*const NotZerocopy: KnownLayout, FromZeroes, !TryFromBytes, !FromBytes, !AsBytes, !Unaligned); - assert_impls!(*mut NotZerocopy: KnownLayout, FromZeroes, !TryFromBytes, !FromBytes, !AsBytes, !Unaligned); - assert_impls!(*const [NotZerocopy]: KnownLayout, !TryFromBytes, !FromZeroes, !FromBytes, !AsBytes, !Unaligned); - assert_impls!(*mut [NotZerocopy]: KnownLayout, !TryFromBytes, !FromZeroes, !FromBytes, !AsBytes, !Unaligned); - assert_impls!(*const dyn Debug: KnownLayout, !TryFromBytes, !FromZeroes, !FromBytes, !AsBytes, !Unaligned); - assert_impls!(*mut dyn Debug: KnownLayout, !TryFromBytes, !FromZeroes, !FromBytes, !AsBytes, !Unaligned); - - #[cfg(feature = "simd")] - { - #[allow(unused_macros)] - macro_rules! test_simd_arch_mod { - ($arch:ident, $($typ:ident),*) => { - { - use core::arch::$arch::{$($typ),*}; - use crate::*; - $( assert_impls!($typ: KnownLayout, TryFromBytes, FromZeroes, FromBytes, AsBytes, !Unaligned); )* - } - }; - } - #[cfg(target_arch = "x86")] - test_simd_arch_mod!(x86, __m128, __m128d, __m128i, __m256, __m256d, __m256i); - - #[cfg(all(feature = "simd-nightly", target_arch = "x86"))] - test_simd_arch_mod!(x86, __m512bh, __m512, __m512d, __m512i); - - #[cfg(target_arch = "x86_64")] - test_simd_arch_mod!(x86_64, __m128, __m128d, __m128i, __m256, __m256d, __m256i); - - #[cfg(all(feature = "simd-nightly", target_arch = "x86_64"))] - test_simd_arch_mod!(x86_64, __m512bh, __m512, __m512d, __m512i); - - #[cfg(target_arch = "wasm32")] - test_simd_arch_mod!(wasm32, v128); - - #[cfg(all(feature = "simd-nightly", target_arch = "powerpc"))] - test_simd_arch_mod!( - powerpc, - vector_bool_long, - vector_double, - vector_signed_long, - vector_unsigned_long - ); - - #[cfg(all(feature = "simd-nightly", target_arch = "powerpc64"))] - test_simd_arch_mod!( - powerpc64, - vector_bool_long, - vector_double, - vector_signed_long, - vector_unsigned_long - ); - #[cfg(target_arch = "aarch64")] - #[rustfmt::skip] - test_simd_arch_mod!( - aarch64, float32x2_t, float32x4_t, float64x1_t, float64x2_t, int8x8_t, int8x8x2_t, - int8x8x3_t, int8x8x4_t, int8x16_t, int8x16x2_t, int8x16x3_t, int8x16x4_t, int16x4_t, - int16x8_t, int32x2_t, int32x4_t, int64x1_t, int64x2_t, poly8x8_t, poly8x8x2_t, poly8x8x3_t, - poly8x8x4_t, poly8x16_t, poly8x16x2_t, poly8x16x3_t, poly8x16x4_t, poly16x4_t, poly16x8_t, - poly64x1_t, poly64x2_t, uint8x8_t, uint8x8x2_t, uint8x8x3_t, uint8x8x4_t, uint8x16_t, - uint8x16x2_t, uint8x16x3_t, uint8x16x4_t, uint16x4_t, uint16x8_t, uint32x2_t, uint32x4_t, - uint64x1_t, uint64x2_t - ); - #[cfg(all(feature = "simd-nightly", target_arch = "arm"))] - #[rustfmt::skip] - test_simd_arch_mod!(arm, int8x4_t, uint8x4_t); - } - } -} - -#[cfg(kani)] -mod proofs { - use super::*; - - impl kani::Arbitrary for DstLayout { - fn any() -> Self { - let align: NonZeroUsize = kani::any(); - let size_info: SizeInfo = kani::any(); - - kani::assume(align.is_power_of_two()); - kani::assume(align < DstLayout::THEORETICAL_MAX_ALIGN); - - // For testing purposes, we most care about instantiations of - // `DstLayout` that can correspond to actual Rust types. We use - // `Layout` to verify that our `DstLayout` satisfies the validity - // conditions of Rust layouts. - kani::assume( - match size_info { - SizeInfo::Sized { _size } => Layout::from_size_align(_size, align.get()), - SizeInfo::SliceDst(TrailingSliceLayout { _offset, _elem_size }) => { - // `SliceDst`` cannot encode an exact size, but we know - // it is at least `_offset` bytes. - Layout::from_size_align(_offset, align.get()) - } - } - .is_ok(), - ); - - Self { align: align, size_info: size_info } - } - } - - impl kani::Arbitrary for SizeInfo { - fn any() -> Self { - let is_sized: bool = kani::any(); - - match is_sized { - true => { - let size: usize = kani::any(); - - kani::assume(size <= isize::MAX as _); - - SizeInfo::Sized { _size: size } - } - false => SizeInfo::SliceDst(kani::any()), - } - } - } - - impl kani::Arbitrary for TrailingSliceLayout { - fn any() -> Self { - let elem_size: usize = kani::any(); - let offset: usize = kani::any(); - - kani::assume(elem_size < isize::MAX as _); - kani::assume(offset < isize::MAX as _); - - TrailingSliceLayout { _elem_size: elem_size, _offset: offset } - } - } - - #[kani::proof] - fn prove_dst_layout_extend() { - use crate::util::{core_layout::padding_needed_for, max, min}; - - let base: DstLayout = kani::any(); - let field: DstLayout = kani::any(); - let packed: Option<NonZeroUsize> = kani::any(); - - if let Some(max_align) = packed { - kani::assume(max_align.is_power_of_two()); - kani::assume(base.align <= max_align); - } - - // The base can only be extended if it's sized. - kani::assume(matches!(base.size_info, SizeInfo::Sized { .. })); - let base_size = if let SizeInfo::Sized { _size: size } = base.size_info { - size - } else { - unreachable!(); - }; - - // Under the above conditions, `DstLayout::extend` will not panic. - let composite = base.extend(field, packed); - - // The field's alignment is clamped by `max_align` (i.e., the - // `packed` attribute, if any) [1]. - // - // [1] Per https://doc.rust-lang.org/reference/type-layout.html#the-alignment-modifiers: - // - // The alignments of each field, for the purpose of positioning - // fields, is the smaller of the specified alignment and the - // alignment of the field's type. - let field_align = min(field.align, packed.unwrap_or(DstLayout::THEORETICAL_MAX_ALIGN)); - - // The struct's alignment is the maximum of its previous alignment and - // `field_align`. - assert_eq!(composite.align, max(base.align, field_align)); - - // Compute the minimum amount of inter-field padding needed to - // satisfy the field's alignment, and offset of the trailing field. - // [1] - // - // [1] Per https://doc.rust-lang.org/reference/type-layout.html#the-alignment-modifiers: - // - // Inter-field padding is guaranteed to be the minimum required in - // order to satisfy each field's (possibly altered) alignment. - let padding = padding_needed_for(base_size, field_align); - let offset = base_size + padding; - - // For testing purposes, we'll also construct `alloc::Layout` - // stand-ins for `DstLayout`, and show that `extend` behaves - // comparably on both types. - let base_analog = Layout::from_size_align(base_size, base.align.get()).unwrap(); - - match field.size_info { - SizeInfo::Sized { _size: field_size } => { - if let SizeInfo::Sized { _size: composite_size } = composite.size_info { - // If the trailing field is sized, the resulting layout - // will be sized. Its size will be the sum of the - // preceeding layout, the size of the new field, and the - // size of inter-field padding between the two. - assert_eq!(composite_size, offset + field_size); - - let field_analog = - Layout::from_size_align(field_size, field_align.get()).unwrap(); - - if let Ok((actual_composite, actual_offset)) = base_analog.extend(field_analog) - { - assert_eq!(actual_offset, offset); - assert_eq!(actual_composite.size(), composite_size); - assert_eq!(actual_composite.align(), composite.align.get()); - } else { - // An error here reflects that composite of `base` - // and `field` cannot correspond to a real Rust type - // fragment, because such a fragment would violate - // the basic invariants of a valid Rust layout. At - // the time of writing, `DstLayout` is a little more - // permissive than `Layout`, so we don't assert - // anything in this branch (e.g., unreachability). - } - } else { - panic!("The composite of two sized layouts must be sized.") - } - } - SizeInfo::SliceDst(TrailingSliceLayout { - _offset: field_offset, - _elem_size: field_elem_size, - }) => { - if let SizeInfo::SliceDst(TrailingSliceLayout { - _offset: composite_offset, - _elem_size: composite_elem_size, - }) = composite.size_info - { - // The offset of the trailing slice component is the sum - // of the offset of the trailing field and the trailing - // slice offset within that field. - assert_eq!(composite_offset, offset + field_offset); - // The elem size is unchanged. - assert_eq!(composite_elem_size, field_elem_size); - - let field_analog = - Layout::from_size_align(field_offset, field_align.get()).unwrap(); - - if let Ok((actual_composite, actual_offset)) = base_analog.extend(field_analog) - { - assert_eq!(actual_offset, offset); - assert_eq!(actual_composite.size(), composite_offset); - assert_eq!(actual_composite.align(), composite.align.get()); - } else { - // An error here reflects that composite of `base` - // and `field` cannot correspond to a real Rust type - // fragment, because such a fragment would violate - // the basic invariants of a valid Rust layout. At - // the time of writing, `DstLayout` is a little more - // permissive than `Layout`, so we don't assert - // anything in this branch (e.g., unreachability). - } - } else { - panic!("The extension of a layout with a DST must result in a DST.") - } - } - } - } - - #[kani::proof] - #[kani::should_panic] - fn prove_dst_layout_extend_dst_panics() { - let base: DstLayout = kani::any(); - let field: DstLayout = kani::any(); - let packed: Option<NonZeroUsize> = kani::any(); - - if let Some(max_align) = packed { - kani::assume(max_align.is_power_of_two()); - kani::assume(base.align <= max_align); - } - - kani::assume(matches!(base.size_info, SizeInfo::SliceDst(..))); - - let _ = base.extend(field, packed); - } - - #[kani::proof] - fn prove_dst_layout_pad_to_align() { - use crate::util::core_layout::padding_needed_for; - - let layout: DstLayout = kani::any(); - - let padded: DstLayout = layout.pad_to_align(); - - // Calling `pad_to_align` does not alter the `DstLayout`'s alignment. - assert_eq!(padded.align, layout.align); - - if let SizeInfo::Sized { _size: unpadded_size } = layout.size_info { - if let SizeInfo::Sized { _size: padded_size } = padded.size_info { - // If the layout is sized, it will remain sized after padding is - // added. Its sum will be its unpadded size and the size of the - // trailing padding needed to satisfy its alignment - // requirements. - let padding = padding_needed_for(unpadded_size, layout.align); - assert_eq!(padded_size, unpadded_size + padding); - - // Prove that calling `DstLayout::pad_to_align` behaves - // identically to `Layout::pad_to_align`. - let layout_analog = - Layout::from_size_align(unpadded_size, layout.align.get()).unwrap(); - let padded_analog = layout_analog.pad_to_align(); - assert_eq!(padded_analog.align(), layout.align.get()); - assert_eq!(padded_analog.size(), padded_size); - } else { - panic!("The padding of a sized layout must result in a sized layout.") - } - } else { - // If the layout is a DST, padding cannot be statically added. - assert_eq!(padded.size_info, layout.size_info); - } - } -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/src/macro_util.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/src/macro_util.rs deleted file mode 100644 index d2c61ca..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/src/macro_util.rs +++ /dev/null
@@ -1,673 +0,0 @@ -// Copyright 2022 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -//! Utilities used by macros and by `zerocopy-derive`. -//! -//! These are defined here `zerocopy` rather than in code generated by macros or -//! by `zerocopy-derive` so that they can be compiled once rather than -//! recompiled for every invocation (e.g., if they were defined in generated -//! code, then deriving `AsBytes` and `FromBytes` on three different types would -//! result in the code in question being emitted and compiled six different -//! times). - -#![allow(missing_debug_implementations)] - -use core::{marker::PhantomData, mem::ManuallyDrop}; - -// TODO(#29), TODO(https://github.com/rust-lang/rust/issues/69835): Remove this -// `cfg` when `size_of_val_raw` is stabilized. -#[cfg(__INTERNAL_USE_ONLY_NIGHLTY_FEATURES_IN_TESTS)] -use core::ptr::{self, NonNull}; - -/// A compile-time check that should be one particular value. -pub trait ShouldBe<const VALUE: bool> {} - -/// A struct for checking whether `T` contains padding. -pub struct HasPadding<T: ?Sized, const VALUE: bool>(PhantomData<T>); - -impl<T: ?Sized, const VALUE: bool> ShouldBe<VALUE> for HasPadding<T, VALUE> {} - -/// A type whose size is equal to `align_of::<T>()`. -#[repr(C)] -pub struct AlignOf<T> { - // This field ensures that: - // - The size is always at least 1 (the minimum possible alignment). - // - If the alignment is greater than 1, Rust has to round up to the next - // multiple of it in order to make sure that `Align`'s size is a multiple - // of that alignment. Without this field, its size could be 0, which is a - // valid multiple of any alignment. - _u: u8, - _a: [T; 0], -} - -impl<T> AlignOf<T> { - #[inline(never)] // Make `missing_inline_in_public_items` happy. - pub fn into_t(self) -> T { - unreachable!() - } -} - -/// A type whose size is equal to `max(align_of::<T>(), align_of::<U>())`. -#[repr(C)] -pub union MaxAlignsOf<T, U> { - _t: ManuallyDrop<AlignOf<T>>, - _u: ManuallyDrop<AlignOf<U>>, -} - -impl<T, U> MaxAlignsOf<T, U> { - #[inline(never)] // Make `missing_inline_in_public_items` happy. - pub fn new(_t: T, _u: U) -> MaxAlignsOf<T, U> { - unreachable!() - } -} - -const _64K: usize = 1 << 16; - -// TODO(#29), TODO(https://github.com/rust-lang/rust/issues/69835): Remove this -// `cfg` when `size_of_val_raw` is stabilized. -#[cfg(__INTERNAL_USE_ONLY_NIGHLTY_FEATURES_IN_TESTS)] -#[repr(C, align(65536))] -struct Aligned64kAllocation([u8; _64K]); - -/// A pointer to an aligned allocation of size 2^16. -/// -/// # Safety -/// -/// `ALIGNED_64K_ALLOCATION` is guaranteed to point to the entirety of an -/// allocation with size and alignment 2^16, and to have valid provenance. -// TODO(#29), TODO(https://github.com/rust-lang/rust/issues/69835): Remove this -// `cfg` when `size_of_val_raw` is stabilized. -#[cfg(__INTERNAL_USE_ONLY_NIGHLTY_FEATURES_IN_TESTS)] -pub const ALIGNED_64K_ALLOCATION: NonNull<[u8]> = { - const REF: &Aligned64kAllocation = &Aligned64kAllocation([0; _64K]); - let ptr: *const Aligned64kAllocation = REF; - let ptr: *const [u8] = ptr::slice_from_raw_parts(ptr.cast(), _64K); - // SAFETY: - // - `ptr` is derived from a Rust reference, which is guaranteed to be - // non-null. - // - `ptr` is derived from an `&Aligned64kAllocation`, which has size and - // alignment `_64K` as promised. Its length is initialized to `_64K`, - // which means that it refers to the entire allocation. - // - `ptr` is derived from a Rust reference, which is guaranteed to have - // valid provenance. - // - // TODO(#429): Once `NonNull::new_unchecked` docs document that it preserves - // provenance, cite those docs. - // TODO: Replace this `as` with `ptr.cast_mut()` once our MSRV >= 1.65 - #[allow(clippy::as_conversions)] - unsafe { - NonNull::new_unchecked(ptr as *mut _) - } -}; - -/// Computes the offset of the base of the field `$trailing_field_name` within -/// the type `$ty`. -/// -/// `trailing_field_offset!` produces code which is valid in a `const` context. -// TODO(#29), TODO(https://github.com/rust-lang/rust/issues/69835): Remove this -// `cfg` when `size_of_val_raw` is stabilized. -#[cfg(__INTERNAL_USE_ONLY_NIGHLTY_FEATURES_IN_TESTS)] -#[doc(hidden)] // `#[macro_export]` bypasses this module's `#[doc(hidden)]`. -#[macro_export] -macro_rules! trailing_field_offset { - ($ty:ty, $trailing_field_name:tt) => {{ - let min_size = { - let zero_elems: *const [()] = - $crate::macro_util::core_reexport::ptr::slice_from_raw_parts( - $crate::macro_util::core_reexport::ptr::NonNull::<()>::dangling() - .as_ptr() - .cast_const(), - 0, - ); - // SAFETY: - // - If `$ty` is `Sized`, `size_of_val_raw` is always safe to call. - // - Otherwise: - // - If `$ty` is not a slice DST, this pointer conversion will - // fail due to "mismatched vtable kinds", and compilation will - // fail. - // - If `$ty` is a slice DST, the safety requirement is that "the - // length of the slice tail must be an initialized integer, and - // the size of the entire value (dynamic tail length + - // statically sized prefix) must fit in isize." The length is - // initialized to 0 above, and Rust guarantees that no type's - // minimum size may overflow `isize`. [1] - // - // [1] TODO(#429), - // TODO(https://github.com/rust-lang/unsafe-code-guidelines/issues/465#issuecomment-1782206516): - // Citation for this? - unsafe { - #[allow(clippy::as_conversions)] - $crate::macro_util::core_reexport::mem::size_of_val_raw(zero_elems as *const $ty) - } - }; - - assert!(min_size <= _64K); - - #[allow(clippy::as_conversions)] - let ptr = ALIGNED_64K_ALLOCATION.as_ptr() as *const $ty; - - // SAFETY: - // - Thanks to the preceding `assert!`, we know that the value with zero - // elements fits in `_64K` bytes, and thus in the allocation addressed - // by `ALIGNED_64K_ALLOCATION`. The offset of the trailing field is - // guaranteed to be no larger than this size, so this field projection - // is guaranteed to remain in-bounds of its allocation. - // - Because the minimum size is no larger than `_64K` bytes, and - // because an object's size must always be a multiple of its alignment - // [1], we know that `$ty`'s alignment is no larger than `_64K`. The - // allocation addressed by `ALIGNED_64K_ALLOCATION` is guaranteed to - // be aligned to `_64K`, so `ptr` is guaranteed to satisfy `$ty`'s - // alignment. - // - // Note that, as of [2], this requirement is technically unnecessary - // for Rust versions >= 1.75.0, but no harm in guaranteeing it anyway - // until we bump our MSRV. - // - // [1] Per https://doc.rust-lang.org/reference/type-layout.html: - // - // The size of a value is always a multiple of its alignment. - // - // [2] https://github.com/rust-lang/reference/pull/1387 - let field = unsafe { - $crate::macro_util::core_reexport::ptr::addr_of!((*ptr).$trailing_field_name) - }; - // SAFETY: - // - Both `ptr` and `field` are derived from the same allocated object. - // - By the preceding safety comment, `field` is in bounds of that - // allocated object. - // - The distance, in bytes, between `ptr` and `field` is required to be - // a multiple of the size of `u8`, which is trivially true because - // `u8`'s size is 1. - // - The distance, in bytes, cannot overflow `isize`. This is guaranteed - // because no allocated object can have a size larger than can fit in - // `isize`. [1] - // - The distance being in-bounds cannot rely on wrapping around the - // address space. This is guaranteed because the same is guaranteed of - // allocated objects. [1] - // - // [1] TODO(#429), TODO(https://github.com/rust-lang/rust/pull/116675): - // Once these are guaranteed in the Reference, cite it. - let offset = unsafe { field.cast::<u8>().offset_from(ptr.cast::<u8>()) }; - // Guaranteed not to be lossy: `field` comes after `ptr`, so the offset - // from `ptr` to `field` is guaranteed to be positive. - assert!(offset >= 0); - Some( - #[allow(clippy::as_conversions)] - { - offset as usize - }, - ) - }}; -} - -/// Computes alignment of `$ty: ?Sized`. -/// -/// `align_of!` produces code which is valid in a `const` context. -// TODO(#29), TODO(https://github.com/rust-lang/rust/issues/69835): Remove this -// `cfg` when `size_of_val_raw` is stabilized. -#[cfg(__INTERNAL_USE_ONLY_NIGHLTY_FEATURES_IN_TESTS)] -#[doc(hidden)] // `#[macro_export]` bypasses this module's `#[doc(hidden)]`. -#[macro_export] -macro_rules! align_of { - ($ty:ty) => {{ - // SAFETY: `OffsetOfTrailingIsAlignment` is `repr(C)`, and its layout is - // guaranteed [1] to begin with the single-byte layout for `_byte`, - // followed by the padding needed to align `_trailing`, then the layout - // for `_trailing`, and finally any trailing padding bytes needed to - // correctly-align the entire struct. - // - // This macro computes the alignment of `$ty` by counting the number of - // bytes preceeding `_trailing`. For instance, if the alignment of `$ty` - // is `1`, then no padding is required align `_trailing` and it will be - // located immediately after `_byte` at offset 1. If the alignment of - // `$ty` is 2, then a single padding byte is required before - // `_trailing`, and `_trailing` will be located at offset 2. - - // This correspondence between offset and alignment holds for all valid - // Rust alignments, and we confirm this exhaustively (or, at least up to - // the maximum alignment supported by `trailing_field_offset!`) in - // `test_align_of_dst`. - // - // [1]: https://doc.rust-lang.org/nomicon/other-reprs.html#reprc - - #[repr(C)] - struct OffsetOfTrailingIsAlignment { - _byte: u8, - _trailing: $ty, - } - - trailing_field_offset!(OffsetOfTrailingIsAlignment, _trailing) - }}; -} - -/// Does the struct type `$t` have padding? -/// -/// `$ts` is the list of the type of every field in `$t`. `$t` must be a -/// struct type, or else `struct_has_padding!`'s result may be meaningless. -/// -/// Note that `struct_has_padding!`'s results are independent of `repr` since -/// they only consider the size of the type and the sizes of the fields. -/// Whatever the repr, the size of the type already takes into account any -/// padding that the compiler has decided to add. Structs with well-defined -/// representations (such as `repr(C)`) can use this macro to check for padding. -/// Note that while this may yield some consistent value for some `repr(Rust)` -/// structs, it is not guaranteed across platforms or compilations. -#[doc(hidden)] // `#[macro_export]` bypasses this module's `#[doc(hidden)]`. -#[macro_export] -macro_rules! struct_has_padding { - ($t:ty, $($ts:ty),*) => { - core::mem::size_of::<$t>() > 0 $(+ core::mem::size_of::<$ts>())* - }; -} - -/// Does the union type `$t` have padding? -/// -/// `$ts` is the list of the type of every field in `$t`. `$t` must be a -/// union type, or else `union_has_padding!`'s result may be meaningless. -/// -/// Note that `union_has_padding!`'s results are independent of `repr` since -/// they only consider the size of the type and the sizes of the fields. -/// Whatever the repr, the size of the type already takes into account any -/// padding that the compiler has decided to add. Unions with well-defined -/// representations (such as `repr(C)`) can use this macro to check for padding. -/// Note that while this may yield some consistent value for some `repr(Rust)` -/// unions, it is not guaranteed across platforms or compilations. -#[doc(hidden)] // `#[macro_export]` bypasses this module's `#[doc(hidden)]`. -#[macro_export] -macro_rules! union_has_padding { - ($t:ty, $($ts:ty),*) => { - false $(|| core::mem::size_of::<$t>() != core::mem::size_of::<$ts>())* - }; -} - -/// Does `t` have alignment greater than or equal to `u`? If not, this macro -/// produces a compile error. It must be invoked in a dead codepath. This is -/// used in `transmute_ref!` and `transmute_mut!`. -#[doc(hidden)] // `#[macro_export]` bypasses this module's `#[doc(hidden)]`. -#[macro_export] -macro_rules! assert_align_gt_eq { - ($t:ident, $u: ident) => {{ - // The comments here should be read in the context of this macro's - // invocations in `transmute_ref!` and `transmute_mut!`. - #[allow(clippy::missing_transmute_annotations)] - if false { - // The type wildcard in this bound is inferred to be `T` because - // `align_of.into_t()` is assigned to `t` (which has type `T`). - let align_of: $crate::macro_util::AlignOf<_> = unreachable!(); - $t = align_of.into_t(); - // `max_aligns` is inferred to have type `MaxAlignsOf<T, U>` because - // of the inferred types of `t` and `u`. - let mut max_aligns = $crate::macro_util::MaxAlignsOf::new($t, $u); - - // This transmute will only compile successfully if - // `align_of::<T>() == max(align_of::<T>(), align_of::<U>())` - in - // other words, if `align_of::<T>() >= align_of::<U>()`. - // - // SAFETY: This code is never run. - max_aligns = unsafe { $crate::macro_util::core_reexport::mem::transmute(align_of) }; - } else { - loop {} - } - }}; -} - -/// Do `t` and `u` have the same size? If not, this macro produces a compile -/// error. It must be invoked in a dead codepath. This is used in -/// `transmute_ref!` and `transmute_mut!`. -#[doc(hidden)] // `#[macro_export]` bypasses this module's `#[doc(hidden)]`. -#[macro_export] -macro_rules! assert_size_eq { - ($t:ident, $u: ident) => {{ - // The comments here should be read in the context of this macro's - // invocations in `transmute_ref!` and `transmute_mut!`. - if false { - // SAFETY: This code is never run. - $u = unsafe { - // Clippy: It's okay to transmute a type to itself. - #[allow(clippy::useless_transmute, clippy::missing_transmute_annotations)] - $crate::macro_util::core_reexport::mem::transmute($t) - }; - } else { - loop {} - } - }}; -} - -/// Transmutes a reference of one type to a reference of another type. -/// -/// # Safety -/// -/// The caller must guarantee that: -/// - `Src: AsBytes` -/// - `Dst: FromBytes` -/// - `size_of::<Src>() == size_of::<Dst>()` -/// - `align_of::<Src>() >= align_of::<Dst>()` -#[inline(always)] -pub const unsafe fn transmute_ref<'dst, 'src: 'dst, Src: 'src, Dst: 'dst>( - src: &'src Src, -) -> &'dst Dst { - let src: *const Src = src; - let dst = src.cast::<Dst>(); - // SAFETY: - // - We know that it is sound to view the target type of the input reference - // (`Src`) as the target type of the output reference (`Dst`) because the - // caller has guaranteed that `Src: AsBytes`, `Dst: FromBytes`, and - // `size_of::<Src>() == size_of::<Dst>()`. - // - We know that there are no `UnsafeCell`s, and thus we don't have to - // worry about `UnsafeCell` overlap, because `Src: AsBytes` and `Dst: - // FromBytes` both forbid `UnsafeCell`s. - // - The caller has guaranteed that alignment is not increased. - // - We know that the returned lifetime will not outlive the input lifetime - // thanks to the lifetime bounds on this function. - unsafe { &*dst } -} - -/// Transmutes a mutable reference of one type to a mutable reference of another -/// type. -/// -/// # Safety -/// -/// The caller must guarantee that: -/// - `Src: FromBytes + AsBytes` -/// - `Dst: FromBytes + AsBytes` -/// - `size_of::<Src>() == size_of::<Dst>()` -/// - `align_of::<Src>() >= align_of::<Dst>()` -#[inline(always)] -pub unsafe fn transmute_mut<'dst, 'src: 'dst, Src: 'src, Dst: 'dst>( - src: &'src mut Src, -) -> &'dst mut Dst { - let src: *mut Src = src; - let dst = src.cast::<Dst>(); - // SAFETY: - // - We know that it is sound to view the target type of the input reference - // (`Src`) as the target type of the output reference (`Dst`) and - // vice-versa because the caller has guaranteed that `Src: FromBytes + - // AsBytes`, `Dst: FromBytes + AsBytes`, and `size_of::<Src>() == - // size_of::<Dst>()`. - // - We know that there are no `UnsafeCell`s, and thus we don't have to - // worry about `UnsafeCell` overlap, because `Src: FromBytes + AsBytes` - // and `Dst: FromBytes + AsBytes` forbid `UnsafeCell`s. - // - The caller has guaranteed that alignment is not increased. - // - We know that the returned lifetime will not outlive the input lifetime - // thanks to the lifetime bounds on this function. - unsafe { &mut *dst } -} - -// NOTE: We can't change this to a `pub use core as core_reexport` until [1] is -// fixed or we update to a semver-breaking version (as of this writing, 0.8.0) -// on the `main` branch. -// -// [1] https://github.com/obi1kenobi/cargo-semver-checks/issues/573 -pub mod core_reexport { - pub use core::*; - - pub mod mem { - pub use core::mem::*; - } -} - -#[cfg(test)] -mod tests { - use core::mem; - - use super::*; - use crate::util::testutil::*; - - #[test] - fn test_align_of() { - macro_rules! test { - ($ty:ty) => { - assert_eq!(mem::size_of::<AlignOf<$ty>>(), mem::align_of::<$ty>()); - }; - } - - test!(()); - test!(u8); - test!(AU64); - test!([AU64; 2]); - } - - #[test] - fn test_max_aligns_of() { - macro_rules! test { - ($t:ty, $u:ty) => { - assert_eq!( - mem::size_of::<MaxAlignsOf<$t, $u>>(), - core::cmp::max(mem::align_of::<$t>(), mem::align_of::<$u>()) - ); - }; - } - - test!(u8, u8); - test!(u8, AU64); - test!(AU64, u8); - } - - #[test] - fn test_typed_align_check() { - // Test that the type-based alignment check used in - // `assert_align_gt_eq!` behaves as expected. - - macro_rules! assert_t_align_gteq_u_align { - ($t:ty, $u:ty, $gteq:expr) => { - assert_eq!( - mem::size_of::<MaxAlignsOf<$t, $u>>() == mem::size_of::<AlignOf<$t>>(), - $gteq - ); - }; - } - - assert_t_align_gteq_u_align!(u8, u8, true); - assert_t_align_gteq_u_align!(AU64, AU64, true); - assert_t_align_gteq_u_align!(AU64, u8, true); - assert_t_align_gteq_u_align!(u8, AU64, false); - } - - // TODO(#29), TODO(https://github.com/rust-lang/rust/issues/69835): Remove - // this `cfg` when `size_of_val_raw` is stabilized. - #[allow(clippy::decimal_literal_representation)] - #[cfg(__INTERNAL_USE_ONLY_NIGHLTY_FEATURES_IN_TESTS)] - #[test] - fn test_trailing_field_offset() { - assert_eq!(mem::align_of::<Aligned64kAllocation>(), _64K); - - macro_rules! test { - (#[$cfg:meta] ($($ts:ty),* ; $trailing_field_ty:ty) => $expect:expr) => {{ - #[$cfg] - #[allow(dead_code)] // fields are never read - struct Test($($ts,)* $trailing_field_ty); - assert_eq!(test!(@offset $($ts),* ; $trailing_field_ty), $expect); - }}; - (#[$cfg:meta] $(#[$cfgs:meta])* ($($ts:ty),* ; $trailing_field_ty:ty) => $expect:expr) => { - test!(#[$cfg] ($($ts),* ; $trailing_field_ty) => $expect); - test!($(#[$cfgs])* ($($ts),* ; $trailing_field_ty) => $expect); - }; - (@offset ; $_trailing:ty) => { trailing_field_offset!(Test, 0) }; - (@offset $_t:ty ; $_trailing:ty) => { trailing_field_offset!(Test, 1) }; - } - - test!(#[repr(C)] #[repr(transparent)] #[repr(packed)](; u8) => Some(0)); - test!(#[repr(C)] #[repr(transparent)] #[repr(packed)](; [u8]) => Some(0)); - test!(#[repr(C)] #[repr(C, packed)] (u8; u8) => Some(1)); - test!(#[repr(C)] (; AU64) => Some(0)); - test!(#[repr(C)] (; [AU64]) => Some(0)); - test!(#[repr(C)] (u8; AU64) => Some(8)); - test!(#[repr(C)] (u8; [AU64]) => Some(8)); - test!(#[repr(C)] (; Nested<u8, AU64>) => Some(0)); - test!(#[repr(C)] (; Nested<u8, [AU64]>) => Some(0)); - test!(#[repr(C)] (u8; Nested<u8, AU64>) => Some(8)); - test!(#[repr(C)] (u8; Nested<u8, [AU64]>) => Some(8)); - - // Test that `packed(N)` limits the offset of the trailing field. - test!(#[repr(C, packed( 1))] (u8; elain::Align< 2>) => Some( 1)); - test!(#[repr(C, packed( 2))] (u8; elain::Align< 4>) => Some( 2)); - test!(#[repr(C, packed( 4))] (u8; elain::Align< 8>) => Some( 4)); - test!(#[repr(C, packed( 8))] (u8; elain::Align< 16>) => Some( 8)); - test!(#[repr(C, packed( 16))] (u8; elain::Align< 32>) => Some( 16)); - test!(#[repr(C, packed( 32))] (u8; elain::Align< 64>) => Some( 32)); - test!(#[repr(C, packed( 64))] (u8; elain::Align< 128>) => Some( 64)); - test!(#[repr(C, packed( 128))] (u8; elain::Align< 256>) => Some( 128)); - test!(#[repr(C, packed( 256))] (u8; elain::Align< 512>) => Some( 256)); - test!(#[repr(C, packed( 512))] (u8; elain::Align< 1024>) => Some( 512)); - test!(#[repr(C, packed( 1024))] (u8; elain::Align< 2048>) => Some( 1024)); - test!(#[repr(C, packed( 2048))] (u8; elain::Align< 4096>) => Some( 2048)); - test!(#[repr(C, packed( 4096))] (u8; elain::Align< 8192>) => Some( 4096)); - test!(#[repr(C, packed( 8192))] (u8; elain::Align< 16384>) => Some( 8192)); - test!(#[repr(C, packed( 16384))] (u8; elain::Align< 32768>) => Some( 16384)); - test!(#[repr(C, packed( 32768))] (u8; elain::Align< 65536>) => Some( 32768)); - test!(#[repr(C, packed( 65536))] (u8; elain::Align< 131072>) => Some( 65536)); - /* Alignments above 65536 are not yet supported. - test!(#[repr(C, packed( 131072))] (u8; elain::Align< 262144>) => Some( 131072)); - test!(#[repr(C, packed( 262144))] (u8; elain::Align< 524288>) => Some( 262144)); - test!(#[repr(C, packed( 524288))] (u8; elain::Align< 1048576>) => Some( 524288)); - test!(#[repr(C, packed( 1048576))] (u8; elain::Align< 2097152>) => Some( 1048576)); - test!(#[repr(C, packed( 2097152))] (u8; elain::Align< 4194304>) => Some( 2097152)); - test!(#[repr(C, packed( 4194304))] (u8; elain::Align< 8388608>) => Some( 4194304)); - test!(#[repr(C, packed( 8388608))] (u8; elain::Align< 16777216>) => Some( 8388608)); - test!(#[repr(C, packed( 16777216))] (u8; elain::Align< 33554432>) => Some( 16777216)); - test!(#[repr(C, packed( 33554432))] (u8; elain::Align< 67108864>) => Some( 33554432)); - test!(#[repr(C, packed( 67108864))] (u8; elain::Align< 33554432>) => Some( 67108864)); - test!(#[repr(C, packed( 33554432))] (u8; elain::Align<134217728>) => Some( 33554432)); - test!(#[repr(C, packed(134217728))] (u8; elain::Align<268435456>) => Some(134217728)); - test!(#[repr(C, packed(268435456))] (u8; elain::Align<268435456>) => Some(268435456)); - */ - - // Test that `align(N)` does not limit the offset of the trailing field. - test!(#[repr(C, align( 1))] (u8; elain::Align< 2>) => Some( 2)); - test!(#[repr(C, align( 2))] (u8; elain::Align< 4>) => Some( 4)); - test!(#[repr(C, align( 4))] (u8; elain::Align< 8>) => Some( 8)); - test!(#[repr(C, align( 8))] (u8; elain::Align< 16>) => Some( 16)); - test!(#[repr(C, align( 16))] (u8; elain::Align< 32>) => Some( 32)); - test!(#[repr(C, align( 32))] (u8; elain::Align< 64>) => Some( 64)); - test!(#[repr(C, align( 64))] (u8; elain::Align< 128>) => Some( 128)); - test!(#[repr(C, align( 128))] (u8; elain::Align< 256>) => Some( 256)); - test!(#[repr(C, align( 256))] (u8; elain::Align< 512>) => Some( 512)); - test!(#[repr(C, align( 512))] (u8; elain::Align< 1024>) => Some( 1024)); - test!(#[repr(C, align( 1024))] (u8; elain::Align< 2048>) => Some( 2048)); - test!(#[repr(C, align( 2048))] (u8; elain::Align< 4096>) => Some( 4096)); - test!(#[repr(C, align( 4096))] (u8; elain::Align< 8192>) => Some( 8192)); - test!(#[repr(C, align( 8192))] (u8; elain::Align< 16384>) => Some( 16384)); - test!(#[repr(C, align( 16384))] (u8; elain::Align< 32768>) => Some( 32768)); - test!(#[repr(C, align( 32768))] (u8; elain::Align< 65536>) => Some( 65536)); - /* Alignments above 65536 are not yet supported. - test!(#[repr(C, align( 65536))] (u8; elain::Align< 131072>) => Some( 131072)); - test!(#[repr(C, align( 131072))] (u8; elain::Align< 262144>) => Some( 262144)); - test!(#[repr(C, align( 262144))] (u8; elain::Align< 524288>) => Some( 524288)); - test!(#[repr(C, align( 524288))] (u8; elain::Align< 1048576>) => Some( 1048576)); - test!(#[repr(C, align( 1048576))] (u8; elain::Align< 2097152>) => Some( 2097152)); - test!(#[repr(C, align( 2097152))] (u8; elain::Align< 4194304>) => Some( 4194304)); - test!(#[repr(C, align( 4194304))] (u8; elain::Align< 8388608>) => Some( 8388608)); - test!(#[repr(C, align( 8388608))] (u8; elain::Align< 16777216>) => Some( 16777216)); - test!(#[repr(C, align( 16777216))] (u8; elain::Align< 33554432>) => Some( 33554432)); - test!(#[repr(C, align( 33554432))] (u8; elain::Align< 67108864>) => Some( 67108864)); - test!(#[repr(C, align( 67108864))] (u8; elain::Align< 33554432>) => Some( 33554432)); - test!(#[repr(C, align( 33554432))] (u8; elain::Align<134217728>) => Some(134217728)); - test!(#[repr(C, align(134217728))] (u8; elain::Align<268435456>) => Some(268435456)); - */ - } - - // TODO(#29), TODO(https://github.com/rust-lang/rust/issues/69835): Remove - // this `cfg` when `size_of_val_raw` is stabilized. - #[allow(clippy::decimal_literal_representation)] - #[cfg(__INTERNAL_USE_ONLY_NIGHLTY_FEATURES_IN_TESTS)] - #[test] - fn test_align_of_dst() { - // Test that `align_of!` correctly computes the alignment of DSTs. - assert_eq!(align_of!([elain::Align<1>]), Some(1)); - assert_eq!(align_of!([elain::Align<2>]), Some(2)); - assert_eq!(align_of!([elain::Align<4>]), Some(4)); - assert_eq!(align_of!([elain::Align<8>]), Some(8)); - assert_eq!(align_of!([elain::Align<16>]), Some(16)); - assert_eq!(align_of!([elain::Align<32>]), Some(32)); - assert_eq!(align_of!([elain::Align<64>]), Some(64)); - assert_eq!(align_of!([elain::Align<128>]), Some(128)); - assert_eq!(align_of!([elain::Align<256>]), Some(256)); - assert_eq!(align_of!([elain::Align<512>]), Some(512)); - assert_eq!(align_of!([elain::Align<1024>]), Some(1024)); - assert_eq!(align_of!([elain::Align<2048>]), Some(2048)); - assert_eq!(align_of!([elain::Align<4096>]), Some(4096)); - assert_eq!(align_of!([elain::Align<8192>]), Some(8192)); - assert_eq!(align_of!([elain::Align<16384>]), Some(16384)); - assert_eq!(align_of!([elain::Align<32768>]), Some(32768)); - assert_eq!(align_of!([elain::Align<65536>]), Some(65536)); - /* Alignments above 65536 are not yet supported. - assert_eq!(align_of!([elain::Align<131072>]), Some(131072)); - assert_eq!(align_of!([elain::Align<262144>]), Some(262144)); - assert_eq!(align_of!([elain::Align<524288>]), Some(524288)); - assert_eq!(align_of!([elain::Align<1048576>]), Some(1048576)); - assert_eq!(align_of!([elain::Align<2097152>]), Some(2097152)); - assert_eq!(align_of!([elain::Align<4194304>]), Some(4194304)); - assert_eq!(align_of!([elain::Align<8388608>]), Some(8388608)); - assert_eq!(align_of!([elain::Align<16777216>]), Some(16777216)); - assert_eq!(align_of!([elain::Align<33554432>]), Some(33554432)); - assert_eq!(align_of!([elain::Align<67108864>]), Some(67108864)); - assert_eq!(align_of!([elain::Align<33554432>]), Some(33554432)); - assert_eq!(align_of!([elain::Align<134217728>]), Some(134217728)); - assert_eq!(align_of!([elain::Align<268435456>]), Some(268435456)); - */ - } - - #[test] - fn test_struct_has_padding() { - // Test that, for each provided repr, `struct_has_padding!` reports the - // expected value. - macro_rules! test { - (#[$cfg:meta] ($($ts:ty),*) => $expect:expr) => {{ - #[$cfg] - #[allow(dead_code)] // fields are never read - struct Test($($ts),*); - assert_eq!(struct_has_padding!(Test, $($ts),*), $expect); - }}; - (#[$cfg:meta] $(#[$cfgs:meta])* ($($ts:ty),*) => $expect:expr) => { - test!(#[$cfg] ($($ts),*) => $expect); - test!($(#[$cfgs])* ($($ts),*) => $expect); - }; - } - - test!(#[repr(C)] #[repr(transparent)] #[repr(packed)] () => false); - test!(#[repr(C)] #[repr(transparent)] #[repr(packed)] (u8) => false); - test!(#[repr(C)] #[repr(transparent)] #[repr(packed)] (u8, ()) => false); - test!(#[repr(C)] #[repr(packed)] (u8, u8) => false); - - test!(#[repr(C)] (u8, AU64) => true); - // Rust won't let you put `#[repr(packed)]` on a type which contains a - // `#[repr(align(n > 1))]` type (`AU64`), so we have to use `u64` here. - // It's not ideal, but it definitely has align > 1 on /some/ of our CI - // targets, and this isn't a particularly complex macro we're testing - // anyway. - test!(#[repr(packed)] (u8, u64) => false); - } - - #[test] - fn test_union_has_padding() { - // Test that, for each provided repr, `union_has_padding!` reports the - // expected value. - macro_rules! test { - (#[$cfg:meta] {$($fs:ident: $ts:ty),*} => $expect:expr) => {{ - #[$cfg] - #[allow(unused)] // fields are never read - union Test{ $($fs: $ts),* } - assert_eq!(union_has_padding!(Test, $($ts),*), $expect); - }}; - (#[$cfg:meta] $(#[$cfgs:meta])* {$($fs:ident: $ts:ty),*} => $expect:expr) => { - test!(#[$cfg] {$($fs: $ts),*} => $expect); - test!($(#[$cfgs])* {$($fs: $ts),*} => $expect); - }; - } - - test!(#[repr(C)] #[repr(packed)] {a: u8} => false); - test!(#[repr(C)] #[repr(packed)] {a: u8, b: u8} => false); - - // Rust won't let you put `#[repr(packed)]` on a type which contains a - // `#[repr(align(n > 1))]` type (`AU64`), so we have to use `u64` here. - // It's not ideal, but it definitely has align > 1 on /some/ of our CI - // targets, and this isn't a particularly complex macro we're testing - // anyway. - test!(#[repr(C)] #[repr(packed)] {a: u8, b: u64} => true); - } -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/src/macros.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/src/macros.rs deleted file mode 100644 index a3d7996..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/src/macros.rs +++ /dev/null
@@ -1,416 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -/// Documents multiple unsafe blocks with a single safety comment. -/// -/// Invoked as: -/// -/// ```rust,ignore -/// safety_comment! { -/// // Non-doc comments come first. -/// /// SAFETY: -/// /// Safety comment starts on its own line. -/// macro_1!(args); -/// macro_2! { args }; -/// /// SAFETY: -/// /// Subsequent safety comments are allowed but not required. -/// macro_3! { args }; -/// } -/// ``` -/// -/// The macro invocations are emitted, each decorated with the following -/// attribute: `#[allow(clippy::undocumented_unsafe_blocks)]`. -macro_rules! safety_comment { - (#[doc = r" SAFETY:"] $($(#[$attr:meta])* $macro:ident!$args:tt;)*) => { - #[allow(clippy::undocumented_unsafe_blocks, unused_attributes)] - const _: () = { $($(#[$attr])* $macro!$args;)* }; - } -} - -/// Unsafely implements trait(s) for a type. -/// -/// # Safety -/// -/// The trait impl must be sound. -/// -/// When implementing `TryFromBytes`: -/// - If no `is_bit_valid` impl is provided, then it must be valid for -/// `is_bit_valid` to unconditionally return `true`. In other words, it must -/// be the case that any initialized sequence of bytes constitutes a valid -/// instance of `$ty`. -/// - If an `is_bit_valid` impl is provided, then: -/// - Regardless of whether the provided closure takes a `Ptr<$repr>` or -/// `&$repr` argument, it must be the case that, given `t: *mut $ty` and -/// `let r = t as *mut $repr`, `r` refers to an object of equal or lesser -/// size than the object referred to by `t`. -/// - If the provided closure takes a `&$repr` argument, then given a `Ptr<'a, -/// $ty>` which satisfies the preconditions of -/// `TryFromBytes::<$ty>::is_bit_valid`, it must be guaranteed that the -/// memory referenced by that `Ptr` always contains a valid `$repr`. -/// - The alignment of `$repr` is less than or equal to the alignment of -/// `$ty`. -/// - The impl of `is_bit_valid` must only return `true` for its argument -/// `Ptr<$repr>` if the original `Ptr<$ty>` refers to a valid `$ty`. -macro_rules! unsafe_impl { - // Implement `$trait` for `$ty` with no bounds. - ($(#[$attr:meta])* $ty:ty: $trait:ident $(; |$candidate:ident: &$repr:ty| $is_bit_valid:expr)?) => { - $(#[$attr])* - unsafe impl $trait for $ty { - unsafe_impl!(@method $trait $(; |$candidate: &$repr| $is_bit_valid)?); - } - }; - // Implement all `$traits` for `$ty` with no bounds. - ($ty:ty: $($traits:ident),*) => { - $( unsafe_impl!($ty: $traits); )* - }; - // This arm is identical to the following one, except it contains a - // preceding `const`. If we attempt to handle these with a single arm, there - // is an inherent ambiguity between `const` (the keyword) and `const` (the - // ident match for `$tyvar:ident`). - // - // To explain how this works, consider the following invocation: - // - // unsafe_impl!(const N: usize, T: ?Sized + Copy => Clone for Foo<T>); - // - // In this invocation, here are the assignments to meta-variables: - // - // |---------------|------------| - // | Meta-variable | Assignment | - // |---------------|------------| - // | $constname | N | - // | $constty | usize | - // | $tyvar | T | - // | $optbound | Sized | - // | $bound | Copy | - // | $trait | Clone | - // | $ty | Foo<T> | - // |---------------|------------| - // - // The following arm has the same behavior with the exception of the lack of - // support for a leading `const` parameter. - ( - $(#[$attr:meta])* - const $constname:ident : $constty:ident $(,)? - $($tyvar:ident $(: $(? $optbound:ident $(+)?)* $($bound:ident $(+)?)* )?),* - => $trait:ident for $ty:ty $(; |$candidate:ident $(: &$ref_repr:ty)? $(: Ptr<$ptr_repr:ty>)?| $is_bit_valid:expr)? - ) => { - unsafe_impl!( - @inner - $(#[$attr])* - @const $constname: $constty, - $($tyvar $(: $(? $optbound +)* + $($bound +)*)?,)* - => $trait for $ty $(; |$candidate $(: &$ref_repr)? $(: Ptr<$ptr_repr>)?| $is_bit_valid)? - ); - }; - ( - $(#[$attr:meta])* - $($tyvar:ident $(: $(? $optbound:ident $(+)?)* $($bound:ident $(+)?)* )?),* - => $trait:ident for $ty:ty $(; |$candidate:ident $(: &$ref_repr:ty)? $(: Ptr<$ptr_repr:ty>)?| $is_bit_valid:expr)? - ) => { - unsafe_impl!( - @inner - $(#[$attr])* - $($tyvar $(: $(? $optbound +)* + $($bound +)*)?,)* - => $trait for $ty $(; |$candidate $(: &$ref_repr)? $(: Ptr<$ptr_repr>)?| $is_bit_valid)? - ); - }; - ( - @inner - $(#[$attr:meta])* - $(@const $constname:ident : $constty:ident,)* - $($tyvar:ident $(: $(? $optbound:ident +)* + $($bound:ident +)* )?,)* - => $trait:ident for $ty:ty $(; |$candidate:ident $(: &$ref_repr:ty)? $(: Ptr<$ptr_repr:ty>)?| $is_bit_valid:expr)? - ) => { - $(#[$attr])* - unsafe impl<$(const $constname: $constty,)* $($tyvar $(: $(? $optbound +)* $($bound +)*)?),*> $trait for $ty { - unsafe_impl!(@method $trait $(; |$candidate: $(&$ref_repr)? $(Ptr<$ptr_repr>)?| $is_bit_valid)?); - } - }; - - (@method TryFromBytes ; |$candidate:ident: &$repr:ty| $is_bit_valid:expr) => { - #[inline] - unsafe fn is_bit_valid(candidate: Ptr<'_, Self>) -> bool { - // SAFETY: - // - The argument to `cast_unsized` is `|p| p as *mut _` as required - // by that method's safety precondition. - // - The caller has promised that the cast results in an object of - // equal or lesser size. - // - The caller has promised that `$repr`'s alignment is less than - // or equal to `Self`'s alignment. - #[allow(clippy::as_conversions)] - let candidate = unsafe { candidate.cast_unsized::<$repr, _>(|p| p as *mut _) }; - // SAFETY: - // - The caller has promised that the referenced memory region will - // contain a valid `$repr` for `'a`. - // - The memory may not be referenced by any mutable references. - // This is a precondition of `is_bit_valid`. - // - The memory may not be mutated even via `UnsafeCell`s. This is a - // precondition of `is_bit_valid`. - // - There must not exist any references to the same memory region - // which contain `UnsafeCell`s at byte ranges which are not - // identical to the byte ranges at which `T` contains - // `UnsafeCell`s. This is a precondition of `is_bit_valid`. - let $candidate: &$repr = unsafe { candidate.as_ref() }; - $is_bit_valid - } - }; - (@method TryFromBytes ; |$candidate:ident: Ptr<$repr:ty>| $is_bit_valid:expr) => { - #[inline] - unsafe fn is_bit_valid(candidate: Ptr<'_, Self>) -> bool { - // SAFETY: - // - The argument to `cast_unsized` is `|p| p as *mut _` as required - // by that method's safety precondition. - // - The caller has promised that the cast results in an object of - // equal or lesser size. - // - The caller has promised that `$repr`'s alignment is less than - // or equal to `Self`'s alignment. - #[allow(clippy::as_conversions)] - let $candidate = unsafe { candidate.cast_unsized::<$repr, _>(|p| p as *mut _) }; - $is_bit_valid - } - }; - (@method TryFromBytes) => { #[inline(always)] unsafe fn is_bit_valid(_: Ptr<'_, Self>) -> bool { true } }; - (@method $trait:ident) => { - #[allow(clippy::missing_inline_in_public_items)] - fn only_derive_is_allowed_to_implement_this_trait() {} - }; - (@method $trait:ident; |$_candidate:ident $(: &$_ref_repr:ty)? $(: NonNull<$_ptr_repr:ty>)?| $_is_bit_valid:expr) => { - compile_error!("Can't provide `is_bit_valid` impl for trait other than `TryFromBytes`"); - }; -} - -/// Implements a trait for a type, bounding on each memeber of the power set of -/// a set of type variables. This is useful for implementing traits for tuples -/// or `fn` types. -/// -/// The last argument is the name of a macro which will be called in every -/// `impl` block, and is expected to expand to the name of the type for which to -/// implement the trait. -/// -/// For example, the invocation: -/// ```ignore -/// unsafe_impl_for_power_set!(A, B => Foo for type!(...)) -/// ``` -/// ...expands to: -/// ```ignore -/// unsafe impl Foo for type!() { ... } -/// unsafe impl<B> Foo for type!(B) { ... } -/// unsafe impl<A, B> Foo for type!(A, B) { ... } -/// ``` -macro_rules! unsafe_impl_for_power_set { - ($first:ident $(, $rest:ident)* $(-> $ret:ident)? => $trait:ident for $macro:ident!(...)) => { - unsafe_impl_for_power_set!($($rest),* $(-> $ret)? => $trait for $macro!(...)); - unsafe_impl_for_power_set!(@impl $first $(, $rest)* $(-> $ret)? => $trait for $macro!(...)); - }; - ($(-> $ret:ident)? => $trait:ident for $macro:ident!(...)) => { - unsafe_impl_for_power_set!(@impl $(-> $ret)? => $trait for $macro!(...)); - }; - (@impl $($vars:ident),* $(-> $ret:ident)? => $trait:ident for $macro:ident!(...)) => { - unsafe impl<$($vars,)* $($ret)?> $trait for $macro!($($vars),* $(-> $ret)?) { - #[allow(clippy::missing_inline_in_public_items)] - fn only_derive_is_allowed_to_implement_this_trait() {} - } - }; -} - -/// Expands to an `Option<extern "C" fn>` type with the given argument types and -/// return type. Designed for use with `unsafe_impl_for_power_set`. -macro_rules! opt_extern_c_fn { - ($($args:ident),* -> $ret:ident) => { Option<extern "C" fn($($args),*) -> $ret> }; -} - -/// Expands to a `Option<fn>` type with the given argument types and return -/// type. Designed for use with `unsafe_impl_for_power_set`. -macro_rules! opt_fn { - ($($args:ident),* -> $ret:ident) => { Option<fn($($args),*) -> $ret> }; -} - -/// Implements trait(s) for a type or verifies the given implementation by -/// referencing an existing (derived) implementation. -/// -/// This macro exists so that we can provide zerocopy-derive as an optional -/// dependency and still get the benefit of using its derives to validate that -/// our trait impls are sound. -/// -/// When compiling without `--cfg 'feature = "derive"` and without `--cfg test`, -/// `impl_or_verify!` emits the provided trait impl. When compiling with either -/// of those cfgs, it is expected that the type in question is deriving the -/// traits instead. In this case, `impl_or_verify!` emits code which validates -/// that the given trait impl is at least as restrictive as the the impl emitted -/// by the custom derive. This has the effect of confirming that the impl which -/// is emitted when the `derive` feature is disabled is actually sound (on the -/// assumption that the impl emitted by the custom derive is sound). -/// -/// The caller is still required to provide a safety comment (e.g. using the -/// `safety_comment!` macro) . The reason for this restriction is that, while -/// `impl_or_verify!` can guarantee that the provided impl is sound when it is -/// compiled with the appropriate cfgs, there is no way to guarantee that it is -/// ever compiled with those cfgs. In particular, it would be possible to -/// accidentally place an `impl_or_verify!` call in a context that is only ever -/// compiled when the `derive` feature is disabled. If that were to happen, -/// there would be nothing to prevent an unsound trait impl from being emitted. -/// Requiring a safety comment reduces the likelihood of emitting an unsound -/// impl in this case, and also provides useful documentation for readers of the -/// code. -/// -/// ## Example -/// -/// ```rust,ignore -/// // Note that these derives are gated by `feature = "derive"` -/// #[cfg_attr(any(feature = "derive", test), derive(FromZeroes, FromBytes, AsBytes, Unaligned))] -/// #[repr(transparent)] -/// struct Wrapper<T>(T); -/// -/// safety_comment! { -/// /// SAFETY: -/// /// `Wrapper<T>` is `repr(transparent)`, so it is sound to implement any -/// /// zerocopy trait if `T` implements that trait. -/// impl_or_verify!(T: FromZeroes => FromZeroes for Wrapper<T>); -/// impl_or_verify!(T: FromBytes => FromBytes for Wrapper<T>); -/// impl_or_verify!(T: AsBytes => AsBytes for Wrapper<T>); -/// impl_or_verify!(T: Unaligned => Unaligned for Wrapper<T>); -/// } -/// ``` -macro_rules! impl_or_verify { - // The following two match arms follow the same pattern as their - // counterparts in `unsafe_impl!`; see the documentation on those arms for - // more details. - ( - const $constname:ident : $constty:ident $(,)? - $($tyvar:ident $(: $(? $optbound:ident $(+)?)* $($bound:ident $(+)?)* )?),* - => $trait:ident for $ty:ty - ) => { - impl_or_verify!(@impl { unsafe_impl!( - const $constname: $constty, $($tyvar $(: $(? $optbound +)* $($bound +)*)?),* => $trait for $ty - ); }); - impl_or_verify!(@verify $trait, { - impl<const $constname: $constty, $($tyvar $(: $(? $optbound +)* $($bound +)*)?),*> Subtrait for $ty {} - }); - }; - ( - $($tyvar:ident $(: $(? $optbound:ident $(+)?)* $($bound:ident $(+)?)* )?),* - => $trait:ident for $ty:ty - ) => { - impl_or_verify!(@impl { unsafe_impl!( - $($tyvar $(: $(? $optbound +)* $($bound +)*)?),* => $trait for $ty - ); }); - impl_or_verify!(@verify $trait, { - impl<$($tyvar $(: $(? $optbound +)* $($bound +)*)?),*> Subtrait for $ty {} - }); - }; - ( - $($tyvar:ident $(: $(? $optbound:ident $(+)?)* $($bound:ident $(+)?)* )?),* - => $trait:ident for $ty:ty - ) => { - unsafe_impl!( - @inner - $($tyvar $(: $(? $optbound +)* + $($bound +)*)?,)* - => $trait for $ty - ); - }; - (@impl $impl_block:tt) => { - #[cfg(not(any(feature = "derive", test)))] - const _: () = { $impl_block }; - }; - (@verify $trait:ident, $impl_block:tt) => { - #[cfg(any(feature = "derive", test))] - const _: () = { - trait Subtrait: $trait {} - $impl_block - }; - }; -} - -/// Implements `KnownLayout` for a sized type. -macro_rules! impl_known_layout { - ($(const $constvar:ident : $constty:ty, $tyvar:ident $(: ?$optbound:ident)? => $ty:ty),* $(,)?) => { - $(impl_known_layout!(@inner const $constvar: $constty, $tyvar $(: ?$optbound)? => $ty);)* - }; - ($($tyvar:ident $(: ?$optbound:ident)? => $ty:ty),* $(,)?) => { - $(impl_known_layout!(@inner , $tyvar $(: ?$optbound)? => $ty);)* - }; - ($($ty:ty),*) => { $(impl_known_layout!(@inner , => $ty);)* }; - (@inner $(const $constvar:ident : $constty:ty)? , $($tyvar:ident $(: ?$optbound:ident)?)? => $ty:ty) => { - const _: () = { - use core::ptr::NonNull; - - // SAFETY: Delegates safety to `DstLayout::for_type`. - unsafe impl<$(const $constvar : $constty,)? $($tyvar $(: ?$optbound)?)?> KnownLayout for $ty { - #[allow(clippy::missing_inline_in_public_items)] - fn only_derive_is_allowed_to_implement_this_trait() where Self: Sized {} - - const LAYOUT: DstLayout = DstLayout::for_type::<$ty>(); - - // SAFETY: `.cast` preserves address and provenance. - // - // TODO(#429): Add documentation to `.cast` that promises that - // it preserves provenance. - #[inline(always)] - fn raw_from_ptr_len(bytes: NonNull<u8>, _elems: usize) -> NonNull<Self> { - bytes.cast::<Self>() - } - } - }; - }; -} - -/// Implements `KnownLayout` for a type in terms of the implementation of -/// another type with the same representation. -/// -/// # Safety -/// -/// - `$ty` and `$repr` must have the same: -/// - Fixed prefix size -/// - Alignment -/// - (For DSTs) trailing slice element size -/// - It must be valid to perform an `as` cast from `*mut $repr` to `*mut $ty`, -/// and this operation must preserve referent size (ie, `size_of_val_raw`). -macro_rules! unsafe_impl_known_layout { - ($($tyvar:ident: ?Sized + KnownLayout =>)? #[repr($repr:ty)] $ty:ty) => { - const _: () = { - use core::ptr::NonNull; - - unsafe impl<$($tyvar: ?Sized + KnownLayout)?> KnownLayout for $ty { - #[allow(clippy::missing_inline_in_public_items)] - fn only_derive_is_allowed_to_implement_this_trait() {} - - const LAYOUT: DstLayout = <$repr as KnownLayout>::LAYOUT; - - // SAFETY: All operations preserve address and provenance. - // Caller has promised that the `as` cast preserves size. - // - // TODO(#429): Add documentation to `NonNull::new_unchecked` - // that it preserves provenance. - #[inline(always)] - fn raw_from_ptr_len(bytes: NonNull<u8>, elems: usize) -> NonNull<Self> { - #[allow(clippy::as_conversions)] - let ptr = <$repr>::raw_from_ptr_len(bytes, elems).as_ptr() as *mut Self; - // SAFETY: `ptr` was converted from `bytes`, which is non-null. - unsafe { NonNull::new_unchecked(ptr) } - } - } - }; - }; -} - -/// Uses `align_of` to confirm that a type or set of types have alignment 1. -/// -/// Note that `align_of<T>` requires `T: Sized`, so this macro doesn't work for -/// unsized types. -macro_rules! assert_unaligned { - ($ty:ty) => { - // We only compile this assertion under `cfg(test)` to avoid taking an - // extra non-dev dependency (and making this crate more expensive to - // compile for our dependents). - #[cfg(test)] - static_assertions::const_assert_eq!(core::mem::align_of::<$ty>(), 1); - }; - ($($ty:ty),*) => { - $(assert_unaligned!($ty);)* - }; -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/src/post_monomorphization_compile_fail_tests.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/src/post_monomorphization_compile_fail_tests.rs deleted file mode 100644 index 32505b66..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/src/post_monomorphization_compile_fail_tests.rs +++ /dev/null
@@ -1,118 +0,0 @@ -// Copyright 2018 The Fuchsia Authors -// -// Licensed under the 2-Clause BSD License <LICENSE-BSD or -// https://opensource.org/license/bsd-2-clause>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -//! Code that should fail to compile during the post-monomorphization compiler -//! pass. -//! -//! Due to [a limitation with the `trybuild` crate][trybuild-issue], we cannot -//! use our UI testing framework to test compilation failures that are -//! encountered after monomorphization has complated. This module has one item -//! for each such test we would prefer to have as a UI test, with the code in -//! question appearing as a rustdoc example which is marked with `compile_fail`. -//! This has the effect of causing doctests to fail if any of these examples -//! compile successfully. -//! -//! This is very much a hack and not a complete replacement for UI tests - most -//! notably because this only provides a single "compile vs fail" bit of -//! information, but does not allow us to depend upon the specific error that -//! causes compilation to fail. -//! -//! [trybuild-issue]: https://github.com/dtolnay/trybuild/issues/241 - -// Miri doesn't detect post-monimorphization failures as compile-time failures, -// but instead as runtime failures. -#![cfg(not(miri))] - -/// ```compile_fail -/// use core::cell::{Ref, RefCell}; -/// -/// let refcell = RefCell::new([0u8, 1, 2, 3]); -/// let core_ref = refcell.borrow(); -/// let core_ref = Ref::map(core_ref, |bytes| &bytes[..]); -/// -/// // `zc_ref` now stores `core_ref` internally. -/// let zc_ref = zerocopy::Ref::<_, u32>::new(core_ref).unwrap(); -/// -/// // This causes `core_ref` to get dropped and synthesizes a Rust -/// // reference to the memory `core_ref` was pointing at. -/// let rust_ref = zc_ref.into_ref(); -/// -/// // UB!!! This mutates `rust_ref`'s referent while it's alive. -/// *refcell.borrow_mut() = [0, 0, 0, 0]; -/// -/// println!("{}", rust_ref); -/// ``` -#[allow(unused)] -const REFCELL_REF_INTO_REF: () = (); - -/// ```compile_fail -/// use core::cell::{RefCell, RefMut}; -/// -/// let refcell = RefCell::new([0u8, 1, 2, 3]); -/// let core_ref_mut = refcell.borrow_mut(); -/// let core_ref_mut = RefMut::map(core_ref_mut, |bytes| &mut bytes[..]); -/// -/// // `zc_ref` now stores `core_ref_mut` internally. -/// let zc_ref = zerocopy::Ref::<_, u32>::new(core_ref_mut).unwrap(); -/// -/// // This causes `core_ref_mut` to get dropped and synthesizes a Rust -/// // reference to the memory `core_ref` was pointing at. -/// let rust_ref_mut = zc_ref.into_mut(); -/// -/// // UB!!! This mutates `rust_ref_mut`'s referent while it's alive. -/// *refcell.borrow_mut() = [0, 0, 0, 0]; -/// -/// println!("{}", rust_ref_mut); -/// ``` -#[allow(unused)] -const REFCELL_REFMUT_INTO_MUT: () = (); - -/// ```compile_fail -/// use core::cell::{Ref, RefCell}; -/// -/// let refcell = RefCell::new([0u8, 1, 2, 3]); -/// let core_ref = refcell.borrow(); -/// let core_ref = Ref::map(core_ref, |bytes| &bytes[..]); -/// -/// // `zc_ref` now stores `core_ref` internally. -/// let zc_ref = zerocopy::Ref::<_, [u16]>::new_slice(core_ref).unwrap(); -/// -/// // This causes `core_ref` to get dropped and synthesizes a Rust -/// // reference to the memory `core_ref` was pointing at. -/// let rust_ref = zc_ref.into_slice(); -/// -/// // UB!!! This mutates `rust_ref`'s referent while it's alive. -/// *refcell.borrow_mut() = [0, 0, 0, 0]; -/// -/// println!("{:?}", rust_ref); -/// ``` -#[allow(unused)] -const REFCELL_REFMUT_INTO_SLICE: () = (); - -/// ```compile_fail -/// use core::cell::{RefCell, RefMut}; -/// -/// let refcell = RefCell::new([0u8, 1, 2, 3]); -/// let core_ref_mut = refcell.borrow_mut(); -/// let core_ref_mut = RefMut::map(core_ref_mut, |bytes| &mut bytes[..]); -/// -/// // `zc_ref` now stores `core_ref_mut` internally. -/// let zc_ref = zerocopy::Ref::<_, [u16]>::new_slice(core_ref_mut).unwrap(); -/// -/// // This causes `core_ref_mut` to get dropped and synthesizes a Rust -/// // reference to the memory `core_ref` was pointing at. -/// let rust_ref_mut = zc_ref.into_mut_slice(); -/// -/// // UB!!! This mutates `rust_ref_mut`'s referent while it's alive. -/// *refcell.borrow_mut() = [0, 0, 0, 0]; -/// -/// println!("{:?}", rust_ref_mut); -/// ``` -#[allow(unused)] -const REFCELL_REFMUT_INTO_MUT_SLICE: () = ();
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/src/third_party/rust/LICENSE-APACHE b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/src/third_party/rust/LICENSE-APACHE deleted file mode 100644 index 1b5ec8b..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/src/third_party/rust/LICENSE-APACHE +++ /dev/null
@@ -1,176 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - -2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - -3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - -4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - -5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - -6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - -8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - -END OF TERMS AND CONDITIONS
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/src/third_party/rust/LICENSE-MIT b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/src/third_party/rust/LICENSE-MIT deleted file mode 100644 index 31aa7938..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/src/third_party/rust/LICENSE-MIT +++ /dev/null
@@ -1,23 +0,0 @@ -Permission is hereby granted, free of charge, to any -person obtaining a copy of this software and associated -documentation files (the "Software"), to deal in the -Software without restriction, including without -limitation the rights to use, copy, modify, merge, -publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software -is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice -shall be included in all copies or substantial portions -of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF -ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED -TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT -SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR -IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE.
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/src/third_party/rust/README.fuchsia b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/src/third_party/rust/README.fuchsia deleted file mode 100644 index e0a23dd..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/src/third_party/rust/README.fuchsia +++ /dev/null
@@ -1,7 +0,0 @@ -Name: rust -License File: LICENSE-APACHE -License File: LICENSE-MIT -Description: - -See https://github.com/google/zerocopy/pull/492 for an explanation of why this -file exists.
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/src/third_party/rust/layout.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/src/third_party/rust/layout.rs deleted file mode 100644 index 19ef7c69..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/src/third_party/rust/layout.rs +++ /dev/null
@@ -1,45 +0,0 @@ -use core::num::NonZeroUsize; - -/// Returns the amount of padding we must insert after `len` bytes to ensure -/// that the following address will satisfy `align` (measured in bytes). -/// -/// e.g., if `len` is 9, then `padding_needed_for(len, 4)` returns 3, because -/// that is the minimum number of bytes of padding required to get a 4-aligned -/// address (assuming that the corresponding memory block starts at a 4-aligned -/// address). -/// -/// The return value of this function has no meaning if `align` is not a -/// power-of-two. -/// -/// # Panics -/// -/// May panic if `align` is not a power of two. -// -// TODO(#419): Replace `len` with a witness type for region size. -#[allow(unused)] -#[inline(always)] -pub(crate) const fn padding_needed_for(len: usize, align: NonZeroUsize) -> usize { - // Rounded up value is: - // len_rounded_up = (len + align - 1) & !(align - 1); - // and then we return the padding difference: `len_rounded_up - len`. - // - // We use modular arithmetic throughout: - // - // 1. align is guaranteed to be > 0, so align - 1 is always - // valid. - // - // 2. `len + align - 1` can overflow by at most `align - 1`, - // so the &-mask with `!(align - 1)` will ensure that in the - // case of overflow, `len_rounded_up` will itself be 0. - // Thus the returned padding, when added to `len`, yields 0, - // which trivially satisfies the alignment `align`. - // - // (Of course, attempts to allocate blocks of memory whose - // size and padding overflow in the above manner should cause - // the allocator to yield an error anyway.) - - let align = align.get(); - debug_assert!(align.is_power_of_two()); - let len_rounded_up = len.wrapping_add(align).wrapping_sub(1) & !align.wrapping_sub(1); - len_rounded_up.wrapping_sub(len) -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/src/util.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/src/util.rs deleted file mode 100644 index 50cad1f6..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/src/util.rs +++ /dev/null
@@ -1,810 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -#[path = "third_party/rust/layout.rs"] -pub(crate) mod core_layout; - -use core::{mem, num::NonZeroUsize}; - -pub(crate) mod ptr { - use core::{ - fmt::{Debug, Formatter}, - marker::PhantomData, - ptr::NonNull, - }; - - use crate::{util::AsAddress, KnownLayout, _CastType}; - - /// A raw pointer with more restrictions. - /// - /// `Ptr<T>` is similar to `NonNull<T>`, but it is more restrictive in the - /// following ways: - /// - It must derive from a valid allocation - /// - It must reference a byte range which is contained inside the - /// allocation from which it derives - /// - As a consequence, the byte range it references must have a size - /// which does not overflow `isize` - /// - It must satisfy `T`'s alignment requirement - /// - /// Thanks to these restrictions, it is easier to prove the soundness of - /// some operations using `Ptr`s. - /// - /// `Ptr<'a, T>` is [covariant] in `'a` and `T`. - /// - /// [covariant]: https://doc.rust-lang.org/reference/subtyping.html - pub struct Ptr<'a, T: 'a + ?Sized> { - // INVARIANTS: - // 1. `ptr` is derived from some valid Rust allocation, `A` - // 2. `ptr` has the same provenance as `A` - // 3. `ptr` addresses a byte range which is entirely contained in `A` - // 4. `ptr` addresses a byte range whose length fits in an `isize` - // 5. `ptr` addresses a byte range which does not wrap around the address - // space - // 6. `ptr` is validly-aligned for `T` - // 7. `A` is guaranteed to live for at least `'a` - // 8. `T: 'a` - ptr: NonNull<T>, - _lifetime: PhantomData<&'a ()>, - } - - impl<'a, T: ?Sized> Copy for Ptr<'a, T> {} - impl<'a, T: ?Sized> Clone for Ptr<'a, T> { - #[inline] - fn clone(&self) -> Self { - *self - } - } - - impl<'a, T: ?Sized> Ptr<'a, T> { - /// Returns a shared reference to the value. - /// - /// # Safety - /// - /// For the duration of `'a`: - /// - The referenced memory must contain a validly-initialized `T` for - /// the duration of `'a`. - /// - The referenced memory must not also be referenced by any mutable - /// references. - /// - The referenced memory must not be mutated, even via an - /// [`UnsafeCell`]. - /// - There must not exist any references to the same memory region - /// which contain `UnsafeCell`s at byte ranges which are not identical - /// to the byte ranges at which `T` contains `UnsafeCell`s. - /// - /// [`UnsafeCell`]: core::cell::UnsafeCell - // TODO(#429): The safety requirements are likely overly-restrictive. - // Notably, mutation via `UnsafeCell`s is probably fine. Once the rules - // are more clearly defined, we should relax the safety requirements. - // For an example of why this is subtle, see: - // https://github.com/rust-lang/unsafe-code-guidelines/issues/463#issuecomment-1736771593 - #[allow(unused)] - pub(crate) unsafe fn as_ref(&self) -> &'a T { - // SAFETY: - // - By invariant, `self.ptr` is properly-aligned for `T`. - // - By invariant, `self.ptr` is "dereferenceable" in that it points - // to a single allocation. - // - By invariant, the allocation is live for `'a`. - // - The caller promises that no mutable references exist to this - // region during `'a`. - // - The caller promises that `UnsafeCell`s match exactly. - // - The caller promises that no mutation will happen during `'a`, - // even via `UnsafeCell`s. - // - The caller promises that the memory region contains a - // validly-intialized `T`. - unsafe { self.ptr.as_ref() } - } - - /// Casts to a different (unsized) target type. - /// - /// # Safety - /// - /// The caller promises that - /// - `cast(p)` is implemented exactly as follows: `|p: *mut T| p as - /// *mut U`. - /// - The size of the object referenced by the resulting pointer is less - /// than or equal to the size of the object referenced by `self`. - /// - The alignment of `U` is less than or equal to the alignment of - /// `T`. - pub(crate) unsafe fn cast_unsized<U: 'a + ?Sized, F: FnOnce(*mut T) -> *mut U>( - self, - cast: F, - ) -> Ptr<'a, U> { - let ptr = cast(self.ptr.as_ptr()); - // SAFETY: Caller promises that `cast` is just an `as` cast. We call - // `cast` on `self.ptr.as_ptr()`, which is non-null by construction. - let ptr = unsafe { NonNull::new_unchecked(ptr) }; - // SAFETY: - // - By invariant, `self.ptr` is derived from some valid Rust - // allocation, and since `ptr` is just `self.ptr as *mut U`, so is - // `ptr`. - // - By invariant, `self.ptr` has the same provenance as `A`, and so - // the same is true of `ptr`. - // - By invariant, `self.ptr` addresses a byte range which is - // entirely contained in `A`, and so the same is true of `ptr`. - // - By invariant, `self.ptr` addresses a byte range whose length - // fits in an `isize`, and so the same is true of `ptr`. - // - By invariant, `self.ptr` addresses a byte range which does not - // wrap around the address space, and so the same is true of - // `ptr`. - // - By invariant, `self.ptr` is validly-aligned for `T`. Since - // `ptr` has the same address, and since the caller promises that - // the alignment of `U` is less than or equal to the alignment of - // `T`, `ptr` is validly-aligned for `U`. - // - By invariant, `A` is guaranteed to live for at least `'a`. - // - `U: 'a` - Ptr { ptr, _lifetime: PhantomData } - } - } - - impl<'a> Ptr<'a, [u8]> { - /// Attempts to cast `self` to a `U` using the given cast type. - /// - /// Returns `None` if the resulting `U` would be invalidly-aligned or if - /// no `U` can fit in `self`. On success, returns a pointer to the - /// largest-possible `U` which fits in `self`. - /// - /// # Safety - /// - /// The caller may assume that this implementation is correct, and may - /// rely on that assumption for the soundness of their code. In - /// particular, the caller may assume that, if `try_cast_into` returns - /// `Some((ptr, split_at))`, then: - /// - If this is a prefix cast, `ptr` refers to the byte range `[0, - /// split_at)` in `self`. - /// - If this is a suffix cast, `ptr` refers to the byte range - /// `[split_at, self.len())` in `self`. - /// - /// # Panics - /// - /// Panics if `U` is a DST whose trailing slice element is zero-sized. - pub(crate) fn try_cast_into<U: 'a + ?Sized + KnownLayout>( - &self, - cast_type: _CastType, - ) -> Option<(Ptr<'a, U>, usize)> { - // PANICS: By invariant, the byte range addressed by `self.ptr` does - // not wrap around the address space. This implies that the sum of - // the address (represented as a `usize`) and length do not overflow - // `usize`, as required by `validate_cast_and_convert_metadata`. - // Thus, this call to `validate_cast_and_convert_metadata` won't - // panic. - let (elems, split_at) = U::LAYOUT.validate_cast_and_convert_metadata( - AsAddress::addr(self.ptr.as_ptr()), - self.len(), - cast_type, - )?; - let offset = match cast_type { - _CastType::_Prefix => 0, - _CastType::_Suffix => split_at, - }; - - let ptr = self.ptr.cast::<u8>().as_ptr(); - // SAFETY: `offset` is either `0` or `split_at`. - // `validate_cast_and_convert_metadata` promises that `split_at` is - // in the range `[0, self.len()]`. Thus, in both cases, `offset` is - // in `[0, self.len()]`. Thus: - // - The resulting pointer is in or one byte past the end of the - // same byte range as `self.ptr`. Since, by invariant, `self.ptr` - // addresses a byte range entirely contained within a single - // allocation, the pointer resulting from this operation is within - // or one byte past the end of that same allocation. - // - By invariant, `self.len() <= isize::MAX`. Since `offset <= - // self.len()`, `offset <= isize::MAX`. - // - By invariant, `self.ptr` addresses a byte range which does not - // wrap around the address space. This means that the base pointer - // plus the `self.len()` does not overflow `usize`. Since `offset - // <= self.len()`, this addition does not overflow `usize`. - let base = unsafe { ptr.add(offset) }; - // SAFETY: Since `add` is not allowed to wrap around, the preceding line - // produces a pointer whose address is greater than or equal to that of - // `ptr`. Since `ptr` is a `NonNull`, `base` is also non-null. - let base = unsafe { NonNull::new_unchecked(base) }; - let ptr = U::raw_from_ptr_len(base, elems); - // SAFETY: - // - By invariant, `self.ptr` is derived from some valid Rust - // allocation, `A`, and has the same provenance as `A`. All - // operations performed on `self.ptr` and values derived from it - // in this method preserve provenance, so: - // - `ptr` is derived from a valid Rust allocation, `A`. - // - `ptr` has the same provenance as `A`. - // - `validate_cast_and_convert_metadata` promises that the object - // described by `elems` and `split_at` lives at a byte range which - // is a subset of the input byte range. Thus: - // - Since, by invariant, `self.ptr` addresses a byte range - // entirely contained in `A`, so does `ptr`. - // - Since, by invariant, `self.ptr` addresses a range whose - // length is not longer than `isize::MAX` bytes, so does `ptr`. - // - Since, by invariant, `self.ptr` addresses a range which does - // not wrap around the address space, so does `ptr`. - // - `validate_cast_and_convert_metadata` promises that the object - // described by `split_at` is validly-aligned for `U`. - // - By invariant on `self`, `A` is guaranteed to live for at least - // `'a`. - // - `U: 'a` by trait bound. - Some((Ptr { ptr, _lifetime: PhantomData }, split_at)) - } - - /// Attempts to cast `self` into a `U`, failing if all of the bytes of - /// `self` cannot be treated as a `U`. - /// - /// In particular, this method fails if `self` is not validly-aligned - /// for `U` or if `self`'s size is not a valid size for `U`. - /// - /// # Safety - /// - /// On success, the caller may assume that the returned pointer - /// references the same byte range as `self`. - #[allow(unused)] - #[inline(always)] - pub(crate) fn try_cast_into_no_leftover<U: 'a + ?Sized + KnownLayout>( - &self, - ) -> Option<Ptr<'a, U>> { - // TODO(#67): Remove this allow. See NonNulSlicelExt for more - // details. - #[allow(unstable_name_collisions)] - match self.try_cast_into(_CastType::_Prefix) { - Some((slf, split_at)) if split_at == self.len() => Some(slf), - Some(_) | None => None, - } - } - } - - impl<'a, T> Ptr<'a, [T]> { - /// The number of slice elements referenced by `self`. - /// - /// # Safety - /// - /// Unsafe code my rely on `len` satisfying the above contract. - fn len(&self) -> usize { - #[allow(clippy::as_conversions)] - let slc = self.ptr.as_ptr() as *const [()]; - // SAFETY: - // - `()` has alignment 1, so `slc` is trivially aligned. - // - `slc` was derived from a non-null pointer. - // - The size is 0 regardless of the length, so it is sound to - // materialize a reference regardless of location. - // - By invariant, `self.ptr` has valid provenance. - let slc = unsafe { &*slc }; - // This is correct because the preceding `as` cast preserves the - // number of slice elements. Per - // https://doc.rust-lang.org/nightly/reference/expressions/operator-expr.html#slice-dst-pointer-to-pointer-cast: - // - // For slice types like `[T]` and `[U]`, the raw pointer types - // `*const [T]`, `*mut [T]`, `*const [U]`, and `*mut [U]` encode - // the number of elements in this slice. Casts between these raw - // pointer types preserve the number of elements. Note that, as a - // consequence, such casts do *not* necessarily preserve the size - // of the pointer's referent (e.g., casting `*const [u16]` to - // `*const [u8]` will result in a raw pointer which refers to an - // object of half the size of the original). The same holds for - // `str` and any compound type whose unsized tail is a slice type, - // such as struct `Foo(i32, [u8])` or `(u64, Foo)`. - // - // TODO(#429), - // TODO(https://github.com/rust-lang/reference/pull/1417): Once this - // text is available on the Stable docs, cite those instead of the - // Nightly docs. - slc.len() - } - - pub(crate) fn iter(&self) -> impl Iterator<Item = Ptr<'a, T>> { - // TODO(#429): Once `NonNull::cast` documents that it preserves - // provenance, cite those docs. - let base = self.ptr.cast::<T>().as_ptr(); - (0..self.len()).map(move |i| { - // TODO(https://github.com/rust-lang/rust/issues/74265): Use - // `NonNull::get_unchecked_mut`. - - // SAFETY: If the following conditions are not satisfied - // `pointer::cast` may induce Undefined Behavior [1]: - // > 1. Both the starting and resulting pointer must be either - // > in bounds or one byte past the end of the same allocated - // > object. - // > 2. The computed offset, in bytes, cannot overflow an - // > `isize`. - // > 3. The offset being in bounds cannot rely on “wrapping - // > around” the address space. That is, the - // > infinite-precision sum must fit in a `usize`. - // - // [1] https://doc.rust-lang.org/std/primitive.pointer.html#method.add - // - // We satisfy all three of these conditions here: - // 1. `base` (by invariant on `self`) points to an allocated - // object. By contract, `self.len()` accurately reflects the - // number of elements in the slice. `i` is in bounds of - // `c.len()` by construction, and so the result of this - // addition cannot overflow past the end of the allocation - // referred to by `c`. - // 2. By invariant on `Ptr`, `self` addresses a byte range whose - // length fits in an `isize`. Since `elem` is contained in - // `self`, the computed offset of `elem` must fit within - // `isize.` - // 3. By invariant on `Ptr`, `self` addresses a byte range which - // does not wrap around the address space. Since `elem` is - // contained in `self`, the computed offset of `elem` must - // wrap around the address space. - // - // TODO(#429): Once `pointer::add` documents that it preserves - // provenance, cite those docs. - let elem = unsafe { base.add(i) }; - - // SAFETY: - // - `elem` must not be null. `base` is constructed from a - // `NonNull` pointer, and the addition that produces `elem` - // must not overflow or wrap around, so `elem >= base > 0`. - // - // TODO(#429): Once `NonNull::new_unchecked` documents that it - // preserves provenance, cite those docs. - let elem = unsafe { NonNull::new_unchecked(elem) }; - - // SAFETY: The safety invariants of `Ptr` (see definition) are - // satisfied: - // 1. `elem` is derived from a valid Rust allocation, because - // `self` is derived from a valid Rust allocation, by - // invariant on `Ptr` - // 2. `elem` has the same provenance as `self`, because it - // derived from `self` using a series of - // provenance-preserving operations - // 3. `elem` is entirely contained in the allocation of `self` - // (see above) - // 4. `elem` addresses a byte range whose length fits in an - // `isize` (see above) - // 5. `elem` addresses a byte range which does not wrap around - // the address space (see above) - // 6. `elem` is validly-aligned for `T`. `self`, which - // represents a `[T]` is validly aligned for `T`, and `elem` - // is an element within that `[T]` - // 7. The allocation of `elem` is guaranteed to live for at - // least `'a`, because `elem` is entirely contained in - // `self`, which lives for at least `'a` by invariant on - // `Ptr`. - // 8. `T: 'a`, because `elem` is an element within `[T]`, and - // `[T]: 'a` by invariant on `Ptr` - Ptr { ptr: elem, _lifetime: PhantomData } - }) - } - } - - impl<'a, T: 'a + ?Sized> From<&'a T> for Ptr<'a, T> { - #[inline(always)] - fn from(t: &'a T) -> Ptr<'a, T> { - // SAFETY: `t` points to a valid Rust allocation, `A`, by - // construction. Thus: - // - `ptr` is derived from `A` - // - Since we use `NonNull::from`, which preserves provenance, `ptr` - // has the same provenance as `A` - // - Since `NonNull::from` creates a pointer which addresses the - // same bytes as `t`, `ptr` addresses a byte range entirely - // contained in (in this case, identical to) `A` - // - Since `t: &T`, it addresses no more than `isize::MAX` bytes [1] - // - Since `t: &T`, it addresses a byte range which does not wrap - // around the address space [2] - // - Since it is constructed from a valid `&T`, `ptr` is - // validly-aligned for `T` - // - Since `t: &'a T`, the allocation `A` is guaranteed to live for - // at least `'a` - // - `T: 'a` by trait bound - // - // TODO(#429), - // TODO(https://github.com/rust-lang/rust/issues/116181): Once it's - // documented, reference the guarantee that `NonNull::from` - // preserves provenance. - // - // TODO(#429), - // TODO(https://github.com/rust-lang/unsafe-code-guidelines/issues/465): - // - [1] Where does the reference document that allocations fit in - // `isize`? - // - [2] Where does the reference document that allocations don't - // wrap around the address space? - Ptr { ptr: NonNull::from(t), _lifetime: PhantomData } - } - } - - impl<'a, T: 'a + ?Sized> Debug for Ptr<'a, T> { - #[inline] - fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { - self.ptr.fmt(f) - } - } - - #[cfg(test)] - mod tests { - use core::mem::{self, MaybeUninit}; - - use super::*; - use crate::{util::testutil::AU64, FromBytes}; - - #[test] - fn test_ptrtry_cast_into_soundness() { - // This test is designed so that if `Ptr::try_cast_into_xxx` are - // buggy, it will manifest as unsoundness that Miri can detect. - - // - If `size_of::<T>() == 0`, `N == 4` - // - Else, `N == 4 * size_of::<T>()` - fn test<const N: usize, T: ?Sized + KnownLayout + FromBytes>() { - let mut bytes = [MaybeUninit::<u8>::uninit(); N]; - let initialized = [MaybeUninit::new(0u8); N]; - for start in 0..=bytes.len() { - for end in start..=bytes.len() { - // Set all bytes to uninitialized other than those in - // the range we're going to pass to `try_cast_from`. - // This allows Miri to detect out-of-bounds reads - // because they read uninitialized memory. Without this, - // some out-of-bounds reads would still be in-bounds of - // `bytes`, and so might spuriously be accepted. - bytes = [MaybeUninit::<u8>::uninit(); N]; - let bytes = &mut bytes[start..end]; - // Initialize only the byte range we're going to pass to - // `try_cast_from`. - bytes.copy_from_slice(&initialized[start..end]); - - let bytes = { - let bytes: *const [MaybeUninit<u8>] = bytes; - #[allow(clippy::as_conversions)] - let bytes = bytes as *const [u8]; - // SAFETY: We just initialized these bytes to valid - // `u8`s. - unsafe { &*bytes } - }; - - /// # Safety - /// - /// - `slf` must reference a byte range which is - /// entirely initialized. - /// - `slf` must reference a byte range which is only - /// referenced by shared references which do not - /// contain `UnsafeCell`s during its lifetime. - unsafe fn validate_and_get_len<T: ?Sized + KnownLayout + FromBytes>( - slf: Ptr<'_, T>, - ) -> usize { - // SAFETY: - // - Since all bytes in `slf` are initialized and - // `T: FromBytes`, `slf` contains a valid `T`. - // - The caller promises that the referenced memory - // is not also referenced by any mutable - // references. - // - The caller promises that the referenced memory - // is not also referenced as a type which contains - // `UnsafeCell`s. - let t = unsafe { slf.as_ref() }; - - let bytes = { - let len = mem::size_of_val(t); - let t: *const T = t; - // SAFETY: - // - We know `t`'s bytes are all initialized - // because we just read it from `slf`, which - // points to an initialized range of bytes. If - // there's a bug and this doesn't hold, then - // that's exactly what we're hoping Miri will - // catch! - // - Since `T: FromBytes`, `T` doesn't contain - // any `UnsafeCell`s, so it's okay for `t: T` - // and a `&[u8]` to the same memory to be - // alive concurrently. - unsafe { core::slice::from_raw_parts(t.cast::<u8>(), len) } - }; - - // This assertion ensures that `t`'s bytes are read - // and compared to another value, which in turn - // ensures that Miri gets a chance to notice if any - // of `t`'s bytes are uninitialized, which they - // shouldn't be (see the comment above). - assert_eq!(bytes, vec![0u8; bytes.len()]); - - mem::size_of_val(t) - } - - for cast_type in [_CastType::_Prefix, _CastType::_Suffix] { - if let Some((slf, split_at)) = - Ptr::from(bytes).try_cast_into::<T>(cast_type) - { - // SAFETY: All bytes in `bytes` have been - // initialized. - let len = unsafe { validate_and_get_len(slf) }; - match cast_type { - _CastType::_Prefix => assert_eq!(split_at, len), - _CastType::_Suffix => assert_eq!(split_at, bytes.len() - len), - } - } - } - - if let Some(slf) = Ptr::from(bytes).try_cast_into_no_leftover::<T>() { - // SAFETY: All bytes in `bytes` have been - // initialized. - let len = unsafe { validate_and_get_len(slf) }; - assert_eq!(len, bytes.len()); - } - } - } - } - - macro_rules! test { - ($($ty:ty),*) => { - $({ - const S: usize = core::mem::size_of::<$ty>(); - const N: usize = if S == 0 { 4 } else { S * 4 }; - test::<N, $ty>(); - // We don't support casting into DSTs whose trailing slice - // element is a ZST. - if S > 0 { - test::<N, [$ty]>(); - } - // TODO: Test with a slice DST once we have any that - // implement `KnownLayout + FromBytes`. - })* - }; - } - - test!(()); - test!(u8, u16, u32, u64, u128, usize, AU64); - test!(i8, i16, i32, i64, i128, isize); - test!(f32, f64); - } - } -} - -pub(crate) trait AsAddress { - fn addr(self) -> usize; -} - -impl<'a, T: ?Sized> AsAddress for &'a T { - #[inline(always)] - fn addr(self) -> usize { - let ptr: *const T = self; - AsAddress::addr(ptr) - } -} - -impl<'a, T: ?Sized> AsAddress for &'a mut T { - #[inline(always)] - fn addr(self) -> usize { - let ptr: *const T = self; - AsAddress::addr(ptr) - } -} - -impl<T: ?Sized> AsAddress for *const T { - #[inline(always)] - fn addr(self) -> usize { - // TODO(#181), TODO(https://github.com/rust-lang/rust/issues/95228): Use - // `.addr()` instead of `as usize` once it's stable, and get rid of this - // `allow`. Currently, `as usize` is the only way to accomplish this. - #[allow(clippy::as_conversions)] - #[cfg_attr(__INTERNAL_USE_ONLY_NIGHLTY_FEATURES_IN_TESTS, allow(lossy_provenance_casts))] - return self.cast::<()>() as usize; - } -} - -impl<T: ?Sized> AsAddress for *mut T { - #[inline(always)] - fn addr(self) -> usize { - let ptr: *const T = self; - AsAddress::addr(ptr) - } -} - -/// Is `t` aligned to `mem::align_of::<U>()`? -#[inline(always)] -pub(crate) fn aligned_to<T: AsAddress, U>(t: T) -> bool { - // `mem::align_of::<U>()` is guaranteed to return a non-zero value, which in - // turn guarantees that this mod operation will not panic. - #[allow(clippy::arithmetic_side_effects)] - let remainder = t.addr() % mem::align_of::<U>(); - remainder == 0 -} - -/// Round `n` down to the largest value `m` such that `m <= n` and `m % align == -/// 0`. -/// -/// # Panics -/// -/// May panic if `align` is not a power of two. Even if it doesn't panic in this -/// case, it will produce nonsense results. -#[inline(always)] -pub(crate) const fn round_down_to_next_multiple_of_alignment( - n: usize, - align: NonZeroUsize, -) -> usize { - let align = align.get(); - debug_assert!(align.is_power_of_two()); - - // Subtraction can't underflow because `align.get() >= 1`. - #[allow(clippy::arithmetic_side_effects)] - let mask = !(align - 1); - n & mask -} - -pub(crate) const fn max(a: NonZeroUsize, b: NonZeroUsize) -> NonZeroUsize { - if a.get() < b.get() { - b - } else { - a - } -} - -pub(crate) const fn min(a: NonZeroUsize, b: NonZeroUsize) -> NonZeroUsize { - if a.get() > b.get() { - b - } else { - a - } -} - -/// Since we support multiple versions of Rust, there are often features which -/// have been stabilized in the most recent stable release which do not yet -/// exist (stably) on our MSRV. This module provides polyfills for those -/// features so that we can write more "modern" code, and just remove the -/// polyfill once our MSRV supports the corresponding feature. Without this, -/// we'd have to write worse/more verbose code and leave TODO comments sprinkled -/// throughout the codebase to update to the new pattern once it's stabilized. -/// -/// Each trait is imported as `_` at the crate root; each polyfill should "just -/// work" at usage sites. -pub(crate) mod polyfills { - use core::ptr::{self, NonNull}; - - // A polyfill for `NonNull::slice_from_raw_parts` that we can use before our - // MSRV is 1.70, when that function was stabilized. - // - // TODO(#67): Once our MSRV is 1.70, remove this. - #[allow(unused)] - pub(crate) trait NonNullExt<T> { - fn slice_from_raw_parts(data: Self, len: usize) -> NonNull<[T]>; - } - - #[allow(unused)] - impl<T> NonNullExt<T> for NonNull<T> { - #[inline(always)] - fn slice_from_raw_parts(data: Self, len: usize) -> NonNull<[T]> { - let ptr = ptr::slice_from_raw_parts_mut(data.as_ptr(), len); - // SAFETY: `ptr` is converted from `data`, which is non-null. - unsafe { NonNull::new_unchecked(ptr) } - } - } -} - -#[cfg(test)] -pub(crate) mod testutil { - use core::fmt::{self, Display, Formatter}; - - use crate::*; - - /// A `T` which is aligned to at least `align_of::<A>()`. - #[derive(Default)] - pub(crate) struct Align<T, A> { - pub(crate) t: T, - _a: [A; 0], - } - - impl<T: Default, A> Align<T, A> { - pub(crate) fn set_default(&mut self) { - self.t = T::default(); - } - } - - impl<T, A> Align<T, A> { - pub(crate) const fn new(t: T) -> Align<T, A> { - Align { t, _a: [] } - } - } - - // A `u64` with alignment 8. - // - // Though `u64` has alignment 8 on some platforms, it's not guaranteed. - // By contrast, `AU64` is guaranteed to have alignment 8. - #[derive( - KnownLayout, - FromZeroes, - FromBytes, - AsBytes, - Eq, - PartialEq, - Ord, - PartialOrd, - Default, - Debug, - Copy, - Clone, - )] - #[repr(C, align(8))] - pub(crate) struct AU64(pub(crate) u64); - - impl AU64 { - // Converts this `AU64` to bytes using this platform's endianness. - pub(crate) fn to_bytes(self) -> [u8; 8] { - crate::transmute!(self) - } - } - - impl Display for AU64 { - fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { - Display::fmt(&self.0, f) - } - } - - #[derive( - FromZeroes, FromBytes, Eq, PartialEq, Ord, PartialOrd, Default, Debug, Copy, Clone, - )] - #[repr(C)] - pub(crate) struct Nested<T, U: ?Sized> { - _t: T, - _u: U, - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_round_down_to_next_multiple_of_alignment() { - fn alt_impl(n: usize, align: NonZeroUsize) -> usize { - let mul = n / align.get(); - mul * align.get() - } - - for align in [1, 2, 4, 8, 16] { - for n in 0..256 { - let align = NonZeroUsize::new(align).unwrap(); - let want = alt_impl(n, align); - let got = round_down_to_next_multiple_of_alignment(n, align); - assert_eq!(got, want, "round_down_to_next_multiple_of_alignment({n}, {align})"); - } - } - } -} - -#[cfg(kani)] -mod proofs { - use super::*; - - #[kani::proof] - fn prove_round_down_to_next_multiple_of_alignment() { - fn model_impl(n: usize, align: NonZeroUsize) -> usize { - assert!(align.get().is_power_of_two()); - let mul = n / align.get(); - mul * align.get() - } - - let align: NonZeroUsize = kani::any(); - kani::assume(align.get().is_power_of_two()); - let n: usize = kani::any(); - - let expected = model_impl(n, align); - let actual = round_down_to_next_multiple_of_alignment(n, align); - assert_eq!(expected, actual, "round_down_to_next_multiple_of_alignment({n}, {align})"); - } - - // Restricted to nightly since we use the unstable `usize::next_multiple_of` - // in our model implementation. - #[cfg(__INTERNAL_USE_ONLY_NIGHLTY_FEATURES_IN_TESTS)] - #[kani::proof] - fn prove_padding_needed_for() { - fn model_impl(len: usize, align: NonZeroUsize) -> usize { - let padded = len.next_multiple_of(align.get()); - let padding = padded - len; - padding - } - - let align: NonZeroUsize = kani::any(); - kani::assume(align.get().is_power_of_two()); - let len: usize = kani::any(); - // Constrain `len` to valid Rust lengths, since our model implementation - // isn't robust to overflow. - kani::assume(len <= isize::MAX as usize); - kani::assume(align.get() < 1 << 29); - - let expected = model_impl(len, align); - let actual = core_layout::padding_needed_for(len, align); - assert_eq!(expected, actual, "padding_needed_for({len}, {align})"); - - let padded_len = actual + len; - assert_eq!(padded_len % align, 0); - assert!(padded_len / align >= len / align); - } -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/src/wrappers.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/src/wrappers.rs deleted file mode 100644 index 6532bb4..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/src/wrappers.rs +++ /dev/null
@@ -1,503 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -use core::{ - cmp::Ordering, - fmt::{self, Debug, Display, Formatter}, - hash::Hash, - mem::{self, ManuallyDrop}, - ops::{Deref, DerefMut}, - ptr, -}; - -use super::*; - -/// A type with no alignment requirement. -/// -/// An `Unalign` wraps a `T`, removing any alignment requirement. `Unalign<T>` -/// has the same size and bit validity as `T`, but not necessarily the same -/// alignment [or ABI]. This is useful if a type with an alignment requirement -/// needs to be read from a chunk of memory which provides no alignment -/// guarantees. -/// -/// Since `Unalign` has no alignment requirement, the inner `T` may not be -/// properly aligned in memory. There are five ways to access the inner `T`: -/// - by value, using [`get`] or [`into_inner`] -/// - by reference inside of a callback, using [`update`] -/// - fallibly by reference, using [`try_deref`] or [`try_deref_mut`]; these can -/// fail if the `Unalign` does not satisfy `T`'s alignment requirement at -/// runtime -/// - unsafely by reference, using [`deref_unchecked`] or -/// [`deref_mut_unchecked`]; it is the caller's responsibility to ensure that -/// the `Unalign` satisfies `T`'s alignment requirement -/// - (where `T: Unaligned`) infallibly by reference, using [`Deref::deref`] or -/// [`DerefMut::deref_mut`] -/// -/// [or ABI]: https://github.com/google/zerocopy/issues/164 -/// [`get`]: Unalign::get -/// [`into_inner`]: Unalign::into_inner -/// [`update`]: Unalign::update -/// [`try_deref`]: Unalign::try_deref -/// [`try_deref_mut`]: Unalign::try_deref_mut -/// [`deref_unchecked`]: Unalign::deref_unchecked -/// [`deref_mut_unchecked`]: Unalign::deref_mut_unchecked -// NOTE: This type is sound to use with types that need to be dropped. The -// reason is that the compiler-generated drop code automatically moves all -// values to aligned memory slots before dropping them in-place. This is not -// well-documented, but it's hinted at in places like [1] and [2]. However, this -// also means that `T` must be `Sized`; unless something changes, we can never -// support unsized `T`. [3] -// -// [1] https://github.com/rust-lang/rust/issues/54148#issuecomment-420529646 -// [2] https://github.com/google/zerocopy/pull/126#discussion_r1018512323 -// [3] https://github.com/google/zerocopy/issues/209 -#[allow(missing_debug_implementations)] -#[derive(Default, Copy)] -#[cfg_attr( - any(feature = "derive", test), - derive(KnownLayout, FromZeroes, FromBytes, AsBytes, Unaligned) -)] -#[repr(C, packed)] -pub struct Unalign<T>(T); - -#[cfg(not(any(feature = "derive", test)))] -impl_known_layout!(T => Unalign<T>); - -safety_comment! { - /// SAFETY: - /// - `Unalign<T>` is `repr(packed)`, so it is unaligned regardless of the - /// alignment of `T`, and so we don't require that `T: Unaligned` - /// - `Unalign<T>` has the same bit validity as `T`, and so it is - /// `FromZeroes`, `FromBytes`, or `AsBytes` exactly when `T` is as well. - impl_or_verify!(T => Unaligned for Unalign<T>); - impl_or_verify!(T: FromZeroes => FromZeroes for Unalign<T>); - impl_or_verify!(T: FromBytes => FromBytes for Unalign<T>); - impl_or_verify!(T: AsBytes => AsBytes for Unalign<T>); -} - -// Note that `Unalign: Clone` only if `T: Copy`. Since the inner `T` may not be -// aligned, there's no way to safely call `T::clone`, and so a `T: Clone` bound -// is not sufficient to implement `Clone` for `Unalign`. -impl<T: Copy> Clone for Unalign<T> { - #[inline(always)] - fn clone(&self) -> Unalign<T> { - *self - } -} - -impl<T> Unalign<T> { - /// Constructs a new `Unalign`. - #[inline(always)] - pub const fn new(val: T) -> Unalign<T> { - Unalign(val) - } - - /// Consumes `self`, returning the inner `T`. - #[inline(always)] - pub const fn into_inner(self) -> T { - // Use this instead of `mem::transmute` since the latter can't tell - // that `Unalign<T>` and `T` have the same size. - #[repr(C)] - union Transmute<T> { - u: ManuallyDrop<Unalign<T>>, - t: ManuallyDrop<T>, - } - - // SAFETY: Since `Unalign` is `#[repr(C, packed)]`, it has the same - // layout as `T`. `ManuallyDrop<U>` is guaranteed to have the same - // layout as `U`, and so `ManuallyDrop<Unalign<T>>` has the same layout - // as `ManuallyDrop<T>`. Since `Transmute<T>` is `#[repr(C)]`, its `t` - // and `u` fields both start at the same offset (namely, 0) within the - // union. - // - // We do this instead of just destructuring in order to prevent - // `Unalign`'s `Drop::drop` from being run, since dropping is not - // supported in `const fn`s. - // - // TODO(https://github.com/rust-lang/rust/issues/73255): Destructure - // instead of using unsafe. - unsafe { ManuallyDrop::into_inner(Transmute { u: ManuallyDrop::new(self) }.t) } - } - - /// Attempts to return a reference to the wrapped `T`, failing if `self` is - /// not properly aligned. - /// - /// If `self` does not satisfy `mem::align_of::<T>()`, then it is unsound to - /// return a reference to the wrapped `T`, and `try_deref` returns `None`. - /// - /// If `T: Unaligned`, then `Unalign<T>` implements [`Deref`], and callers - /// may prefer [`Deref::deref`], which is infallible. - #[inline(always)] - pub fn try_deref(&self) -> Option<&T> { - if !util::aligned_to::<_, T>(self) { - return None; - } - - // SAFETY: `deref_unchecked`'s safety requirement is that `self` is - // aligned to `align_of::<T>()`, which we just checked. - unsafe { Some(self.deref_unchecked()) } - } - - /// Attempts to return a mutable reference to the wrapped `T`, failing if - /// `self` is not properly aligned. - /// - /// If `self` does not satisfy `mem::align_of::<T>()`, then it is unsound to - /// return a reference to the wrapped `T`, and `try_deref_mut` returns - /// `None`. - /// - /// If `T: Unaligned`, then `Unalign<T>` implements [`DerefMut`], and - /// callers may prefer [`DerefMut::deref_mut`], which is infallible. - #[inline(always)] - pub fn try_deref_mut(&mut self) -> Option<&mut T> { - if !util::aligned_to::<_, T>(&*self) { - return None; - } - - // SAFETY: `deref_mut_unchecked`'s safety requirement is that `self` is - // aligned to `align_of::<T>()`, which we just checked. - unsafe { Some(self.deref_mut_unchecked()) } - } - - /// Returns a reference to the wrapped `T` without checking alignment. - /// - /// If `T: Unaligned`, then `Unalign<T>` implements[ `Deref`], and callers - /// may prefer [`Deref::deref`], which is safe. - /// - /// # Safety - /// - /// If `self` does not satisfy `mem::align_of::<T>()`, then - /// `self.deref_unchecked()` may cause undefined behavior. - #[inline(always)] - pub const unsafe fn deref_unchecked(&self) -> &T { - // SAFETY: `Unalign<T>` is `repr(transparent)`, so there is a valid `T` - // at the same memory location as `self`. It has no alignment guarantee, - // but the caller has promised that `self` is properly aligned, so we - // know that it is sound to create a reference to `T` at this memory - // location. - // - // We use `mem::transmute` instead of `&*self.get_ptr()` because - // dereferencing pointers is not stable in `const` on our current MSRV - // (1.56 as of this writing). - unsafe { mem::transmute(self) } - } - - /// Returns a mutable reference to the wrapped `T` without checking - /// alignment. - /// - /// If `T: Unaligned`, then `Unalign<T>` implements[ `DerefMut`], and - /// callers may prefer [`DerefMut::deref_mut`], which is safe. - /// - /// # Safety - /// - /// If `self` does not satisfy `mem::align_of::<T>()`, then - /// `self.deref_mut_unchecked()` may cause undefined behavior. - #[inline(always)] - pub unsafe fn deref_mut_unchecked(&mut self) -> &mut T { - // SAFETY: `self.get_mut_ptr()` returns a raw pointer to a valid `T` at - // the same memory location as `self`. It has no alignment guarantee, - // but the caller has promised that `self` is properly aligned, so we - // know that the pointer itself is aligned, and thus that it is sound to - // create a reference to a `T` at this memory location. - unsafe { &mut *self.get_mut_ptr() } - } - - /// Gets an unaligned raw pointer to the inner `T`. - /// - /// # Safety - /// - /// The returned raw pointer is not necessarily aligned to - /// `align_of::<T>()`. Most functions which operate on raw pointers require - /// those pointers to be aligned, so calling those functions with the result - /// of `get_ptr` will be undefined behavior if alignment is not guaranteed - /// using some out-of-band mechanism. In general, the only functions which - /// are safe to call with this pointer are those which are explicitly - /// documented as being sound to use with an unaligned pointer, such as - /// [`read_unaligned`]. - /// - /// [`read_unaligned`]: core::ptr::read_unaligned - #[inline(always)] - pub const fn get_ptr(&self) -> *const T { - ptr::addr_of!(self.0) - } - - /// Gets an unaligned mutable raw pointer to the inner `T`. - /// - /// # Safety - /// - /// The returned raw pointer is not necessarily aligned to - /// `align_of::<T>()`. Most functions which operate on raw pointers require - /// those pointers to be aligned, so calling those functions with the result - /// of `get_ptr` will be undefined behavior if alignment is not guaranteed - /// using some out-of-band mechanism. In general, the only functions which - /// are safe to call with this pointer are those which are explicitly - /// documented as being sound to use with an unaligned pointer, such as - /// [`read_unaligned`]. - /// - /// [`read_unaligned`]: core::ptr::read_unaligned - // TODO(https://github.com/rust-lang/rust/issues/57349): Make this `const`. - #[inline(always)] - pub fn get_mut_ptr(&mut self) -> *mut T { - ptr::addr_of_mut!(self.0) - } - - /// Sets the inner `T`, dropping the previous value. - // TODO(https://github.com/rust-lang/rust/issues/57349): Make this `const`. - #[inline(always)] - pub fn set(&mut self, t: T) { - *self = Unalign::new(t); - } - - /// Updates the inner `T` by calling a function on it. - /// - /// If [`T: Unaligned`], then `Unalign<T>` implements [`DerefMut`], and that - /// impl should be preferred over this method when performing updates, as it - /// will usually be faster and more ergonomic. - /// - /// For large types, this method may be expensive, as it requires copying - /// `2 * size_of::<T>()` bytes. \[1\] - /// - /// \[1\] Since the inner `T` may not be aligned, it would not be sound to - /// invoke `f` on it directly. Instead, `update` moves it into a - /// properly-aligned location in the local stack frame, calls `f` on it, and - /// then moves it back to its original location in `self`. - /// - /// [`T: Unaligned`]: Unaligned - #[inline] - pub fn update<O, F: FnOnce(&mut T) -> O>(&mut self, f: F) -> O { - // On drop, this moves `copy` out of itself and uses `ptr::write` to - // overwrite `slf`. - struct WriteBackOnDrop<T> { - copy: ManuallyDrop<T>, - slf: *mut Unalign<T>, - } - - impl<T> Drop for WriteBackOnDrop<T> { - fn drop(&mut self) { - // SAFETY: We never use `copy` again as required by - // `ManuallyDrop::take`. - let copy = unsafe { ManuallyDrop::take(&mut self.copy) }; - // SAFETY: `slf` is the raw pointer value of `self`. We know it - // is valid for writes and properly aligned because `self` is a - // mutable reference, which guarantees both of these properties. - unsafe { ptr::write(self.slf, Unalign::new(copy)) }; - } - } - - // SAFETY: We know that `self` is valid for reads, properly aligned, and - // points to an initialized `Unalign<T>` because it is a mutable - // reference, which guarantees all of these properties. - // - // Since `T: !Copy`, it would be unsound in the general case to allow - // both the original `Unalign<T>` and the copy to be used by safe code. - // We guarantee that the copy is used to overwrite the original in the - // `Drop::drop` impl of `WriteBackOnDrop`. So long as this `drop` is - // called before any other safe code executes, soundness is upheld. - // While this method can terminate in two ways (by returning normally or - // by unwinding due to a panic in `f`), in both cases, `write_back` is - // dropped - and its `drop` called - before any other safe code can - // execute. - let copy = unsafe { ptr::read(self) }.into_inner(); - let mut write_back = WriteBackOnDrop { copy: ManuallyDrop::new(copy), slf: self }; - - let ret = f(&mut write_back.copy); - - drop(write_back); - ret - } -} - -impl<T: Copy> Unalign<T> { - /// Gets a copy of the inner `T`. - // TODO(https://github.com/rust-lang/rust/issues/57349): Make this `const`. - #[inline(always)] - pub fn get(&self) -> T { - let Unalign(val) = *self; - val - } -} - -impl<T: Unaligned> Deref for Unalign<T> { - type Target = T; - - #[inline(always)] - fn deref(&self) -> &T { - // SAFETY: `deref_unchecked`'s safety requirement is that `self` is - // aligned to `align_of::<T>()`. `T: Unaligned` guarantees that - // `align_of::<T>() == 1`, and all pointers are one-aligned because all - // addresses are divisible by 1. - unsafe { self.deref_unchecked() } - } -} - -impl<T: Unaligned> DerefMut for Unalign<T> { - #[inline(always)] - fn deref_mut(&mut self) -> &mut T { - // SAFETY: `deref_mut_unchecked`'s safety requirement is that `self` is - // aligned to `align_of::<T>()`. `T: Unaligned` guarantees that - // `align_of::<T>() == 1`, and all pointers are one-aligned because all - // addresses are divisible by 1. - unsafe { self.deref_mut_unchecked() } - } -} - -impl<T: Unaligned + PartialOrd> PartialOrd<Unalign<T>> for Unalign<T> { - #[inline(always)] - fn partial_cmp(&self, other: &Unalign<T>) -> Option<Ordering> { - PartialOrd::partial_cmp(self.deref(), other.deref()) - } -} - -impl<T: Unaligned + Ord> Ord for Unalign<T> { - #[inline(always)] - fn cmp(&self, other: &Unalign<T>) -> Ordering { - Ord::cmp(self.deref(), other.deref()) - } -} - -impl<T: Unaligned + PartialEq> PartialEq<Unalign<T>> for Unalign<T> { - #[inline(always)] - fn eq(&self, other: &Unalign<T>) -> bool { - PartialEq::eq(self.deref(), other.deref()) - } -} - -impl<T: Unaligned + Eq> Eq for Unalign<T> {} - -impl<T: Unaligned + Hash> Hash for Unalign<T> { - #[inline(always)] - fn hash<H>(&self, state: &mut H) - where - H: Hasher, - { - self.deref().hash(state); - } -} - -impl<T: Unaligned + Debug> Debug for Unalign<T> { - #[inline(always)] - fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { - Debug::fmt(self.deref(), f) - } -} - -impl<T: Unaligned + Display> Display for Unalign<T> { - #[inline(always)] - fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { - Display::fmt(self.deref(), f) - } -} - -#[cfg(test)] -mod tests { - use core::panic::AssertUnwindSafe; - - use super::*; - use crate::util::testutil::*; - - /// A `T` which is guaranteed not to satisfy `align_of::<A>()`. - /// - /// It must be the case that `align_of::<T>() < align_of::<A>()` in order - /// fot this type to work properly. - #[repr(C)] - struct ForceUnalign<T, A> { - // The outer struct is aligned to `A`, and, thanks to `repr(C)`, `t` is - // placed at the minimum offset that guarantees its alignment. If - // `align_of::<T>() < align_of::<A>()`, then that offset will be - // guaranteed *not* to satisfy `align_of::<A>()`. - _u: u8, - t: T, - _a: [A; 0], - } - - impl<T, A> ForceUnalign<T, A> { - const fn new(t: T) -> ForceUnalign<T, A> { - ForceUnalign { _u: 0, t, _a: [] } - } - } - - #[test] - fn test_unalign() { - // Test methods that don't depend on alignment. - let mut u = Unalign::new(AU64(123)); - assert_eq!(u.get(), AU64(123)); - assert_eq!(u.into_inner(), AU64(123)); - assert_eq!(u.get_ptr(), <*const _>::cast::<AU64>(&u)); - assert_eq!(u.get_mut_ptr(), <*mut _>::cast::<AU64>(&mut u)); - u.set(AU64(321)); - assert_eq!(u.get(), AU64(321)); - - // Test methods that depend on alignment (when alignment is satisfied). - let mut u: Align<_, AU64> = Align::new(Unalign::new(AU64(123))); - assert_eq!(u.t.try_deref(), Some(&AU64(123))); - assert_eq!(u.t.try_deref_mut(), Some(&mut AU64(123))); - // SAFETY: The `Align<_, AU64>` guarantees proper alignment. - assert_eq!(unsafe { u.t.deref_unchecked() }, &AU64(123)); - // SAFETY: The `Align<_, AU64>` guarantees proper alignment. - assert_eq!(unsafe { u.t.deref_mut_unchecked() }, &mut AU64(123)); - *u.t.try_deref_mut().unwrap() = AU64(321); - assert_eq!(u.t.get(), AU64(321)); - - // Test methods that depend on alignment (when alignment is not - // satisfied). - let mut u: ForceUnalign<_, AU64> = ForceUnalign::new(Unalign::new(AU64(123))); - assert_eq!(u.t.try_deref(), None); - assert_eq!(u.t.try_deref_mut(), None); - - // Test methods that depend on `T: Unaligned`. - let mut u = Unalign::new(123u8); - assert_eq!(u.try_deref(), Some(&123)); - assert_eq!(u.try_deref_mut(), Some(&mut 123)); - assert_eq!(u.deref(), &123); - assert_eq!(u.deref_mut(), &mut 123); - *u = 21; - assert_eq!(u.get(), 21); - - // Test that some `Unalign` functions and methods are `const`. - const _UNALIGN: Unalign<u64> = Unalign::new(0); - const _UNALIGN_PTR: *const u64 = _UNALIGN.get_ptr(); - const _U64: u64 = _UNALIGN.into_inner(); - // Make sure all code is considered "used". - // - // TODO(https://github.com/rust-lang/rust/issues/104084): Remove this - // attribute. - #[allow(dead_code)] - const _: () = { - let x: Align<_, AU64> = Align::new(Unalign::new(AU64(123))); - // Make sure that `deref_unchecked` is `const`. - // - // SAFETY: The `Align<_, AU64>` guarantees proper alignment. - let au64 = unsafe { x.t.deref_unchecked() }; - match au64 { - AU64(123) => {} - _ => unreachable!(), - } - }; - } - - #[test] - fn test_unalign_update() { - let mut u = Unalign::new(AU64(123)); - u.update(|a| a.0 += 1); - assert_eq!(u.get(), AU64(124)); - - // Test that, even if the callback panics, the original is still - // correctly overwritten. Use a `Box` so that Miri is more likely to - // catch any unsoundness (which would likely result in two `Box`es for - // the same heap object, which is the sort of thing that Miri would - // probably catch). - let mut u = Unalign::new(Box::new(AU64(123))); - let res = std::panic::catch_unwind(AssertUnwindSafe(|| { - u.update(|a| { - a.0 += 1; - panic!(); - }) - })); - assert!(res.is_err()); - assert_eq!(u.into_inner(), Box::new(AU64(124))); - } -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/testdata/include_value/data b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/testdata/include_value/data deleted file mode 100644 index 85df507..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/testdata/include_value/data +++ /dev/null
@@ -1 +0,0 @@ -abcd \ No newline at end of file
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/trybuild.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/trybuild.rs deleted file mode 100644 index 24abc286..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/trybuild.rs +++ /dev/null
@@ -1,41 +0,0 @@ -// Copyright 2019 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -use testutil::ToolchainVersion; - -#[test] -#[cfg_attr(miri, ignore)] -fn ui() { - let version = ToolchainVersion::extract_from_pwd().unwrap(); - // See the doc comment on this method for an explanation of what this does - // and why we store source files in different directories. - let source_files_dirname = version.get_ui_source_files_dirname_and_maybe_print_warning(); - - let t = trybuild::TestCases::new(); - t.compile_fail(format!("tests/{source_files_dirname}/*.rs")); -} - -// The file `invalid-impls.rs` directly includes `src/macros.rs` in order to -// test the `impl_or_verify!` macro which is defined in that file. Specifically, -// it tests the verification portion of that macro, which is enabled when -// `cfg(any(feature = "derive", test))`. While `--cfg test` is of course passed -// to the code in the file you're reading right now, `trybuild` does not pass -// `--cfg test` when it invokes Cargo. As a result, this `trybuild` test only -// tests the correct behavior when the "derive" feature is enabled. -#[cfg(feature = "derive")] -#[test] -#[cfg_attr(miri, ignore)] -fn ui_invalid_impls() { - let version = ToolchainVersion::extract_from_pwd().unwrap(); - // See the doc comment on this method for an explanation of what this does - // and why we store source files in different directories. - let source_files_dirname = version.get_ui_source_files_dirname_and_maybe_print_warning(); - - let t = trybuild::TestCases::new(); - t.compile_fail(format!("tests/{source_files_dirname}/invalid-impls/*.rs")); -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/include_value_not_from_bytes.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/include_value_not_from_bytes.rs deleted file mode 100644 index 45b6138f..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/include_value_not_from_bytes.rs +++ /dev/null
@@ -1,12 +0,0 @@ -// Copyright 2022 The Fuchsia Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#[macro_use] -extern crate zerocopy; - -fn main() {} - -// Should fail because `UnsafeCell<u32>: !FromBytes`. -const NOT_FROM_BYTES: core::cell::UnsafeCell<u32> = - include_value!("../../testdata/include_value/data");
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/include_value_not_from_bytes.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/include_value_not_from_bytes.stderr deleted file mode 100644 index 21f6443b..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/include_value_not_from_bytes.stderr +++ /dev/null
@@ -1,12 +0,0 @@ -error[E0277]: the trait bound `UnsafeCell<u32>: FromBytes` is not satisfied - --> tests/ui-msrv/include_value_not_from_bytes.rs:12:5 - | -12 | include_value!("../../testdata/include_value/data"); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `FromBytes` is not implemented for `UnsafeCell<u32>` - | -note: required by a bound in `AssertIsFromBytes` - --> tests/ui-msrv/include_value_not_from_bytes.rs:12:5 - | -12 | include_value!("../../testdata/include_value/data"); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertIsFromBytes` - = note: this error originates in the macro `$crate::transmute` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/include_value_wrong_size.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/include_value_wrong_size.rs deleted file mode 100644 index d87b306..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/include_value_wrong_size.rs +++ /dev/null
@@ -1,11 +0,0 @@ -// Copyright 2022 The Fuchsia Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#[macro_use] -extern crate zerocopy; - -fn main() {} - -// Should fail because the file is 4 bytes long, not 8. -const WRONG_SIZE: u64 = include_value!("../../testdata/include_value/data");
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/include_value_wrong_size.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/include_value_wrong_size.stderr deleted file mode 100644 index 3004584..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/include_value_wrong_size.stderr +++ /dev/null
@@ -1,9 +0,0 @@ -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-msrv/include_value_wrong_size.rs:11:25 - | -11 | const WRONG_SIZE: u64 = include_value!("../../testdata/include_value/data"); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: source type: `[u8; 4]` (32 bits) - = note: target type: `u64` (64 bits) - = note: this error originates in the macro `$crate::transmute` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/invalid-impls/invalid-impls.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/invalid-impls/invalid-impls.rs deleted file mode 100644 index ea96390..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/invalid-impls/invalid-impls.rs +++ /dev/null
@@ -1,29 +0,0 @@ -// Copyright 2022 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -// Since some macros from `macros.rs` are unused. -#![allow(unused)] - -extern crate zerocopy; -extern crate zerocopy_derive; - -include!("../../../src/macros.rs"); - -use zerocopy::*; -use zerocopy_derive::*; - -fn main() {} - -#[derive(FromZeroes, FromBytes, AsBytes, Unaligned)] -#[repr(transparent)] -struct Foo<T>(T); - -impl_or_verify!(T => FromZeroes for Foo<T>); -impl_or_verify!(T => FromBytes for Foo<T>); -impl_or_verify!(T => AsBytes for Foo<T>); -impl_or_verify!(T => Unaligned for Foo<T>);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/invalid-impls/invalid-impls.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/invalid-impls/invalid-impls.stderr deleted file mode 100644 index c1de466..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/invalid-impls/invalid-impls.stderr +++ /dev/null
@@ -1,127 +0,0 @@ -error[E0277]: the trait bound `T: zerocopy::FromZeroes` is not satisfied - --> tests/ui-msrv/invalid-impls/../../../src/macros.rs - | - | impl<$($tyvar $(: $(? $optbound +)* $($bound +)*)?),*> Subtrait for $ty {} - | ^^^^^^^^ the trait `zerocopy::FromZeroes` is not implemented for `T` - | - ::: tests/ui-msrv/invalid-impls/invalid-impls.rs:26:1 - | -26 | impl_or_verify!(T => FromZeroes for Foo<T>); - | ------------------------------------------- in this macro invocation - | -note: required because of the requirements on the impl of `zerocopy::FromZeroes` for `Foo<T>` - --> tests/ui-msrv/invalid-impls/invalid-impls.rs:22:10 - | -22 | #[derive(FromZeroes, FromBytes, AsBytes, Unaligned)] - | ^^^^^^^^^^ -note: required by a bound in `_::Subtrait` - --> tests/ui-msrv/invalid-impls/../../../src/macros.rs - | - | trait Subtrait: $trait {} - | ^^^^^^ required by this bound in `_::Subtrait` - | - ::: tests/ui-msrv/invalid-impls/invalid-impls.rs:26:1 - | -26 | impl_or_verify!(T => FromZeroes for Foo<T>); - | ------------------------------------------- in this macro invocation - = note: this error originates in the macro `impl_or_verify` (in Nightly builds, run with -Z macro-backtrace for more info) -help: consider restricting type parameter `T` - | -26 | impl_or_verify!(T: zerocopy::FromZeroes => FromZeroes for Foo<T>); - | ++++++++++++++++++++++ - -error[E0277]: the trait bound `T: zerocopy::FromBytes` is not satisfied - --> tests/ui-msrv/invalid-impls/../../../src/macros.rs - | - | impl<$($tyvar $(: $(? $optbound +)* $($bound +)*)?),*> Subtrait for $ty {} - | ^^^^^^^^ the trait `zerocopy::FromBytes` is not implemented for `T` - | - ::: tests/ui-msrv/invalid-impls/invalid-impls.rs:27:1 - | -27 | impl_or_verify!(T => FromBytes for Foo<T>); - | ------------------------------------------ in this macro invocation - | -note: required because of the requirements on the impl of `zerocopy::FromBytes` for `Foo<T>` - --> tests/ui-msrv/invalid-impls/invalid-impls.rs:22:22 - | -22 | #[derive(FromZeroes, FromBytes, AsBytes, Unaligned)] - | ^^^^^^^^^ -note: required by a bound in `_::Subtrait` - --> tests/ui-msrv/invalid-impls/../../../src/macros.rs - | - | trait Subtrait: $trait {} - | ^^^^^^ required by this bound in `_::Subtrait` - | - ::: tests/ui-msrv/invalid-impls/invalid-impls.rs:27:1 - | -27 | impl_or_verify!(T => FromBytes for Foo<T>); - | ------------------------------------------ in this macro invocation - = note: this error originates in the macro `impl_or_verify` (in Nightly builds, run with -Z macro-backtrace for more info) -help: consider restricting type parameter `T` - | -27 | impl_or_verify!(T: zerocopy::FromBytes => FromBytes for Foo<T>); - | +++++++++++++++++++++ - -error[E0277]: the trait bound `T: zerocopy::AsBytes` is not satisfied - --> tests/ui-msrv/invalid-impls/../../../src/macros.rs - | - | impl<$($tyvar $(: $(? $optbound +)* $($bound +)*)?),*> Subtrait for $ty {} - | ^^^^^^^^ the trait `zerocopy::AsBytes` is not implemented for `T` - | - ::: tests/ui-msrv/invalid-impls/invalid-impls.rs:28:1 - | -28 | impl_or_verify!(T => AsBytes for Foo<T>); - | ---------------------------------------- in this macro invocation - | -note: required because of the requirements on the impl of `zerocopy::AsBytes` for `Foo<T>` - --> tests/ui-msrv/invalid-impls/invalid-impls.rs:22:33 - | -22 | #[derive(FromZeroes, FromBytes, AsBytes, Unaligned)] - | ^^^^^^^ -note: required by a bound in `_::Subtrait` - --> tests/ui-msrv/invalid-impls/../../../src/macros.rs - | - | trait Subtrait: $trait {} - | ^^^^^^ required by this bound in `_::Subtrait` - | - ::: tests/ui-msrv/invalid-impls/invalid-impls.rs:28:1 - | -28 | impl_or_verify!(T => AsBytes for Foo<T>); - | ---------------------------------------- in this macro invocation - = note: this error originates in the macro `impl_or_verify` (in Nightly builds, run with -Z macro-backtrace for more info) -help: consider restricting type parameter `T` - | -28 | impl_or_verify!(T: zerocopy::AsBytes => AsBytes for Foo<T>); - | +++++++++++++++++++ - -error[E0277]: the trait bound `T: zerocopy::Unaligned` is not satisfied - --> tests/ui-msrv/invalid-impls/../../../src/macros.rs - | - | impl<$($tyvar $(: $(? $optbound +)* $($bound +)*)?),*> Subtrait for $ty {} - | ^^^^^^^^ the trait `zerocopy::Unaligned` is not implemented for `T` - | - ::: tests/ui-msrv/invalid-impls/invalid-impls.rs:29:1 - | -29 | impl_or_verify!(T => Unaligned for Foo<T>); - | ------------------------------------------ in this macro invocation - | -note: required because of the requirements on the impl of `zerocopy::Unaligned` for `Foo<T>` - --> tests/ui-msrv/invalid-impls/invalid-impls.rs:22:42 - | -22 | #[derive(FromZeroes, FromBytes, AsBytes, Unaligned)] - | ^^^^^^^^^ -note: required by a bound in `_::Subtrait` - --> tests/ui-msrv/invalid-impls/../../../src/macros.rs - | - | trait Subtrait: $trait {} - | ^^^^^^ required by this bound in `_::Subtrait` - | - ::: tests/ui-msrv/invalid-impls/invalid-impls.rs:29:1 - | -29 | impl_or_verify!(T => Unaligned for Foo<T>); - | ------------------------------------------ in this macro invocation - = note: this error originates in the macro `impl_or_verify` (in Nightly builds, run with -Z macro-backtrace for more info) -help: consider restricting type parameter `T` - | -29 | impl_or_verify!(T: zerocopy::Unaligned => Unaligned for Foo<T>); - | +++++++++++++++++++++
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/max-align.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/max-align.rs deleted file mode 100644 index 53e3eb9..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/max-align.rs +++ /dev/null
@@ -1,99 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -#[repr(C, align(1))] -struct Align1; - -#[repr(C, align(2))] -struct Align2; - -#[repr(C, align(4))] -struct Align4; - -#[repr(C, align(8))] -struct Align8; - -#[repr(C, align(16))] -struct Align16; - -#[repr(C, align(32))] -struct Align32; - -#[repr(C, align(64))] -struct Align64; - -#[repr(C, align(128))] -struct Align128; - -#[repr(C, align(256))] -struct Align256; - -#[repr(C, align(512))] -struct Align512; - -#[repr(C, align(1024))] -struct Align1024; - -#[repr(C, align(2048))] -struct Align2048; - -#[repr(C, align(4096))] -struct Align4096; - -#[repr(C, align(8192))] -struct Align8192; - -#[repr(C, align(16384))] -struct Align16384; - -#[repr(C, align(32768))] -struct Align32768; - -#[repr(C, align(65536))] -struct Align65536; - -#[repr(C, align(131072))] -struct Align131072; - -#[repr(C, align(262144))] -struct Align262144; - -#[repr(C, align(524288))] -struct Align524288; - -#[repr(C, align(1048576))] -struct Align1048576; - -#[repr(C, align(2097152))] -struct Align2097152; - -#[repr(C, align(4194304))] -struct Align4194304; - -#[repr(C, align(8388608))] -struct Align8388608; - -#[repr(C, align(16777216))] -struct Align16777216; - -#[repr(C, align(33554432))] -struct Align33554432; - -#[repr(C, align(67108864))] -struct Align67108864; - -#[repr(C, align(134217728))] -struct Align13421772; - -#[repr(C, align(268435456))] -struct Align26843545; - -#[repr(C, align(1073741824))] -struct Align1073741824; - -fn main() {}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/max-align.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/max-align.stderr deleted file mode 100644 index 6ab6e47e..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/max-align.stderr +++ /dev/null
@@ -1,5 +0,0 @@ -error[E0589]: invalid `repr(align)` attribute: larger than 2^29 - --> tests/ui-msrv/max-align.rs:96:11 - | -96 | #[repr(C, align(1073741824))] - | ^^^^^^^^^^^^^^^^^
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-dst-not-frombytes.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-dst-not-frombytes.rs deleted file mode 100644 index c4caaff9..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-dst-not-frombytes.rs +++ /dev/null
@@ -1,18 +0,0 @@ -// Copyright 2022 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -include!("../../zerocopy-derive/tests/util.rs"); - -extern crate zerocopy; - -use zerocopy::transmute; - -fn main() {} - -// `transmute` requires that the destination type implements `FromBytes` -const DST_NOT_FROM_BYTES: NotZerocopy = transmute!(AU16(0));
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-dst-not-frombytes.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-dst-not-frombytes.stderr deleted file mode 100644 index b4afbbd..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-dst-not-frombytes.stderr +++ /dev/null
@@ -1,12 +0,0 @@ -error[E0277]: the trait bound `NotZerocopy: FromBytes` is not satisfied - --> tests/ui-msrv/transmute-dst-not-frombytes.rs:18:41 - | -18 | const DST_NOT_FROM_BYTES: NotZerocopy = transmute!(AU16(0)); - | ^^^^^^^^^^^^^^^^^^^ the trait `FromBytes` is not implemented for `NotZerocopy` - | -note: required by a bound in `AssertIsFromBytes` - --> tests/ui-msrv/transmute-dst-not-frombytes.rs:18:41 - | -18 | const DST_NOT_FROM_BYTES: NotZerocopy = transmute!(AU16(0)); - | ^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertIsFromBytes` - = note: this error originates in the macro `transmute` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-alignment-increase.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-alignment-increase.rs deleted file mode 100644 index 0928564d..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-alignment-increase.rs +++ /dev/null
@@ -1,19 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -include!("../../zerocopy-derive/tests/util.rs"); - -extern crate zerocopy; - -use zerocopy::transmute_mut; - -fn main() {} - -// `transmute_mut!` does not support transmuting from a type of smaller -// alignment to one of larger alignment. -const INCREASE_ALIGNMENT: &mut AU16 = transmute_mut!(&mut [0u8; 2]);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-alignment-increase.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-alignment-increase.stderr deleted file mode 100644 index 033031c..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-alignment-increase.stderr +++ /dev/null
@@ -1,36 +0,0 @@ -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-msrv/transmute-mut-alignment-increase.rs:19:39 - | -19 | const INCREASE_ALIGNMENT: &mut AU16 = transmute_mut!(&mut [0u8; 2]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: source type: `AlignOf<[u8; 2]>` (8 bits) - = note: target type: `MaxAlignsOf<[u8; 2], AU16>` (16 bits) - = note: this error originates in the macro `$crate::assert_align_gt_eq` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0658]: mutable references are not allowed in constants - --> tests/ui-msrv/transmute-mut-alignment-increase.rs:19:54 - | -19 | const INCREASE_ALIGNMENT: &mut AU16 = transmute_mut!(&mut [0u8; 2]); - | ^^^^^^^^^^^^^ - | - = note: see issue #57349 <https://github.com/rust-lang/rust/issues/57349> for more information - -error[E0015]: cannot call non-const fn `transmute_mut::<[u8; 2], AU16>` in constants - --> tests/ui-msrv/transmute-mut-alignment-increase.rs:19:39 - | -19 | const INCREASE_ALIGNMENT: &mut AU16 = transmute_mut!(&mut [0u8; 2]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: calls in constants are limited to constant functions, tuple structs and tuple variants - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0716]: temporary value dropped while borrowed - --> tests/ui-msrv/transmute-mut-alignment-increase.rs:19:59 - | -19 | const INCREASE_ALIGNMENT: &mut AU16 = transmute_mut!(&mut [0u8; 2]); - | --------------------^^^^^^^^- - | | | - | | creates a temporary which is freed while still in use - | temporary value is freed at the end of this statement - | using this value as a constant requires that borrow lasts for `'static`
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-const.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-const.rs deleted file mode 100644 index 021b562f1..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-const.rs +++ /dev/null
@@ -1,20 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -include!("../../zerocopy-derive/tests/util.rs"); - -extern crate zerocopy; - -use zerocopy::transmute_mut; - -fn main() {} - -const ARRAY_OF_U8S: [u8; 2] = [0u8; 2]; - -// `transmute_mut!` cannot, generally speaking, be used in const contexts. -const CONST_CONTEXT: &mut [u8; 2] = transmute_mut!(&mut ARRAY_OF_U8S);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-const.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-const.stderr deleted file mode 100644 index 30bfe454..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-const.stderr +++ /dev/null
@@ -1,41 +0,0 @@ -warning: taking a mutable reference to a `const` item - --> tests/ui-msrv/transmute-mut-const.rs:20:52 - | -20 | const CONST_CONTEXT: &mut [u8; 2] = transmute_mut!(&mut ARRAY_OF_U8S); - | ^^^^^^^^^^^^^^^^^ - | - = note: `#[warn(const_item_mutation)]` on by default - = note: each usage of a `const` item creates a new temporary - = note: the mutable reference will refer to this temporary, not the original `const` item -note: `const` item defined here - --> tests/ui-msrv/transmute-mut-const.rs:17:1 - | -17 | const ARRAY_OF_U8S: [u8; 2] = [0u8; 2]; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -error[E0658]: mutable references are not allowed in constants - --> tests/ui-msrv/transmute-mut-const.rs:20:52 - | -20 | const CONST_CONTEXT: &mut [u8; 2] = transmute_mut!(&mut ARRAY_OF_U8S); - | ^^^^^^^^^^^^^^^^^ - | - = note: see issue #57349 <https://github.com/rust-lang/rust/issues/57349> for more information - -error[E0015]: cannot call non-const fn `transmute_mut::<[u8; 2], [u8; 2]>` in constants - --> tests/ui-msrv/transmute-mut-const.rs:20:37 - | -20 | const CONST_CONTEXT: &mut [u8; 2] = transmute_mut!(&mut ARRAY_OF_U8S); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: calls in constants are limited to constant functions, tuple structs and tuple variants - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0716]: temporary value dropped while borrowed - --> tests/ui-msrv/transmute-mut-const.rs:20:57 - | -20 | const CONST_CONTEXT: &mut [u8; 2] = transmute_mut!(&mut ARRAY_OF_U8S); - | --------------------^^^^^^^^^^^^- - | | | - | | creates a temporary which is freed while still in use - | temporary value is freed at the end of this statement - | using this value as a constant requires that borrow lasts for `'static`
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-dst-generic.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-dst-generic.rs deleted file mode 100644 index 7068f102..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-dst-generic.rs +++ /dev/null
@@ -1,18 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::{transmute_mut, AsBytes, FromBytes}; - -fn main() {} - -fn transmute_mut<T: AsBytes + FromBytes>(u: &mut u8) -> &mut T { - // `transmute_mut!` requires the destination type to be concrete. - transmute_mut!(u) -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-dst-generic.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-dst-generic.stderr deleted file mode 100644 index f6b54ce..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-dst-generic.stderr +++ /dev/null
@@ -1,19 +0,0 @@ -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-msrv/transmute-mut-dst-generic.rs:17:5 - | -17 | transmute_mut!(u) - | ^^^^^^^^^^^^^^^^^ - | - = note: source type: `u8` (8 bits) - = note: target type: `T` (this type does not have a fixed size) - = note: this error originates in the macro `$crate::assert_size_eq` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-msrv/transmute-mut-dst-generic.rs:17:5 - | -17 | transmute_mut!(u) - | ^^^^^^^^^^^^^^^^^ - | - = note: source type: `AlignOf<u8>` (8 bits) - = note: target type: `MaxAlignsOf<u8, T>` (size can vary because of T) - = note: this error originates in the macro `$crate::assert_align_gt_eq` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-dst-not-a-reference.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-dst-not-a-reference.rs deleted file mode 100644 index 33a9ecd9..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-dst-not-a-reference.rs +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_mut; - -fn main() {} - -// `transmute_mut!` does not support transmuting into a non-reference -// destination type. -const DST_NOT_A_REFERENCE: usize = transmute_mut!(&mut 0u8);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-dst-not-a-reference.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-dst-not-a-reference.stderr deleted file mode 100644 index 8f0ea801e..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-dst-not-a-reference.stderr +++ /dev/null
@@ -1,39 +0,0 @@ -error[E0308]: mismatched types - --> tests/ui-msrv/transmute-mut-dst-not-a-reference.rs:17:36 - | -17 | const DST_NOT_A_REFERENCE: usize = transmute_mut!(&mut 0u8); - | ^^^^^^^^^^^^^^^^^^^^^^^^ expected `usize`, found `&mut _` - | - = note: expected type `usize` - found mutable reference `&mut _` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0308]: mismatched types - --> tests/ui-msrv/transmute-mut-dst-not-a-reference.rs:17:36 - | -17 | const DST_NOT_A_REFERENCE: usize = transmute_mut!(&mut 0u8); - | ^^^^^^^^^^^^^^^^^^^^^^^^ expected `usize`, found `&mut _` - | - = note: expected type `usize` - found mutable reference `&mut _` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0308]: mismatched types - --> tests/ui-msrv/transmute-mut-dst-not-a-reference.rs:17:36 - | -17 | const DST_NOT_A_REFERENCE: usize = transmute_mut!(&mut 0u8); - | ^^^^^^^^^^^^^^^^^^^^^^^^ expected `usize`, found `&mut _` - | - = note: expected type `usize` - found mutable reference `&mut _` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0308]: mismatched types - --> tests/ui-msrv/transmute-mut-dst-not-a-reference.rs:17:36 - | -17 | const DST_NOT_A_REFERENCE: usize = transmute_mut!(&mut 0u8); - | ^^^^^^^^^^^^^^^^^^^^^^^^ expected `usize`, found `&mut _` - | - = note: expected type `usize` - found mutable reference `&mut _` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-dst-not-asbytes.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-dst-not-asbytes.rs deleted file mode 100644 index b72f129..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-dst-not-asbytes.rs +++ /dev/null
@@ -1,24 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_mut; - -fn main() {} - -#[derive(zerocopy::FromZeroes, zerocopy::FromBytes, zerocopy::AsBytes)] -#[repr(C)] -struct Src; - -#[derive(zerocopy::FromZeroes, zerocopy::FromBytes)] -#[repr(C)] -struct Dst; - -// `transmute_mut` requires that the destination type implements `AsBytes` -const DST_NOT_AS_BYTES: &mut Dst = transmute_mut!(&mut Src);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-dst-not-asbytes.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-dst-not-asbytes.stderr deleted file mode 100644 index 7e2dd78..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-dst-not-asbytes.stderr +++ /dev/null
@@ -1,12 +0,0 @@ -error[E0277]: the trait bound `Dst: AsBytes` is not satisfied - --> tests/ui-msrv/transmute-mut-dst-not-asbytes.rs:24:36 - | -24 | const DST_NOT_AS_BYTES: &mut Dst = transmute_mut!(&mut Src); - | ^^^^^^^^^^^^^^^^^^^^^^^^ the trait `AsBytes` is not implemented for `Dst` - | -note: required by a bound in `AssertDstIsAsBytes` - --> tests/ui-msrv/transmute-mut-dst-not-asbytes.rs:24:36 - | -24 | const DST_NOT_AS_BYTES: &mut Dst = transmute_mut!(&mut Src); - | ^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertDstIsAsBytes` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-dst-not-frombytes.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-dst-not-frombytes.rs deleted file mode 100644 index 102fced..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-dst-not-frombytes.rs +++ /dev/null
@@ -1,24 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_mut; - -fn main() {} - -#[derive(zerocopy::FromZeroes, zerocopy::FromBytes, zerocopy::AsBytes)] -#[repr(C)] -struct Src; - -#[derive(zerocopy::AsBytes)] -#[repr(C)] -struct Dst; - -// `transmute_mut` requires that the destination type implements `FromBytes` -const DST_NOT_FROM_BYTES: &mut Dst = transmute_mut!(&mut Src);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-dst-not-frombytes.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-dst-not-frombytes.stderr deleted file mode 100644 index 663e085a3..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-dst-not-frombytes.stderr +++ /dev/null
@@ -1,12 +0,0 @@ -error[E0277]: the trait bound `Dst: FromBytes` is not satisfied - --> tests/ui-msrv/transmute-mut-dst-not-frombytes.rs:24:38 - | -24 | const DST_NOT_FROM_BYTES: &mut Dst = transmute_mut!(&mut Src); - | ^^^^^^^^^^^^^^^^^^^^^^^^ the trait `FromBytes` is not implemented for `Dst` - | -note: required by a bound in `AssertDstIsFromBytes` - --> tests/ui-msrv/transmute-mut-dst-not-frombytes.rs:24:38 - | -24 | const DST_NOT_FROM_BYTES: &mut Dst = transmute_mut!(&mut Src); - | ^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertDstIsFromBytes` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-dst-unsized.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-dst-unsized.rs deleted file mode 100644 index 693ccda..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-dst-unsized.rs +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_mut; - -fn main() {} - -// `transmute_mut!` does not support transmuting into an unsized destination -// type. -const DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8; 1]);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-dst-unsized.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-dst-unsized.stderr deleted file mode 100644 index cb60a82..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-dst-unsized.stderr +++ /dev/null
@@ -1,108 +0,0 @@ -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-mut-dst-unsized.rs:17:32 - | -17 | const DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8; 1]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AssertDstIsFromBytes` - --> tests/ui-msrv/transmute-mut-dst-unsized.rs:17:32 - | -17 | const DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8; 1]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertDstIsFromBytes` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-mut-dst-unsized.rs:17:32 - | -17 | const DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8; 1]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AssertDstIsAsBytes` - --> tests/ui-msrv/transmute-mut-dst-unsized.rs:17:32 - | -17 | const DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8; 1]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertDstIsAsBytes` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-mut-dst-unsized.rs:17:32 - | -17 | const DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8; 1]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` - = note: all local variables must have a statically known size - = help: unsized locals are gated as an unstable feature - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-mut-dst-unsized.rs:17:32 - | -17 | const DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8; 1]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `MaxAlignsOf` - --> src/macro_util.rs - | - | pub union MaxAlignsOf<T, U> { - | ^ required by this bound in `MaxAlignsOf` - = note: this error originates in the macro `$crate::assert_align_gt_eq` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-mut-dst-unsized.rs:17:32 - | -17 | const DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8; 1]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `transmute` - --> $RUST/core/src/intrinsics.rs - | - | pub fn transmute<T, U>(e: T) -> U; - | ^ required by this bound in `transmute` - = note: this error originates in the macro `$crate::assert_size_eq` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-mut-dst-unsized.rs:17:32 - | -17 | const DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8; 1]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `MaxAlignsOf::<T, U>::new` - --> src/macro_util.rs - | - | impl<T, U> MaxAlignsOf<T, U> { - | ^ required by this bound in `MaxAlignsOf::<T, U>::new` - = note: this error originates in the macro `$crate::assert_align_gt_eq` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-mut-dst-unsized.rs:17:32 - | -17 | const DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8; 1]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `MaxAlignsOf` - --> src/macro_util.rs - | - | pub union MaxAlignsOf<T, U> { - | ^ required by this bound in `MaxAlignsOf` - = note: this error originates in the macro `$crate::assert_align_gt_eq` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-mut-dst-unsized.rs:17:32 - | -17 | const DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8; 1]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `transmute_mut` - --> src/macro_util.rs - | - | pub unsafe fn transmute_mut<'dst, 'src: 'dst, Src: 'src, Dst: 'dst>( - | ^^^ required by this bound in `transmute_mut` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-illegal-lifetime.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-illegal-lifetime.rs deleted file mode 100644 index c31765e..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-illegal-lifetime.rs +++ /dev/null
@@ -1,15 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -fn main() {} - -fn increase_lifetime() { - let mut x = 0u64; - // It is illegal to increase the lifetime scope. - let _: &'static mut u64 = zerocopy::transmute_mut!(&mut x); -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-illegal-lifetime.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-illegal-lifetime.stderr deleted file mode 100644 index 5ff7145..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-illegal-lifetime.stderr +++ /dev/null
@@ -1,9 +0,0 @@ -error[E0597]: `x` does not live long enough - --> tests/ui-msrv/transmute-mut-illegal-lifetime.rs:14:56 - | -14 | let _: &'static mut u64 = zerocopy::transmute_mut!(&mut x); - | ---------------- ^^^^^^ borrowed value does not live long enough - | | - | type annotation requires that `x` is borrowed for `'static` -15 | } - | - `x` dropped here while still borrowed
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-size-decrease.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-size-decrease.rs deleted file mode 100644 index c6eec3a..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-size-decrease.rs +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_mut; - -fn main() {} - -// We require that the size of the destination type is not smaller than the size -// of the source type. -const DECREASE_SIZE: &mut u8 = transmute_mut!(&mut [0u8; 2]);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-size-decrease.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-size-decrease.stderr deleted file mode 100644 index 2bfc218..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-size-decrease.stderr +++ /dev/null
@@ -1,36 +0,0 @@ -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-msrv/transmute-mut-size-decrease.rs:17:32 - | -17 | const DECREASE_SIZE: &mut u8 = transmute_mut!(&mut [0u8; 2]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: source type: `[u8; 2]` (16 bits) - = note: target type: `u8` (8 bits) - = note: this error originates in the macro `$crate::assert_size_eq` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0658]: mutable references are not allowed in constants - --> tests/ui-msrv/transmute-mut-size-decrease.rs:17:47 - | -17 | const DECREASE_SIZE: &mut u8 = transmute_mut!(&mut [0u8; 2]); - | ^^^^^^^^^^^^^ - | - = note: see issue #57349 <https://github.com/rust-lang/rust/issues/57349> for more information - -error[E0015]: cannot call non-const fn `transmute_mut::<[u8; 2], u8>` in constants - --> tests/ui-msrv/transmute-mut-size-decrease.rs:17:32 - | -17 | const DECREASE_SIZE: &mut u8 = transmute_mut!(&mut [0u8; 2]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: calls in constants are limited to constant functions, tuple structs and tuple variants - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0716]: temporary value dropped while borrowed - --> tests/ui-msrv/transmute-mut-size-decrease.rs:17:52 - | -17 | const DECREASE_SIZE: &mut u8 = transmute_mut!(&mut [0u8; 2]); - | --------------------^^^^^^^^- - | | | - | | creates a temporary which is freed while still in use - | temporary value is freed at the end of this statement - | using this value as a constant requires that borrow lasts for `'static`
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-size-increase.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-size-increase.rs deleted file mode 100644 index a4657c28..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-size-increase.rs +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_mut; - -fn main() {} - -// `transmute_mut!` does not support transmuting from a smaller type to a larger -// one. -const INCREASE_SIZE: &mut [u8; 2] = transmute_mut!(&mut 0u8);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-size-increase.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-size-increase.stderr deleted file mode 100644 index 6e866a0..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-size-increase.stderr +++ /dev/null
@@ -1,36 +0,0 @@ -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-msrv/transmute-mut-size-increase.rs:17:37 - | -17 | const INCREASE_SIZE: &mut [u8; 2] = transmute_mut!(&mut 0u8); - | ^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: source type: `u8` (8 bits) - = note: target type: `[u8; 2]` (16 bits) - = note: this error originates in the macro `$crate::assert_size_eq` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0658]: mutable references are not allowed in constants - --> tests/ui-msrv/transmute-mut-size-increase.rs:17:52 - | -17 | const INCREASE_SIZE: &mut [u8; 2] = transmute_mut!(&mut 0u8); - | ^^^^^^^^ - | - = note: see issue #57349 <https://github.com/rust-lang/rust/issues/57349> for more information - -error[E0015]: cannot call non-const fn `transmute_mut::<u8, [u8; 2]>` in constants - --> tests/ui-msrv/transmute-mut-size-increase.rs:17:37 - | -17 | const INCREASE_SIZE: &mut [u8; 2] = transmute_mut!(&mut 0u8); - | ^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: calls in constants are limited to constant functions, tuple structs and tuple variants - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0716]: temporary value dropped while borrowed - --> tests/ui-msrv/transmute-mut-size-increase.rs:17:57 - | -17 | const INCREASE_SIZE: &mut [u8; 2] = transmute_mut!(&mut 0u8); - | --------------------^^^- - | | | - | | creates a temporary which is freed while still in use - | temporary value is freed at the end of this statement - | using this value as a constant requires that borrow lasts for `'static`
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-src-dst-generic.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-src-dst-generic.rs deleted file mode 100644 index aed7ded9..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-src-dst-generic.rs +++ /dev/null
@@ -1,19 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::{transmute_mut, AsBytes, FromBytes}; - -fn main() {} - -fn transmute_mut<T: AsBytes + FromBytes, U: AsBytes + FromBytes>(t: &mut T) -> &mut U { - // `transmute_mut!` requires the source and destination types to be - // concrete. - transmute_mut!(t) -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-src-dst-generic.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-src-dst-generic.stderr deleted file mode 100644 index 1162f21..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-src-dst-generic.stderr +++ /dev/null
@@ -1,19 +0,0 @@ -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-msrv/transmute-mut-src-dst-generic.rs:18:5 - | -18 | transmute_mut!(t) - | ^^^^^^^^^^^^^^^^^ - | - = note: source type: `T` (this type does not have a fixed size) - = note: target type: `U` (this type does not have a fixed size) - = note: this error originates in the macro `$crate::assert_size_eq` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-msrv/transmute-mut-src-dst-generic.rs:18:5 - | -18 | transmute_mut!(t) - | ^^^^^^^^^^^^^^^^^ - | - = note: source type: `AlignOf<T>` (size can vary because of T) - = note: target type: `MaxAlignsOf<T, U>` (size can vary because of T) - = note: this error originates in the macro `$crate::assert_align_gt_eq` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-src-dst-not-references.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-src-dst-not-references.rs deleted file mode 100644 index 98cc520..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-src-dst-not-references.rs +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_mut; - -fn main() {} - -// `transmute_mut!` does not support transmuting between non-reference source -// and destination types. -const SRC_DST_NOT_REFERENCES: &mut usize = transmute_mut!(0usize);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-src-dst-not-references.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-src-dst-not-references.stderr deleted file mode 100644 index c500a93a..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-src-dst-not-references.stderr +++ /dev/null
@@ -1,12 +0,0 @@ -error[E0308]: mismatched types - --> tests/ui-msrv/transmute-mut-src-dst-not-references.rs:17:59 - | -17 | const SRC_DST_NOT_REFERENCES: &mut usize = transmute_mut!(0usize); - | ---------------^^^^^^- - | | | - | | expected `&mut _`, found `usize` - | | help: consider mutably borrowing here: `&mut 0usize` - | expected due to this - | - = note: expected mutable reference `&mut _` - found type `usize`
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-src-dst-unsized.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-src-dst-unsized.rs deleted file mode 100644 index 1bebcf2..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-src-dst-unsized.rs +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_mut; - -fn main() {} - -// `transmute_mut!` does not support transmuting between unsized source and -// destination types. -const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-src-dst-unsized.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-src-dst-unsized.stderr deleted file mode 100644 index 00201a6..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-src-dst-unsized.stderr +++ /dev/null
@@ -1,237 +0,0 @@ -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AssertSrcIsFromBytes` - --> tests/ui-msrv/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertSrcIsFromBytes` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AssertSrcIsFromBytes` - --> tests/ui-msrv/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertSrcIsFromBytes` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AssertSrcIsAsBytes` - --> tests/ui-msrv/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertSrcIsAsBytes` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AssertSrcIsAsBytes` - --> tests/ui-msrv/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertSrcIsAsBytes` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AssertDstIsFromBytes` - --> tests/ui-msrv/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertDstIsFromBytes` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AssertDstIsAsBytes` - --> tests/ui-msrv/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertDstIsAsBytes` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` - = note: all local variables must have a statically known size - = help: unsized locals are gated as an unstable feature - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `transmute` - --> $RUST/core/src/intrinsics.rs - | - | pub fn transmute<T, U>(e: T) -> U; - | ^ required by this bound in `transmute` - = note: this error originates in the macro `$crate::assert_size_eq` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AlignOf::<T>::into_t` - --> src/macro_util.rs - | - | impl<T> AlignOf<T> { - | ^ required by this bound in `AlignOf::<T>::into_t` - = note: this error originates in the macro `$crate::assert_align_gt_eq` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` - = note: the left-hand-side of an assignment must have a statically known size - = note: this error originates in the macro `$crate::assert_align_gt_eq` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AlignOf` - --> src/macro_util.rs - | - | pub struct AlignOf<T> { - | ^ required by this bound in `AlignOf` - = note: this error originates in the macro `$crate::assert_align_gt_eq` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `MaxAlignsOf::<T, U>::new` - --> src/macro_util.rs - | - | impl<T, U> MaxAlignsOf<T, U> { - | ^ required by this bound in `MaxAlignsOf::<T, U>::new` - = note: this error originates in the macro `$crate::assert_align_gt_eq` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `MaxAlignsOf` - --> src/macro_util.rs - | - | pub union MaxAlignsOf<T, U> { - | ^ required by this bound in `MaxAlignsOf` - = note: this error originates in the macro `$crate::assert_align_gt_eq` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `MaxAlignsOf` - --> src/macro_util.rs - | - | pub union MaxAlignsOf<T, U> { - | ^ required by this bound in `MaxAlignsOf` - = note: this error originates in the macro `$crate::assert_align_gt_eq` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AlignOf` - --> src/macro_util.rs - | - | pub struct AlignOf<T> { - | ^ required by this bound in `AlignOf` - = note: this error originates in the macro `$crate::assert_align_gt_eq` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` - = note: all local variables must have a statically known size - = help: unsized locals are gated as an unstable feature - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `transmute_mut` - --> src/macro_util.rs - | - | pub unsafe fn transmute_mut<'dst, 'src: 'dst, Src: 'src, Dst: 'dst>( - | ^^^ required by this bound in `transmute_mut` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` - = note: all function arguments must have a statically known size - = note: this error originates in the macro `$crate::assert_size_eq` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-src-generic.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-src-generic.rs deleted file mode 100644 index a3ef397..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-src-generic.rs +++ /dev/null
@@ -1,18 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::{transmute_mut, AsBytes}; - -fn main() {} - -fn transmute_mut<T: AsBytes + FromBytes>(t: &mut T) -> &mut u8 { - // `transmute_mut!` requires the source type to be concrete. - transmute_mut!(t) -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-src-generic.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-src-generic.stderr deleted file mode 100644 index 8a9296ca..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-src-generic.stderr +++ /dev/null
@@ -1,10 +0,0 @@ -error[E0405]: cannot find trait `FromBytes` in this scope - --> tests/ui-msrv/transmute-mut-src-generic.rs:15:31 - | -15 | fn transmute_mut<T: AsBytes + FromBytes>(t: &mut T) -> &mut u8 { - | ^^^^^^^^^ not found in this scope - | -help: consider importing this trait - | -11 | use zerocopy::FromBytes; - |
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-src-immutable.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-src-immutable.rs deleted file mode 100644 index 08088d0..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-src-immutable.rs +++ /dev/null
@@ -1,18 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_mut; - -fn main() {} - -fn ref_src_immutable() { - // `transmute_mut!` requires that its source type be a mutable reference. - let _: &mut u8 = transmute_mut!(&0u8); -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-src-immutable.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-src-immutable.stderr deleted file mode 100644 index 8262f16..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-src-immutable.stderr +++ /dev/null
@@ -1,11 +0,0 @@ -error[E0308]: mismatched types - --> tests/ui-msrv/transmute-mut-src-immutable.rs:17:37 - | -17 | let _: &mut u8 = transmute_mut!(&0u8); - | ---------------^^^^- - | | | - | | types differ in mutability - | expected due to this - | - = note: expected mutable reference `&mut _` - found reference `&u8`
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-src-not-a-reference.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-src-not-a-reference.rs deleted file mode 100644 index bf8bc32..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-src-not-a-reference.rs +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_mut; - -fn main() {} - -// `transmute_mut!` does not support transmuting from a non-reference source -// type. -const SRC_NOT_A_REFERENCE: &mut u8 = transmute_mut!(0usize);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-src-not-a-reference.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-src-not-a-reference.stderr deleted file mode 100644 index 3a6bdf7..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-src-not-a-reference.stderr +++ /dev/null
@@ -1,12 +0,0 @@ -error[E0308]: mismatched types - --> tests/ui-msrv/transmute-mut-src-not-a-reference.rs:17:53 - | -17 | const SRC_NOT_A_REFERENCE: &mut u8 = transmute_mut!(0usize); - | ---------------^^^^^^- - | | | - | | expected `&mut _`, found `usize` - | | help: consider mutably borrowing here: `&mut 0usize` - | expected due to this - | - = note: expected mutable reference `&mut _` - found type `usize`
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-src-not-asbytes.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-src-not-asbytes.rs deleted file mode 100644 index 6a14f12..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-src-not-asbytes.rs +++ /dev/null
@@ -1,24 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_mut; - -fn main() {} - -#[derive(zerocopy::FromZeroes, zerocopy::FromBytes)] -#[repr(C)] -struct Src; - -#[derive(zerocopy::FromZeroes, zerocopy::FromBytes, zerocopy::AsBytes)] -#[repr(C)] -struct Dst; - -// `transmute_mut` requires that the source type implements `AsBytes` -const SRC_NOT_AS_BYTES: &mut Dst = transmute_mut!(&mut Src);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-src-not-asbytes.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-src-not-asbytes.stderr deleted file mode 100644 index 4056975..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-src-not-asbytes.stderr +++ /dev/null
@@ -1,25 +0,0 @@ -error[E0277]: the trait bound `Src: AsBytes` is not satisfied - --> tests/ui-msrv/transmute-mut-src-not-asbytes.rs:24:36 - | -24 | const SRC_NOT_AS_BYTES: &mut Dst = transmute_mut!(&mut Src); - | ^^^^^^^^^^^^^^^^^^^^^^^^ the trait `AsBytes` is not implemented for `Src` - | -note: required by a bound in `AssertSrcIsAsBytes` - --> tests/ui-msrv/transmute-mut-src-not-asbytes.rs:24:36 - | -24 | const SRC_NOT_AS_BYTES: &mut Dst = transmute_mut!(&mut Src); - | ^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertSrcIsAsBytes` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `Src: AsBytes` is not satisfied - --> tests/ui-msrv/transmute-mut-src-not-asbytes.rs:24:36 - | -24 | const SRC_NOT_AS_BYTES: &mut Dst = transmute_mut!(&mut Src); - | ^^^^^^^^^^^^^^^^^^^^^^^^ the trait `AsBytes` is not implemented for `Src` - | -note: required by a bound in `AssertSrcIsAsBytes` - --> tests/ui-msrv/transmute-mut-src-not-asbytes.rs:24:36 - | -24 | const SRC_NOT_AS_BYTES: &mut Dst = transmute_mut!(&mut Src); - | ^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertSrcIsAsBytes` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-src-not-frombytes.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-src-not-frombytes.rs deleted file mode 100644 index 2ebe036..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-src-not-frombytes.rs +++ /dev/null
@@ -1,24 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_mut; - -fn main() {} - -#[derive(zerocopy::AsBytes)] -#[repr(C)] -struct Src; - -#[derive(zerocopy::FromZeroes, zerocopy::FromBytes, zerocopy::AsBytes)] -#[repr(C)] -struct Dst; - -// `transmute_mut` requires that the source type implements `FromBytes` -const SRC_NOT_FROM_BYTES: &mut Dst = transmute_mut!(&mut Src);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-src-not-frombytes.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-src-not-frombytes.stderr deleted file mode 100644 index b859c41c..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-src-not-frombytes.stderr +++ /dev/null
@@ -1,25 +0,0 @@ -error[E0277]: the trait bound `Src: FromBytes` is not satisfied - --> tests/ui-msrv/transmute-mut-src-not-frombytes.rs:24:38 - | -24 | const SRC_NOT_FROM_BYTES: &mut Dst = transmute_mut!(&mut Src); - | ^^^^^^^^^^^^^^^^^^^^^^^^ the trait `FromBytes` is not implemented for `Src` - | -note: required by a bound in `AssertSrcIsFromBytes` - --> tests/ui-msrv/transmute-mut-src-not-frombytes.rs:24:38 - | -24 | const SRC_NOT_FROM_BYTES: &mut Dst = transmute_mut!(&mut Src); - | ^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertSrcIsFromBytes` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `Src: FromBytes` is not satisfied - --> tests/ui-msrv/transmute-mut-src-not-frombytes.rs:24:38 - | -24 | const SRC_NOT_FROM_BYTES: &mut Dst = transmute_mut!(&mut Src); - | ^^^^^^^^^^^^^^^^^^^^^^^^ the trait `FromBytes` is not implemented for `Src` - | -note: required by a bound in `AssertSrcIsFromBytes` - --> tests/ui-msrv/transmute-mut-src-not-frombytes.rs:24:38 - | -24 | const SRC_NOT_FROM_BYTES: &mut Dst = transmute_mut!(&mut Src); - | ^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertSrcIsFromBytes` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-src-unsized.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-src-unsized.rs deleted file mode 100644 index 413dd68..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-src-unsized.rs +++ /dev/null
@@ -1,16 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_mut; - -fn main() {} - -// `transmute_mut!` does not support transmuting from an unsized source type. -const SRC_UNSIZED: &mut [u8; 1] = transmute_mut!(&mut [0u8][..]);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-src-unsized.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-src-unsized.stderr deleted file mode 100644 index 6b18695e..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-mut-src-unsized.stderr +++ /dev/null
@@ -1,198 +0,0 @@ -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-mut-src-unsized.rs:16:35 - | -16 | const SRC_UNSIZED: &mut [u8; 1] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AssertSrcIsFromBytes` - --> tests/ui-msrv/transmute-mut-src-unsized.rs:16:35 - | -16 | const SRC_UNSIZED: &mut [u8; 1] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertSrcIsFromBytes` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-mut-src-unsized.rs:16:35 - | -16 | const SRC_UNSIZED: &mut [u8; 1] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AssertSrcIsFromBytes` - --> tests/ui-msrv/transmute-mut-src-unsized.rs:16:35 - | -16 | const SRC_UNSIZED: &mut [u8; 1] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertSrcIsFromBytes` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-mut-src-unsized.rs:16:35 - | -16 | const SRC_UNSIZED: &mut [u8; 1] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AssertSrcIsAsBytes` - --> tests/ui-msrv/transmute-mut-src-unsized.rs:16:35 - | -16 | const SRC_UNSIZED: &mut [u8; 1] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertSrcIsAsBytes` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-mut-src-unsized.rs:16:35 - | -16 | const SRC_UNSIZED: &mut [u8; 1] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AssertSrcIsAsBytes` - --> tests/ui-msrv/transmute-mut-src-unsized.rs:16:35 - | -16 | const SRC_UNSIZED: &mut [u8; 1] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertSrcIsAsBytes` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-mut-src-unsized.rs:16:35 - | -16 | const SRC_UNSIZED: &mut [u8; 1] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` - = note: all local variables must have a statically known size - = help: unsized locals are gated as an unstable feature - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-mut-src-unsized.rs:16:35 - | -16 | const SRC_UNSIZED: &mut [u8; 1] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `transmute` - --> $RUST/core/src/intrinsics.rs - | - | pub fn transmute<T, U>(e: T) -> U; - | ^ required by this bound in `transmute` - = note: this error originates in the macro `$crate::assert_size_eq` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-mut-src-unsized.rs:16:35 - | -16 | const SRC_UNSIZED: &mut [u8; 1] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AlignOf::<T>::into_t` - --> src/macro_util.rs - | - | impl<T> AlignOf<T> { - | ^ required by this bound in `AlignOf::<T>::into_t` - = note: this error originates in the macro `$crate::assert_align_gt_eq` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-mut-src-unsized.rs:16:35 - | -16 | const SRC_UNSIZED: &mut [u8; 1] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` - = note: the left-hand-side of an assignment must have a statically known size - = note: this error originates in the macro `$crate::assert_align_gt_eq` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-mut-src-unsized.rs:16:35 - | -16 | const SRC_UNSIZED: &mut [u8; 1] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AlignOf` - --> src/macro_util.rs - | - | pub struct AlignOf<T> { - | ^ required by this bound in `AlignOf` - = note: this error originates in the macro `$crate::assert_align_gt_eq` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-mut-src-unsized.rs:16:35 - | -16 | const SRC_UNSIZED: &mut [u8; 1] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `MaxAlignsOf::<T, U>::new` - --> src/macro_util.rs - | - | impl<T, U> MaxAlignsOf<T, U> { - | ^ required by this bound in `MaxAlignsOf::<T, U>::new` - = note: this error originates in the macro `$crate::assert_align_gt_eq` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-mut-src-unsized.rs:16:35 - | -16 | const SRC_UNSIZED: &mut [u8; 1] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `MaxAlignsOf` - --> src/macro_util.rs - | - | pub union MaxAlignsOf<T, U> { - | ^ required by this bound in `MaxAlignsOf` - = note: this error originates in the macro `$crate::assert_align_gt_eq` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-mut-src-unsized.rs:16:35 - | -16 | const SRC_UNSIZED: &mut [u8; 1] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `MaxAlignsOf` - --> src/macro_util.rs - | - | pub union MaxAlignsOf<T, U> { - | ^ required by this bound in `MaxAlignsOf` - = note: this error originates in the macro `$crate::assert_align_gt_eq` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-mut-src-unsized.rs:16:35 - | -16 | const SRC_UNSIZED: &mut [u8; 1] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AlignOf` - --> src/macro_util.rs - | - | pub struct AlignOf<T> { - | ^ required by this bound in `AlignOf` - = note: this error originates in the macro `$crate::assert_align_gt_eq` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-mut-src-unsized.rs:16:35 - | -16 | const SRC_UNSIZED: &mut [u8; 1] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `transmute_mut` - --> src/macro_util.rs - | - | pub unsafe fn transmute_mut<'dst, 'src: 'dst, Src: 'src, Dst: 'dst>( - | ^^^ required by this bound in `transmute_mut` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-mut-src-unsized.rs:16:35 - | -16 | const SRC_UNSIZED: &mut [u8; 1] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` - = note: all function arguments must have a statically known size - = note: this error originates in the macro `$crate::assert_size_eq` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ptr-to-usize.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ptr-to-usize.rs deleted file mode 100644 index 5af8859..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ptr-to-usize.rs +++ /dev/null
@@ -1,20 +0,0 @@ -// Copyright 2022 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute; - -fn main() {} - -// It is unclear whether we can or should support this transmutation, especially -// in a const context. This test ensures that even if such a transmutation -// becomes valid due to the requisite implementations of `FromBytes` being -// added, that we re-examine whether it should specifically be valid in a const -// context. -const POINTER_VALUE: usize = transmute!(&0usize as *const usize);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ptr-to-usize.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ptr-to-usize.stderr deleted file mode 100644 index 06b1bba..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ptr-to-usize.stderr +++ /dev/null
@@ -1,37 +0,0 @@ -error[E0277]: the trait bound `*const usize: AsBytes` is not satisfied - --> tests/ui-msrv/transmute-ptr-to-usize.rs:20:30 - | -20 | const POINTER_VALUE: usize = transmute!(&0usize as *const usize); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `AsBytes` is not implemented for `*const usize` - | - = help: the following implementations were found: - <usize as AsBytes> - <f32 as AsBytes> - <f64 as AsBytes> - <i128 as AsBytes> - and $N others -note: required by a bound in `AssertIsAsBytes` - --> tests/ui-msrv/transmute-ptr-to-usize.rs:20:30 - | -20 | const POINTER_VALUE: usize = transmute!(&0usize as *const usize); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertIsAsBytes` - = note: this error originates in the macro `transmute` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `*const usize: AsBytes` is not satisfied - --> tests/ui-msrv/transmute-ptr-to-usize.rs:20:30 - | -20 | const POINTER_VALUE: usize = transmute!(&0usize as *const usize); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `AsBytes` is not implemented for `*const usize` - | - = help: the following implementations were found: - <usize as AsBytes> - <f32 as AsBytes> - <f64 as AsBytes> - <i128 as AsBytes> - and $N others -note: required by a bound in `AssertIsAsBytes` - --> tests/ui-msrv/transmute-ptr-to-usize.rs:20:30 - | -20 | const POINTER_VALUE: usize = transmute!(&0usize as *const usize); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertIsAsBytes` - = note: this error originates in the macro `transmute` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-alignment-increase.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-alignment-increase.rs deleted file mode 100644 index bf1988c6..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-alignment-increase.rs +++ /dev/null
@@ -1,19 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -include!("../../zerocopy-derive/tests/util.rs"); - -extern crate zerocopy; - -use zerocopy::transmute_ref; - -fn main() {} - -// `transmute_ref!` does not support transmuting from a type of smaller -// alignment to one of larger alignment. -const INCREASE_ALIGNMENT: &AU16 = transmute_ref!(&[0u8; 2]);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-alignment-increase.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-alignment-increase.stderr deleted file mode 100644 index 72864e14..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-alignment-increase.stderr +++ /dev/null
@@ -1,9 +0,0 @@ -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-msrv/transmute-ref-alignment-increase.rs:19:35 - | -19 | const INCREASE_ALIGNMENT: &AU16 = transmute_ref!(&[0u8; 2]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: source type: `AlignOf<[u8; 2]>` (8 bits) - = note: target type: `MaxAlignsOf<[u8; 2], AU16>` (16 bits) - = note: this error originates in the macro `$crate::assert_align_gt_eq` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-dst-generic.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-dst-generic.rs deleted file mode 100644 index bf4a0f9a..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-dst-generic.rs +++ /dev/null
@@ -1,18 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::{transmute_ref, FromBytes}; - -fn main() {} - -fn transmute_ref<T: FromBytes>(u: &u8) -> &T { - // `transmute_ref!` requires the destination type to be concrete. - transmute_ref!(u) -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-dst-generic.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-dst-generic.stderr deleted file mode 100644 index ec7ec74..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-dst-generic.stderr +++ /dev/null
@@ -1,19 +0,0 @@ -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-msrv/transmute-ref-dst-generic.rs:17:5 - | -17 | transmute_ref!(u) - | ^^^^^^^^^^^^^^^^^ - | - = note: source type: `u8` (8 bits) - = note: target type: `T` (this type does not have a fixed size) - = note: this error originates in the macro `$crate::assert_size_eq` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-msrv/transmute-ref-dst-generic.rs:17:5 - | -17 | transmute_ref!(u) - | ^^^^^^^^^^^^^^^^^ - | - = note: source type: `AlignOf<u8>` (8 bits) - = note: target type: `MaxAlignsOf<u8, T>` (size can vary because of T) - = note: this error originates in the macro `$crate::assert_align_gt_eq` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-dst-mutable.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-dst-mutable.rs deleted file mode 100644 index fa0e6e4..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-dst-mutable.rs +++ /dev/null
@@ -1,19 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_ref; - -fn main() {} - -fn ref_dst_mutable() { - // `transmute_ref!` requires that its destination type be an immutable - // reference. - let _: &mut u8 = transmute_ref!(&0u8); -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-dst-mutable.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-dst-mutable.stderr deleted file mode 100644 index 5ccf2cd2..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-dst-mutable.stderr +++ /dev/null
@@ -1,29 +0,0 @@ -error[E0308]: mismatched types - --> tests/ui-msrv/transmute-ref-dst-mutable.rs:18:22 - | -18 | let _: &mut u8 = transmute_ref!(&0u8); - | ^^^^^^^^^^^^^^^^^^^^ types differ in mutability - | - = note: expected mutable reference `&mut u8` - found reference `&_` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0308]: mismatched types - --> tests/ui-msrv/transmute-ref-dst-mutable.rs:18:22 - | -18 | let _: &mut u8 = transmute_ref!(&0u8); - | ^^^^^^^^^^^^^^^^^^^^ types differ in mutability - | - = note: expected mutable reference `&mut u8` - found reference `&_` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0308]: mismatched types - --> tests/ui-msrv/transmute-ref-dst-mutable.rs:18:22 - | -18 | let _: &mut u8 = transmute_ref!(&0u8); - | ^^^^^^^^^^^^^^^^^^^^ types differ in mutability - | - = note: expected mutable reference `&mut u8` - found reference `&_` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-dst-not-a-reference.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-dst-not-a-reference.rs deleted file mode 100644 index de55f9a..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-dst-not-a-reference.rs +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_ref; - -fn main() {} - -// `transmute_ref!` does not support transmuting into a non-reference -// destination type. -const DST_NOT_A_REFERENCE: usize = transmute_ref!(&0u8);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-dst-not-a-reference.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-dst-not-a-reference.stderr deleted file mode 100644 index 9a61c4c..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-dst-not-a-reference.stderr +++ /dev/null
@@ -1,29 +0,0 @@ -error[E0308]: mismatched types - --> tests/ui-msrv/transmute-ref-dst-not-a-reference.rs:17:36 - | -17 | const DST_NOT_A_REFERENCE: usize = transmute_ref!(&0u8); - | ^^^^^^^^^^^^^^^^^^^^ expected `usize`, found reference - | - = note: expected type `usize` - found reference `&_` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0308]: mismatched types - --> tests/ui-msrv/transmute-ref-dst-not-a-reference.rs:17:36 - | -17 | const DST_NOT_A_REFERENCE: usize = transmute_ref!(&0u8); - | ^^^^^^^^^^^^^^^^^^^^ expected `usize`, found reference - | - = note: expected type `usize` - found reference `&_` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0308]: mismatched types - --> tests/ui-msrv/transmute-ref-dst-not-a-reference.rs:17:36 - | -17 | const DST_NOT_A_REFERENCE: usize = transmute_ref!(&0u8); - | ^^^^^^^^^^^^^^^^^^^^ expected `usize`, found reference - | - = note: expected type `usize` - found reference `&_` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-dst-not-frombytes.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-dst-not-frombytes.rs deleted file mode 100644 index d81f64d..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-dst-not-frombytes.rs +++ /dev/null
@@ -1,18 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -include!("../../zerocopy-derive/tests/util.rs"); - -extern crate zerocopy; - -use zerocopy::transmute_ref; - -fn main() {} - -// `transmute_ref` requires that the destination type implements `FromBytes` -const DST_NOT_FROM_BYTES: &NotZerocopy = transmute_ref!(&AU16(0));
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-dst-not-frombytes.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-dst-not-frombytes.stderr deleted file mode 100644 index d3176754..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-dst-not-frombytes.stderr +++ /dev/null
@@ -1,12 +0,0 @@ -error[E0277]: the trait bound `NotZerocopy: FromBytes` is not satisfied - --> tests/ui-msrv/transmute-ref-dst-not-frombytes.rs:18:42 - | -18 | const DST_NOT_FROM_BYTES: &NotZerocopy = transmute_ref!(&AU16(0)); - | ^^^^^^^^^^^^^^^^^^^^^^^^ the trait `FromBytes` is not implemented for `NotZerocopy` - | -note: required by a bound in `AssertIsFromBytes` - --> tests/ui-msrv/transmute-ref-dst-not-frombytes.rs:18:42 - | -18 | const DST_NOT_FROM_BYTES: &NotZerocopy = transmute_ref!(&AU16(0)); - | ^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertIsFromBytes` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-dst-unsized.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-dst-unsized.rs deleted file mode 100644 index 625f1fa..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-dst-unsized.rs +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_ref; - -fn main() {} - -// `transmute_ref!` does not support transmuting into an unsized destination -// type. -const DST_UNSIZED: &[u8] = transmute_ref!(&[0u8; 1]);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-dst-unsized.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-dst-unsized.stderr deleted file mode 100644 index 78135de..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-dst-unsized.stderr +++ /dev/null
@@ -1,94 +0,0 @@ -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-ref-dst-unsized.rs:17:28 - | -17 | const DST_UNSIZED: &[u8] = transmute_ref!(&[0u8; 1]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AssertIsFromBytes` - --> tests/ui-msrv/transmute-ref-dst-unsized.rs:17:28 - | -17 | const DST_UNSIZED: &[u8] = transmute_ref!(&[0u8; 1]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertIsFromBytes` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-ref-dst-unsized.rs:17:28 - | -17 | const DST_UNSIZED: &[u8] = transmute_ref!(&[0u8; 1]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` - = note: all local variables must have a statically known size - = help: unsized locals are gated as an unstable feature - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-ref-dst-unsized.rs:17:28 - | -17 | const DST_UNSIZED: &[u8] = transmute_ref!(&[0u8; 1]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `MaxAlignsOf` - --> src/macro_util.rs - | - | pub union MaxAlignsOf<T, U> { - | ^ required by this bound in `MaxAlignsOf` - = note: this error originates in the macro `$crate::assert_align_gt_eq` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-ref-dst-unsized.rs:17:28 - | -17 | const DST_UNSIZED: &[u8] = transmute_ref!(&[0u8; 1]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `transmute` - --> $RUST/core/src/intrinsics.rs - | - | pub fn transmute<T, U>(e: T) -> U; - | ^ required by this bound in `transmute` - = note: this error originates in the macro `$crate::assert_size_eq` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-ref-dst-unsized.rs:17:28 - | -17 | const DST_UNSIZED: &[u8] = transmute_ref!(&[0u8; 1]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `MaxAlignsOf::<T, U>::new` - --> src/macro_util.rs - | - | impl<T, U> MaxAlignsOf<T, U> { - | ^ required by this bound in `MaxAlignsOf::<T, U>::new` - = note: this error originates in the macro `$crate::assert_align_gt_eq` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-ref-dst-unsized.rs:17:28 - | -17 | const DST_UNSIZED: &[u8] = transmute_ref!(&[0u8; 1]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `MaxAlignsOf` - --> src/macro_util.rs - | - | pub union MaxAlignsOf<T, U> { - | ^ required by this bound in `MaxAlignsOf` - = note: this error originates in the macro `$crate::assert_align_gt_eq` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-ref-dst-unsized.rs:17:28 - | -17 | const DST_UNSIZED: &[u8] = transmute_ref!(&[0u8; 1]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `transmute_ref` - --> src/macro_util.rs - | - | pub const unsafe fn transmute_ref<'dst, 'src: 'dst, Src: 'src, Dst: 'dst>( - | ^^^ required by this bound in `transmute_ref` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-illegal-lifetime.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-illegal-lifetime.rs deleted file mode 100644 index 8dd191e..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-illegal-lifetime.rs +++ /dev/null
@@ -1,15 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -fn main() {} - -fn increase_lifetime() { - let x = 0u64; - // It is illegal to increase the lifetime scope. - let _: &'static u64 = zerocopy::transmute_ref!(&x); -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-illegal-lifetime.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-illegal-lifetime.stderr deleted file mode 100644 index 866ea56..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-illegal-lifetime.stderr +++ /dev/null
@@ -1,9 +0,0 @@ -error[E0597]: `x` does not live long enough - --> tests/ui-msrv/transmute-ref-illegal-lifetime.rs:14:52 - | -14 | let _: &'static u64 = zerocopy::transmute_ref!(&x); - | ------------ ^^ borrowed value does not live long enough - | | - | type annotation requires that `x` is borrowed for `'static` -15 | } - | - `x` dropped here while still borrowed
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-size-decrease.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-size-decrease.rs deleted file mode 100644 index 1d66a54..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-size-decrease.rs +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_ref; - -fn main() {} - -// Although this is not a soundness requirement, we currently require that the -// size of the destination type is not smaller than the size of the source type. -const DECREASE_SIZE: &u8 = transmute_ref!(&[0u8; 2]);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-size-decrease.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-size-decrease.stderr deleted file mode 100644 index 95669f9..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-size-decrease.stderr +++ /dev/null
@@ -1,9 +0,0 @@ -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-msrv/transmute-ref-size-decrease.rs:17:28 - | -17 | const DECREASE_SIZE: &u8 = transmute_ref!(&[0u8; 2]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: source type: `[u8; 2]` (16 bits) - = note: target type: `u8` (8 bits) - = note: this error originates in the macro `$crate::assert_size_eq` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-size-increase.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-size-increase.rs deleted file mode 100644 index cdca560b..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-size-increase.rs +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_ref; - -fn main() {} - -// `transmute_ref!` does not support transmuting from a smaller type to a larger -// one. -const INCREASE_SIZE: &[u8; 2] = transmute_ref!(&0u8);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-size-increase.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-size-increase.stderr deleted file mode 100644 index 10f0e10..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-size-increase.stderr +++ /dev/null
@@ -1,9 +0,0 @@ -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-msrv/transmute-ref-size-increase.rs:17:33 - | -17 | const INCREASE_SIZE: &[u8; 2] = transmute_ref!(&0u8); - | ^^^^^^^^^^^^^^^^^^^^ - | - = note: source type: `u8` (8 bits) - = note: target type: `[u8; 2]` (16 bits) - = note: this error originates in the macro `$crate::assert_size_eq` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-src-dst-generic.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-src-dst-generic.rs deleted file mode 100644 index 409d785b..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-src-dst-generic.rs +++ /dev/null
@@ -1,19 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::{transmute_ref, AsBytes, FromBytes}; - -fn main() {} - -fn transmute_ref<T: AsBytes, U: FromBytes>(t: &T) -> &U { - // `transmute_ref!` requires the source and destination types to be - // concrete. - transmute_ref!(t) -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-src-dst-generic.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-src-dst-generic.stderr deleted file mode 100644 index eb3268f..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-src-dst-generic.stderr +++ /dev/null
@@ -1,19 +0,0 @@ -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-msrv/transmute-ref-src-dst-generic.rs:18:5 - | -18 | transmute_ref!(t) - | ^^^^^^^^^^^^^^^^^ - | - = note: source type: `T` (this type does not have a fixed size) - = note: target type: `U` (this type does not have a fixed size) - = note: this error originates in the macro `$crate::assert_size_eq` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-msrv/transmute-ref-src-dst-generic.rs:18:5 - | -18 | transmute_ref!(t) - | ^^^^^^^^^^^^^^^^^ - | - = note: source type: `AlignOf<T>` (size can vary because of T) - = note: target type: `MaxAlignsOf<T, U>` (size can vary because of T) - = note: this error originates in the macro `$crate::assert_align_gt_eq` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-src-dst-not-references.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-src-dst-not-references.rs deleted file mode 100644 index 114e917..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-src-dst-not-references.rs +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_ref; - -fn main() {} - -// `transmute_ref!` does not support transmuting between non-reference source -// and destination types. -const SRC_DST_NOT_REFERENCES: usize = transmute_ref!(0usize);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-src-dst-not-references.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-src-dst-not-references.stderr deleted file mode 100644 index 2c5e23b..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-src-dst-not-references.stderr +++ /dev/null
@@ -1,42 +0,0 @@ -error[E0308]: mismatched types - --> tests/ui-msrv/transmute-ref-src-dst-not-references.rs:17:54 - | -17 | const SRC_DST_NOT_REFERENCES: usize = transmute_ref!(0usize); - | ---------------^^^^^^- - | | | - | | expected reference, found `usize` - | | help: consider borrowing here: `&0usize` - | expected due to this - | - = note: expected reference `&_` - found type `usize` - -error[E0308]: mismatched types - --> tests/ui-msrv/transmute-ref-src-dst-not-references.rs:17:39 - | -17 | const SRC_DST_NOT_REFERENCES: usize = transmute_ref!(0usize); - | ^^^^^^^^^^^^^^^^^^^^^^ expected `usize`, found reference - | - = note: expected type `usize` - found reference `&_` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0308]: mismatched types - --> tests/ui-msrv/transmute-ref-src-dst-not-references.rs:17:39 - | -17 | const SRC_DST_NOT_REFERENCES: usize = transmute_ref!(0usize); - | ^^^^^^^^^^^^^^^^^^^^^^ expected `usize`, found reference - | - = note: expected type `usize` - found reference `&_` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0308]: mismatched types - --> tests/ui-msrv/transmute-ref-src-dst-not-references.rs:17:39 - | -17 | const SRC_DST_NOT_REFERENCES: usize = transmute_ref!(0usize); - | ^^^^^^^^^^^^^^^^^^^^^^ expected `usize`, found reference - | - = note: expected type `usize` - found reference `&_` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-src-dst-unsized.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-src-dst-unsized.rs deleted file mode 100644 index 6bfe7ff..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-src-dst-unsized.rs +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_ref; - -fn main() {} - -// `transmute_ref!` does not support transmuting between unsized source and -// destination types. -const SRC_DST_UNSIZED: &[u8] = transmute_ref!(&[0u8][..]);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-src-dst-unsized.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-src-dst-unsized.stderr deleted file mode 100644 index adfd5979..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-src-dst-unsized.stderr +++ /dev/null
@@ -1,195 +0,0 @@ -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-ref-src-dst-unsized.rs:17:32 - | -17 | const SRC_DST_UNSIZED: &[u8] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AssertIsAsBytes` - --> tests/ui-msrv/transmute-ref-src-dst-unsized.rs:17:32 - | -17 | const SRC_DST_UNSIZED: &[u8] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertIsAsBytes` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-ref-src-dst-unsized.rs:17:32 - | -17 | const SRC_DST_UNSIZED: &[u8] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AssertIsAsBytes` - --> tests/ui-msrv/transmute-ref-src-dst-unsized.rs:17:32 - | -17 | const SRC_DST_UNSIZED: &[u8] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertIsAsBytes` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-ref-src-dst-unsized.rs:17:32 - | -17 | const SRC_DST_UNSIZED: &[u8] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AssertIsFromBytes` - --> tests/ui-msrv/transmute-ref-src-dst-unsized.rs:17:32 - | -17 | const SRC_DST_UNSIZED: &[u8] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertIsFromBytes` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-ref-src-dst-unsized.rs:17:32 - | -17 | const SRC_DST_UNSIZED: &[u8] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` - = note: all local variables must have a statically known size - = help: unsized locals are gated as an unstable feature - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-ref-src-dst-unsized.rs:17:32 - | -17 | const SRC_DST_UNSIZED: &[u8] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `transmute` - --> $RUST/core/src/intrinsics.rs - | - | pub fn transmute<T, U>(e: T) -> U; - | ^ required by this bound in `transmute` - = note: this error originates in the macro `$crate::assert_size_eq` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-ref-src-dst-unsized.rs:17:32 - | -17 | const SRC_DST_UNSIZED: &[u8] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AlignOf::<T>::into_t` - --> src/macro_util.rs - | - | impl<T> AlignOf<T> { - | ^ required by this bound in `AlignOf::<T>::into_t` - = note: this error originates in the macro `$crate::assert_align_gt_eq` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-ref-src-dst-unsized.rs:17:32 - | -17 | const SRC_DST_UNSIZED: &[u8] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` - = note: the left-hand-side of an assignment must have a statically known size - = note: this error originates in the macro `$crate::assert_align_gt_eq` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-ref-src-dst-unsized.rs:17:32 - | -17 | const SRC_DST_UNSIZED: &[u8] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AlignOf` - --> src/macro_util.rs - | - | pub struct AlignOf<T> { - | ^ required by this bound in `AlignOf` - = note: this error originates in the macro `$crate::assert_align_gt_eq` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-ref-src-dst-unsized.rs:17:32 - | -17 | const SRC_DST_UNSIZED: &[u8] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `MaxAlignsOf::<T, U>::new` - --> src/macro_util.rs - | - | impl<T, U> MaxAlignsOf<T, U> { - | ^ required by this bound in `MaxAlignsOf::<T, U>::new` - = note: this error originates in the macro `$crate::assert_align_gt_eq` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-ref-src-dst-unsized.rs:17:32 - | -17 | const SRC_DST_UNSIZED: &[u8] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `MaxAlignsOf` - --> src/macro_util.rs - | - | pub union MaxAlignsOf<T, U> { - | ^ required by this bound in `MaxAlignsOf` - = note: this error originates in the macro `$crate::assert_align_gt_eq` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-ref-src-dst-unsized.rs:17:32 - | -17 | const SRC_DST_UNSIZED: &[u8] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `MaxAlignsOf` - --> src/macro_util.rs - | - | pub union MaxAlignsOf<T, U> { - | ^ required by this bound in `MaxAlignsOf` - = note: this error originates in the macro `$crate::assert_align_gt_eq` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-ref-src-dst-unsized.rs:17:32 - | -17 | const SRC_DST_UNSIZED: &[u8] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AlignOf` - --> src/macro_util.rs - | - | pub struct AlignOf<T> { - | ^ required by this bound in `AlignOf` - = note: this error originates in the macro `$crate::assert_align_gt_eq` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-ref-src-dst-unsized.rs:17:32 - | -17 | const SRC_DST_UNSIZED: &[u8] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` - = note: all local variables must have a statically known size - = help: unsized locals are gated as an unstable feature - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-ref-src-dst-unsized.rs:17:32 - | -17 | const SRC_DST_UNSIZED: &[u8] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `transmute_ref` - --> src/macro_util.rs - | - | pub const unsafe fn transmute_ref<'dst, 'src: 'dst, Src: 'src, Dst: 'dst>( - | ^^^ required by this bound in `transmute_ref` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-ref-src-dst-unsized.rs:17:32 - | -17 | const SRC_DST_UNSIZED: &[u8] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` - = note: all function arguments must have a statically known size - = note: this error originates in the macro `$crate::assert_size_eq` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-src-generic.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-src-generic.rs deleted file mode 100644 index 010281c3..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-src-generic.rs +++ /dev/null
@@ -1,18 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::{transmute_ref, AsBytes}; - -fn main() {} - -fn transmute_ref<T: AsBytes>(t: &T) -> &u8 { - // `transmute_ref!` requires the source type to be concrete. - transmute_ref!(t) -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-src-generic.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-src-generic.stderr deleted file mode 100644 index 4cb3e51..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-src-generic.stderr +++ /dev/null
@@ -1,19 +0,0 @@ -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-msrv/transmute-ref-src-generic.rs:17:5 - | -17 | transmute_ref!(t) - | ^^^^^^^^^^^^^^^^^ - | - = note: source type: `T` (this type does not have a fixed size) - = note: target type: `u8` (8 bits) - = note: this error originates in the macro `$crate::assert_size_eq` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-msrv/transmute-ref-src-generic.rs:17:5 - | -17 | transmute_ref!(t) - | ^^^^^^^^^^^^^^^^^ - | - = note: source type: `AlignOf<T>` (size can vary because of T) - = note: target type: `MaxAlignsOf<T, u8>` (size can vary because of T) - = note: this error originates in the macro `$crate::assert_align_gt_eq` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-src-not-a-reference.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-src-not-a-reference.rs deleted file mode 100644 index 90661b3e..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-src-not-a-reference.rs +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_ref; - -fn main() {} - -// `transmute_ref!` does not support transmuting from a non-reference source -// type. -const SRC_NOT_A_REFERENCE: &u8 = transmute_ref!(0usize);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-src-not-a-reference.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-src-not-a-reference.stderr deleted file mode 100644 index 0f4aeec..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-src-not-a-reference.stderr +++ /dev/null
@@ -1,12 +0,0 @@ -error[E0308]: mismatched types - --> tests/ui-msrv/transmute-ref-src-not-a-reference.rs:17:49 - | -17 | const SRC_NOT_A_REFERENCE: &u8 = transmute_ref!(0usize); - | ---------------^^^^^^- - | | | - | | expected reference, found `usize` - | | help: consider borrowing here: `&0usize` - | expected due to this - | - = note: expected reference `&_` - found type `usize`
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-src-not-asbytes.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-src-not-asbytes.rs deleted file mode 100644 index 6ab19f3c..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-src-not-asbytes.rs +++ /dev/null
@@ -1,18 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -include!("../../zerocopy-derive/tests/util.rs"); - -extern crate zerocopy; - -use zerocopy::transmute_ref; - -fn main() {} - -// `transmute_ref` requires that the source type implements `AsBytes` -const SRC_NOT_AS_BYTES: &AU16 = transmute_ref!(&NotZerocopy(AU16(0)));
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-src-not-asbytes.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-src-not-asbytes.stderr deleted file mode 100644 index 6b80d4f4..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-src-not-asbytes.stderr +++ /dev/null
@@ -1,25 +0,0 @@ -error[E0277]: the trait bound `NotZerocopy<AU16>: AsBytes` is not satisfied - --> tests/ui-msrv/transmute-ref-src-not-asbytes.rs:18:33 - | -18 | const SRC_NOT_AS_BYTES: &AU16 = transmute_ref!(&NotZerocopy(AU16(0))); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `AsBytes` is not implemented for `NotZerocopy<AU16>` - | -note: required by a bound in `AssertIsAsBytes` - --> tests/ui-msrv/transmute-ref-src-not-asbytes.rs:18:33 - | -18 | const SRC_NOT_AS_BYTES: &AU16 = transmute_ref!(&NotZerocopy(AU16(0))); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertIsAsBytes` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `NotZerocopy<AU16>: AsBytes` is not satisfied - --> tests/ui-msrv/transmute-ref-src-not-asbytes.rs:18:33 - | -18 | const SRC_NOT_AS_BYTES: &AU16 = transmute_ref!(&NotZerocopy(AU16(0))); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `AsBytes` is not implemented for `NotZerocopy<AU16>` - | -note: required by a bound in `AssertIsAsBytes` - --> tests/ui-msrv/transmute-ref-src-not-asbytes.rs:18:33 - | -18 | const SRC_NOT_AS_BYTES: &AU16 = transmute_ref!(&NotZerocopy(AU16(0))); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertIsAsBytes` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-src-unsized.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-src-unsized.rs deleted file mode 100644 index 14e72b4..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-src-unsized.rs +++ /dev/null
@@ -1,16 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_ref; - -fn main() {} - -// `transmute_ref!` does not support transmuting from an unsized source type. -const SRC_UNSIZED: &[u8; 1] = transmute_ref!(&[0u8][..]);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-src-unsized.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-src-unsized.stderr deleted file mode 100644 index 43bac53..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-ref-src-unsized.stderr +++ /dev/null
@@ -1,170 +0,0 @@ -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-ref-src-unsized.rs:16:31 - | -16 | const SRC_UNSIZED: &[u8; 1] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AssertIsAsBytes` - --> tests/ui-msrv/transmute-ref-src-unsized.rs:16:31 - | -16 | const SRC_UNSIZED: &[u8; 1] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertIsAsBytes` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-ref-src-unsized.rs:16:31 - | -16 | const SRC_UNSIZED: &[u8; 1] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AssertIsAsBytes` - --> tests/ui-msrv/transmute-ref-src-unsized.rs:16:31 - | -16 | const SRC_UNSIZED: &[u8; 1] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertIsAsBytes` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-ref-src-unsized.rs:16:31 - | -16 | const SRC_UNSIZED: &[u8; 1] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` - = note: all local variables must have a statically known size - = help: unsized locals are gated as an unstable feature - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-ref-src-unsized.rs:16:31 - | -16 | const SRC_UNSIZED: &[u8; 1] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `transmute` - --> $RUST/core/src/intrinsics.rs - | - | pub fn transmute<T, U>(e: T) -> U; - | ^ required by this bound in `transmute` - = note: this error originates in the macro `$crate::assert_size_eq` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-ref-src-unsized.rs:16:31 - | -16 | const SRC_UNSIZED: &[u8; 1] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AlignOf::<T>::into_t` - --> src/macro_util.rs - | - | impl<T> AlignOf<T> { - | ^ required by this bound in `AlignOf::<T>::into_t` - = note: this error originates in the macro `$crate::assert_align_gt_eq` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-ref-src-unsized.rs:16:31 - | -16 | const SRC_UNSIZED: &[u8; 1] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` - = note: the left-hand-side of an assignment must have a statically known size - = note: this error originates in the macro `$crate::assert_align_gt_eq` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-ref-src-unsized.rs:16:31 - | -16 | const SRC_UNSIZED: &[u8; 1] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AlignOf` - --> src/macro_util.rs - | - | pub struct AlignOf<T> { - | ^ required by this bound in `AlignOf` - = note: this error originates in the macro `$crate::assert_align_gt_eq` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-ref-src-unsized.rs:16:31 - | -16 | const SRC_UNSIZED: &[u8; 1] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `MaxAlignsOf::<T, U>::new` - --> src/macro_util.rs - | - | impl<T, U> MaxAlignsOf<T, U> { - | ^ required by this bound in `MaxAlignsOf::<T, U>::new` - = note: this error originates in the macro `$crate::assert_align_gt_eq` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-ref-src-unsized.rs:16:31 - | -16 | const SRC_UNSIZED: &[u8; 1] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `MaxAlignsOf` - --> src/macro_util.rs - | - | pub union MaxAlignsOf<T, U> { - | ^ required by this bound in `MaxAlignsOf` - = note: this error originates in the macro `$crate::assert_align_gt_eq` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-ref-src-unsized.rs:16:31 - | -16 | const SRC_UNSIZED: &[u8; 1] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `MaxAlignsOf` - --> src/macro_util.rs - | - | pub union MaxAlignsOf<T, U> { - | ^ required by this bound in `MaxAlignsOf` - = note: this error originates in the macro `$crate::assert_align_gt_eq` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-ref-src-unsized.rs:16:31 - | -16 | const SRC_UNSIZED: &[u8; 1] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AlignOf` - --> src/macro_util.rs - | - | pub struct AlignOf<T> { - | ^ required by this bound in `AlignOf` - = note: this error originates in the macro `$crate::assert_align_gt_eq` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-ref-src-unsized.rs:16:31 - | -16 | const SRC_UNSIZED: &[u8; 1] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `transmute_ref` - --> src/macro_util.rs - | - | pub const unsafe fn transmute_ref<'dst, 'src: 'dst, Src: 'src, Dst: 'dst>( - | ^^^ required by this bound in `transmute_ref` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/transmute-ref-src-unsized.rs:16:31 - | -16 | const SRC_UNSIZED: &[u8; 1] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` - = note: all function arguments must have a statically known size - = note: this error originates in the macro `$crate::assert_size_eq` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-size-decrease.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-size-decrease.rs deleted file mode 100644 index 1d56831f..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-size-decrease.rs +++ /dev/null
@@ -1,19 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -include!("../../zerocopy-derive/tests/util.rs"); - -extern crate zerocopy; - -use zerocopy::transmute; - -fn main() {} - -// Although this is not a soundness requirement, we currently require that the -// size of the destination type is not smaller than the size of the source type. -const DECREASE_SIZE: u8 = transmute!(AU16(0));
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-size-decrease.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-size-decrease.stderr deleted file mode 100644 index ffa56884..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-size-decrease.stderr +++ /dev/null
@@ -1,9 +0,0 @@ -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-msrv/transmute-size-decrease.rs:19:27 - | -19 | const DECREASE_SIZE: u8 = transmute!(AU16(0)); - | ^^^^^^^^^^^^^^^^^^^ - | - = note: source type: `AU16` (16 bits) - = note: target type: `u8` (8 bits) - = note: this error originates in the macro `transmute` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-size-increase.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-size-increase.rs deleted file mode 100644 index 32f9363..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-size-increase.rs +++ /dev/null
@@ -1,19 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -include!("../../zerocopy-derive/tests/util.rs"); - -extern crate zerocopy; - -use zerocopy::transmute; - -fn main() {} - -// `transmute!` does not support transmuting from a smaller type to a larger -// one. -const INCREASE_SIZE: AU16 = transmute!(0u8);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-size-increase.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-size-increase.stderr deleted file mode 100644 index 865d0ca..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-size-increase.stderr +++ /dev/null
@@ -1,9 +0,0 @@ -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-msrv/transmute-size-increase.rs:19:29 - | -19 | const INCREASE_SIZE: AU16 = transmute!(0u8); - | ^^^^^^^^^^^^^^^ - | - = note: source type: `u8` (8 bits) - = note: target type: `AU16` (16 bits) - = note: this error originates in the macro `transmute` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-src-not-asbytes.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-src-not-asbytes.rs deleted file mode 100644 index dd73021..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-src-not-asbytes.rs +++ /dev/null
@@ -1,18 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -include!("../../zerocopy-derive/tests/util.rs"); - -extern crate zerocopy; - -use zerocopy::transmute; - -fn main() {} - -// `transmute` requires that the source type implements `AsBytes` -const SRC_NOT_AS_BYTES: AU16 = transmute!(NotZerocopy(AU16(0)));
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-src-not-asbytes.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-src-not-asbytes.stderr deleted file mode 100644 index 93eeda0..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-msrv/transmute-src-not-asbytes.stderr +++ /dev/null
@@ -1,25 +0,0 @@ -error[E0277]: the trait bound `NotZerocopy<AU16>: AsBytes` is not satisfied - --> tests/ui-msrv/transmute-src-not-asbytes.rs:18:32 - | -18 | const SRC_NOT_AS_BYTES: AU16 = transmute!(NotZerocopy(AU16(0))); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `AsBytes` is not implemented for `NotZerocopy<AU16>` - | -note: required by a bound in `AssertIsAsBytes` - --> tests/ui-msrv/transmute-src-not-asbytes.rs:18:32 - | -18 | const SRC_NOT_AS_BYTES: AU16 = transmute!(NotZerocopy(AU16(0))); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertIsAsBytes` - = note: this error originates in the macro `transmute` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `NotZerocopy<AU16>: AsBytes` is not satisfied - --> tests/ui-msrv/transmute-src-not-asbytes.rs:18:32 - | -18 | const SRC_NOT_AS_BYTES: AU16 = transmute!(NotZerocopy(AU16(0))); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `AsBytes` is not implemented for `NotZerocopy<AU16>` - | -note: required by a bound in `AssertIsAsBytes` - --> tests/ui-msrv/transmute-src-not-asbytes.rs:18:32 - | -18 | const SRC_NOT_AS_BYTES: AU16 = transmute!(NotZerocopy(AU16(0))); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertIsAsBytes` - = note: this error originates in the macro `transmute` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/include_value_not_from_bytes.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/include_value_not_from_bytes.rs deleted file mode 100644 index 45b6138f..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/include_value_not_from_bytes.rs +++ /dev/null
@@ -1,12 +0,0 @@ -// Copyright 2022 The Fuchsia Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#[macro_use] -extern crate zerocopy; - -fn main() {} - -// Should fail because `UnsafeCell<u32>: !FromBytes`. -const NOT_FROM_BYTES: core::cell::UnsafeCell<u32> = - include_value!("../../testdata/include_value/data");
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/include_value_not_from_bytes.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/include_value_not_from_bytes.stderr deleted file mode 100644 index f7c7fdd7..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/include_value_not_from_bytes.stderr +++ /dev/null
@@ -1,25 +0,0 @@ -error[E0277]: the trait bound `UnsafeCell<u32>: FromBytes` is not satisfied - --> tests/ui-nightly/include_value_not_from_bytes.rs:12:5 - | -12 | include_value!("../../testdata/include_value/data"); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | the trait `FromBytes` is not implemented for `UnsafeCell<u32>` - | required by a bound introduced by this call - | - = help: the following other types implement trait `FromBytes`: - () - F32<O> - F64<O> - I128<O> - I16<O> - I32<O> - I64<O> - ManuallyDrop<T> - and $N others -note: required by a bound in `AssertIsFromBytes` - --> tests/ui-nightly/include_value_not_from_bytes.rs:12:5 - | -12 | include_value!("../../testdata/include_value/data"); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertIsFromBytes` - = note: this error originates in the macro `$crate::transmute` which comes from the expansion of the macro `include_value` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/include_value_wrong_size.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/include_value_wrong_size.rs deleted file mode 100644 index d87b306..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/include_value_wrong_size.rs +++ /dev/null
@@ -1,11 +0,0 @@ -// Copyright 2022 The Fuchsia Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#[macro_use] -extern crate zerocopy; - -fn main() {} - -// Should fail because the file is 4 bytes long, not 8. -const WRONG_SIZE: u64 = include_value!("../../testdata/include_value/data");
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/include_value_wrong_size.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/include_value_wrong_size.stderr deleted file mode 100644 index f592ece1..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/include_value_wrong_size.stderr +++ /dev/null
@@ -1,9 +0,0 @@ -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-nightly/include_value_wrong_size.rs:11:25 - | -11 | const WRONG_SIZE: u64 = include_value!("../../testdata/include_value/data"); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: source type: `[u8; 4]` (32 bits) - = note: target type: `u64` (64 bits) - = note: this error originates in the macro `$crate::transmute` which comes from the expansion of the macro `include_value` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/invalid-impls/invalid-impls.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/invalid-impls/invalid-impls.rs deleted file mode 100644 index ea96390..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/invalid-impls/invalid-impls.rs +++ /dev/null
@@ -1,29 +0,0 @@ -// Copyright 2022 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -// Since some macros from `macros.rs` are unused. -#![allow(unused)] - -extern crate zerocopy; -extern crate zerocopy_derive; - -include!("../../../src/macros.rs"); - -use zerocopy::*; -use zerocopy_derive::*; - -fn main() {} - -#[derive(FromZeroes, FromBytes, AsBytes, Unaligned)] -#[repr(transparent)] -struct Foo<T>(T); - -impl_or_verify!(T => FromZeroes for Foo<T>); -impl_or_verify!(T => FromBytes for Foo<T>); -impl_or_verify!(T => AsBytes for Foo<T>); -impl_or_verify!(T => Unaligned for Foo<T>);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/invalid-impls/invalid-impls.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/invalid-impls/invalid-impls.stderr deleted file mode 100644 index 1c91309..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/invalid-impls/invalid-impls.stderr +++ /dev/null
@@ -1,107 +0,0 @@ -error[E0277]: the trait bound `T: zerocopy::FromZeroes` is not satisfied - --> tests/ui-nightly/invalid-impls/invalid-impls.rs:26:37 - | -26 | impl_or_verify!(T => FromZeroes for Foo<T>); - | ^^^^^^ the trait `zerocopy::FromZeroes` is not implemented for `T`, which is required by `Foo<T>: zerocopy::FromZeroes` - | -note: required for `Foo<T>` to implement `zerocopy::FromZeroes` - --> tests/ui-nightly/invalid-impls/invalid-impls.rs:22:10 - | -22 | #[derive(FromZeroes, FromBytes, AsBytes, Unaligned)] - | ^^^^^^^^^^ unsatisfied trait bound introduced in this `derive` macro -note: required by a bound in `_::Subtrait` - --> tests/ui-nightly/invalid-impls/../../../src/macros.rs - | - | trait Subtrait: $trait {} - | ^^^^^^ required by this bound in `Subtrait` - | - ::: tests/ui-nightly/invalid-impls/invalid-impls.rs:26:1 - | -26 | impl_or_verify!(T => FromZeroes for Foo<T>); - | ------------------------------------------- in this macro invocation - = note: this error originates in the derive macro `FromZeroes` which comes from the expansion of the macro `impl_or_verify` (in Nightly builds, run with -Z macro-backtrace for more info) -help: consider restricting type parameter `T` - | -26 | impl_or_verify!(T: zerocopy::FromZeroes => FromZeroes for Foo<T>); - | ++++++++++++++++++++++ - -error[E0277]: the trait bound `T: zerocopy::FromBytes` is not satisfied - --> tests/ui-nightly/invalid-impls/invalid-impls.rs:27:36 - | -27 | impl_or_verify!(T => FromBytes for Foo<T>); - | ^^^^^^ the trait `zerocopy::FromBytes` is not implemented for `T`, which is required by `Foo<T>: zerocopy::FromBytes` - | -note: required for `Foo<T>` to implement `zerocopy::FromBytes` - --> tests/ui-nightly/invalid-impls/invalid-impls.rs:22:22 - | -22 | #[derive(FromZeroes, FromBytes, AsBytes, Unaligned)] - | ^^^^^^^^^ unsatisfied trait bound introduced in this `derive` macro -note: required by a bound in `_::Subtrait` - --> tests/ui-nightly/invalid-impls/../../../src/macros.rs - | - | trait Subtrait: $trait {} - | ^^^^^^ required by this bound in `Subtrait` - | - ::: tests/ui-nightly/invalid-impls/invalid-impls.rs:27:1 - | -27 | impl_or_verify!(T => FromBytes for Foo<T>); - | ------------------------------------------ in this macro invocation - = note: this error originates in the derive macro `FromBytes` which comes from the expansion of the macro `impl_or_verify` (in Nightly builds, run with -Z macro-backtrace for more info) -help: consider restricting type parameter `T` - | -27 | impl_or_verify!(T: zerocopy::FromBytes => FromBytes for Foo<T>); - | +++++++++++++++++++++ - -error[E0277]: the trait bound `T: zerocopy::AsBytes` is not satisfied - --> tests/ui-nightly/invalid-impls/invalid-impls.rs:28:34 - | -28 | impl_or_verify!(T => AsBytes for Foo<T>); - | ^^^^^^ the trait `zerocopy::AsBytes` is not implemented for `T`, which is required by `Foo<T>: zerocopy::AsBytes` - | -note: required for `Foo<T>` to implement `zerocopy::AsBytes` - --> tests/ui-nightly/invalid-impls/invalid-impls.rs:22:33 - | -22 | #[derive(FromZeroes, FromBytes, AsBytes, Unaligned)] - | ^^^^^^^ unsatisfied trait bound introduced in this `derive` macro -note: required by a bound in `_::Subtrait` - --> tests/ui-nightly/invalid-impls/../../../src/macros.rs - | - | trait Subtrait: $trait {} - | ^^^^^^ required by this bound in `Subtrait` - | - ::: tests/ui-nightly/invalid-impls/invalid-impls.rs:28:1 - | -28 | impl_or_verify!(T => AsBytes for Foo<T>); - | ---------------------------------------- in this macro invocation - = note: this error originates in the derive macro `AsBytes` which comes from the expansion of the macro `impl_or_verify` (in Nightly builds, run with -Z macro-backtrace for more info) -help: consider restricting type parameter `T` - | -28 | impl_or_verify!(T: zerocopy::AsBytes => AsBytes for Foo<T>); - | +++++++++++++++++++ - -error[E0277]: the trait bound `T: zerocopy::Unaligned` is not satisfied - --> tests/ui-nightly/invalid-impls/invalid-impls.rs:29:36 - | -29 | impl_or_verify!(T => Unaligned for Foo<T>); - | ^^^^^^ the trait `zerocopy::Unaligned` is not implemented for `T`, which is required by `Foo<T>: zerocopy::Unaligned` - | -note: required for `Foo<T>` to implement `zerocopy::Unaligned` - --> tests/ui-nightly/invalid-impls/invalid-impls.rs:22:42 - | -22 | #[derive(FromZeroes, FromBytes, AsBytes, Unaligned)] - | ^^^^^^^^^ unsatisfied trait bound introduced in this `derive` macro -note: required by a bound in `_::Subtrait` - --> tests/ui-nightly/invalid-impls/../../../src/macros.rs - | - | trait Subtrait: $trait {} - | ^^^^^^ required by this bound in `Subtrait` - | - ::: tests/ui-nightly/invalid-impls/invalid-impls.rs:29:1 - | -29 | impl_or_verify!(T => Unaligned for Foo<T>); - | ------------------------------------------ in this macro invocation - = note: this error originates in the derive macro `Unaligned` which comes from the expansion of the macro `impl_or_verify` (in Nightly builds, run with -Z macro-backtrace for more info) -help: consider restricting type parameter `T` - | -29 | impl_or_verify!(T: zerocopy::Unaligned => Unaligned for Foo<T>); - | +++++++++++++++++++++
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/max-align.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/max-align.rs deleted file mode 100644 index 53e3eb9..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/max-align.rs +++ /dev/null
@@ -1,99 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -#[repr(C, align(1))] -struct Align1; - -#[repr(C, align(2))] -struct Align2; - -#[repr(C, align(4))] -struct Align4; - -#[repr(C, align(8))] -struct Align8; - -#[repr(C, align(16))] -struct Align16; - -#[repr(C, align(32))] -struct Align32; - -#[repr(C, align(64))] -struct Align64; - -#[repr(C, align(128))] -struct Align128; - -#[repr(C, align(256))] -struct Align256; - -#[repr(C, align(512))] -struct Align512; - -#[repr(C, align(1024))] -struct Align1024; - -#[repr(C, align(2048))] -struct Align2048; - -#[repr(C, align(4096))] -struct Align4096; - -#[repr(C, align(8192))] -struct Align8192; - -#[repr(C, align(16384))] -struct Align16384; - -#[repr(C, align(32768))] -struct Align32768; - -#[repr(C, align(65536))] -struct Align65536; - -#[repr(C, align(131072))] -struct Align131072; - -#[repr(C, align(262144))] -struct Align262144; - -#[repr(C, align(524288))] -struct Align524288; - -#[repr(C, align(1048576))] -struct Align1048576; - -#[repr(C, align(2097152))] -struct Align2097152; - -#[repr(C, align(4194304))] -struct Align4194304; - -#[repr(C, align(8388608))] -struct Align8388608; - -#[repr(C, align(16777216))] -struct Align16777216; - -#[repr(C, align(33554432))] -struct Align33554432; - -#[repr(C, align(67108864))] -struct Align67108864; - -#[repr(C, align(134217728))] -struct Align13421772; - -#[repr(C, align(268435456))] -struct Align26843545; - -#[repr(C, align(1073741824))] -struct Align1073741824; - -fn main() {}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/max-align.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/max-align.stderr deleted file mode 100644 index c11eed53..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/max-align.stderr +++ /dev/null
@@ -1,5 +0,0 @@ -error[E0589]: invalid `repr(align)` attribute: larger than 2^29 - --> tests/ui-nightly/max-align.rs:96:17 - | -96 | #[repr(C, align(1073741824))] - | ^^^^^^^^^^
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-dst-not-frombytes.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-dst-not-frombytes.rs deleted file mode 100644 index c4caaff9..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-dst-not-frombytes.rs +++ /dev/null
@@ -1,18 +0,0 @@ -// Copyright 2022 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -include!("../../zerocopy-derive/tests/util.rs"); - -extern crate zerocopy; - -use zerocopy::transmute; - -fn main() {} - -// `transmute` requires that the destination type implements `FromBytes` -const DST_NOT_FROM_BYTES: NotZerocopy = transmute!(AU16(0));
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-dst-not-frombytes.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-dst-not-frombytes.stderr deleted file mode 100644 index 70bec216..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-dst-not-frombytes.stderr +++ /dev/null
@@ -1,25 +0,0 @@ -error[E0277]: the trait bound `NotZerocopy: FromBytes` is not satisfied - --> tests/ui-nightly/transmute-dst-not-frombytes.rs:18:41 - | -18 | const DST_NOT_FROM_BYTES: NotZerocopy = transmute!(AU16(0)); - | ^^^^^^^^^^^^^^^^^^^ - | | - | the trait `FromBytes` is not implemented for `NotZerocopy` - | required by a bound introduced by this call - | - = help: the following other types implement trait `FromBytes`: - () - AU16 - F32<O> - F64<O> - I128<O> - I16<O> - I32<O> - I64<O> - and $N others -note: required by a bound in `AssertIsFromBytes` - --> tests/ui-nightly/transmute-dst-not-frombytes.rs:18:41 - | -18 | const DST_NOT_FROM_BYTES: NotZerocopy = transmute!(AU16(0)); - | ^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertIsFromBytes` - = note: this error originates in the macro `transmute` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-alignment-increase.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-alignment-increase.rs deleted file mode 100644 index 0928564d..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-alignment-increase.rs +++ /dev/null
@@ -1,19 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -include!("../../zerocopy-derive/tests/util.rs"); - -extern crate zerocopy; - -use zerocopy::transmute_mut; - -fn main() {} - -// `transmute_mut!` does not support transmuting from a type of smaller -// alignment to one of larger alignment. -const INCREASE_ALIGNMENT: &mut AU16 = transmute_mut!(&mut [0u8; 2]);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-alignment-increase.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-alignment-increase.stderr deleted file mode 100644 index 0666f8b..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-alignment-increase.stderr +++ /dev/null
@@ -1,9 +0,0 @@ -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-nightly/transmute-mut-alignment-increase.rs:19:39 - | -19 | const INCREASE_ALIGNMENT: &mut AU16 = transmute_mut!(&mut [0u8; 2]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: source type: `AlignOf<[u8; 2]>` (8 bits) - = note: target type: `MaxAlignsOf<[u8; 2], AU16>` (16 bits) - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-const.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-const.rs deleted file mode 100644 index 021b562f1..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-const.rs +++ /dev/null
@@ -1,20 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -include!("../../zerocopy-derive/tests/util.rs"); - -extern crate zerocopy; - -use zerocopy::transmute_mut; - -fn main() {} - -const ARRAY_OF_U8S: [u8; 2] = [0u8; 2]; - -// `transmute_mut!` cannot, generally speaking, be used in const contexts. -const CONST_CONTEXT: &mut [u8; 2] = transmute_mut!(&mut ARRAY_OF_U8S);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-const.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-const.stderr deleted file mode 100644 index 61a34b9a..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-const.stderr +++ /dev/null
@@ -1,33 +0,0 @@ -warning: taking a mutable reference to a `const` item - --> tests/ui-nightly/transmute-mut-const.rs:20:52 - | -20 | const CONST_CONTEXT: &mut [u8; 2] = transmute_mut!(&mut ARRAY_OF_U8S); - | ^^^^^^^^^^^^^^^^^ - | - = note: each usage of a `const` item creates a new temporary - = note: the mutable reference will refer to this temporary, not the original `const` item -note: `const` item defined here - --> tests/ui-nightly/transmute-mut-const.rs:17:1 - | -17 | const ARRAY_OF_U8S: [u8; 2] = [0u8; 2]; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ - = note: `#[warn(const_item_mutation)]` on by default - -error[E0658]: mutable references are not allowed in constants - --> tests/ui-nightly/transmute-mut-const.rs:20:52 - | -20 | const CONST_CONTEXT: &mut [u8; 2] = transmute_mut!(&mut ARRAY_OF_U8S); - | ^^^^^^^^^^^^^^^^^ - | - = note: see issue #57349 <https://github.com/rust-lang/rust/issues/57349> for more information - = help: add `#![feature(const_mut_refs)]` to the crate attributes to enable - = note: this compiler was built on 2024-06-18; consider upgrading it if it is out of date - -error[E0015]: cannot call non-const fn `transmute_mut::<'_, '_, [u8; 2], [u8; 2]>` in constants - --> tests/ui-nightly/transmute-mut-const.rs:20:37 - | -20 | const CONST_CONTEXT: &mut [u8; 2] = transmute_mut!(&mut ARRAY_OF_U8S); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: calls in constants are limited to constant functions, tuple structs and tuple variants - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-dst-generic.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-dst-generic.rs deleted file mode 100644 index 7068f102..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-dst-generic.rs +++ /dev/null
@@ -1,18 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::{transmute_mut, AsBytes, FromBytes}; - -fn main() {} - -fn transmute_mut<T: AsBytes + FromBytes>(u: &mut u8) -> &mut T { - // `transmute_mut!` requires the destination type to be concrete. - transmute_mut!(u) -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-dst-generic.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-dst-generic.stderr deleted file mode 100644 index f278558c..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-dst-generic.stderr +++ /dev/null
@@ -1,19 +0,0 @@ -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-nightly/transmute-mut-dst-generic.rs:17:5 - | -17 | transmute_mut!(u) - | ^^^^^^^^^^^^^^^^^ - | - = note: source type: `u8` (8 bits) - = note: target type: `T` (this type does not have a fixed size) - = note: this error originates in the macro `$crate::assert_size_eq` which comes from the expansion of the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-nightly/transmute-mut-dst-generic.rs:17:5 - | -17 | transmute_mut!(u) - | ^^^^^^^^^^^^^^^^^ - | - = note: source type: `AlignOf<u8>` (8 bits) - = note: target type: `MaxAlignsOf<u8, T>` (size can vary because of T) - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-dst-not-a-reference.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-dst-not-a-reference.rs deleted file mode 100644 index 33a9ecd9..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-dst-not-a-reference.rs +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_mut; - -fn main() {} - -// `transmute_mut!` does not support transmuting into a non-reference -// destination type. -const DST_NOT_A_REFERENCE: usize = transmute_mut!(&mut 0u8);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-dst-not-a-reference.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-dst-not-a-reference.stderr deleted file mode 100644 index a84547b..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-dst-not-a-reference.stderr +++ /dev/null
@@ -1,39 +0,0 @@ -error[E0308]: mismatched types - --> tests/ui-nightly/transmute-mut-dst-not-a-reference.rs:17:36 - | -17 | const DST_NOT_A_REFERENCE: usize = transmute_mut!(&mut 0u8); - | ^^^^^^^^^^^^^^^^^^^^^^^^ expected `usize`, found `&mut _` - | - = note: expected type `usize` - found mutable reference `&mut _` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0308]: mismatched types - --> tests/ui-nightly/transmute-mut-dst-not-a-reference.rs:17:36 - | -17 | const DST_NOT_A_REFERENCE: usize = transmute_mut!(&mut 0u8); - | ^^^^^^^^^^^^^^^^^^^^^^^^ expected `usize`, found `&mut _` - | - = note: expected type `usize` - found mutable reference `&mut _` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0308]: mismatched types - --> tests/ui-nightly/transmute-mut-dst-not-a-reference.rs:17:36 - | -17 | const DST_NOT_A_REFERENCE: usize = transmute_mut!(&mut 0u8); - | ^^^^^^^^^^^^^^^^^^^^^^^^ expected `usize`, found `&mut _` - | - = note: expected type `usize` - found mutable reference `&mut _` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0308]: mismatched types - --> tests/ui-nightly/transmute-mut-dst-not-a-reference.rs:17:36 - | -17 | const DST_NOT_A_REFERENCE: usize = transmute_mut!(&mut 0u8); - | ^^^^^^^^^^^^^^^^^^^^^^^^ expected `usize`, found `&mut _` - | - = note: expected type `usize` - found mutable reference `&mut _` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-dst-not-asbytes.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-dst-not-asbytes.rs deleted file mode 100644 index b72f129..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-dst-not-asbytes.rs +++ /dev/null
@@ -1,24 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_mut; - -fn main() {} - -#[derive(zerocopy::FromZeroes, zerocopy::FromBytes, zerocopy::AsBytes)] -#[repr(C)] -struct Src; - -#[derive(zerocopy::FromZeroes, zerocopy::FromBytes)] -#[repr(C)] -struct Dst; - -// `transmute_mut` requires that the destination type implements `AsBytes` -const DST_NOT_AS_BYTES: &mut Dst = transmute_mut!(&mut Src);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-dst-not-asbytes.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-dst-not-asbytes.stderr deleted file mode 100644 index 7de5da60..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-dst-not-asbytes.stderr +++ /dev/null
@@ -1,25 +0,0 @@ -error[E0277]: the trait bound `Dst: AsBytes` is not satisfied - --> tests/ui-nightly/transmute-mut-dst-not-asbytes.rs:24:36 - | -24 | const DST_NOT_AS_BYTES: &mut Dst = transmute_mut!(&mut Src); - | ^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | the trait `AsBytes` is not implemented for `Dst` - | required by a bound introduced by this call - | - = help: the following other types implement trait `AsBytes`: - () - F32<O> - F64<O> - I128<O> - I16<O> - I32<O> - I64<O> - ManuallyDrop<T> - and $N others -note: required by a bound in `AssertDstIsAsBytes` - --> tests/ui-nightly/transmute-mut-dst-not-asbytes.rs:24:36 - | -24 | const DST_NOT_AS_BYTES: &mut Dst = transmute_mut!(&mut Src); - | ^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertDstIsAsBytes` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-dst-not-frombytes.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-dst-not-frombytes.rs deleted file mode 100644 index 102fced..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-dst-not-frombytes.rs +++ /dev/null
@@ -1,24 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_mut; - -fn main() {} - -#[derive(zerocopy::FromZeroes, zerocopy::FromBytes, zerocopy::AsBytes)] -#[repr(C)] -struct Src; - -#[derive(zerocopy::AsBytes)] -#[repr(C)] -struct Dst; - -// `transmute_mut` requires that the destination type implements `FromBytes` -const DST_NOT_FROM_BYTES: &mut Dst = transmute_mut!(&mut Src);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-dst-not-frombytes.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-dst-not-frombytes.stderr deleted file mode 100644 index 9df4ebc..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-dst-not-frombytes.stderr +++ /dev/null
@@ -1,25 +0,0 @@ -error[E0277]: the trait bound `Dst: FromBytes` is not satisfied - --> tests/ui-nightly/transmute-mut-dst-not-frombytes.rs:24:38 - | -24 | const DST_NOT_FROM_BYTES: &mut Dst = transmute_mut!(&mut Src); - | ^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | the trait `FromBytes` is not implemented for `Dst` - | required by a bound introduced by this call - | - = help: the following other types implement trait `FromBytes`: - () - F32<O> - F64<O> - I128<O> - I16<O> - I32<O> - I64<O> - ManuallyDrop<T> - and $N others -note: required by a bound in `AssertDstIsFromBytes` - --> tests/ui-nightly/transmute-mut-dst-not-frombytes.rs:24:38 - | -24 | const DST_NOT_FROM_BYTES: &mut Dst = transmute_mut!(&mut Src); - | ^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertDstIsFromBytes` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-dst-unsized.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-dst-unsized.rs deleted file mode 100644 index 693ccda..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-dst-unsized.rs +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_mut; - -fn main() {} - -// `transmute_mut!` does not support transmuting into an unsized destination -// type. -const DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8; 1]);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-dst-unsized.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-dst-unsized.stderr deleted file mode 100644 index 5e3fbb4..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-dst-unsized.stderr +++ /dev/null
@@ -1,86 +0,0 @@ -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-mut-dst-unsized.rs:17:32 - | -17 | const DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8; 1]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | doesn't have a size known at compile-time - | required by a bound introduced by this call - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AssertDstIsFromBytes` - --> tests/ui-nightly/transmute-mut-dst-unsized.rs:17:32 - | -17 | const DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8; 1]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertDstIsFromBytes` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-mut-dst-unsized.rs:17:32 - | -17 | const DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8; 1]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | doesn't have a size known at compile-time - | required by a bound introduced by this call - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AssertDstIsAsBytes` - --> tests/ui-nightly/transmute-mut-dst-unsized.rs:17:32 - | -17 | const DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8; 1]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertDstIsAsBytes` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-mut-dst-unsized.rs:17:32 - | -17 | const DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8; 1]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` - = note: all local variables must have a statically known size - = help: unsized locals are gated as an unstable feature - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-mut-dst-unsized.rs:17:32 - | -17 | const DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8; 1]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by an implicit `Sized` bound in `MaxAlignsOf` - --> src/macro_util.rs - | - | pub union MaxAlignsOf<T, U> { - | ^ required by the implicit `Sized` requirement on this type parameter in `MaxAlignsOf` - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-mut-dst-unsized.rs:17:32 - | -17 | const DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8; 1]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by an implicit `Sized` bound in `transmute` - --> $RUST/core/src/intrinsics.rs - | - | pub fn transmute<Src, Dst>(src: Src) -> Dst; - | ^^^ required by the implicit `Sized` requirement on this type parameter in `transmute` - = note: this error originates in the macro `$crate::assert_size_eq` which comes from the expansion of the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-mut-dst-unsized.rs:17:32 - | -17 | const DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8; 1]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by an implicit `Sized` bound in `transmute_mut` - --> src/macro_util.rs - | - | pub unsafe fn transmute_mut<'dst, 'src: 'dst, Src: 'src, Dst: 'dst>( - | ^^^ required by the implicit `Sized` requirement on this type parameter in `transmute_mut` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-illegal-lifetime.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-illegal-lifetime.rs deleted file mode 100644 index c31765e..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-illegal-lifetime.rs +++ /dev/null
@@ -1,15 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -fn main() {} - -fn increase_lifetime() { - let mut x = 0u64; - // It is illegal to increase the lifetime scope. - let _: &'static mut u64 = zerocopy::transmute_mut!(&mut x); -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-illegal-lifetime.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-illegal-lifetime.stderr deleted file mode 100644 index b826fcc..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-illegal-lifetime.stderr +++ /dev/null
@@ -1,12 +0,0 @@ -error[E0597]: `x` does not live long enough - --> tests/ui-nightly/transmute-mut-illegal-lifetime.rs:14:56 - | -12 | let mut x = 0u64; - | ----- binding `x` declared here -13 | // It is illegal to increase the lifetime scope. -14 | let _: &'static mut u64 = zerocopy::transmute_mut!(&mut x); - | ---------------- ^^^^^^ borrowed value does not live long enough - | | - | type annotation requires that `x` is borrowed for `'static` -15 | } - | - `x` dropped here while still borrowed
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-size-decrease.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-size-decrease.rs deleted file mode 100644 index c6eec3a..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-size-decrease.rs +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_mut; - -fn main() {} - -// We require that the size of the destination type is not smaller than the size -// of the source type. -const DECREASE_SIZE: &mut u8 = transmute_mut!(&mut [0u8; 2]);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-size-decrease.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-size-decrease.stderr deleted file mode 100644 index ac1e35ce..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-size-decrease.stderr +++ /dev/null
@@ -1,9 +0,0 @@ -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-nightly/transmute-mut-size-decrease.rs:17:32 - | -17 | const DECREASE_SIZE: &mut u8 = transmute_mut!(&mut [0u8; 2]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: source type: `[u8; 2]` (16 bits) - = note: target type: `u8` (8 bits) - = note: this error originates in the macro `$crate::assert_size_eq` which comes from the expansion of the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-size-increase.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-size-increase.rs deleted file mode 100644 index a4657c28..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-size-increase.rs +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_mut; - -fn main() {} - -// `transmute_mut!` does not support transmuting from a smaller type to a larger -// one. -const INCREASE_SIZE: &mut [u8; 2] = transmute_mut!(&mut 0u8);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-size-increase.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-size-increase.stderr deleted file mode 100644 index d343bd6..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-size-increase.stderr +++ /dev/null
@@ -1,9 +0,0 @@ -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-nightly/transmute-mut-size-increase.rs:17:37 - | -17 | const INCREASE_SIZE: &mut [u8; 2] = transmute_mut!(&mut 0u8); - | ^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: source type: `u8` (8 bits) - = note: target type: `[u8; 2]` (16 bits) - = note: this error originates in the macro `$crate::assert_size_eq` which comes from the expansion of the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-src-dst-generic.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-src-dst-generic.rs deleted file mode 100644 index aed7ded9..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-src-dst-generic.rs +++ /dev/null
@@ -1,19 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::{transmute_mut, AsBytes, FromBytes}; - -fn main() {} - -fn transmute_mut<T: AsBytes + FromBytes, U: AsBytes + FromBytes>(t: &mut T) -> &mut U { - // `transmute_mut!` requires the source and destination types to be - // concrete. - transmute_mut!(t) -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-src-dst-generic.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-src-dst-generic.stderr deleted file mode 100644 index e3f3a3fd..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-src-dst-generic.stderr +++ /dev/null
@@ -1,19 +0,0 @@ -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-nightly/transmute-mut-src-dst-generic.rs:18:5 - | -18 | transmute_mut!(t) - | ^^^^^^^^^^^^^^^^^ - | - = note: source type: `T` (this type does not have a fixed size) - = note: target type: `U` (this type does not have a fixed size) - = note: this error originates in the macro `$crate::assert_size_eq` which comes from the expansion of the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-nightly/transmute-mut-src-dst-generic.rs:18:5 - | -18 | transmute_mut!(t) - | ^^^^^^^^^^^^^^^^^ - | - = note: source type: `AlignOf<T>` (size can vary because of T) - = note: target type: `MaxAlignsOf<T, U>` (size can vary because of T) - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-src-dst-not-references.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-src-dst-not-references.rs deleted file mode 100644 index 98cc520..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-src-dst-not-references.rs +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_mut; - -fn main() {} - -// `transmute_mut!` does not support transmuting between non-reference source -// and destination types. -const SRC_DST_NOT_REFERENCES: &mut usize = transmute_mut!(0usize);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-src-dst-not-references.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-src-dst-not-references.stderr deleted file mode 100644 index bdd3f42..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-src-dst-not-references.stderr +++ /dev/null
@@ -1,44 +0,0 @@ -error[E0308]: mismatched types - --> tests/ui-nightly/transmute-mut-src-dst-not-references.rs:17:59 - | -17 | const SRC_DST_NOT_REFERENCES: &mut usize = transmute_mut!(0usize); - | ---------------^^^^^^- - | | | - | | expected `&mut _`, found `usize` - | expected due to this - | - = note: expected mutable reference `&mut _` - found type `usize` -help: consider mutably borrowing here - | -17 | const SRC_DST_NOT_REFERENCES: &mut usize = transmute_mut!(&mut 0usize); - | ++++ - -warning: this function depends on never type fallback being `()` - --> tests/ui-nightly/transmute-mut-src-dst-not-references.rs:17:1 - | -17 | const SRC_DST_NOT_REFERENCES: &mut usize = transmute_mut!(0usize); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - = note: for more information, see issue #123748 <https://github.com/rust-lang/rust/issues/123748> - = help: specify the types explicitly -note: in edition 2024, the requirement `!: FromBytes` will fail - --> tests/ui-nightly/transmute-mut-src-dst-not-references.rs:17:44 - | -17 | const SRC_DST_NOT_REFERENCES: &mut usize = transmute_mut!(0usize); - | ^^^^^^^^^^^^^^^^^^^^^^ - = note: `#[warn(dependency_on_unit_never_type_fallback)]` on by default - = note: this warning originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -warning: never type fallback affects this call to an `unsafe` function - --> tests/ui-nightly/transmute-mut-src-dst-not-references.rs:17:44 - | -17 | const SRC_DST_NOT_REFERENCES: &mut usize = transmute_mut!(0usize); - | ^^^^^^^^^^^^^^^^^^^^^^ - | - = warning: this will change its meaning in a future release! - = note: for more information, see issue #123748 <https://github.com/rust-lang/rust/issues/123748> - = help: specify the type explicitly - = note: `#[warn(never_type_fallback_flowing_into_unsafe)]` on by default - = note: this warning originates in the macro `$crate::assert_size_eq` which comes from the expansion of the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-src-dst-unsized.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-src-dst-unsized.rs deleted file mode 100644 index 1bebcf2..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-src-dst-unsized.rs +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_mut; - -fn main() {} - -// `transmute_mut!` does not support transmuting between unsized source and -// destination types. -const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-src-dst-unsized.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-src-dst-unsized.stderr deleted file mode 100644 index 2fe66581..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-src-dst-unsized.stderr +++ /dev/null
@@ -1,231 +0,0 @@ -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | doesn't have a size known at compile-time - | required by a bound introduced by this call - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AssertSrcIsFromBytes` - --> tests/ui-nightly/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertSrcIsFromBytes` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AssertSrcIsFromBytes` - --> tests/ui-nightly/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertSrcIsFromBytes` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | doesn't have a size known at compile-time - | required by a bound introduced by this call - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AssertSrcIsAsBytes` - --> tests/ui-nightly/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertSrcIsAsBytes` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AssertSrcIsAsBytes` - --> tests/ui-nightly/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertSrcIsAsBytes` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | doesn't have a size known at compile-time - | required by a bound introduced by this call - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AssertDstIsFromBytes` - --> tests/ui-nightly/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertDstIsFromBytes` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | doesn't have a size known at compile-time - | required by a bound introduced by this call - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AssertDstIsAsBytes` - --> tests/ui-nightly/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertDstIsAsBytes` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` - = note: all local variables must have a statically known size - = help: unsized locals are gated as an unstable feature - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AlignOf::<T>::into_t` - --> src/macro_util.rs - | - | impl<T> AlignOf<T> { - | ^ required by this bound in `AlignOf::<T>::into_t` - | #[inline(never)] // Make `missing_inline_in_public_items` happy. - | pub fn into_t(self) -> T { - | ------ required by a bound in this associated function - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` - = note: the left-hand-side of an assignment must have a statically known size - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by an implicit `Sized` bound in `AlignOf` - --> src/macro_util.rs - | - | pub struct AlignOf<T> { - | ^ required by the implicit `Sized` requirement on this type parameter in `AlignOf` - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by an implicit `Sized` bound in `MaxAlignsOf` - --> src/macro_util.rs - | - | pub union MaxAlignsOf<T, U> { - | ^ required by the implicit `Sized` requirement on this type parameter in `MaxAlignsOf` - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by an implicit `Sized` bound in `AlignOf` - --> src/macro_util.rs - | - | pub struct AlignOf<T> { - | ^ required by the implicit `Sized` requirement on this type parameter in `AlignOf` - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` - = note: all local variables must have a statically known size - = help: unsized locals are gated as an unstable feature - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by an implicit `Sized` bound in `transmute` - --> $RUST/core/src/intrinsics.rs - | - | pub fn transmute<Src, Dst>(src: Src) -> Dst; - | ^^^ required by the implicit `Sized` requirement on this type parameter in `transmute` - = note: this error originates in the macro `$crate::assert_size_eq` which comes from the expansion of the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | doesn't have a size known at compile-time - | required by a bound introduced by this call - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by an implicit `Sized` bound in `transmute_mut` - --> src/macro_util.rs - | - | pub unsafe fn transmute_mut<'dst, 'src: 'dst, Src: 'src, Dst: 'dst>( - | ^^^ required by the implicit `Sized` requirement on this type parameter in `transmute_mut` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by an implicit `Sized` bound in `transmute_mut` - --> src/macro_util.rs - | - | pub unsafe fn transmute_mut<'dst, 'src: 'dst, Src: 'src, Dst: 'dst>( - | ^^^ required by the implicit `Sized` requirement on this type parameter in `transmute_mut` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-src-generic.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-src-generic.rs deleted file mode 100644 index a3ef397..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-src-generic.rs +++ /dev/null
@@ -1,18 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::{transmute_mut, AsBytes}; - -fn main() {} - -fn transmute_mut<T: AsBytes + FromBytes>(t: &mut T) -> &mut u8 { - // `transmute_mut!` requires the source type to be concrete. - transmute_mut!(t) -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-src-generic.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-src-generic.stderr deleted file mode 100644 index c06d7750..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-src-generic.stderr +++ /dev/null
@@ -1,10 +0,0 @@ -error[E0405]: cannot find trait `FromBytes` in this scope - --> tests/ui-nightly/transmute-mut-src-generic.rs:15:31 - | -15 | fn transmute_mut<T: AsBytes + FromBytes>(t: &mut T) -> &mut u8 { - | ^^^^^^^^^ not found in this scope - | -help: consider importing this trait - | -11 + use zerocopy::FromBytes; - |
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-src-immutable.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-src-immutable.rs deleted file mode 100644 index 08088d0..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-src-immutable.rs +++ /dev/null
@@ -1,18 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_mut; - -fn main() {} - -fn ref_src_immutable() { - // `transmute_mut!` requires that its source type be a mutable reference. - let _: &mut u8 = transmute_mut!(&0u8); -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-src-immutable.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-src-immutable.stderr deleted file mode 100644 index abaac995..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-src-immutable.stderr +++ /dev/null
@@ -1,40 +0,0 @@ -error[E0308]: mismatched types - --> tests/ui-nightly/transmute-mut-src-immutable.rs:17:37 - | -17 | let _: &mut u8 = transmute_mut!(&0u8); - | ---------------^^^^- - | | | - | | types differ in mutability - | expected due to this - | - = note: expected mutable reference `&mut _` - found reference `&u8` - -warning: this function depends on never type fallback being `()` - --> tests/ui-nightly/transmute-mut-src-immutable.rs:15:1 - | -15 | fn ref_src_immutable() { - | ^^^^^^^^^^^^^^^^^^^^^^ - | - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - = note: for more information, see issue #123748 <https://github.com/rust-lang/rust/issues/123748> - = help: specify the types explicitly -note: in edition 2024, the requirement `!: FromBytes` will fail - --> tests/ui-nightly/transmute-mut-src-immutable.rs:17:22 - | -17 | let _: &mut u8 = transmute_mut!(&0u8); - | ^^^^^^^^^^^^^^^^^^^^ - = note: `#[warn(dependency_on_unit_never_type_fallback)]` on by default - = note: this warning originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -warning: never type fallback affects this call to an `unsafe` function - --> tests/ui-nightly/transmute-mut-src-immutable.rs:17:22 - | -17 | let _: &mut u8 = transmute_mut!(&0u8); - | ^^^^^^^^^^^^^^^^^^^^ - | - = warning: this will change its meaning in a future release! - = note: for more information, see issue #123748 <https://github.com/rust-lang/rust/issues/123748> - = help: specify the type explicitly - = note: `#[warn(never_type_fallback_flowing_into_unsafe)]` on by default - = note: this warning originates in the macro `$crate::assert_size_eq` which comes from the expansion of the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-src-not-a-reference.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-src-not-a-reference.rs deleted file mode 100644 index bf8bc32..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-src-not-a-reference.rs +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_mut; - -fn main() {} - -// `transmute_mut!` does not support transmuting from a non-reference source -// type. -const SRC_NOT_A_REFERENCE: &mut u8 = transmute_mut!(0usize);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-src-not-a-reference.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-src-not-a-reference.stderr deleted file mode 100644 index 8fc4476d1..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-src-not-a-reference.stderr +++ /dev/null
@@ -1,44 +0,0 @@ -error[E0308]: mismatched types - --> tests/ui-nightly/transmute-mut-src-not-a-reference.rs:17:53 - | -17 | const SRC_NOT_A_REFERENCE: &mut u8 = transmute_mut!(0usize); - | ---------------^^^^^^- - | | | - | | expected `&mut _`, found `usize` - | expected due to this - | - = note: expected mutable reference `&mut _` - found type `usize` -help: consider mutably borrowing here - | -17 | const SRC_NOT_A_REFERENCE: &mut u8 = transmute_mut!(&mut 0usize); - | ++++ - -warning: this function depends on never type fallback being `()` - --> tests/ui-nightly/transmute-mut-src-not-a-reference.rs:17:1 - | -17 | const SRC_NOT_A_REFERENCE: &mut u8 = transmute_mut!(0usize); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - = note: for more information, see issue #123748 <https://github.com/rust-lang/rust/issues/123748> - = help: specify the types explicitly -note: in edition 2024, the requirement `!: FromBytes` will fail - --> tests/ui-nightly/transmute-mut-src-not-a-reference.rs:17:38 - | -17 | const SRC_NOT_A_REFERENCE: &mut u8 = transmute_mut!(0usize); - | ^^^^^^^^^^^^^^^^^^^^^^ - = note: `#[warn(dependency_on_unit_never_type_fallback)]` on by default - = note: this warning originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -warning: never type fallback affects this call to an `unsafe` function - --> tests/ui-nightly/transmute-mut-src-not-a-reference.rs:17:38 - | -17 | const SRC_NOT_A_REFERENCE: &mut u8 = transmute_mut!(0usize); - | ^^^^^^^^^^^^^^^^^^^^^^ - | - = warning: this will change its meaning in a future release! - = note: for more information, see issue #123748 <https://github.com/rust-lang/rust/issues/123748> - = help: specify the type explicitly - = note: `#[warn(never_type_fallback_flowing_into_unsafe)]` on by default - = note: this warning originates in the macro `$crate::assert_size_eq` which comes from the expansion of the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-src-not-asbytes.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-src-not-asbytes.rs deleted file mode 100644 index 6a14f12..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-src-not-asbytes.rs +++ /dev/null
@@ -1,24 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_mut; - -fn main() {} - -#[derive(zerocopy::FromZeroes, zerocopy::FromBytes)] -#[repr(C)] -struct Src; - -#[derive(zerocopy::FromZeroes, zerocopy::FromBytes, zerocopy::AsBytes)] -#[repr(C)] -struct Dst; - -// `transmute_mut` requires that the source type implements `AsBytes` -const SRC_NOT_AS_BYTES: &mut Dst = transmute_mut!(&mut Src);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-src-not-asbytes.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-src-not-asbytes.stderr deleted file mode 100644 index 0b4154b..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-src-not-asbytes.stderr +++ /dev/null
@@ -1,48 +0,0 @@ -error[E0277]: the trait bound `Src: AsBytes` is not satisfied - --> tests/ui-nightly/transmute-mut-src-not-asbytes.rs:24:36 - | -24 | const SRC_NOT_AS_BYTES: &mut Dst = transmute_mut!(&mut Src); - | ^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | the trait `AsBytes` is not implemented for `Src` - | required by a bound introduced by this call - | - = help: the following other types implement trait `AsBytes`: - () - Dst - F32<O> - F64<O> - I128<O> - I16<O> - I32<O> - I64<O> - and $N others -note: required by a bound in `AssertSrcIsAsBytes` - --> tests/ui-nightly/transmute-mut-src-not-asbytes.rs:24:36 - | -24 | const SRC_NOT_AS_BYTES: &mut Dst = transmute_mut!(&mut Src); - | ^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertSrcIsAsBytes` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `Src: AsBytes` is not satisfied - --> tests/ui-nightly/transmute-mut-src-not-asbytes.rs:24:36 - | -24 | const SRC_NOT_AS_BYTES: &mut Dst = transmute_mut!(&mut Src); - | ^^^^^^^^^^^^^^^^^^^^^^^^ the trait `AsBytes` is not implemented for `Src` - | - = help: the following other types implement trait `AsBytes`: - () - Dst - F32<O> - F64<O> - I128<O> - I16<O> - I32<O> - I64<O> - and $N others -note: required by a bound in `AssertSrcIsAsBytes` - --> tests/ui-nightly/transmute-mut-src-not-asbytes.rs:24:36 - | -24 | const SRC_NOT_AS_BYTES: &mut Dst = transmute_mut!(&mut Src); - | ^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertSrcIsAsBytes` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-src-not-frombytes.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-src-not-frombytes.rs deleted file mode 100644 index 2ebe036..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-src-not-frombytes.rs +++ /dev/null
@@ -1,24 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_mut; - -fn main() {} - -#[derive(zerocopy::AsBytes)] -#[repr(C)] -struct Src; - -#[derive(zerocopy::FromZeroes, zerocopy::FromBytes, zerocopy::AsBytes)] -#[repr(C)] -struct Dst; - -// `transmute_mut` requires that the source type implements `FromBytes` -const SRC_NOT_FROM_BYTES: &mut Dst = transmute_mut!(&mut Src);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-src-not-frombytes.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-src-not-frombytes.stderr deleted file mode 100644 index 858fc509..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-src-not-frombytes.stderr +++ /dev/null
@@ -1,48 +0,0 @@ -error[E0277]: the trait bound `Src: FromBytes` is not satisfied - --> tests/ui-nightly/transmute-mut-src-not-frombytes.rs:24:38 - | -24 | const SRC_NOT_FROM_BYTES: &mut Dst = transmute_mut!(&mut Src); - | ^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | the trait `FromBytes` is not implemented for `Src` - | required by a bound introduced by this call - | - = help: the following other types implement trait `FromBytes`: - () - Dst - F32<O> - F64<O> - I128<O> - I16<O> - I32<O> - I64<O> - and $N others -note: required by a bound in `AssertSrcIsFromBytes` - --> tests/ui-nightly/transmute-mut-src-not-frombytes.rs:24:38 - | -24 | const SRC_NOT_FROM_BYTES: &mut Dst = transmute_mut!(&mut Src); - | ^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertSrcIsFromBytes` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `Src: FromBytes` is not satisfied - --> tests/ui-nightly/transmute-mut-src-not-frombytes.rs:24:38 - | -24 | const SRC_NOT_FROM_BYTES: &mut Dst = transmute_mut!(&mut Src); - | ^^^^^^^^^^^^^^^^^^^^^^^^ the trait `FromBytes` is not implemented for `Src` - | - = help: the following other types implement trait `FromBytes`: - () - Dst - F32<O> - F64<O> - I128<O> - I16<O> - I32<O> - I64<O> - and $N others -note: required by a bound in `AssertSrcIsFromBytes` - --> tests/ui-nightly/transmute-mut-src-not-frombytes.rs:24:38 - | -24 | const SRC_NOT_FROM_BYTES: &mut Dst = transmute_mut!(&mut Src); - | ^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertSrcIsFromBytes` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-src-unsized.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-src-unsized.rs deleted file mode 100644 index 413dd68..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-src-unsized.rs +++ /dev/null
@@ -1,16 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_mut; - -fn main() {} - -// `transmute_mut!` does not support transmuting from an unsized source type. -const SRC_UNSIZED: &mut [u8; 1] = transmute_mut!(&mut [0u8][..]);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-src-unsized.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-src-unsized.stderr deleted file mode 100644 index b859994..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-mut-src-unsized.stderr +++ /dev/null
@@ -1,158 +0,0 @@ -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-mut-src-unsized.rs:16:35 - | -16 | const SRC_UNSIZED: &mut [u8; 1] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | doesn't have a size known at compile-time - | required by a bound introduced by this call - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AssertSrcIsFromBytes` - --> tests/ui-nightly/transmute-mut-src-unsized.rs:16:35 - | -16 | const SRC_UNSIZED: &mut [u8; 1] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertSrcIsFromBytes` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-mut-src-unsized.rs:16:35 - | -16 | const SRC_UNSIZED: &mut [u8; 1] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AssertSrcIsFromBytes` - --> tests/ui-nightly/transmute-mut-src-unsized.rs:16:35 - | -16 | const SRC_UNSIZED: &mut [u8; 1] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertSrcIsFromBytes` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-mut-src-unsized.rs:16:35 - | -16 | const SRC_UNSIZED: &mut [u8; 1] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | doesn't have a size known at compile-time - | required by a bound introduced by this call - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AssertSrcIsAsBytes` - --> tests/ui-nightly/transmute-mut-src-unsized.rs:16:35 - | -16 | const SRC_UNSIZED: &mut [u8; 1] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertSrcIsAsBytes` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-mut-src-unsized.rs:16:35 - | -16 | const SRC_UNSIZED: &mut [u8; 1] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AssertSrcIsAsBytes` - --> tests/ui-nightly/transmute-mut-src-unsized.rs:16:35 - | -16 | const SRC_UNSIZED: &mut [u8; 1] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertSrcIsAsBytes` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-mut-src-unsized.rs:16:35 - | -16 | const SRC_UNSIZED: &mut [u8; 1] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` - = note: all local variables must have a statically known size - = help: unsized locals are gated as an unstable feature - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-mut-src-unsized.rs:16:35 - | -16 | const SRC_UNSIZED: &mut [u8; 1] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AlignOf::<T>::into_t` - --> src/macro_util.rs - | - | impl<T> AlignOf<T> { - | ^ required by this bound in `AlignOf::<T>::into_t` - | #[inline(never)] // Make `missing_inline_in_public_items` happy. - | pub fn into_t(self) -> T { - | ------ required by a bound in this associated function - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-mut-src-unsized.rs:16:35 - | -16 | const SRC_UNSIZED: &mut [u8; 1] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` - = note: the left-hand-side of an assignment must have a statically known size - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-mut-src-unsized.rs:16:35 - | -16 | const SRC_UNSIZED: &mut [u8; 1] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by an implicit `Sized` bound in `AlignOf` - --> src/macro_util.rs - | - | pub struct AlignOf<T> { - | ^ required by the implicit `Sized` requirement on this type parameter in `AlignOf` - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-mut-src-unsized.rs:16:35 - | -16 | const SRC_UNSIZED: &mut [u8; 1] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by an implicit `Sized` bound in `MaxAlignsOf` - --> src/macro_util.rs - | - | pub union MaxAlignsOf<T, U> { - | ^ required by the implicit `Sized` requirement on this type parameter in `MaxAlignsOf` - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-mut-src-unsized.rs:16:35 - | -16 | const SRC_UNSIZED: &mut [u8; 1] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by an implicit `Sized` bound in `AlignOf` - --> src/macro_util.rs - | - | pub struct AlignOf<T> { - | ^ required by the implicit `Sized` requirement on this type parameter in `AlignOf` - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-mut-src-unsized.rs:16:35 - | -16 | const SRC_UNSIZED: &mut [u8; 1] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | doesn't have a size known at compile-time - | required by a bound introduced by this call - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by an implicit `Sized` bound in `transmute_mut` - --> src/macro_util.rs - | - | pub unsafe fn transmute_mut<'dst, 'src: 'dst, Src: 'src, Dst: 'dst>( - | ^^^ required by the implicit `Sized` requirement on this type parameter in `transmute_mut` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ptr-to-usize.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ptr-to-usize.rs deleted file mode 100644 index 5af8859..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ptr-to-usize.rs +++ /dev/null
@@ -1,20 +0,0 @@ -// Copyright 2022 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute; - -fn main() {} - -// It is unclear whether we can or should support this transmutation, especially -// in a const context. This test ensures that even if such a transmutation -// becomes valid due to the requisite implementations of `FromBytes` being -// added, that we re-examine whether it should specifically be valid in a const -// context. -const POINTER_VALUE: usize = transmute!(&0usize as *const usize);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ptr-to-usize.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ptr-to-usize.stderr deleted file mode 100644 index 2fcba2fb..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ptr-to-usize.stderr +++ /dev/null
@@ -1,30 +0,0 @@ -error[E0277]: the trait bound `*const usize: AsBytes` is not satisfied - --> tests/ui-nightly/transmute-ptr-to-usize.rs:20:30 - | -20 | const POINTER_VALUE: usize = transmute!(&0usize as *const usize); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | the trait `AsBytes` is not implemented for `*const usize` - | required by a bound introduced by this call - | - = help: the trait `AsBytes` is implemented for `usize` -note: required by a bound in `AssertIsAsBytes` - --> tests/ui-nightly/transmute-ptr-to-usize.rs:20:30 - | -20 | const POINTER_VALUE: usize = transmute!(&0usize as *const usize); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertIsAsBytes` - = note: this error originates in the macro `transmute` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `*const usize: AsBytes` is not satisfied - --> tests/ui-nightly/transmute-ptr-to-usize.rs:20:30 - | -20 | const POINTER_VALUE: usize = transmute!(&0usize as *const usize); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `AsBytes` is not implemented for `*const usize` - | - = help: the trait `AsBytes` is implemented for `usize` -note: required by a bound in `AssertIsAsBytes` - --> tests/ui-nightly/transmute-ptr-to-usize.rs:20:30 - | -20 | const POINTER_VALUE: usize = transmute!(&0usize as *const usize); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertIsAsBytes` - = note: this error originates in the macro `transmute` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-alignment-increase.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-alignment-increase.rs deleted file mode 100644 index bf1988c6..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-alignment-increase.rs +++ /dev/null
@@ -1,19 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -include!("../../zerocopy-derive/tests/util.rs"); - -extern crate zerocopy; - -use zerocopy::transmute_ref; - -fn main() {} - -// `transmute_ref!` does not support transmuting from a type of smaller -// alignment to one of larger alignment. -const INCREASE_ALIGNMENT: &AU16 = transmute_ref!(&[0u8; 2]);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-alignment-increase.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-alignment-increase.stderr deleted file mode 100644 index 1cef246..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-alignment-increase.stderr +++ /dev/null
@@ -1,9 +0,0 @@ -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-nightly/transmute-ref-alignment-increase.rs:19:35 - | -19 | const INCREASE_ALIGNMENT: &AU16 = transmute_ref!(&[0u8; 2]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: source type: `AlignOf<[u8; 2]>` (8 bits) - = note: target type: `MaxAlignsOf<[u8; 2], AU16>` (16 bits) - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-dst-generic.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-dst-generic.rs deleted file mode 100644 index bf4a0f9a..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-dst-generic.rs +++ /dev/null
@@ -1,18 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::{transmute_ref, FromBytes}; - -fn main() {} - -fn transmute_ref<T: FromBytes>(u: &u8) -> &T { - // `transmute_ref!` requires the destination type to be concrete. - transmute_ref!(u) -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-dst-generic.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-dst-generic.stderr deleted file mode 100644 index 4c94d501..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-dst-generic.stderr +++ /dev/null
@@ -1,19 +0,0 @@ -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-nightly/transmute-ref-dst-generic.rs:17:5 - | -17 | transmute_ref!(u) - | ^^^^^^^^^^^^^^^^^ - | - = note: source type: `u8` (8 bits) - = note: target type: `T` (this type does not have a fixed size) - = note: this error originates in the macro `$crate::assert_size_eq` which comes from the expansion of the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-nightly/transmute-ref-dst-generic.rs:17:5 - | -17 | transmute_ref!(u) - | ^^^^^^^^^^^^^^^^^ - | - = note: source type: `AlignOf<u8>` (8 bits) - = note: target type: `MaxAlignsOf<u8, T>` (size can vary because of T) - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-dst-mutable.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-dst-mutable.rs deleted file mode 100644 index fa0e6e4..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-dst-mutable.rs +++ /dev/null
@@ -1,19 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_ref; - -fn main() {} - -fn ref_dst_mutable() { - // `transmute_ref!` requires that its destination type be an immutable - // reference. - let _: &mut u8 = transmute_ref!(&0u8); -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-dst-mutable.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-dst-mutable.stderr deleted file mode 100644 index 0cbdd176..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-dst-mutable.stderr +++ /dev/null
@@ -1,29 +0,0 @@ -error[E0308]: mismatched types - --> tests/ui-nightly/transmute-ref-dst-mutable.rs:18:22 - | -18 | let _: &mut u8 = transmute_ref!(&0u8); - | ^^^^^^^^^^^^^^^^^^^^ types differ in mutability - | - = note: expected mutable reference `&mut u8` - found reference `&_` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0308]: mismatched types - --> tests/ui-nightly/transmute-ref-dst-mutable.rs:18:22 - | -18 | let _: &mut u8 = transmute_ref!(&0u8); - | ^^^^^^^^^^^^^^^^^^^^ types differ in mutability - | - = note: expected mutable reference `&mut u8` - found reference `&_` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0308]: mismatched types - --> tests/ui-nightly/transmute-ref-dst-mutable.rs:18:22 - | -18 | let _: &mut u8 = transmute_ref!(&0u8); - | ^^^^^^^^^^^^^^^^^^^^ types differ in mutability - | - = note: expected mutable reference `&mut u8` - found reference `&_` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-dst-not-a-reference.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-dst-not-a-reference.rs deleted file mode 100644 index de55f9a..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-dst-not-a-reference.rs +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_ref; - -fn main() {} - -// `transmute_ref!` does not support transmuting into a non-reference -// destination type. -const DST_NOT_A_REFERENCE: usize = transmute_ref!(&0u8);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-dst-not-a-reference.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-dst-not-a-reference.stderr deleted file mode 100644 index 847d5473..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-dst-not-a-reference.stderr +++ /dev/null
@@ -1,29 +0,0 @@ -error[E0308]: mismatched types - --> tests/ui-nightly/transmute-ref-dst-not-a-reference.rs:17:36 - | -17 | const DST_NOT_A_REFERENCE: usize = transmute_ref!(&0u8); - | ^^^^^^^^^^^^^^^^^^^^ expected `usize`, found `&_` - | - = note: expected type `usize` - found reference `&_` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0308]: mismatched types - --> tests/ui-nightly/transmute-ref-dst-not-a-reference.rs:17:36 - | -17 | const DST_NOT_A_REFERENCE: usize = transmute_ref!(&0u8); - | ^^^^^^^^^^^^^^^^^^^^ expected `usize`, found `&_` - | - = note: expected type `usize` - found reference `&_` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0308]: mismatched types - --> tests/ui-nightly/transmute-ref-dst-not-a-reference.rs:17:36 - | -17 | const DST_NOT_A_REFERENCE: usize = transmute_ref!(&0u8); - | ^^^^^^^^^^^^^^^^^^^^ expected `usize`, found `&_` - | - = note: expected type `usize` - found reference `&_` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-dst-not-frombytes.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-dst-not-frombytes.rs deleted file mode 100644 index d81f64d..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-dst-not-frombytes.rs +++ /dev/null
@@ -1,18 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -include!("../../zerocopy-derive/tests/util.rs"); - -extern crate zerocopy; - -use zerocopy::transmute_ref; - -fn main() {} - -// `transmute_ref` requires that the destination type implements `FromBytes` -const DST_NOT_FROM_BYTES: &NotZerocopy = transmute_ref!(&AU16(0));
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-dst-not-frombytes.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-dst-not-frombytes.stderr deleted file mode 100644 index a09f9966..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-dst-not-frombytes.stderr +++ /dev/null
@@ -1,25 +0,0 @@ -error[E0277]: the trait bound `NotZerocopy: FromBytes` is not satisfied - --> tests/ui-nightly/transmute-ref-dst-not-frombytes.rs:18:42 - | -18 | const DST_NOT_FROM_BYTES: &NotZerocopy = transmute_ref!(&AU16(0)); - | ^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | the trait `FromBytes` is not implemented for `NotZerocopy` - | required by a bound introduced by this call - | - = help: the following other types implement trait `FromBytes`: - () - AU16 - F32<O> - F64<O> - I128<O> - I16<O> - I32<O> - I64<O> - and $N others -note: required by a bound in `AssertIsFromBytes` - --> tests/ui-nightly/transmute-ref-dst-not-frombytes.rs:18:42 - | -18 | const DST_NOT_FROM_BYTES: &NotZerocopy = transmute_ref!(&AU16(0)); - | ^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertIsFromBytes` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-dst-unsized.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-dst-unsized.rs deleted file mode 100644 index 625f1fa..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-dst-unsized.rs +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_ref; - -fn main() {} - -// `transmute_ref!` does not support transmuting into an unsized destination -// type. -const DST_UNSIZED: &[u8] = transmute_ref!(&[0u8; 1]);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-dst-unsized.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-dst-unsized.stderr deleted file mode 100644 index 1e97b5b0e..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-dst-unsized.stderr +++ /dev/null
@@ -1,69 +0,0 @@ -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-ref-dst-unsized.rs:17:28 - | -17 | const DST_UNSIZED: &[u8] = transmute_ref!(&[0u8; 1]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | doesn't have a size known at compile-time - | required by a bound introduced by this call - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AssertIsFromBytes` - --> tests/ui-nightly/transmute-ref-dst-unsized.rs:17:28 - | -17 | const DST_UNSIZED: &[u8] = transmute_ref!(&[0u8; 1]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertIsFromBytes` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-ref-dst-unsized.rs:17:28 - | -17 | const DST_UNSIZED: &[u8] = transmute_ref!(&[0u8; 1]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` - = note: all local variables must have a statically known size - = help: unsized locals are gated as an unstable feature - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-ref-dst-unsized.rs:17:28 - | -17 | const DST_UNSIZED: &[u8] = transmute_ref!(&[0u8; 1]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by an implicit `Sized` bound in `MaxAlignsOf` - --> src/macro_util.rs - | - | pub union MaxAlignsOf<T, U> { - | ^ required by the implicit `Sized` requirement on this type parameter in `MaxAlignsOf` - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-ref-dst-unsized.rs:17:28 - | -17 | const DST_UNSIZED: &[u8] = transmute_ref!(&[0u8; 1]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by an implicit `Sized` bound in `transmute` - --> $RUST/core/src/intrinsics.rs - | - | pub fn transmute<Src, Dst>(src: Src) -> Dst; - | ^^^ required by the implicit `Sized` requirement on this type parameter in `transmute` - = note: this error originates in the macro `$crate::assert_size_eq` which comes from the expansion of the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-ref-dst-unsized.rs:17:28 - | -17 | const DST_UNSIZED: &[u8] = transmute_ref!(&[0u8; 1]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by an implicit `Sized` bound in `transmute_ref` - --> src/macro_util.rs - | - | pub const unsafe fn transmute_ref<'dst, 'src: 'dst, Src: 'src, Dst: 'dst>( - | ^^^ required by the implicit `Sized` requirement on this type parameter in `transmute_ref` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-illegal-lifetime.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-illegal-lifetime.rs deleted file mode 100644 index 8dd191e..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-illegal-lifetime.rs +++ /dev/null
@@ -1,15 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -fn main() {} - -fn increase_lifetime() { - let x = 0u64; - // It is illegal to increase the lifetime scope. - let _: &'static u64 = zerocopy::transmute_ref!(&x); -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-illegal-lifetime.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-illegal-lifetime.stderr deleted file mode 100644 index e16a557..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-illegal-lifetime.stderr +++ /dev/null
@@ -1,12 +0,0 @@ -error[E0597]: `x` does not live long enough - --> tests/ui-nightly/transmute-ref-illegal-lifetime.rs:14:52 - | -12 | let x = 0u64; - | - binding `x` declared here -13 | // It is illegal to increase the lifetime scope. -14 | let _: &'static u64 = zerocopy::transmute_ref!(&x); - | ------------ ^^ borrowed value does not live long enough - | | - | type annotation requires that `x` is borrowed for `'static` -15 | } - | - `x` dropped here while still borrowed
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-size-decrease.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-size-decrease.rs deleted file mode 100644 index 1d66a54..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-size-decrease.rs +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_ref; - -fn main() {} - -// Although this is not a soundness requirement, we currently require that the -// size of the destination type is not smaller than the size of the source type. -const DECREASE_SIZE: &u8 = transmute_ref!(&[0u8; 2]);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-size-decrease.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-size-decrease.stderr deleted file mode 100644 index 793ecc5..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-size-decrease.stderr +++ /dev/null
@@ -1,9 +0,0 @@ -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-nightly/transmute-ref-size-decrease.rs:17:28 - | -17 | const DECREASE_SIZE: &u8 = transmute_ref!(&[0u8; 2]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: source type: `[u8; 2]` (16 bits) - = note: target type: `u8` (8 bits) - = note: this error originates in the macro `$crate::assert_size_eq` which comes from the expansion of the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-size-increase.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-size-increase.rs deleted file mode 100644 index cdca560b..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-size-increase.rs +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_ref; - -fn main() {} - -// `transmute_ref!` does not support transmuting from a smaller type to a larger -// one. -const INCREASE_SIZE: &[u8; 2] = transmute_ref!(&0u8);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-size-increase.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-size-increase.stderr deleted file mode 100644 index 40c69f63..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-size-increase.stderr +++ /dev/null
@@ -1,9 +0,0 @@ -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-nightly/transmute-ref-size-increase.rs:17:33 - | -17 | const INCREASE_SIZE: &[u8; 2] = transmute_ref!(&0u8); - | ^^^^^^^^^^^^^^^^^^^^ - | - = note: source type: `u8` (8 bits) - = note: target type: `[u8; 2]` (16 bits) - = note: this error originates in the macro `$crate::assert_size_eq` which comes from the expansion of the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-src-dst-generic.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-src-dst-generic.rs deleted file mode 100644 index 409d785b..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-src-dst-generic.rs +++ /dev/null
@@ -1,19 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::{transmute_ref, AsBytes, FromBytes}; - -fn main() {} - -fn transmute_ref<T: AsBytes, U: FromBytes>(t: &T) -> &U { - // `transmute_ref!` requires the source and destination types to be - // concrete. - transmute_ref!(t) -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-src-dst-generic.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-src-dst-generic.stderr deleted file mode 100644 index 6a3a4fd..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-src-dst-generic.stderr +++ /dev/null
@@ -1,19 +0,0 @@ -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-nightly/transmute-ref-src-dst-generic.rs:18:5 - | -18 | transmute_ref!(t) - | ^^^^^^^^^^^^^^^^^ - | - = note: source type: `T` (this type does not have a fixed size) - = note: target type: `U` (this type does not have a fixed size) - = note: this error originates in the macro `$crate::assert_size_eq` which comes from the expansion of the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-nightly/transmute-ref-src-dst-generic.rs:18:5 - | -18 | transmute_ref!(t) - | ^^^^^^^^^^^^^^^^^ - | - = note: source type: `AlignOf<T>` (size can vary because of T) - = note: target type: `MaxAlignsOf<T, U>` (size can vary because of T) - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-src-dst-not-references.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-src-dst-not-references.rs deleted file mode 100644 index 114e917..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-src-dst-not-references.rs +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_ref; - -fn main() {} - -// `transmute_ref!` does not support transmuting between non-reference source -// and destination types. -const SRC_DST_NOT_REFERENCES: usize = transmute_ref!(0usize);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-src-dst-not-references.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-src-dst-not-references.stderr deleted file mode 100644 index 94a73872..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-src-dst-not-references.stderr +++ /dev/null
@@ -1,85 +0,0 @@ -error[E0308]: mismatched types - --> tests/ui-nightly/transmute-ref-src-dst-not-references.rs:17:54 - | -17 | const SRC_DST_NOT_REFERENCES: usize = transmute_ref!(0usize); - | ---------------^^^^^^- - | | | - | | expected `&_`, found `usize` - | expected due to this - | - = note: expected reference `&_` - found type `usize` -help: consider borrowing here - | -17 | const SRC_DST_NOT_REFERENCES: usize = transmute_ref!(&0usize); - | + - -error[E0308]: mismatched types - --> tests/ui-nightly/transmute-ref-src-dst-not-references.rs:17:39 - | -17 | const SRC_DST_NOT_REFERENCES: usize = transmute_ref!(0usize); - | ^^^^^^^^^^^^^^^^^^^^^^ expected `usize`, found `&_` - | - = note: expected type `usize` - found reference `&_` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0308]: mismatched types - --> tests/ui-nightly/transmute-ref-src-dst-not-references.rs:17:39 - | -17 | const SRC_DST_NOT_REFERENCES: usize = transmute_ref!(0usize); - | ^^^^^^^^^^^^^^^^^^^^^^ expected `usize`, found `&_` - | - = note: expected type `usize` - found reference `&_` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0308]: mismatched types - --> tests/ui-nightly/transmute-ref-src-dst-not-references.rs:17:39 - | -17 | const SRC_DST_NOT_REFERENCES: usize = transmute_ref!(0usize); - | ^^^^^^^^^^^^^^^^^^^^^^ expected `usize`, found `&_` - | - = note: expected type `usize` - found reference `&_` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -warning: this function depends on never type fallback being `()` - --> tests/ui-nightly/transmute-ref-src-dst-not-references.rs:17:1 - | -17 | const SRC_DST_NOT_REFERENCES: usize = transmute_ref!(0usize); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - = note: for more information, see issue #123748 <https://github.com/rust-lang/rust/issues/123748> - = help: specify the types explicitly -note: in edition 2024, the requirement `!: AsBytes` will fail - --> tests/ui-nightly/transmute-ref-src-dst-not-references.rs:17:39 - | -17 | const SRC_DST_NOT_REFERENCES: usize = transmute_ref!(0usize); - | ^^^^^^^^^^^^^^^^^^^^^^ - = note: `#[warn(dependency_on_unit_never_type_fallback)]` on by default - = note: this warning originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -warning: never type fallback affects this call to an `unsafe` function - --> tests/ui-nightly/transmute-ref-src-dst-not-references.rs:17:39 - | -17 | const SRC_DST_NOT_REFERENCES: usize = transmute_ref!(0usize); - | ^^^^^^^^^^^^^^^^^^^^^^ - | - = warning: this will change its meaning in a future release! - = note: for more information, see issue #123748 <https://github.com/rust-lang/rust/issues/123748> - = help: specify the type explicitly - = note: `#[warn(never_type_fallback_flowing_into_unsafe)]` on by default - = note: this warning originates in the macro `$crate::assert_size_eq` which comes from the expansion of the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -warning: never type fallback affects this call to an `unsafe` function - --> tests/ui-nightly/transmute-ref-src-dst-not-references.rs:17:39 - | -17 | const SRC_DST_NOT_REFERENCES: usize = transmute_ref!(0usize); - | ^^^^^^^^^^^^^^^^^^^^^^ - | - = warning: this will change its meaning in a future release! - = note: for more information, see issue #123748 <https://github.com/rust-lang/rust/issues/123748> - = help: specify the type explicitly - = note: this warning originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-src-dst-unsized.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-src-dst-unsized.rs deleted file mode 100644 index 6bfe7ff..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-src-dst-unsized.rs +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_ref; - -fn main() {} - -// `transmute_ref!` does not support transmuting between unsized source and -// destination types. -const SRC_DST_UNSIZED: &[u8] = transmute_ref!(&[0u8][..]);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-src-dst-unsized.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-src-dst-unsized.stderr deleted file mode 100644 index cb1e443..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-src-dst-unsized.stderr +++ /dev/null
@@ -1,183 +0,0 @@ -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-ref-src-dst-unsized.rs:17:32 - | -17 | const SRC_DST_UNSIZED: &[u8] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | doesn't have a size known at compile-time - | required by a bound introduced by this call - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AssertIsAsBytes` - --> tests/ui-nightly/transmute-ref-src-dst-unsized.rs:17:32 - | -17 | const SRC_DST_UNSIZED: &[u8] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertIsAsBytes` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-ref-src-dst-unsized.rs:17:32 - | -17 | const SRC_DST_UNSIZED: &[u8] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AssertIsAsBytes` - --> tests/ui-nightly/transmute-ref-src-dst-unsized.rs:17:32 - | -17 | const SRC_DST_UNSIZED: &[u8] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertIsAsBytes` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-ref-src-dst-unsized.rs:17:32 - | -17 | const SRC_DST_UNSIZED: &[u8] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | doesn't have a size known at compile-time - | required by a bound introduced by this call - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AssertIsFromBytes` - --> tests/ui-nightly/transmute-ref-src-dst-unsized.rs:17:32 - | -17 | const SRC_DST_UNSIZED: &[u8] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertIsFromBytes` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-ref-src-dst-unsized.rs:17:32 - | -17 | const SRC_DST_UNSIZED: &[u8] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` - = note: all local variables must have a statically known size - = help: unsized locals are gated as an unstable feature - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-ref-src-dst-unsized.rs:17:32 - | -17 | const SRC_DST_UNSIZED: &[u8] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AlignOf::<T>::into_t` - --> src/macro_util.rs - | - | impl<T> AlignOf<T> { - | ^ required by this bound in `AlignOf::<T>::into_t` - | #[inline(never)] // Make `missing_inline_in_public_items` happy. - | pub fn into_t(self) -> T { - | ------ required by a bound in this associated function - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-ref-src-dst-unsized.rs:17:32 - | -17 | const SRC_DST_UNSIZED: &[u8] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` - = note: the left-hand-side of an assignment must have a statically known size - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-ref-src-dst-unsized.rs:17:32 - | -17 | const SRC_DST_UNSIZED: &[u8] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by an implicit `Sized` bound in `AlignOf` - --> src/macro_util.rs - | - | pub struct AlignOf<T> { - | ^ required by the implicit `Sized` requirement on this type parameter in `AlignOf` - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-ref-src-dst-unsized.rs:17:32 - | -17 | const SRC_DST_UNSIZED: &[u8] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by an implicit `Sized` bound in `MaxAlignsOf` - --> src/macro_util.rs - | - | pub union MaxAlignsOf<T, U> { - | ^ required by the implicit `Sized` requirement on this type parameter in `MaxAlignsOf` - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-ref-src-dst-unsized.rs:17:32 - | -17 | const SRC_DST_UNSIZED: &[u8] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by an implicit `Sized` bound in `AlignOf` - --> src/macro_util.rs - | - | pub struct AlignOf<T> { - | ^ required by the implicit `Sized` requirement on this type parameter in `AlignOf` - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-ref-src-dst-unsized.rs:17:32 - | -17 | const SRC_DST_UNSIZED: &[u8] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` - = note: all local variables must have a statically known size - = help: unsized locals are gated as an unstable feature - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-ref-src-dst-unsized.rs:17:32 - | -17 | const SRC_DST_UNSIZED: &[u8] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by an implicit `Sized` bound in `transmute` - --> $RUST/core/src/intrinsics.rs - | - | pub fn transmute<Src, Dst>(src: Src) -> Dst; - | ^^^ required by the implicit `Sized` requirement on this type parameter in `transmute` - = note: this error originates in the macro `$crate::assert_size_eq` which comes from the expansion of the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-ref-src-dst-unsized.rs:17:32 - | -17 | const SRC_DST_UNSIZED: &[u8] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | doesn't have a size known at compile-time - | required by a bound introduced by this call - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by an implicit `Sized` bound in `transmute_ref` - --> src/macro_util.rs - | - | pub const unsafe fn transmute_ref<'dst, 'src: 'dst, Src: 'src, Dst: 'dst>( - | ^^^ required by the implicit `Sized` requirement on this type parameter in `transmute_ref` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-ref-src-dst-unsized.rs:17:32 - | -17 | const SRC_DST_UNSIZED: &[u8] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by an implicit `Sized` bound in `transmute_ref` - --> src/macro_util.rs - | - | pub const unsafe fn transmute_ref<'dst, 'src: 'dst, Src: 'src, Dst: 'dst>( - | ^^^ required by the implicit `Sized` requirement on this type parameter in `transmute_ref` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-src-generic.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-src-generic.rs deleted file mode 100644 index 010281c3..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-src-generic.rs +++ /dev/null
@@ -1,18 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::{transmute_ref, AsBytes}; - -fn main() {} - -fn transmute_ref<T: AsBytes>(t: &T) -> &u8 { - // `transmute_ref!` requires the source type to be concrete. - transmute_ref!(t) -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-src-generic.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-src-generic.stderr deleted file mode 100644 index a168f44..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-src-generic.stderr +++ /dev/null
@@ -1,19 +0,0 @@ -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-nightly/transmute-ref-src-generic.rs:17:5 - | -17 | transmute_ref!(t) - | ^^^^^^^^^^^^^^^^^ - | - = note: source type: `T` (this type does not have a fixed size) - = note: target type: `u8` (8 bits) - = note: this error originates in the macro `$crate::assert_size_eq` which comes from the expansion of the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-nightly/transmute-ref-src-generic.rs:17:5 - | -17 | transmute_ref!(t) - | ^^^^^^^^^^^^^^^^^ - | - = note: source type: `AlignOf<T>` (size can vary because of T) - = note: target type: `MaxAlignsOf<T, u8>` (size can vary because of T) - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-src-not-a-reference.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-src-not-a-reference.rs deleted file mode 100644 index 90661b3e..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-src-not-a-reference.rs +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_ref; - -fn main() {} - -// `transmute_ref!` does not support transmuting from a non-reference source -// type. -const SRC_NOT_A_REFERENCE: &u8 = transmute_ref!(0usize);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-src-not-a-reference.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-src-not-a-reference.stderr deleted file mode 100644 index 3418f21c..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-src-not-a-reference.stderr +++ /dev/null
@@ -1,55 +0,0 @@ -error[E0308]: mismatched types - --> tests/ui-nightly/transmute-ref-src-not-a-reference.rs:17:49 - | -17 | const SRC_NOT_A_REFERENCE: &u8 = transmute_ref!(0usize); - | ---------------^^^^^^- - | | | - | | expected `&_`, found `usize` - | expected due to this - | - = note: expected reference `&_` - found type `usize` -help: consider borrowing here - | -17 | const SRC_NOT_A_REFERENCE: &u8 = transmute_ref!(&0usize); - | + - -warning: this function depends on never type fallback being `()` - --> tests/ui-nightly/transmute-ref-src-not-a-reference.rs:17:1 - | -17 | const SRC_NOT_A_REFERENCE: &u8 = transmute_ref!(0usize); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - = note: for more information, see issue #123748 <https://github.com/rust-lang/rust/issues/123748> - = help: specify the types explicitly -note: in edition 2024, the requirement `!: AsBytes` will fail - --> tests/ui-nightly/transmute-ref-src-not-a-reference.rs:17:34 - | -17 | const SRC_NOT_A_REFERENCE: &u8 = transmute_ref!(0usize); - | ^^^^^^^^^^^^^^^^^^^^^^ - = note: `#[warn(dependency_on_unit_never_type_fallback)]` on by default - = note: this warning originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -warning: never type fallback affects this call to an `unsafe` function - --> tests/ui-nightly/transmute-ref-src-not-a-reference.rs:17:34 - | -17 | const SRC_NOT_A_REFERENCE: &u8 = transmute_ref!(0usize); - | ^^^^^^^^^^^^^^^^^^^^^^ - | - = warning: this will change its meaning in a future release! - = note: for more information, see issue #123748 <https://github.com/rust-lang/rust/issues/123748> - = help: specify the type explicitly - = note: `#[warn(never_type_fallback_flowing_into_unsafe)]` on by default - = note: this warning originates in the macro `$crate::assert_size_eq` which comes from the expansion of the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -warning: never type fallback affects this call to an `unsafe` function - --> tests/ui-nightly/transmute-ref-src-not-a-reference.rs:17:34 - | -17 | const SRC_NOT_A_REFERENCE: &u8 = transmute_ref!(0usize); - | ^^^^^^^^^^^^^^^^^^^^^^ - | - = warning: this will change its meaning in a future release! - = note: for more information, see issue #123748 <https://github.com/rust-lang/rust/issues/123748> - = help: specify the type explicitly - = note: this warning originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-src-not-asbytes.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-src-not-asbytes.rs deleted file mode 100644 index 6ab19f3c..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-src-not-asbytes.rs +++ /dev/null
@@ -1,18 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -include!("../../zerocopy-derive/tests/util.rs"); - -extern crate zerocopy; - -use zerocopy::transmute_ref; - -fn main() {} - -// `transmute_ref` requires that the source type implements `AsBytes` -const SRC_NOT_AS_BYTES: &AU16 = transmute_ref!(&NotZerocopy(AU16(0)));
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-src-not-asbytes.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-src-not-asbytes.stderr deleted file mode 100644 index 5ae6b5a..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-src-not-asbytes.stderr +++ /dev/null
@@ -1,48 +0,0 @@ -error[E0277]: the trait bound `NotZerocopy<AU16>: AsBytes` is not satisfied - --> tests/ui-nightly/transmute-ref-src-not-asbytes.rs:18:33 - | -18 | const SRC_NOT_AS_BYTES: &AU16 = transmute_ref!(&NotZerocopy(AU16(0))); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | the trait `AsBytes` is not implemented for `NotZerocopy<AU16>` - | required by a bound introduced by this call - | - = help: the following other types implement trait `AsBytes`: - () - AU16 - F32<O> - F64<O> - I128<O> - I16<O> - I32<O> - I64<O> - and $N others -note: required by a bound in `AssertIsAsBytes` - --> tests/ui-nightly/transmute-ref-src-not-asbytes.rs:18:33 - | -18 | const SRC_NOT_AS_BYTES: &AU16 = transmute_ref!(&NotZerocopy(AU16(0))); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertIsAsBytes` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `NotZerocopy<AU16>: AsBytes` is not satisfied - --> tests/ui-nightly/transmute-ref-src-not-asbytes.rs:18:33 - | -18 | const SRC_NOT_AS_BYTES: &AU16 = transmute_ref!(&NotZerocopy(AU16(0))); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `AsBytes` is not implemented for `NotZerocopy<AU16>` - | - = help: the following other types implement trait `AsBytes`: - () - AU16 - F32<O> - F64<O> - I128<O> - I16<O> - I32<O> - I64<O> - and $N others -note: required by a bound in `AssertIsAsBytes` - --> tests/ui-nightly/transmute-ref-src-not-asbytes.rs:18:33 - | -18 | const SRC_NOT_AS_BYTES: &AU16 = transmute_ref!(&NotZerocopy(AU16(0))); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertIsAsBytes` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-src-unsized.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-src-unsized.rs deleted file mode 100644 index 14e72b4..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-src-unsized.rs +++ /dev/null
@@ -1,16 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_ref; - -fn main() {} - -// `transmute_ref!` does not support transmuting from an unsized source type. -const SRC_UNSIZED: &[u8; 1] = transmute_ref!(&[0u8][..]);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-src-unsized.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-src-unsized.stderr deleted file mode 100644 index 3ce31ca..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-ref-src-unsized.stderr +++ /dev/null
@@ -1,127 +0,0 @@ -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-ref-src-unsized.rs:16:31 - | -16 | const SRC_UNSIZED: &[u8; 1] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | doesn't have a size known at compile-time - | required by a bound introduced by this call - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AssertIsAsBytes` - --> tests/ui-nightly/transmute-ref-src-unsized.rs:16:31 - | -16 | const SRC_UNSIZED: &[u8; 1] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertIsAsBytes` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-ref-src-unsized.rs:16:31 - | -16 | const SRC_UNSIZED: &[u8; 1] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AssertIsAsBytes` - --> tests/ui-nightly/transmute-ref-src-unsized.rs:16:31 - | -16 | const SRC_UNSIZED: &[u8; 1] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertIsAsBytes` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-ref-src-unsized.rs:16:31 - | -16 | const SRC_UNSIZED: &[u8; 1] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` - = note: all local variables must have a statically known size - = help: unsized locals are gated as an unstable feature - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-ref-src-unsized.rs:16:31 - | -16 | const SRC_UNSIZED: &[u8; 1] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AlignOf::<T>::into_t` - --> src/macro_util.rs - | - | impl<T> AlignOf<T> { - | ^ required by this bound in `AlignOf::<T>::into_t` - | #[inline(never)] // Make `missing_inline_in_public_items` happy. - | pub fn into_t(self) -> T { - | ------ required by a bound in this associated function - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-ref-src-unsized.rs:16:31 - | -16 | const SRC_UNSIZED: &[u8; 1] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` - = note: the left-hand-side of an assignment must have a statically known size - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-ref-src-unsized.rs:16:31 - | -16 | const SRC_UNSIZED: &[u8; 1] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by an implicit `Sized` bound in `AlignOf` - --> src/macro_util.rs - | - | pub struct AlignOf<T> { - | ^ required by the implicit `Sized` requirement on this type parameter in `AlignOf` - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-ref-src-unsized.rs:16:31 - | -16 | const SRC_UNSIZED: &[u8; 1] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by an implicit `Sized` bound in `MaxAlignsOf` - --> src/macro_util.rs - | - | pub union MaxAlignsOf<T, U> { - | ^ required by the implicit `Sized` requirement on this type parameter in `MaxAlignsOf` - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-ref-src-unsized.rs:16:31 - | -16 | const SRC_UNSIZED: &[u8; 1] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by an implicit `Sized` bound in `AlignOf` - --> src/macro_util.rs - | - | pub struct AlignOf<T> { - | ^ required by the implicit `Sized` requirement on this type parameter in `AlignOf` - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/transmute-ref-src-unsized.rs:16:31 - | -16 | const SRC_UNSIZED: &[u8; 1] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | doesn't have a size known at compile-time - | required by a bound introduced by this call - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by an implicit `Sized` bound in `transmute_ref` - --> src/macro_util.rs - | - | pub const unsafe fn transmute_ref<'dst, 'src: 'dst, Src: 'src, Dst: 'dst>( - | ^^^ required by the implicit `Sized` requirement on this type parameter in `transmute_ref` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-size-decrease.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-size-decrease.rs deleted file mode 100644 index 1d56831f..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-size-decrease.rs +++ /dev/null
@@ -1,19 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -include!("../../zerocopy-derive/tests/util.rs"); - -extern crate zerocopy; - -use zerocopy::transmute; - -fn main() {} - -// Although this is not a soundness requirement, we currently require that the -// size of the destination type is not smaller than the size of the source type. -const DECREASE_SIZE: u8 = transmute!(AU16(0));
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-size-decrease.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-size-decrease.stderr deleted file mode 100644 index 83742d7..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-size-decrease.stderr +++ /dev/null
@@ -1,9 +0,0 @@ -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-nightly/transmute-size-decrease.rs:19:27 - | -19 | const DECREASE_SIZE: u8 = transmute!(AU16(0)); - | ^^^^^^^^^^^^^^^^^^^ - | - = note: source type: `AU16` (16 bits) - = note: target type: `u8` (8 bits) - = note: this error originates in the macro `transmute` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-size-increase.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-size-increase.rs deleted file mode 100644 index 32f9363..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-size-increase.rs +++ /dev/null
@@ -1,19 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -include!("../../zerocopy-derive/tests/util.rs"); - -extern crate zerocopy; - -use zerocopy::transmute; - -fn main() {} - -// `transmute!` does not support transmuting from a smaller type to a larger -// one. -const INCREASE_SIZE: AU16 = transmute!(0u8);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-size-increase.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-size-increase.stderr deleted file mode 100644 index 230bb17a..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-size-increase.stderr +++ /dev/null
@@ -1,9 +0,0 @@ -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-nightly/transmute-size-increase.rs:19:29 - | -19 | const INCREASE_SIZE: AU16 = transmute!(0u8); - | ^^^^^^^^^^^^^^^ - | - = note: source type: `u8` (8 bits) - = note: target type: `AU16` (16 bits) - = note: this error originates in the macro `transmute` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-src-not-asbytes.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-src-not-asbytes.rs deleted file mode 100644 index dd73021..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-src-not-asbytes.rs +++ /dev/null
@@ -1,18 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -include!("../../zerocopy-derive/tests/util.rs"); - -extern crate zerocopy; - -use zerocopy::transmute; - -fn main() {} - -// `transmute` requires that the source type implements `AsBytes` -const SRC_NOT_AS_BYTES: AU16 = transmute!(NotZerocopy(AU16(0)));
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-src-not-asbytes.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-src-not-asbytes.stderr deleted file mode 100644 index 20f1b18..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-nightly/transmute-src-not-asbytes.stderr +++ /dev/null
@@ -1,48 +0,0 @@ -error[E0277]: the trait bound `NotZerocopy<AU16>: AsBytes` is not satisfied - --> tests/ui-nightly/transmute-src-not-asbytes.rs:18:32 - | -18 | const SRC_NOT_AS_BYTES: AU16 = transmute!(NotZerocopy(AU16(0))); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | the trait `AsBytes` is not implemented for `NotZerocopy<AU16>` - | required by a bound introduced by this call - | - = help: the following other types implement trait `AsBytes`: - () - AU16 - F32<O> - F64<O> - I128<O> - I16<O> - I32<O> - I64<O> - and $N others -note: required by a bound in `AssertIsAsBytes` - --> tests/ui-nightly/transmute-src-not-asbytes.rs:18:32 - | -18 | const SRC_NOT_AS_BYTES: AU16 = transmute!(NotZerocopy(AU16(0))); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertIsAsBytes` - = note: this error originates in the macro `transmute` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `NotZerocopy<AU16>: AsBytes` is not satisfied - --> tests/ui-nightly/transmute-src-not-asbytes.rs:18:32 - | -18 | const SRC_NOT_AS_BYTES: AU16 = transmute!(NotZerocopy(AU16(0))); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `AsBytes` is not implemented for `NotZerocopy<AU16>` - | - = help: the following other types implement trait `AsBytes`: - () - AU16 - F32<O> - F64<O> - I128<O> - I16<O> - I32<O> - I64<O> - and $N others -note: required by a bound in `AssertIsAsBytes` - --> tests/ui-nightly/transmute-src-not-asbytes.rs:18:32 - | -18 | const SRC_NOT_AS_BYTES: AU16 = transmute!(NotZerocopy(AU16(0))); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertIsAsBytes` - = note: this error originates in the macro `transmute` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/include_value_not_from_bytes.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/include_value_not_from_bytes.rs deleted file mode 100644 index 45b6138f..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/include_value_not_from_bytes.rs +++ /dev/null
@@ -1,12 +0,0 @@ -// Copyright 2022 The Fuchsia Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#[macro_use] -extern crate zerocopy; - -fn main() {} - -// Should fail because `UnsafeCell<u32>: !FromBytes`. -const NOT_FROM_BYTES: core::cell::UnsafeCell<u32> = - include_value!("../../testdata/include_value/data");
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/include_value_not_from_bytes.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/include_value_not_from_bytes.stderr deleted file mode 100644 index 4bb4e24f..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/include_value_not_from_bytes.stderr +++ /dev/null
@@ -1,25 +0,0 @@ -error[E0277]: the trait bound `UnsafeCell<u32>: FromBytes` is not satisfied - --> tests/ui-stable/include_value_not_from_bytes.rs:12:5 - | -12 | include_value!("../../testdata/include_value/data"); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | the trait `FromBytes` is not implemented for `UnsafeCell<u32>` - | required by a bound introduced by this call - | - = help: the following other types implement trait `FromBytes`: - () - F32<O> - F64<O> - I128<O> - I16<O> - I32<O> - I64<O> - ManuallyDrop<T> - and $N others -note: required by a bound in `AssertIsFromBytes` - --> tests/ui-stable/include_value_not_from_bytes.rs:12:5 - | -12 | include_value!("../../testdata/include_value/data"); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertIsFromBytes` - = note: this error originates in the macro `$crate::transmute` which comes from the expansion of the macro `include_value` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/include_value_wrong_size.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/include_value_wrong_size.rs deleted file mode 100644 index d87b306..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/include_value_wrong_size.rs +++ /dev/null
@@ -1,11 +0,0 @@ -// Copyright 2022 The Fuchsia Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#[macro_use] -extern crate zerocopy; - -fn main() {} - -// Should fail because the file is 4 bytes long, not 8. -const WRONG_SIZE: u64 = include_value!("../../testdata/include_value/data");
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/include_value_wrong_size.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/include_value_wrong_size.stderr deleted file mode 100644 index 956d74c..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/include_value_wrong_size.stderr +++ /dev/null
@@ -1,9 +0,0 @@ -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-stable/include_value_wrong_size.rs:11:25 - | -11 | const WRONG_SIZE: u64 = include_value!("../../testdata/include_value/data"); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: source type: `[u8; 4]` (32 bits) - = note: target type: `u64` (64 bits) - = note: this error originates in the macro `$crate::transmute` which comes from the expansion of the macro `include_value` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/invalid-impls/invalid-impls.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/invalid-impls/invalid-impls.rs deleted file mode 100644 index ea96390..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/invalid-impls/invalid-impls.rs +++ /dev/null
@@ -1,29 +0,0 @@ -// Copyright 2022 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -// Since some macros from `macros.rs` are unused. -#![allow(unused)] - -extern crate zerocopy; -extern crate zerocopy_derive; - -include!("../../../src/macros.rs"); - -use zerocopy::*; -use zerocopy_derive::*; - -fn main() {} - -#[derive(FromZeroes, FromBytes, AsBytes, Unaligned)] -#[repr(transparent)] -struct Foo<T>(T); - -impl_or_verify!(T => FromZeroes for Foo<T>); -impl_or_verify!(T => FromBytes for Foo<T>); -impl_or_verify!(T => AsBytes for Foo<T>); -impl_or_verify!(T => Unaligned for Foo<T>);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/invalid-impls/invalid-impls.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/invalid-impls/invalid-impls.stderr deleted file mode 100644 index c7ba84b..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/invalid-impls/invalid-impls.stderr +++ /dev/null
@@ -1,107 +0,0 @@ -error[E0277]: the trait bound `T: zerocopy::FromZeroes` is not satisfied - --> tests/ui-stable/invalid-impls/invalid-impls.rs:26:37 - | -26 | impl_or_verify!(T => FromZeroes for Foo<T>); - | ^^^^^^ the trait `zerocopy::FromZeroes` is not implemented for `T`, which is required by `Foo<T>: zerocopy::FromZeroes` - | -note: required for `Foo<T>` to implement `zerocopy::FromZeroes` - --> tests/ui-stable/invalid-impls/invalid-impls.rs:22:10 - | -22 | #[derive(FromZeroes, FromBytes, AsBytes, Unaligned)] - | ^^^^^^^^^^ unsatisfied trait bound introduced in this `derive` macro -note: required by a bound in `_::Subtrait` - --> tests/ui-stable/invalid-impls/../../../src/macros.rs - | - | trait Subtrait: $trait {} - | ^^^^^^ required by this bound in `Subtrait` - | - ::: tests/ui-stable/invalid-impls/invalid-impls.rs:26:1 - | -26 | impl_or_verify!(T => FromZeroes for Foo<T>); - | ------------------------------------------- in this macro invocation - = note: this error originates in the derive macro `FromZeroes` which comes from the expansion of the macro `impl_or_verify` (in Nightly builds, run with -Z macro-backtrace for more info) -help: consider restricting type parameter `T` - | -26 | impl_or_verify!(T: zerocopy::FromZeroes => FromZeroes for Foo<T>); - | ++++++++++++++++++++++ - -error[E0277]: the trait bound `T: zerocopy::FromBytes` is not satisfied - --> tests/ui-stable/invalid-impls/invalid-impls.rs:27:36 - | -27 | impl_or_verify!(T => FromBytes for Foo<T>); - | ^^^^^^ the trait `zerocopy::FromBytes` is not implemented for `T`, which is required by `Foo<T>: zerocopy::FromBytes` - | -note: required for `Foo<T>` to implement `zerocopy::FromBytes` - --> tests/ui-stable/invalid-impls/invalid-impls.rs:22:22 - | -22 | #[derive(FromZeroes, FromBytes, AsBytes, Unaligned)] - | ^^^^^^^^^ unsatisfied trait bound introduced in this `derive` macro -note: required by a bound in `_::Subtrait` - --> tests/ui-stable/invalid-impls/../../../src/macros.rs - | - | trait Subtrait: $trait {} - | ^^^^^^ required by this bound in `Subtrait` - | - ::: tests/ui-stable/invalid-impls/invalid-impls.rs:27:1 - | -27 | impl_or_verify!(T => FromBytes for Foo<T>); - | ------------------------------------------ in this macro invocation - = note: this error originates in the derive macro `FromBytes` which comes from the expansion of the macro `impl_or_verify` (in Nightly builds, run with -Z macro-backtrace for more info) -help: consider restricting type parameter `T` - | -27 | impl_or_verify!(T: zerocopy::FromBytes => FromBytes for Foo<T>); - | +++++++++++++++++++++ - -error[E0277]: the trait bound `T: zerocopy::AsBytes` is not satisfied - --> tests/ui-stable/invalid-impls/invalid-impls.rs:28:34 - | -28 | impl_or_verify!(T => AsBytes for Foo<T>); - | ^^^^^^ the trait `zerocopy::AsBytes` is not implemented for `T`, which is required by `Foo<T>: zerocopy::AsBytes` - | -note: required for `Foo<T>` to implement `zerocopy::AsBytes` - --> tests/ui-stable/invalid-impls/invalid-impls.rs:22:33 - | -22 | #[derive(FromZeroes, FromBytes, AsBytes, Unaligned)] - | ^^^^^^^ unsatisfied trait bound introduced in this `derive` macro -note: required by a bound in `_::Subtrait` - --> tests/ui-stable/invalid-impls/../../../src/macros.rs - | - | trait Subtrait: $trait {} - | ^^^^^^ required by this bound in `Subtrait` - | - ::: tests/ui-stable/invalid-impls/invalid-impls.rs:28:1 - | -28 | impl_or_verify!(T => AsBytes for Foo<T>); - | ---------------------------------------- in this macro invocation - = note: this error originates in the derive macro `AsBytes` which comes from the expansion of the macro `impl_or_verify` (in Nightly builds, run with -Z macro-backtrace for more info) -help: consider restricting type parameter `T` - | -28 | impl_or_verify!(T: zerocopy::AsBytes => AsBytes for Foo<T>); - | +++++++++++++++++++ - -error[E0277]: the trait bound `T: zerocopy::Unaligned` is not satisfied - --> tests/ui-stable/invalid-impls/invalid-impls.rs:29:36 - | -29 | impl_or_verify!(T => Unaligned for Foo<T>); - | ^^^^^^ the trait `zerocopy::Unaligned` is not implemented for `T`, which is required by `Foo<T>: zerocopy::Unaligned` - | -note: required for `Foo<T>` to implement `zerocopy::Unaligned` - --> tests/ui-stable/invalid-impls/invalid-impls.rs:22:42 - | -22 | #[derive(FromZeroes, FromBytes, AsBytes, Unaligned)] - | ^^^^^^^^^ unsatisfied trait bound introduced in this `derive` macro -note: required by a bound in `_::Subtrait` - --> tests/ui-stable/invalid-impls/../../../src/macros.rs - | - | trait Subtrait: $trait {} - | ^^^^^^ required by this bound in `Subtrait` - | - ::: tests/ui-stable/invalid-impls/invalid-impls.rs:29:1 - | -29 | impl_or_verify!(T => Unaligned for Foo<T>); - | ------------------------------------------ in this macro invocation - = note: this error originates in the derive macro `Unaligned` which comes from the expansion of the macro `impl_or_verify` (in Nightly builds, run with -Z macro-backtrace for more info) -help: consider restricting type parameter `T` - | -29 | impl_or_verify!(T: zerocopy::Unaligned => Unaligned for Foo<T>); - | +++++++++++++++++++++
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/max-align.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/max-align.rs deleted file mode 100644 index 53e3eb9..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/max-align.rs +++ /dev/null
@@ -1,99 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -#[repr(C, align(1))] -struct Align1; - -#[repr(C, align(2))] -struct Align2; - -#[repr(C, align(4))] -struct Align4; - -#[repr(C, align(8))] -struct Align8; - -#[repr(C, align(16))] -struct Align16; - -#[repr(C, align(32))] -struct Align32; - -#[repr(C, align(64))] -struct Align64; - -#[repr(C, align(128))] -struct Align128; - -#[repr(C, align(256))] -struct Align256; - -#[repr(C, align(512))] -struct Align512; - -#[repr(C, align(1024))] -struct Align1024; - -#[repr(C, align(2048))] -struct Align2048; - -#[repr(C, align(4096))] -struct Align4096; - -#[repr(C, align(8192))] -struct Align8192; - -#[repr(C, align(16384))] -struct Align16384; - -#[repr(C, align(32768))] -struct Align32768; - -#[repr(C, align(65536))] -struct Align65536; - -#[repr(C, align(131072))] -struct Align131072; - -#[repr(C, align(262144))] -struct Align262144; - -#[repr(C, align(524288))] -struct Align524288; - -#[repr(C, align(1048576))] -struct Align1048576; - -#[repr(C, align(2097152))] -struct Align2097152; - -#[repr(C, align(4194304))] -struct Align4194304; - -#[repr(C, align(8388608))] -struct Align8388608; - -#[repr(C, align(16777216))] -struct Align16777216; - -#[repr(C, align(33554432))] -struct Align33554432; - -#[repr(C, align(67108864))] -struct Align67108864; - -#[repr(C, align(134217728))] -struct Align13421772; - -#[repr(C, align(268435456))] -struct Align26843545; - -#[repr(C, align(1073741824))] -struct Align1073741824; - -fn main() {}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/max-align.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/max-align.stderr deleted file mode 100644 index 7e83b2f..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/max-align.stderr +++ /dev/null
@@ -1,5 +0,0 @@ -error[E0589]: invalid `repr(align)` attribute: larger than 2^29 - --> tests/ui-stable/max-align.rs:96:17 - | -96 | #[repr(C, align(1073741824))] - | ^^^^^^^^^^
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-dst-not-frombytes.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-dst-not-frombytes.rs deleted file mode 100644 index c4caaff9..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-dst-not-frombytes.rs +++ /dev/null
@@ -1,18 +0,0 @@ -// Copyright 2022 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -include!("../../zerocopy-derive/tests/util.rs"); - -extern crate zerocopy; - -use zerocopy::transmute; - -fn main() {} - -// `transmute` requires that the destination type implements `FromBytes` -const DST_NOT_FROM_BYTES: NotZerocopy = transmute!(AU16(0));
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-dst-not-frombytes.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-dst-not-frombytes.stderr deleted file mode 100644 index 6b1e046..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-dst-not-frombytes.stderr +++ /dev/null
@@ -1,25 +0,0 @@ -error[E0277]: the trait bound `NotZerocopy: FromBytes` is not satisfied - --> tests/ui-stable/transmute-dst-not-frombytes.rs:18:41 - | -18 | const DST_NOT_FROM_BYTES: NotZerocopy = transmute!(AU16(0)); - | ^^^^^^^^^^^^^^^^^^^ - | | - | the trait `FromBytes` is not implemented for `NotZerocopy` - | required by a bound introduced by this call - | - = help: the following other types implement trait `FromBytes`: - () - AU16 - F32<O> - F64<O> - I128<O> - I16<O> - I32<O> - I64<O> - and $N others -note: required by a bound in `AssertIsFromBytes` - --> tests/ui-stable/transmute-dst-not-frombytes.rs:18:41 - | -18 | const DST_NOT_FROM_BYTES: NotZerocopy = transmute!(AU16(0)); - | ^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertIsFromBytes` - = note: this error originates in the macro `transmute` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-alignment-increase.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-alignment-increase.rs deleted file mode 100644 index 0928564d..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-alignment-increase.rs +++ /dev/null
@@ -1,19 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -include!("../../zerocopy-derive/tests/util.rs"); - -extern crate zerocopy; - -use zerocopy::transmute_mut; - -fn main() {} - -// `transmute_mut!` does not support transmuting from a type of smaller -// alignment to one of larger alignment. -const INCREASE_ALIGNMENT: &mut AU16 = transmute_mut!(&mut [0u8; 2]);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-alignment-increase.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-alignment-increase.stderr deleted file mode 100644 index 252fec9..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-alignment-increase.stderr +++ /dev/null
@@ -1,9 +0,0 @@ -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-stable/transmute-mut-alignment-increase.rs:19:39 - | -19 | const INCREASE_ALIGNMENT: &mut AU16 = transmute_mut!(&mut [0u8; 2]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: source type: `AlignOf<[u8; 2]>` (8 bits) - = note: target type: `MaxAlignsOf<[u8; 2], AU16>` (16 bits) - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-const.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-const.rs deleted file mode 100644 index 021b562f1..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-const.rs +++ /dev/null
@@ -1,20 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -include!("../../zerocopy-derive/tests/util.rs"); - -extern crate zerocopy; - -use zerocopy::transmute_mut; - -fn main() {} - -const ARRAY_OF_U8S: [u8; 2] = [0u8; 2]; - -// `transmute_mut!` cannot, generally speaking, be used in const contexts. -const CONST_CONTEXT: &mut [u8; 2] = transmute_mut!(&mut ARRAY_OF_U8S);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-const.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-const.stderr deleted file mode 100644 index 076dcf5..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-const.stderr +++ /dev/null
@@ -1,31 +0,0 @@ -warning: taking a mutable reference to a `const` item - --> tests/ui-stable/transmute-mut-const.rs:20:52 - | -20 | const CONST_CONTEXT: &mut [u8; 2] = transmute_mut!(&mut ARRAY_OF_U8S); - | ^^^^^^^^^^^^^^^^^ - | - = note: each usage of a `const` item creates a new temporary - = note: the mutable reference will refer to this temporary, not the original `const` item -note: `const` item defined here - --> tests/ui-stable/transmute-mut-const.rs:17:1 - | -17 | const ARRAY_OF_U8S: [u8; 2] = [0u8; 2]; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ - = note: `#[warn(const_item_mutation)]` on by default - -error[E0658]: mutable references are not allowed in constants - --> tests/ui-stable/transmute-mut-const.rs:20:52 - | -20 | const CONST_CONTEXT: &mut [u8; 2] = transmute_mut!(&mut ARRAY_OF_U8S); - | ^^^^^^^^^^^^^^^^^ - | - = note: see issue #57349 <https://github.com/rust-lang/rust/issues/57349> for more information - -error[E0015]: cannot call non-const fn `transmute_mut::<'_, '_, [u8; 2], [u8; 2]>` in constants - --> tests/ui-stable/transmute-mut-const.rs:20:37 - | -20 | const CONST_CONTEXT: &mut [u8; 2] = transmute_mut!(&mut ARRAY_OF_U8S); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: calls in constants are limited to constant functions, tuple structs and tuple variants - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-dst-generic.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-dst-generic.rs deleted file mode 100644 index 7068f102..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-dst-generic.rs +++ /dev/null
@@ -1,18 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::{transmute_mut, AsBytes, FromBytes}; - -fn main() {} - -fn transmute_mut<T: AsBytes + FromBytes>(u: &mut u8) -> &mut T { - // `transmute_mut!` requires the destination type to be concrete. - transmute_mut!(u) -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-dst-generic.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-dst-generic.stderr deleted file mode 100644 index 0000eb0..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-dst-generic.stderr +++ /dev/null
@@ -1,19 +0,0 @@ -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-stable/transmute-mut-dst-generic.rs:17:5 - | -17 | transmute_mut!(u) - | ^^^^^^^^^^^^^^^^^ - | - = note: source type: `u8` (8 bits) - = note: target type: `T` (this type does not have a fixed size) - = note: this error originates in the macro `$crate::assert_size_eq` which comes from the expansion of the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-stable/transmute-mut-dst-generic.rs:17:5 - | -17 | transmute_mut!(u) - | ^^^^^^^^^^^^^^^^^ - | - = note: source type: `AlignOf<u8>` (8 bits) - = note: target type: `MaxAlignsOf<u8, T>` (size can vary because of T) - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-dst-not-a-reference.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-dst-not-a-reference.rs deleted file mode 100644 index 33a9ecd9..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-dst-not-a-reference.rs +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_mut; - -fn main() {} - -// `transmute_mut!` does not support transmuting into a non-reference -// destination type. -const DST_NOT_A_REFERENCE: usize = transmute_mut!(&mut 0u8);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-dst-not-a-reference.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-dst-not-a-reference.stderr deleted file mode 100644 index 14ee444c..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-dst-not-a-reference.stderr +++ /dev/null
@@ -1,39 +0,0 @@ -error[E0308]: mismatched types - --> tests/ui-stable/transmute-mut-dst-not-a-reference.rs:17:36 - | -17 | const DST_NOT_A_REFERENCE: usize = transmute_mut!(&mut 0u8); - | ^^^^^^^^^^^^^^^^^^^^^^^^ expected `usize`, found `&mut _` - | - = note: expected type `usize` - found mutable reference `&mut _` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0308]: mismatched types - --> tests/ui-stable/transmute-mut-dst-not-a-reference.rs:17:36 - | -17 | const DST_NOT_A_REFERENCE: usize = transmute_mut!(&mut 0u8); - | ^^^^^^^^^^^^^^^^^^^^^^^^ expected `usize`, found `&mut _` - | - = note: expected type `usize` - found mutable reference `&mut _` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0308]: mismatched types - --> tests/ui-stable/transmute-mut-dst-not-a-reference.rs:17:36 - | -17 | const DST_NOT_A_REFERENCE: usize = transmute_mut!(&mut 0u8); - | ^^^^^^^^^^^^^^^^^^^^^^^^ expected `usize`, found `&mut _` - | - = note: expected type `usize` - found mutable reference `&mut _` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0308]: mismatched types - --> tests/ui-stable/transmute-mut-dst-not-a-reference.rs:17:36 - | -17 | const DST_NOT_A_REFERENCE: usize = transmute_mut!(&mut 0u8); - | ^^^^^^^^^^^^^^^^^^^^^^^^ expected `usize`, found `&mut _` - | - = note: expected type `usize` - found mutable reference `&mut _` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-dst-not-asbytes.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-dst-not-asbytes.rs deleted file mode 100644 index b72f129..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-dst-not-asbytes.rs +++ /dev/null
@@ -1,24 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_mut; - -fn main() {} - -#[derive(zerocopy::FromZeroes, zerocopy::FromBytes, zerocopy::AsBytes)] -#[repr(C)] -struct Src; - -#[derive(zerocopy::FromZeroes, zerocopy::FromBytes)] -#[repr(C)] -struct Dst; - -// `transmute_mut` requires that the destination type implements `AsBytes` -const DST_NOT_AS_BYTES: &mut Dst = transmute_mut!(&mut Src);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-dst-not-asbytes.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-dst-not-asbytes.stderr deleted file mode 100644 index 6ea5a2fb..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-dst-not-asbytes.stderr +++ /dev/null
@@ -1,25 +0,0 @@ -error[E0277]: the trait bound `Dst: AsBytes` is not satisfied - --> tests/ui-stable/transmute-mut-dst-not-asbytes.rs:24:36 - | -24 | const DST_NOT_AS_BYTES: &mut Dst = transmute_mut!(&mut Src); - | ^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | the trait `AsBytes` is not implemented for `Dst` - | required by a bound introduced by this call - | - = help: the following other types implement trait `AsBytes`: - () - F32<O> - F64<O> - I128<O> - I16<O> - I32<O> - I64<O> - ManuallyDrop<T> - and $N others -note: required by a bound in `AssertDstIsAsBytes` - --> tests/ui-stable/transmute-mut-dst-not-asbytes.rs:24:36 - | -24 | const DST_NOT_AS_BYTES: &mut Dst = transmute_mut!(&mut Src); - | ^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertDstIsAsBytes` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-dst-not-frombytes.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-dst-not-frombytes.rs deleted file mode 100644 index 102fced..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-dst-not-frombytes.rs +++ /dev/null
@@ -1,24 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_mut; - -fn main() {} - -#[derive(zerocopy::FromZeroes, zerocopy::FromBytes, zerocopy::AsBytes)] -#[repr(C)] -struct Src; - -#[derive(zerocopy::AsBytes)] -#[repr(C)] -struct Dst; - -// `transmute_mut` requires that the destination type implements `FromBytes` -const DST_NOT_FROM_BYTES: &mut Dst = transmute_mut!(&mut Src);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-dst-not-frombytes.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-dst-not-frombytes.stderr deleted file mode 100644 index a8e39ba..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-dst-not-frombytes.stderr +++ /dev/null
@@ -1,25 +0,0 @@ -error[E0277]: the trait bound `Dst: FromBytes` is not satisfied - --> tests/ui-stable/transmute-mut-dst-not-frombytes.rs:24:38 - | -24 | const DST_NOT_FROM_BYTES: &mut Dst = transmute_mut!(&mut Src); - | ^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | the trait `FromBytes` is not implemented for `Dst` - | required by a bound introduced by this call - | - = help: the following other types implement trait `FromBytes`: - () - F32<O> - F64<O> - I128<O> - I16<O> - I32<O> - I64<O> - ManuallyDrop<T> - and $N others -note: required by a bound in `AssertDstIsFromBytes` - --> tests/ui-stable/transmute-mut-dst-not-frombytes.rs:24:38 - | -24 | const DST_NOT_FROM_BYTES: &mut Dst = transmute_mut!(&mut Src); - | ^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertDstIsFromBytes` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-dst-unsized.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-dst-unsized.rs deleted file mode 100644 index 693ccda..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-dst-unsized.rs +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_mut; - -fn main() {} - -// `transmute_mut!` does not support transmuting into an unsized destination -// type. -const DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8; 1]);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-dst-unsized.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-dst-unsized.stderr deleted file mode 100644 index 19b88e7..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-dst-unsized.stderr +++ /dev/null
@@ -1,86 +0,0 @@ -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-mut-dst-unsized.rs:17:32 - | -17 | const DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8; 1]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | doesn't have a size known at compile-time - | required by a bound introduced by this call - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AssertDstIsFromBytes` - --> tests/ui-stable/transmute-mut-dst-unsized.rs:17:32 - | -17 | const DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8; 1]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertDstIsFromBytes` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-mut-dst-unsized.rs:17:32 - | -17 | const DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8; 1]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | doesn't have a size known at compile-time - | required by a bound introduced by this call - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AssertDstIsAsBytes` - --> tests/ui-stable/transmute-mut-dst-unsized.rs:17:32 - | -17 | const DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8; 1]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertDstIsAsBytes` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-mut-dst-unsized.rs:17:32 - | -17 | const DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8; 1]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` - = note: all local variables must have a statically known size - = help: unsized locals are gated as an unstable feature - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-mut-dst-unsized.rs:17:32 - | -17 | const DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8; 1]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by an implicit `Sized` bound in `MaxAlignsOf` - --> src/macro_util.rs - | - | pub union MaxAlignsOf<T, U> { - | ^ required by the implicit `Sized` requirement on this type parameter in `MaxAlignsOf` - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-mut-dst-unsized.rs:17:32 - | -17 | const DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8; 1]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by an implicit `Sized` bound in `transmute` - --> $RUST/core/src/intrinsics.rs - | - | pub fn transmute<Src, Dst>(src: Src) -> Dst; - | ^^^ required by the implicit `Sized` requirement on this type parameter in `transmute` - = note: this error originates in the macro `$crate::assert_size_eq` which comes from the expansion of the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-mut-dst-unsized.rs:17:32 - | -17 | const DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8; 1]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by an implicit `Sized` bound in `transmute_mut` - --> src/macro_util.rs - | - | pub unsafe fn transmute_mut<'dst, 'src: 'dst, Src: 'src, Dst: 'dst>( - | ^^^ required by the implicit `Sized` requirement on this type parameter in `transmute_mut` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-illegal-lifetime.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-illegal-lifetime.rs deleted file mode 100644 index c31765e..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-illegal-lifetime.rs +++ /dev/null
@@ -1,15 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -fn main() {} - -fn increase_lifetime() { - let mut x = 0u64; - // It is illegal to increase the lifetime scope. - let _: &'static mut u64 = zerocopy::transmute_mut!(&mut x); -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-illegal-lifetime.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-illegal-lifetime.stderr deleted file mode 100644 index 7f12813..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-illegal-lifetime.stderr +++ /dev/null
@@ -1,12 +0,0 @@ -error[E0597]: `x` does not live long enough - --> tests/ui-stable/transmute-mut-illegal-lifetime.rs:14:56 - | -12 | let mut x = 0u64; - | ----- binding `x` declared here -13 | // It is illegal to increase the lifetime scope. -14 | let _: &'static mut u64 = zerocopy::transmute_mut!(&mut x); - | ---------------- ^^^^^^ borrowed value does not live long enough - | | - | type annotation requires that `x` is borrowed for `'static` -15 | } - | - `x` dropped here while still borrowed
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-size-decrease.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-size-decrease.rs deleted file mode 100644 index c6eec3a..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-size-decrease.rs +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_mut; - -fn main() {} - -// We require that the size of the destination type is not smaller than the size -// of the source type. -const DECREASE_SIZE: &mut u8 = transmute_mut!(&mut [0u8; 2]);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-size-decrease.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-size-decrease.stderr deleted file mode 100644 index 23999135..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-size-decrease.stderr +++ /dev/null
@@ -1,9 +0,0 @@ -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-stable/transmute-mut-size-decrease.rs:17:32 - | -17 | const DECREASE_SIZE: &mut u8 = transmute_mut!(&mut [0u8; 2]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: source type: `[u8; 2]` (16 bits) - = note: target type: `u8` (8 bits) - = note: this error originates in the macro `$crate::assert_size_eq` which comes from the expansion of the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-size-increase.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-size-increase.rs deleted file mode 100644 index a4657c28..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-size-increase.rs +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_mut; - -fn main() {} - -// `transmute_mut!` does not support transmuting from a smaller type to a larger -// one. -const INCREASE_SIZE: &mut [u8; 2] = transmute_mut!(&mut 0u8);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-size-increase.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-size-increase.stderr deleted file mode 100644 index 1427c7b..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-size-increase.stderr +++ /dev/null
@@ -1,9 +0,0 @@ -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-stable/transmute-mut-size-increase.rs:17:37 - | -17 | const INCREASE_SIZE: &mut [u8; 2] = transmute_mut!(&mut 0u8); - | ^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: source type: `u8` (8 bits) - = note: target type: `[u8; 2]` (16 bits) - = note: this error originates in the macro `$crate::assert_size_eq` which comes from the expansion of the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-src-dst-generic.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-src-dst-generic.rs deleted file mode 100644 index aed7ded9..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-src-dst-generic.rs +++ /dev/null
@@ -1,19 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::{transmute_mut, AsBytes, FromBytes}; - -fn main() {} - -fn transmute_mut<T: AsBytes + FromBytes, U: AsBytes + FromBytes>(t: &mut T) -> &mut U { - // `transmute_mut!` requires the source and destination types to be - // concrete. - transmute_mut!(t) -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-src-dst-generic.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-src-dst-generic.stderr deleted file mode 100644 index ddb8bb6..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-src-dst-generic.stderr +++ /dev/null
@@ -1,19 +0,0 @@ -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-stable/transmute-mut-src-dst-generic.rs:18:5 - | -18 | transmute_mut!(t) - | ^^^^^^^^^^^^^^^^^ - | - = note: source type: `T` (this type does not have a fixed size) - = note: target type: `U` (this type does not have a fixed size) - = note: this error originates in the macro `$crate::assert_size_eq` which comes from the expansion of the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-stable/transmute-mut-src-dst-generic.rs:18:5 - | -18 | transmute_mut!(t) - | ^^^^^^^^^^^^^^^^^ - | - = note: source type: `AlignOf<T>` (size can vary because of T) - = note: target type: `MaxAlignsOf<T, U>` (size can vary because of T) - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-src-dst-not-references.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-src-dst-not-references.rs deleted file mode 100644 index 98cc520..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-src-dst-not-references.rs +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_mut; - -fn main() {} - -// `transmute_mut!` does not support transmuting between non-reference source -// and destination types. -const SRC_DST_NOT_REFERENCES: &mut usize = transmute_mut!(0usize);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-src-dst-not-references.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-src-dst-not-references.stderr deleted file mode 100644 index c0d9e0f0..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-src-dst-not-references.stderr +++ /dev/null
@@ -1,15 +0,0 @@ -error[E0308]: mismatched types - --> tests/ui-stable/transmute-mut-src-dst-not-references.rs:17:59 - | -17 | const SRC_DST_NOT_REFERENCES: &mut usize = transmute_mut!(0usize); - | ---------------^^^^^^- - | | | - | | expected `&mut _`, found `usize` - | expected due to this - | - = note: expected mutable reference `&mut _` - found type `usize` -help: consider mutably borrowing here - | -17 | const SRC_DST_NOT_REFERENCES: &mut usize = transmute_mut!(&mut 0usize); - | ++++
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-src-dst-unsized.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-src-dst-unsized.rs deleted file mode 100644 index 1bebcf2..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-src-dst-unsized.rs +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_mut; - -fn main() {} - -// `transmute_mut!` does not support transmuting between unsized source and -// destination types. -const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-src-dst-unsized.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-src-dst-unsized.stderr deleted file mode 100644 index 0cb8362..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-src-dst-unsized.stderr +++ /dev/null
@@ -1,231 +0,0 @@ -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | doesn't have a size known at compile-time - | required by a bound introduced by this call - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AssertSrcIsFromBytes` - --> tests/ui-stable/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertSrcIsFromBytes` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AssertSrcIsFromBytes` - --> tests/ui-stable/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertSrcIsFromBytes` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | doesn't have a size known at compile-time - | required by a bound introduced by this call - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AssertSrcIsAsBytes` - --> tests/ui-stable/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertSrcIsAsBytes` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AssertSrcIsAsBytes` - --> tests/ui-stable/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertSrcIsAsBytes` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | doesn't have a size known at compile-time - | required by a bound introduced by this call - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AssertDstIsFromBytes` - --> tests/ui-stable/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertDstIsFromBytes` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | doesn't have a size known at compile-time - | required by a bound introduced by this call - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AssertDstIsAsBytes` - --> tests/ui-stable/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertDstIsAsBytes` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` - = note: all local variables must have a statically known size - = help: unsized locals are gated as an unstable feature - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AlignOf::<T>::into_t` - --> src/macro_util.rs - | - | impl<T> AlignOf<T> { - | ^ required by this bound in `AlignOf::<T>::into_t` - | #[inline(never)] // Make `missing_inline_in_public_items` happy. - | pub fn into_t(self) -> T { - | ------ required by a bound in this associated function - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` - = note: the left-hand-side of an assignment must have a statically known size - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by an implicit `Sized` bound in `AlignOf` - --> src/macro_util.rs - | - | pub struct AlignOf<T> { - | ^ required by the implicit `Sized` requirement on this type parameter in `AlignOf` - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by an implicit `Sized` bound in `MaxAlignsOf` - --> src/macro_util.rs - | - | pub union MaxAlignsOf<T, U> { - | ^ required by the implicit `Sized` requirement on this type parameter in `MaxAlignsOf` - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by an implicit `Sized` bound in `AlignOf` - --> src/macro_util.rs - | - | pub struct AlignOf<T> { - | ^ required by the implicit `Sized` requirement on this type parameter in `AlignOf` - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` - = note: all local variables must have a statically known size - = help: unsized locals are gated as an unstable feature - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by an implicit `Sized` bound in `transmute` - --> $RUST/core/src/intrinsics.rs - | - | pub fn transmute<Src, Dst>(src: Src) -> Dst; - | ^^^ required by the implicit `Sized` requirement on this type parameter in `transmute` - = note: this error originates in the macro `$crate::assert_size_eq` which comes from the expansion of the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | doesn't have a size known at compile-time - | required by a bound introduced by this call - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by an implicit `Sized` bound in `transmute_mut` - --> src/macro_util.rs - | - | pub unsafe fn transmute_mut<'dst, 'src: 'dst, Src: 'src, Dst: 'dst>( - | ^^^ required by the implicit `Sized` requirement on this type parameter in `transmute_mut` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-mut-src-dst-unsized.rs:17:36 - | -17 | const SRC_DST_UNSIZED: &mut [u8] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by an implicit `Sized` bound in `transmute_mut` - --> src/macro_util.rs - | - | pub unsafe fn transmute_mut<'dst, 'src: 'dst, Src: 'src, Dst: 'dst>( - | ^^^ required by the implicit `Sized` requirement on this type parameter in `transmute_mut` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-src-generic.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-src-generic.rs deleted file mode 100644 index a3ef397..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-src-generic.rs +++ /dev/null
@@ -1,18 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::{transmute_mut, AsBytes}; - -fn main() {} - -fn transmute_mut<T: AsBytes + FromBytes>(t: &mut T) -> &mut u8 { - // `transmute_mut!` requires the source type to be concrete. - transmute_mut!(t) -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-src-generic.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-src-generic.stderr deleted file mode 100644 index fc4809e..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-src-generic.stderr +++ /dev/null
@@ -1,10 +0,0 @@ -error[E0405]: cannot find trait `FromBytes` in this scope - --> tests/ui-stable/transmute-mut-src-generic.rs:15:31 - | -15 | fn transmute_mut<T: AsBytes + FromBytes>(t: &mut T) -> &mut u8 { - | ^^^^^^^^^ not found in this scope - | -help: consider importing this trait - | -11 + use zerocopy::FromBytes; - |
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-src-immutable.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-src-immutable.rs deleted file mode 100644 index 08088d0..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-src-immutable.rs +++ /dev/null
@@ -1,18 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_mut; - -fn main() {} - -fn ref_src_immutable() { - // `transmute_mut!` requires that its source type be a mutable reference. - let _: &mut u8 = transmute_mut!(&0u8); -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-src-immutable.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-src-immutable.stderr deleted file mode 100644 index 0115c79..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-src-immutable.stderr +++ /dev/null
@@ -1,11 +0,0 @@ -error[E0308]: mismatched types - --> tests/ui-stable/transmute-mut-src-immutable.rs:17:37 - | -17 | let _: &mut u8 = transmute_mut!(&0u8); - | ---------------^^^^- - | | | - | | types differ in mutability - | expected due to this - | - = note: expected mutable reference `&mut _` - found reference `&u8`
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-src-not-a-reference.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-src-not-a-reference.rs deleted file mode 100644 index bf8bc32..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-src-not-a-reference.rs +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_mut; - -fn main() {} - -// `transmute_mut!` does not support transmuting from a non-reference source -// type. -const SRC_NOT_A_REFERENCE: &mut u8 = transmute_mut!(0usize);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-src-not-a-reference.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-src-not-a-reference.stderr deleted file mode 100644 index 8c1d9b47..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-src-not-a-reference.stderr +++ /dev/null
@@ -1,15 +0,0 @@ -error[E0308]: mismatched types - --> tests/ui-stable/transmute-mut-src-not-a-reference.rs:17:53 - | -17 | const SRC_NOT_A_REFERENCE: &mut u8 = transmute_mut!(0usize); - | ---------------^^^^^^- - | | | - | | expected `&mut _`, found `usize` - | expected due to this - | - = note: expected mutable reference `&mut _` - found type `usize` -help: consider mutably borrowing here - | -17 | const SRC_NOT_A_REFERENCE: &mut u8 = transmute_mut!(&mut 0usize); - | ++++
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-src-not-asbytes.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-src-not-asbytes.rs deleted file mode 100644 index 6a14f12..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-src-not-asbytes.rs +++ /dev/null
@@ -1,24 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_mut; - -fn main() {} - -#[derive(zerocopy::FromZeroes, zerocopy::FromBytes)] -#[repr(C)] -struct Src; - -#[derive(zerocopy::FromZeroes, zerocopy::FromBytes, zerocopy::AsBytes)] -#[repr(C)] -struct Dst; - -// `transmute_mut` requires that the source type implements `AsBytes` -const SRC_NOT_AS_BYTES: &mut Dst = transmute_mut!(&mut Src);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-src-not-asbytes.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-src-not-asbytes.stderr deleted file mode 100644 index a428ae2..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-src-not-asbytes.stderr +++ /dev/null
@@ -1,48 +0,0 @@ -error[E0277]: the trait bound `Src: AsBytes` is not satisfied - --> tests/ui-stable/transmute-mut-src-not-asbytes.rs:24:36 - | -24 | const SRC_NOT_AS_BYTES: &mut Dst = transmute_mut!(&mut Src); - | ^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | the trait `AsBytes` is not implemented for `Src` - | required by a bound introduced by this call - | - = help: the following other types implement trait `AsBytes`: - () - Dst - F32<O> - F64<O> - I128<O> - I16<O> - I32<O> - I64<O> - and $N others -note: required by a bound in `AssertSrcIsAsBytes` - --> tests/ui-stable/transmute-mut-src-not-asbytes.rs:24:36 - | -24 | const SRC_NOT_AS_BYTES: &mut Dst = transmute_mut!(&mut Src); - | ^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertSrcIsAsBytes` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `Src: AsBytes` is not satisfied - --> tests/ui-stable/transmute-mut-src-not-asbytes.rs:24:36 - | -24 | const SRC_NOT_AS_BYTES: &mut Dst = transmute_mut!(&mut Src); - | ^^^^^^^^^^^^^^^^^^^^^^^^ the trait `AsBytes` is not implemented for `Src` - | - = help: the following other types implement trait `AsBytes`: - () - Dst - F32<O> - F64<O> - I128<O> - I16<O> - I32<O> - I64<O> - and $N others -note: required by a bound in `AssertSrcIsAsBytes` - --> tests/ui-stable/transmute-mut-src-not-asbytes.rs:24:36 - | -24 | const SRC_NOT_AS_BYTES: &mut Dst = transmute_mut!(&mut Src); - | ^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertSrcIsAsBytes` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-src-not-frombytes.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-src-not-frombytes.rs deleted file mode 100644 index 2ebe036..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-src-not-frombytes.rs +++ /dev/null
@@ -1,24 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_mut; - -fn main() {} - -#[derive(zerocopy::AsBytes)] -#[repr(C)] -struct Src; - -#[derive(zerocopy::FromZeroes, zerocopy::FromBytes, zerocopy::AsBytes)] -#[repr(C)] -struct Dst; - -// `transmute_mut` requires that the source type implements `FromBytes` -const SRC_NOT_FROM_BYTES: &mut Dst = transmute_mut!(&mut Src);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-src-not-frombytes.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-src-not-frombytes.stderr deleted file mode 100644 index 6a21ff1..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-src-not-frombytes.stderr +++ /dev/null
@@ -1,48 +0,0 @@ -error[E0277]: the trait bound `Src: FromBytes` is not satisfied - --> tests/ui-stable/transmute-mut-src-not-frombytes.rs:24:38 - | -24 | const SRC_NOT_FROM_BYTES: &mut Dst = transmute_mut!(&mut Src); - | ^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | the trait `FromBytes` is not implemented for `Src` - | required by a bound introduced by this call - | - = help: the following other types implement trait `FromBytes`: - () - Dst - F32<O> - F64<O> - I128<O> - I16<O> - I32<O> - I64<O> - and $N others -note: required by a bound in `AssertSrcIsFromBytes` - --> tests/ui-stable/transmute-mut-src-not-frombytes.rs:24:38 - | -24 | const SRC_NOT_FROM_BYTES: &mut Dst = transmute_mut!(&mut Src); - | ^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertSrcIsFromBytes` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `Src: FromBytes` is not satisfied - --> tests/ui-stable/transmute-mut-src-not-frombytes.rs:24:38 - | -24 | const SRC_NOT_FROM_BYTES: &mut Dst = transmute_mut!(&mut Src); - | ^^^^^^^^^^^^^^^^^^^^^^^^ the trait `FromBytes` is not implemented for `Src` - | - = help: the following other types implement trait `FromBytes`: - () - Dst - F32<O> - F64<O> - I128<O> - I16<O> - I32<O> - I64<O> - and $N others -note: required by a bound in `AssertSrcIsFromBytes` - --> tests/ui-stable/transmute-mut-src-not-frombytes.rs:24:38 - | -24 | const SRC_NOT_FROM_BYTES: &mut Dst = transmute_mut!(&mut Src); - | ^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertSrcIsFromBytes` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-src-unsized.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-src-unsized.rs deleted file mode 100644 index 413dd68..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-src-unsized.rs +++ /dev/null
@@ -1,16 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_mut; - -fn main() {} - -// `transmute_mut!` does not support transmuting from an unsized source type. -const SRC_UNSIZED: &mut [u8; 1] = transmute_mut!(&mut [0u8][..]);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-src-unsized.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-src-unsized.stderr deleted file mode 100644 index 07069ec6..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-mut-src-unsized.stderr +++ /dev/null
@@ -1,158 +0,0 @@ -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-mut-src-unsized.rs:16:35 - | -16 | const SRC_UNSIZED: &mut [u8; 1] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | doesn't have a size known at compile-time - | required by a bound introduced by this call - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AssertSrcIsFromBytes` - --> tests/ui-stable/transmute-mut-src-unsized.rs:16:35 - | -16 | const SRC_UNSIZED: &mut [u8; 1] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertSrcIsFromBytes` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-mut-src-unsized.rs:16:35 - | -16 | const SRC_UNSIZED: &mut [u8; 1] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AssertSrcIsFromBytes` - --> tests/ui-stable/transmute-mut-src-unsized.rs:16:35 - | -16 | const SRC_UNSIZED: &mut [u8; 1] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertSrcIsFromBytes` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-mut-src-unsized.rs:16:35 - | -16 | const SRC_UNSIZED: &mut [u8; 1] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | doesn't have a size known at compile-time - | required by a bound introduced by this call - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AssertSrcIsAsBytes` - --> tests/ui-stable/transmute-mut-src-unsized.rs:16:35 - | -16 | const SRC_UNSIZED: &mut [u8; 1] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertSrcIsAsBytes` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-mut-src-unsized.rs:16:35 - | -16 | const SRC_UNSIZED: &mut [u8; 1] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AssertSrcIsAsBytes` - --> tests/ui-stable/transmute-mut-src-unsized.rs:16:35 - | -16 | const SRC_UNSIZED: &mut [u8; 1] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertSrcIsAsBytes` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-mut-src-unsized.rs:16:35 - | -16 | const SRC_UNSIZED: &mut [u8; 1] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` - = note: all local variables must have a statically known size - = help: unsized locals are gated as an unstable feature - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-mut-src-unsized.rs:16:35 - | -16 | const SRC_UNSIZED: &mut [u8; 1] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AlignOf::<T>::into_t` - --> src/macro_util.rs - | - | impl<T> AlignOf<T> { - | ^ required by this bound in `AlignOf::<T>::into_t` - | #[inline(never)] // Make `missing_inline_in_public_items` happy. - | pub fn into_t(self) -> T { - | ------ required by a bound in this associated function - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-mut-src-unsized.rs:16:35 - | -16 | const SRC_UNSIZED: &mut [u8; 1] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` - = note: the left-hand-side of an assignment must have a statically known size - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-mut-src-unsized.rs:16:35 - | -16 | const SRC_UNSIZED: &mut [u8; 1] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by an implicit `Sized` bound in `AlignOf` - --> src/macro_util.rs - | - | pub struct AlignOf<T> { - | ^ required by the implicit `Sized` requirement on this type parameter in `AlignOf` - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-mut-src-unsized.rs:16:35 - | -16 | const SRC_UNSIZED: &mut [u8; 1] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by an implicit `Sized` bound in `MaxAlignsOf` - --> src/macro_util.rs - | - | pub union MaxAlignsOf<T, U> { - | ^ required by the implicit `Sized` requirement on this type parameter in `MaxAlignsOf` - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-mut-src-unsized.rs:16:35 - | -16 | const SRC_UNSIZED: &mut [u8; 1] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by an implicit `Sized` bound in `AlignOf` - --> src/macro_util.rs - | - | pub struct AlignOf<T> { - | ^ required by the implicit `Sized` requirement on this type parameter in `AlignOf` - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-mut-src-unsized.rs:16:35 - | -16 | const SRC_UNSIZED: &mut [u8; 1] = transmute_mut!(&mut [0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | doesn't have a size known at compile-time - | required by a bound introduced by this call - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by an implicit `Sized` bound in `transmute_mut` - --> src/macro_util.rs - | - | pub unsafe fn transmute_mut<'dst, 'src: 'dst, Src: 'src, Dst: 'dst>( - | ^^^ required by the implicit `Sized` requirement on this type parameter in `transmute_mut` - = note: this error originates in the macro `transmute_mut` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ptr-to-usize.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ptr-to-usize.rs deleted file mode 100644 index 5af8859..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ptr-to-usize.rs +++ /dev/null
@@ -1,20 +0,0 @@ -// Copyright 2022 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute; - -fn main() {} - -// It is unclear whether we can or should support this transmutation, especially -// in a const context. This test ensures that even if such a transmutation -// becomes valid due to the requisite implementations of `FromBytes` being -// added, that we re-examine whether it should specifically be valid in a const -// context. -const POINTER_VALUE: usize = transmute!(&0usize as *const usize);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ptr-to-usize.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ptr-to-usize.stderr deleted file mode 100644 index 4f4d583..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ptr-to-usize.stderr +++ /dev/null
@@ -1,30 +0,0 @@ -error[E0277]: the trait bound `*const usize: AsBytes` is not satisfied - --> tests/ui-stable/transmute-ptr-to-usize.rs:20:30 - | -20 | const POINTER_VALUE: usize = transmute!(&0usize as *const usize); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | the trait `AsBytes` is not implemented for `*const usize` - | required by a bound introduced by this call - | - = help: the trait `AsBytes` is implemented for `usize` -note: required by a bound in `AssertIsAsBytes` - --> tests/ui-stable/transmute-ptr-to-usize.rs:20:30 - | -20 | const POINTER_VALUE: usize = transmute!(&0usize as *const usize); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertIsAsBytes` - = note: this error originates in the macro `transmute` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `*const usize: AsBytes` is not satisfied - --> tests/ui-stable/transmute-ptr-to-usize.rs:20:30 - | -20 | const POINTER_VALUE: usize = transmute!(&0usize as *const usize); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `AsBytes` is not implemented for `*const usize` - | - = help: the trait `AsBytes` is implemented for `usize` -note: required by a bound in `AssertIsAsBytes` - --> tests/ui-stable/transmute-ptr-to-usize.rs:20:30 - | -20 | const POINTER_VALUE: usize = transmute!(&0usize as *const usize); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertIsAsBytes` - = note: this error originates in the macro `transmute` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-alignment-increase.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-alignment-increase.rs deleted file mode 100644 index bf1988c6..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-alignment-increase.rs +++ /dev/null
@@ -1,19 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -include!("../../zerocopy-derive/tests/util.rs"); - -extern crate zerocopy; - -use zerocopy::transmute_ref; - -fn main() {} - -// `transmute_ref!` does not support transmuting from a type of smaller -// alignment to one of larger alignment. -const INCREASE_ALIGNMENT: &AU16 = transmute_ref!(&[0u8; 2]);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-alignment-increase.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-alignment-increase.stderr deleted file mode 100644 index a34c406..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-alignment-increase.stderr +++ /dev/null
@@ -1,9 +0,0 @@ -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-stable/transmute-ref-alignment-increase.rs:19:35 - | -19 | const INCREASE_ALIGNMENT: &AU16 = transmute_ref!(&[0u8; 2]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: source type: `AlignOf<[u8; 2]>` (8 bits) - = note: target type: `MaxAlignsOf<[u8; 2], AU16>` (16 bits) - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-dst-generic.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-dst-generic.rs deleted file mode 100644 index bf4a0f9a..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-dst-generic.rs +++ /dev/null
@@ -1,18 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::{transmute_ref, FromBytes}; - -fn main() {} - -fn transmute_ref<T: FromBytes>(u: &u8) -> &T { - // `transmute_ref!` requires the destination type to be concrete. - transmute_ref!(u) -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-dst-generic.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-dst-generic.stderr deleted file mode 100644 index e30b9f6..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-dst-generic.stderr +++ /dev/null
@@ -1,19 +0,0 @@ -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-stable/transmute-ref-dst-generic.rs:17:5 - | -17 | transmute_ref!(u) - | ^^^^^^^^^^^^^^^^^ - | - = note: source type: `u8` (8 bits) - = note: target type: `T` (this type does not have a fixed size) - = note: this error originates in the macro `$crate::assert_size_eq` which comes from the expansion of the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-stable/transmute-ref-dst-generic.rs:17:5 - | -17 | transmute_ref!(u) - | ^^^^^^^^^^^^^^^^^ - | - = note: source type: `AlignOf<u8>` (8 bits) - = note: target type: `MaxAlignsOf<u8, T>` (size can vary because of T) - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-dst-mutable.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-dst-mutable.rs deleted file mode 100644 index fa0e6e4..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-dst-mutable.rs +++ /dev/null
@@ -1,19 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_ref; - -fn main() {} - -fn ref_dst_mutable() { - // `transmute_ref!` requires that its destination type be an immutable - // reference. - let _: &mut u8 = transmute_ref!(&0u8); -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-dst-mutable.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-dst-mutable.stderr deleted file mode 100644 index c70f6ea6..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-dst-mutable.stderr +++ /dev/null
@@ -1,29 +0,0 @@ -error[E0308]: mismatched types - --> tests/ui-stable/transmute-ref-dst-mutable.rs:18:22 - | -18 | let _: &mut u8 = transmute_ref!(&0u8); - | ^^^^^^^^^^^^^^^^^^^^ types differ in mutability - | - = note: expected mutable reference `&mut u8` - found reference `&_` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0308]: mismatched types - --> tests/ui-stable/transmute-ref-dst-mutable.rs:18:22 - | -18 | let _: &mut u8 = transmute_ref!(&0u8); - | ^^^^^^^^^^^^^^^^^^^^ types differ in mutability - | - = note: expected mutable reference `&mut u8` - found reference `&_` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0308]: mismatched types - --> tests/ui-stable/transmute-ref-dst-mutable.rs:18:22 - | -18 | let _: &mut u8 = transmute_ref!(&0u8); - | ^^^^^^^^^^^^^^^^^^^^ types differ in mutability - | - = note: expected mutable reference `&mut u8` - found reference `&_` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-dst-not-a-reference.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-dst-not-a-reference.rs deleted file mode 100644 index de55f9a..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-dst-not-a-reference.rs +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_ref; - -fn main() {} - -// `transmute_ref!` does not support transmuting into a non-reference -// destination type. -const DST_NOT_A_REFERENCE: usize = transmute_ref!(&0u8);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-dst-not-a-reference.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-dst-not-a-reference.stderr deleted file mode 100644 index ab3f90c..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-dst-not-a-reference.stderr +++ /dev/null
@@ -1,29 +0,0 @@ -error[E0308]: mismatched types - --> tests/ui-stable/transmute-ref-dst-not-a-reference.rs:17:36 - | -17 | const DST_NOT_A_REFERENCE: usize = transmute_ref!(&0u8); - | ^^^^^^^^^^^^^^^^^^^^ expected `usize`, found `&_` - | - = note: expected type `usize` - found reference `&_` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0308]: mismatched types - --> tests/ui-stable/transmute-ref-dst-not-a-reference.rs:17:36 - | -17 | const DST_NOT_A_REFERENCE: usize = transmute_ref!(&0u8); - | ^^^^^^^^^^^^^^^^^^^^ expected `usize`, found `&_` - | - = note: expected type `usize` - found reference `&_` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0308]: mismatched types - --> tests/ui-stable/transmute-ref-dst-not-a-reference.rs:17:36 - | -17 | const DST_NOT_A_REFERENCE: usize = transmute_ref!(&0u8); - | ^^^^^^^^^^^^^^^^^^^^ expected `usize`, found `&_` - | - = note: expected type `usize` - found reference `&_` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-dst-not-frombytes.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-dst-not-frombytes.rs deleted file mode 100644 index d81f64d..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-dst-not-frombytes.rs +++ /dev/null
@@ -1,18 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -include!("../../zerocopy-derive/tests/util.rs"); - -extern crate zerocopy; - -use zerocopy::transmute_ref; - -fn main() {} - -// `transmute_ref` requires that the destination type implements `FromBytes` -const DST_NOT_FROM_BYTES: &NotZerocopy = transmute_ref!(&AU16(0));
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-dst-not-frombytes.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-dst-not-frombytes.stderr deleted file mode 100644 index ac8ebad..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-dst-not-frombytes.stderr +++ /dev/null
@@ -1,25 +0,0 @@ -error[E0277]: the trait bound `NotZerocopy: FromBytes` is not satisfied - --> tests/ui-stable/transmute-ref-dst-not-frombytes.rs:18:42 - | -18 | const DST_NOT_FROM_BYTES: &NotZerocopy = transmute_ref!(&AU16(0)); - | ^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | the trait `FromBytes` is not implemented for `NotZerocopy` - | required by a bound introduced by this call - | - = help: the following other types implement trait `FromBytes`: - () - AU16 - F32<O> - F64<O> - I128<O> - I16<O> - I32<O> - I64<O> - and $N others -note: required by a bound in `AssertIsFromBytes` - --> tests/ui-stable/transmute-ref-dst-not-frombytes.rs:18:42 - | -18 | const DST_NOT_FROM_BYTES: &NotZerocopy = transmute_ref!(&AU16(0)); - | ^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertIsFromBytes` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-dst-unsized.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-dst-unsized.rs deleted file mode 100644 index 625f1fa..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-dst-unsized.rs +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_ref; - -fn main() {} - -// `transmute_ref!` does not support transmuting into an unsized destination -// type. -const DST_UNSIZED: &[u8] = transmute_ref!(&[0u8; 1]);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-dst-unsized.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-dst-unsized.stderr deleted file mode 100644 index 71cae850..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-dst-unsized.stderr +++ /dev/null
@@ -1,69 +0,0 @@ -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-ref-dst-unsized.rs:17:28 - | -17 | const DST_UNSIZED: &[u8] = transmute_ref!(&[0u8; 1]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | doesn't have a size known at compile-time - | required by a bound introduced by this call - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AssertIsFromBytes` - --> tests/ui-stable/transmute-ref-dst-unsized.rs:17:28 - | -17 | const DST_UNSIZED: &[u8] = transmute_ref!(&[0u8; 1]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertIsFromBytes` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-ref-dst-unsized.rs:17:28 - | -17 | const DST_UNSIZED: &[u8] = transmute_ref!(&[0u8; 1]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` - = note: all local variables must have a statically known size - = help: unsized locals are gated as an unstable feature - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-ref-dst-unsized.rs:17:28 - | -17 | const DST_UNSIZED: &[u8] = transmute_ref!(&[0u8; 1]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by an implicit `Sized` bound in `MaxAlignsOf` - --> src/macro_util.rs - | - | pub union MaxAlignsOf<T, U> { - | ^ required by the implicit `Sized` requirement on this type parameter in `MaxAlignsOf` - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-ref-dst-unsized.rs:17:28 - | -17 | const DST_UNSIZED: &[u8] = transmute_ref!(&[0u8; 1]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by an implicit `Sized` bound in `transmute` - --> $RUST/core/src/intrinsics.rs - | - | pub fn transmute<Src, Dst>(src: Src) -> Dst; - | ^^^ required by the implicit `Sized` requirement on this type parameter in `transmute` - = note: this error originates in the macro `$crate::assert_size_eq` which comes from the expansion of the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-ref-dst-unsized.rs:17:28 - | -17 | const DST_UNSIZED: &[u8] = transmute_ref!(&[0u8; 1]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by an implicit `Sized` bound in `transmute_ref` - --> src/macro_util.rs - | - | pub const unsafe fn transmute_ref<'dst, 'src: 'dst, Src: 'src, Dst: 'dst>( - | ^^^ required by the implicit `Sized` requirement on this type parameter in `transmute_ref` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-illegal-lifetime.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-illegal-lifetime.rs deleted file mode 100644 index 8dd191e..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-illegal-lifetime.rs +++ /dev/null
@@ -1,15 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -fn main() {} - -fn increase_lifetime() { - let x = 0u64; - // It is illegal to increase the lifetime scope. - let _: &'static u64 = zerocopy::transmute_ref!(&x); -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-illegal-lifetime.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-illegal-lifetime.stderr deleted file mode 100644 index 1ef34fe..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-illegal-lifetime.stderr +++ /dev/null
@@ -1,12 +0,0 @@ -error[E0597]: `x` does not live long enough - --> tests/ui-stable/transmute-ref-illegal-lifetime.rs:14:52 - | -12 | let x = 0u64; - | - binding `x` declared here -13 | // It is illegal to increase the lifetime scope. -14 | let _: &'static u64 = zerocopy::transmute_ref!(&x); - | ------------ ^^ borrowed value does not live long enough - | | - | type annotation requires that `x` is borrowed for `'static` -15 | } - | - `x` dropped here while still borrowed
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-size-decrease.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-size-decrease.rs deleted file mode 100644 index 1d66a54..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-size-decrease.rs +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_ref; - -fn main() {} - -// Although this is not a soundness requirement, we currently require that the -// size of the destination type is not smaller than the size of the source type. -const DECREASE_SIZE: &u8 = transmute_ref!(&[0u8; 2]);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-size-decrease.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-size-decrease.stderr deleted file mode 100644 index f353b26e..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-size-decrease.stderr +++ /dev/null
@@ -1,9 +0,0 @@ -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-stable/transmute-ref-size-decrease.rs:17:28 - | -17 | const DECREASE_SIZE: &u8 = transmute_ref!(&[0u8; 2]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: source type: `[u8; 2]` (16 bits) - = note: target type: `u8` (8 bits) - = note: this error originates in the macro `$crate::assert_size_eq` which comes from the expansion of the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-size-increase.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-size-increase.rs deleted file mode 100644 index cdca560b..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-size-increase.rs +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_ref; - -fn main() {} - -// `transmute_ref!` does not support transmuting from a smaller type to a larger -// one. -const INCREASE_SIZE: &[u8; 2] = transmute_ref!(&0u8);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-size-increase.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-size-increase.stderr deleted file mode 100644 index f51eb63f..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-size-increase.stderr +++ /dev/null
@@ -1,9 +0,0 @@ -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-stable/transmute-ref-size-increase.rs:17:33 - | -17 | const INCREASE_SIZE: &[u8; 2] = transmute_ref!(&0u8); - | ^^^^^^^^^^^^^^^^^^^^ - | - = note: source type: `u8` (8 bits) - = note: target type: `[u8; 2]` (16 bits) - = note: this error originates in the macro `$crate::assert_size_eq` which comes from the expansion of the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-src-dst-generic.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-src-dst-generic.rs deleted file mode 100644 index 409d785b..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-src-dst-generic.rs +++ /dev/null
@@ -1,19 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::{transmute_ref, AsBytes, FromBytes}; - -fn main() {} - -fn transmute_ref<T: AsBytes, U: FromBytes>(t: &T) -> &U { - // `transmute_ref!` requires the source and destination types to be - // concrete. - transmute_ref!(t) -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-src-dst-generic.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-src-dst-generic.stderr deleted file mode 100644 index 0905dc6..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-src-dst-generic.stderr +++ /dev/null
@@ -1,19 +0,0 @@ -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-stable/transmute-ref-src-dst-generic.rs:18:5 - | -18 | transmute_ref!(t) - | ^^^^^^^^^^^^^^^^^ - | - = note: source type: `T` (this type does not have a fixed size) - = note: target type: `U` (this type does not have a fixed size) - = note: this error originates in the macro `$crate::assert_size_eq` which comes from the expansion of the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-stable/transmute-ref-src-dst-generic.rs:18:5 - | -18 | transmute_ref!(t) - | ^^^^^^^^^^^^^^^^^ - | - = note: source type: `AlignOf<T>` (size can vary because of T) - = note: target type: `MaxAlignsOf<T, U>` (size can vary because of T) - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-src-dst-not-references.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-src-dst-not-references.rs deleted file mode 100644 index 114e917..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-src-dst-not-references.rs +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_ref; - -fn main() {} - -// `transmute_ref!` does not support transmuting between non-reference source -// and destination types. -const SRC_DST_NOT_REFERENCES: usize = transmute_ref!(0usize);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-src-dst-not-references.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-src-dst-not-references.stderr deleted file mode 100644 index 8a80e99..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-src-dst-not-references.stderr +++ /dev/null
@@ -1,45 +0,0 @@ -error[E0308]: mismatched types - --> tests/ui-stable/transmute-ref-src-dst-not-references.rs:17:54 - | -17 | const SRC_DST_NOT_REFERENCES: usize = transmute_ref!(0usize); - | ---------------^^^^^^- - | | | - | | expected `&_`, found `usize` - | expected due to this - | - = note: expected reference `&_` - found type `usize` -help: consider borrowing here - | -17 | const SRC_DST_NOT_REFERENCES: usize = transmute_ref!(&0usize); - | + - -error[E0308]: mismatched types - --> tests/ui-stable/transmute-ref-src-dst-not-references.rs:17:39 - | -17 | const SRC_DST_NOT_REFERENCES: usize = transmute_ref!(0usize); - | ^^^^^^^^^^^^^^^^^^^^^^ expected `usize`, found `&_` - | - = note: expected type `usize` - found reference `&_` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0308]: mismatched types - --> tests/ui-stable/transmute-ref-src-dst-not-references.rs:17:39 - | -17 | const SRC_DST_NOT_REFERENCES: usize = transmute_ref!(0usize); - | ^^^^^^^^^^^^^^^^^^^^^^ expected `usize`, found `&_` - | - = note: expected type `usize` - found reference `&_` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0308]: mismatched types - --> tests/ui-stable/transmute-ref-src-dst-not-references.rs:17:39 - | -17 | const SRC_DST_NOT_REFERENCES: usize = transmute_ref!(0usize); - | ^^^^^^^^^^^^^^^^^^^^^^ expected `usize`, found `&_` - | - = note: expected type `usize` - found reference `&_` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-src-dst-unsized.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-src-dst-unsized.rs deleted file mode 100644 index 6bfe7ff..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-src-dst-unsized.rs +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_ref; - -fn main() {} - -// `transmute_ref!` does not support transmuting between unsized source and -// destination types. -const SRC_DST_UNSIZED: &[u8] = transmute_ref!(&[0u8][..]);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-src-dst-unsized.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-src-dst-unsized.stderr deleted file mode 100644 index 7017c2f8..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-src-dst-unsized.stderr +++ /dev/null
@@ -1,183 +0,0 @@ -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-ref-src-dst-unsized.rs:17:32 - | -17 | const SRC_DST_UNSIZED: &[u8] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | doesn't have a size known at compile-time - | required by a bound introduced by this call - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AssertIsAsBytes` - --> tests/ui-stable/transmute-ref-src-dst-unsized.rs:17:32 - | -17 | const SRC_DST_UNSIZED: &[u8] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertIsAsBytes` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-ref-src-dst-unsized.rs:17:32 - | -17 | const SRC_DST_UNSIZED: &[u8] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AssertIsAsBytes` - --> tests/ui-stable/transmute-ref-src-dst-unsized.rs:17:32 - | -17 | const SRC_DST_UNSIZED: &[u8] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertIsAsBytes` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-ref-src-dst-unsized.rs:17:32 - | -17 | const SRC_DST_UNSIZED: &[u8] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | doesn't have a size known at compile-time - | required by a bound introduced by this call - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AssertIsFromBytes` - --> tests/ui-stable/transmute-ref-src-dst-unsized.rs:17:32 - | -17 | const SRC_DST_UNSIZED: &[u8] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertIsFromBytes` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-ref-src-dst-unsized.rs:17:32 - | -17 | const SRC_DST_UNSIZED: &[u8] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` - = note: all local variables must have a statically known size - = help: unsized locals are gated as an unstable feature - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-ref-src-dst-unsized.rs:17:32 - | -17 | const SRC_DST_UNSIZED: &[u8] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AlignOf::<T>::into_t` - --> src/macro_util.rs - | - | impl<T> AlignOf<T> { - | ^ required by this bound in `AlignOf::<T>::into_t` - | #[inline(never)] // Make `missing_inline_in_public_items` happy. - | pub fn into_t(self) -> T { - | ------ required by a bound in this associated function - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-ref-src-dst-unsized.rs:17:32 - | -17 | const SRC_DST_UNSIZED: &[u8] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` - = note: the left-hand-side of an assignment must have a statically known size - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-ref-src-dst-unsized.rs:17:32 - | -17 | const SRC_DST_UNSIZED: &[u8] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by an implicit `Sized` bound in `AlignOf` - --> src/macro_util.rs - | - | pub struct AlignOf<T> { - | ^ required by the implicit `Sized` requirement on this type parameter in `AlignOf` - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-ref-src-dst-unsized.rs:17:32 - | -17 | const SRC_DST_UNSIZED: &[u8] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by an implicit `Sized` bound in `MaxAlignsOf` - --> src/macro_util.rs - | - | pub union MaxAlignsOf<T, U> { - | ^ required by the implicit `Sized` requirement on this type parameter in `MaxAlignsOf` - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-ref-src-dst-unsized.rs:17:32 - | -17 | const SRC_DST_UNSIZED: &[u8] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by an implicit `Sized` bound in `AlignOf` - --> src/macro_util.rs - | - | pub struct AlignOf<T> { - | ^ required by the implicit `Sized` requirement on this type parameter in `AlignOf` - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-ref-src-dst-unsized.rs:17:32 - | -17 | const SRC_DST_UNSIZED: &[u8] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` - = note: all local variables must have a statically known size - = help: unsized locals are gated as an unstable feature - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-ref-src-dst-unsized.rs:17:32 - | -17 | const SRC_DST_UNSIZED: &[u8] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by an implicit `Sized` bound in `transmute` - --> $RUST/core/src/intrinsics.rs - | - | pub fn transmute<Src, Dst>(src: Src) -> Dst; - | ^^^ required by the implicit `Sized` requirement on this type parameter in `transmute` - = note: this error originates in the macro `$crate::assert_size_eq` which comes from the expansion of the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-ref-src-dst-unsized.rs:17:32 - | -17 | const SRC_DST_UNSIZED: &[u8] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | doesn't have a size known at compile-time - | required by a bound introduced by this call - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by an implicit `Sized` bound in `transmute_ref` - --> src/macro_util.rs - | - | pub const unsafe fn transmute_ref<'dst, 'src: 'dst, Src: 'src, Dst: 'dst>( - | ^^^ required by the implicit `Sized` requirement on this type parameter in `transmute_ref` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-ref-src-dst-unsized.rs:17:32 - | -17 | const SRC_DST_UNSIZED: &[u8] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by an implicit `Sized` bound in `transmute_ref` - --> src/macro_util.rs - | - | pub const unsafe fn transmute_ref<'dst, 'src: 'dst, Src: 'src, Dst: 'dst>( - | ^^^ required by the implicit `Sized` requirement on this type parameter in `transmute_ref` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-src-generic.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-src-generic.rs deleted file mode 100644 index 010281c3..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-src-generic.rs +++ /dev/null
@@ -1,18 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::{transmute_ref, AsBytes}; - -fn main() {} - -fn transmute_ref<T: AsBytes>(t: &T) -> &u8 { - // `transmute_ref!` requires the source type to be concrete. - transmute_ref!(t) -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-src-generic.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-src-generic.stderr deleted file mode 100644 index b6bbd164..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-src-generic.stderr +++ /dev/null
@@ -1,19 +0,0 @@ -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-stable/transmute-ref-src-generic.rs:17:5 - | -17 | transmute_ref!(t) - | ^^^^^^^^^^^^^^^^^ - | - = note: source type: `T` (this type does not have a fixed size) - = note: target type: `u8` (8 bits) - = note: this error originates in the macro `$crate::assert_size_eq` which comes from the expansion of the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-stable/transmute-ref-src-generic.rs:17:5 - | -17 | transmute_ref!(t) - | ^^^^^^^^^^^^^^^^^ - | - = note: source type: `AlignOf<T>` (size can vary because of T) - = note: target type: `MaxAlignsOf<T, u8>` (size can vary because of T) - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-src-not-a-reference.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-src-not-a-reference.rs deleted file mode 100644 index 90661b3e..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-src-not-a-reference.rs +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_ref; - -fn main() {} - -// `transmute_ref!` does not support transmuting from a non-reference source -// type. -const SRC_NOT_A_REFERENCE: &u8 = transmute_ref!(0usize);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-src-not-a-reference.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-src-not-a-reference.stderr deleted file mode 100644 index 622c3db..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-src-not-a-reference.stderr +++ /dev/null
@@ -1,15 +0,0 @@ -error[E0308]: mismatched types - --> tests/ui-stable/transmute-ref-src-not-a-reference.rs:17:49 - | -17 | const SRC_NOT_A_REFERENCE: &u8 = transmute_ref!(0usize); - | ---------------^^^^^^- - | | | - | | expected `&_`, found `usize` - | expected due to this - | - = note: expected reference `&_` - found type `usize` -help: consider borrowing here - | -17 | const SRC_NOT_A_REFERENCE: &u8 = transmute_ref!(&0usize); - | +
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-src-not-asbytes.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-src-not-asbytes.rs deleted file mode 100644 index 6ab19f3c..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-src-not-asbytes.rs +++ /dev/null
@@ -1,18 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -include!("../../zerocopy-derive/tests/util.rs"); - -extern crate zerocopy; - -use zerocopy::transmute_ref; - -fn main() {} - -// `transmute_ref` requires that the source type implements `AsBytes` -const SRC_NOT_AS_BYTES: &AU16 = transmute_ref!(&NotZerocopy(AU16(0)));
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-src-not-asbytes.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-src-not-asbytes.stderr deleted file mode 100644 index 3b01fad..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-src-not-asbytes.stderr +++ /dev/null
@@ -1,48 +0,0 @@ -error[E0277]: the trait bound `NotZerocopy<AU16>: AsBytes` is not satisfied - --> tests/ui-stable/transmute-ref-src-not-asbytes.rs:18:33 - | -18 | const SRC_NOT_AS_BYTES: &AU16 = transmute_ref!(&NotZerocopy(AU16(0))); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | the trait `AsBytes` is not implemented for `NotZerocopy<AU16>` - | required by a bound introduced by this call - | - = help: the following other types implement trait `AsBytes`: - () - AU16 - F32<O> - F64<O> - I128<O> - I16<O> - I32<O> - I64<O> - and $N others -note: required by a bound in `AssertIsAsBytes` - --> tests/ui-stable/transmute-ref-src-not-asbytes.rs:18:33 - | -18 | const SRC_NOT_AS_BYTES: &AU16 = transmute_ref!(&NotZerocopy(AU16(0))); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertIsAsBytes` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `NotZerocopy<AU16>: AsBytes` is not satisfied - --> tests/ui-stable/transmute-ref-src-not-asbytes.rs:18:33 - | -18 | const SRC_NOT_AS_BYTES: &AU16 = transmute_ref!(&NotZerocopy(AU16(0))); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `AsBytes` is not implemented for `NotZerocopy<AU16>` - | - = help: the following other types implement trait `AsBytes`: - () - AU16 - F32<O> - F64<O> - I128<O> - I16<O> - I32<O> - I64<O> - and $N others -note: required by a bound in `AssertIsAsBytes` - --> tests/ui-stable/transmute-ref-src-not-asbytes.rs:18:33 - | -18 | const SRC_NOT_AS_BYTES: &AU16 = transmute_ref!(&NotZerocopy(AU16(0))); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertIsAsBytes` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-src-unsized.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-src-unsized.rs deleted file mode 100644 index 14e72b4..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-src-unsized.rs +++ /dev/null
@@ -1,16 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::transmute_ref; - -fn main() {} - -// `transmute_ref!` does not support transmuting from an unsized source type. -const SRC_UNSIZED: &[u8; 1] = transmute_ref!(&[0u8][..]);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-src-unsized.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-src-unsized.stderr deleted file mode 100644 index 73984d0..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-ref-src-unsized.stderr +++ /dev/null
@@ -1,127 +0,0 @@ -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-ref-src-unsized.rs:16:31 - | -16 | const SRC_UNSIZED: &[u8; 1] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | doesn't have a size known at compile-time - | required by a bound introduced by this call - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AssertIsAsBytes` - --> tests/ui-stable/transmute-ref-src-unsized.rs:16:31 - | -16 | const SRC_UNSIZED: &[u8; 1] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertIsAsBytes` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-ref-src-unsized.rs:16:31 - | -16 | const SRC_UNSIZED: &[u8; 1] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AssertIsAsBytes` - --> tests/ui-stable/transmute-ref-src-unsized.rs:16:31 - | -16 | const SRC_UNSIZED: &[u8; 1] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertIsAsBytes` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-ref-src-unsized.rs:16:31 - | -16 | const SRC_UNSIZED: &[u8; 1] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` - = note: all local variables must have a statically known size - = help: unsized locals are gated as an unstable feature - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-ref-src-unsized.rs:16:31 - | -16 | const SRC_UNSIZED: &[u8; 1] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `AlignOf::<T>::into_t` - --> src/macro_util.rs - | - | impl<T> AlignOf<T> { - | ^ required by this bound in `AlignOf::<T>::into_t` - | #[inline(never)] // Make `missing_inline_in_public_items` happy. - | pub fn into_t(self) -> T { - | ------ required by a bound in this associated function - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-ref-src-unsized.rs:16:31 - | -16 | const SRC_UNSIZED: &[u8; 1] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` - = note: the left-hand-side of an assignment must have a statically known size - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-ref-src-unsized.rs:16:31 - | -16 | const SRC_UNSIZED: &[u8; 1] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by an implicit `Sized` bound in `AlignOf` - --> src/macro_util.rs - | - | pub struct AlignOf<T> { - | ^ required by the implicit `Sized` requirement on this type parameter in `AlignOf` - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-ref-src-unsized.rs:16:31 - | -16 | const SRC_UNSIZED: &[u8; 1] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by an implicit `Sized` bound in `MaxAlignsOf` - --> src/macro_util.rs - | - | pub union MaxAlignsOf<T, U> { - | ^ required by the implicit `Sized` requirement on this type parameter in `MaxAlignsOf` - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-ref-src-unsized.rs:16:31 - | -16 | const SRC_UNSIZED: &[u8; 1] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by an implicit `Sized` bound in `AlignOf` - --> src/macro_util.rs - | - | pub struct AlignOf<T> { - | ^ required by the implicit `Sized` requirement on this type parameter in `AlignOf` - = note: this error originates in the macro `$crate::assert_align_gt_eq` which comes from the expansion of the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/transmute-ref-src-unsized.rs:16:31 - | -16 | const SRC_UNSIZED: &[u8; 1] = transmute_ref!(&[0u8][..]); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | doesn't have a size known at compile-time - | required by a bound introduced by this call - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by an implicit `Sized` bound in `transmute_ref` - --> src/macro_util.rs - | - | pub const unsafe fn transmute_ref<'dst, 'src: 'dst, Src: 'src, Dst: 'dst>( - | ^^^ required by the implicit `Sized` requirement on this type parameter in `transmute_ref` - = note: this error originates in the macro `transmute_ref` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-size-decrease.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-size-decrease.rs deleted file mode 100644 index 1d56831f..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-size-decrease.rs +++ /dev/null
@@ -1,19 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -include!("../../zerocopy-derive/tests/util.rs"); - -extern crate zerocopy; - -use zerocopy::transmute; - -fn main() {} - -// Although this is not a soundness requirement, we currently require that the -// size of the destination type is not smaller than the size of the source type. -const DECREASE_SIZE: u8 = transmute!(AU16(0));
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-size-decrease.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-size-decrease.stderr deleted file mode 100644 index 0241662f..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-size-decrease.stderr +++ /dev/null
@@ -1,9 +0,0 @@ -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-stable/transmute-size-decrease.rs:19:27 - | -19 | const DECREASE_SIZE: u8 = transmute!(AU16(0)); - | ^^^^^^^^^^^^^^^^^^^ - | - = note: source type: `AU16` (16 bits) - = note: target type: `u8` (8 bits) - = note: this error originates in the macro `transmute` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-size-increase.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-size-increase.rs deleted file mode 100644 index 32f9363..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-size-increase.rs +++ /dev/null
@@ -1,19 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -include!("../../zerocopy-derive/tests/util.rs"); - -extern crate zerocopy; - -use zerocopy::transmute; - -fn main() {} - -// `transmute!` does not support transmuting from a smaller type to a larger -// one. -const INCREASE_SIZE: AU16 = transmute!(0u8);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-size-increase.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-size-increase.stderr deleted file mode 100644 index 87d82a2..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-size-increase.stderr +++ /dev/null
@@ -1,9 +0,0 @@ -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> tests/ui-stable/transmute-size-increase.rs:19:29 - | -19 | const INCREASE_SIZE: AU16 = transmute!(0u8); - | ^^^^^^^^^^^^^^^ - | - = note: source type: `u8` (8 bits) - = note: target type: `AU16` (16 bits) - = note: this error originates in the macro `transmute` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-src-not-asbytes.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-src-not-asbytes.rs deleted file mode 100644 index dd73021..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-src-not-asbytes.rs +++ /dev/null
@@ -1,18 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -include!("../../zerocopy-derive/tests/util.rs"); - -extern crate zerocopy; - -use zerocopy::transmute; - -fn main() {} - -// `transmute` requires that the source type implements `AsBytes` -const SRC_NOT_AS_BYTES: AU16 = transmute!(NotZerocopy(AU16(0)));
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-src-not-asbytes.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-src-not-asbytes.stderr deleted file mode 100644 index 836bf23..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/tests/ui-stable/transmute-src-not-asbytes.stderr +++ /dev/null
@@ -1,48 +0,0 @@ -error[E0277]: the trait bound `NotZerocopy<AU16>: AsBytes` is not satisfied - --> tests/ui-stable/transmute-src-not-asbytes.rs:18:32 - | -18 | const SRC_NOT_AS_BYTES: AU16 = transmute!(NotZerocopy(AU16(0))); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | the trait `AsBytes` is not implemented for `NotZerocopy<AU16>` - | required by a bound introduced by this call - | - = help: the following other types implement trait `AsBytes`: - () - AU16 - F32<O> - F64<O> - I128<O> - I16<O> - I32<O> - I64<O> - and $N others -note: required by a bound in `AssertIsAsBytes` - --> tests/ui-stable/transmute-src-not-asbytes.rs:18:32 - | -18 | const SRC_NOT_AS_BYTES: AU16 = transmute!(NotZerocopy(AU16(0))); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertIsAsBytes` - = note: this error originates in the macro `transmute` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `NotZerocopy<AU16>: AsBytes` is not satisfied - --> tests/ui-stable/transmute-src-not-asbytes.rs:18:32 - | -18 | const SRC_NOT_AS_BYTES: AU16 = transmute!(NotZerocopy(AU16(0))); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `AsBytes` is not implemented for `NotZerocopy<AU16>` - | - = help: the following other types implement trait `AsBytes`: - () - AU16 - F32<O> - F64<O> - I128<O> - I16<O> - I32<O> - I64<O> - and $N others -note: required by a bound in `AssertIsAsBytes` - --> tests/ui-stable/transmute-src-not-asbytes.rs:18:32 - | -18 | const SRC_NOT_AS_BYTES: AU16 = transmute!(NotZerocopy(AU16(0))); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `AssertIsAsBytes` - = note: this error originates in the macro `transmute` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/.cargo-checksum.json b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/.cargo-checksum.json deleted file mode 100644 index 697c9ce..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/.cargo-checksum.json +++ /dev/null
@@ -1 +0,0 @@ -{"files":{}}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/.cargo_vcs_info.json b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/.cargo_vcs_info.json deleted file mode 100644 index 754de32..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/.cargo_vcs_info.json +++ /dev/null
@@ -1,6 +0,0 @@ -{ - "git": { - "sha1": "727de668608f2d16e151c42e344d172c0931b1e9" - }, - "path_in_vcs": "zerocopy-derive" -} \ No newline at end of file
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/Cargo.toml b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/Cargo.toml deleted file mode 100644 index 70758ac9..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/Cargo.toml +++ /dev/null
@@ -1,43 +0,0 @@ -# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO -# -# When uploading crates to the registry Cargo will automatically -# "normalize" Cargo.toml files for maximal compatibility -# with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g., crates.io) dependencies. -# -# If you are reading this file be aware that the original Cargo.toml -# will likely look very different (and much more reasonable). -# See Cargo.toml.orig for the original contents. - -[package] -edition = "2018" -name = "zerocopy-derive" -version = "0.7.35" -authors = ["Joshua Liebow-Feeser <joshlf@google.com>"] -exclude = [ - ".*", - "tests/enum_from_bytes.rs", - "tests/ui-nightly/enum_from_bytes_u16_too_few.rs.disabled", -] -description = "Custom derive for traits from the zerocopy crate" -license = "BSD-2-Clause OR Apache-2.0 OR MIT" -repository = "https://github.com/google/zerocopy" - -[lib] -proc-macro = true - -[dependencies.proc-macro2] -version = "1.0.1" - -[dependencies.quote] -version = "1.0.10" - -[dependencies.syn] -version = "2.0.31" - -[dev-dependencies.static_assertions] -version = "1.1" - -[dev-dependencies.trybuild] -version = "=1.0.85" -features = ["diff"]
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/Cargo.toml.orig b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/Cargo.toml.orig deleted file mode 100644 index bde423d..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/Cargo.toml.orig +++ /dev/null
@@ -1,41 +0,0 @@ -# Copyright 2019 The Fuchsia Authors -# -# Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -# <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -# license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -# This file may not be copied, modified, or distributed except according to -# those terms. - -[package] -edition = "2018" -name = "zerocopy-derive" -version = "0.7.35" -authors = ["Joshua Liebow-Feeser <joshlf@google.com>"] -description = "Custom derive for traits from the zerocopy crate" -license = "BSD-2-Clause OR Apache-2.0 OR MIT" -repository = "https://github.com/google/zerocopy" - -# We prefer to include tests when publishing to crates.io so that Crater [1] can -# detect regressions in our test suite. These two tests are excessively large, -# so we exclude them to keep the published crate file small. -# -# [1] https://github.com/rust-lang/crater -exclude = [".*", "tests/enum_from_bytes.rs", "tests/ui-nightly/enum_from_bytes_u16_too_few.rs.disabled"] - -[lib] -proc-macro = true - -[dependencies] -proc-macro2 = "1.0.1" -quote = "1.0.10" -syn = "2.0.31" - -[dev-dependencies] -static_assertions = "1.1" -testutil = { path = "../testutil" } -# Pinned to a specific version so that the version used for local development -# and the version used in CI are guaranteed to be the same. Future versions -# sometimes change the output format slightly, so a version mismatch can cause -# CI test failures. -trybuild = { version = "=1.0.85", features = ["diff"] } -zerocopy = { path = "../", features = ["default", "derive"] }
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/LICENSE-APACHE b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/LICENSE-APACHE deleted file mode 100644 index 2dc22c1..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/LICENSE-APACHE +++ /dev/null
@@ -1,202 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright 2023 The Fuchsia Authors - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/LICENSE-BSD b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/LICENSE-BSD deleted file mode 100644 index 7ed244f..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/LICENSE-BSD +++ /dev/null
@@ -1,24 +0,0 @@ -Copyright 2019 The Fuchsia Authors. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/LICENSE-MIT b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/LICENSE-MIT deleted file mode 100644 index 26e1521..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/LICENSE-MIT +++ /dev/null
@@ -1,26 +0,0 @@ -Copyright 2023 The Fuchsia Authors - -Permission is hereby granted, free of charge, to any -person obtaining a copy of this software and associated -documentation files (the "Software"), to deal in the -Software without restriction, including without -limitation the rights to use, copy, modify, merge, -publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software -is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice -shall be included in all copies or substantial portions -of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF -ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED -TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT -SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR -IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. -
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/src/ext.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/src/ext.rs deleted file mode 100644 index 87cf838..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/src/ext.rs +++ /dev/null
@@ -1,53 +0,0 @@ -// Copyright 2019 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -use syn::{Data, DataEnum, DataStruct, DataUnion, Type}; - -pub trait DataExt { - /// Extract the types of all fields. For enums, extract the types of fields - /// from each variant. - fn field_types(&self) -> Vec<&Type>; -} - -impl DataExt for Data { - fn field_types(&self) -> Vec<&Type> { - match self { - Data::Struct(strc) => strc.field_types(), - Data::Enum(enm) => enm.field_types(), - Data::Union(un) => un.field_types(), - } - } -} - -impl DataExt for DataStruct { - fn field_types(&self) -> Vec<&Type> { - self.fields.iter().map(|f| &f.ty).collect() - } -} - -impl DataExt for DataEnum { - fn field_types(&self) -> Vec<&Type> { - self.variants.iter().flat_map(|var| &var.fields).map(|f| &f.ty).collect() - } -} - -impl DataExt for DataUnion { - fn field_types(&self) -> Vec<&Type> { - self.fields.named.iter().map(|f| &f.ty).collect() - } -} - -pub trait EnumExt { - fn is_c_like(&self) -> bool; -} - -impl EnumExt for DataEnum { - fn is_c_like(&self) -> bool { - self.field_types().is_empty() - } -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/src/lib.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/src/lib.rs deleted file mode 100644 index 1767310e..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/src/lib.rs +++ /dev/null
@@ -1,887 +0,0 @@ -// Copyright 2019 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -//! Derive macros for [zerocopy]'s traits. -//! -//! [zerocopy]: https://docs.rs/zerocopy - -// Sometimes we want to use lints which were added after our MSRV. -// `unknown_lints` is `warn` by default and we deny warnings in CI, so without -// this attribute, any unknown lint would cause a CI failure when testing with -// our MSRV. -#![allow(unknown_lints)] -#![deny(renamed_and_removed_lints)] -#![deny(clippy::all, clippy::missing_safety_doc, clippy::undocumented_unsafe_blocks)] -#![deny( - rustdoc::bare_urls, - rustdoc::broken_intra_doc_links, - rustdoc::invalid_codeblock_attributes, - rustdoc::invalid_html_tags, - rustdoc::invalid_rust_codeblocks, - rustdoc::missing_crate_level_docs, - rustdoc::private_intra_doc_links -)] -#![recursion_limit = "128"] - -mod ext; -mod repr; - -use { - proc_macro2::Span, - quote::quote, - syn::{ - parse_quote, Data, DataEnum, DataStruct, DataUnion, DeriveInput, Error, Expr, ExprLit, - GenericParam, Ident, Lit, - }, -}; - -use {crate::ext::*, crate::repr::*}; - -// Unwraps a `Result<_, Vec<Error>>`, converting any `Err` value into a -// `TokenStream` and returning it. -macro_rules! try_or_print { - ($e:expr) => { - match $e { - Ok(x) => x, - Err(errors) => return print_all_errors(errors).into(), - } - }; -} - -// TODO(https://github.com/rust-lang/rust/issues/54140): Some errors could be -// made better if we could add multiple lines of error output like this: -// -// error: unsupported representation -// --> enum.rs:28:8 -// | -// 28 | #[repr(transparent)] -// | -// help: required by the derive of FromBytes -// -// Instead, we have more verbose error messages like "unsupported representation -// for deriving FromZeroes, FromBytes, AsBytes, or Unaligned on an enum" -// -// This will probably require Span::error -// (https://doc.rust-lang.org/nightly/proc_macro/struct.Span.html#method.error), -// which is currently unstable. Revisit this once it's stable. - -#[proc_macro_derive(KnownLayout)] -pub fn derive_known_layout(ts: proc_macro::TokenStream) -> proc_macro::TokenStream { - let ast = syn::parse_macro_input!(ts as DeriveInput); - - let is_repr_c_struct = match &ast.data { - Data::Struct(..) => { - let reprs = try_or_print!(repr::reprs::<Repr>(&ast.attrs)); - if reprs.iter().any(|(_meta, repr)| repr == &Repr::C) { - Some(reprs) - } else { - None - } - } - Data::Enum(..) | Data::Union(..) => None, - }; - - let fields = ast.data.field_types(); - - let (require_self_sized, extras) = if let ( - Some(reprs), - Some((trailing_field, leading_fields)), - ) = (is_repr_c_struct, fields.split_last()) - { - let repr_align = reprs - .iter() - .find_map( - |(_meta, repr)| { - if let Repr::Align(repr_align) = repr { - Some(repr_align) - } else { - None - } - }, - ) - .map(|repr_align| quote!(NonZeroUsize::new(#repr_align as usize))) - .unwrap_or(quote!(None)); - - let repr_packed = reprs - .iter() - .find_map(|(_meta, repr)| match repr { - Repr::Packed => Some(1), - Repr::PackedN(repr_packed) => Some(*repr_packed), - _ => None, - }) - .map(|repr_packed| quote!(NonZeroUsize::new(#repr_packed as usize))) - .unwrap_or(quote!(None)); - - ( - false, - quote!( - // SAFETY: `LAYOUT` accurately describes the layout of `Self`. - // The layout of `Self` is reflected using a sequence of - // invocations of `DstLayout::{new_zst,extend,pad_to_align}`. - // The documentation of these items vows that invocations in - // this manner will acurately describe a type, so long as: - // - // - that type is `repr(C)`, - // - its fields are enumerated in the order they appear, - // - the presence of `repr_align` and `repr_packed` are correctly accounted for. - // - // We respect all three of these preconditions here. This - // expansion is only used if `is_repr_c_struct`, we enumerate - // the fields in order, and we extract the values of `align(N)` - // and `packed(N)`. - const LAYOUT: ::zerocopy::DstLayout = { - use ::zerocopy::macro_util::core_reexport::num::NonZeroUsize; - use ::zerocopy::{DstLayout, KnownLayout}; - - let repr_align = #repr_align; - let repr_packed = #repr_packed; - - DstLayout::new_zst(repr_align) - #(.extend(DstLayout::for_type::<#leading_fields>(), repr_packed))* - .extend(<#trailing_field as KnownLayout>::LAYOUT, repr_packed) - .pad_to_align() - }; - - // SAFETY: - // - The recursive call to `raw_from_ptr_len` preserves both address and provenance. - // - The `as` cast preserves both address and provenance. - // - `NonNull::new_unchecked` preserves both address and provenance. - #[inline(always)] - fn raw_from_ptr_len( - bytes: ::zerocopy::macro_util::core_reexport::ptr::NonNull<u8>, - elems: usize, - ) -> ::zerocopy::macro_util::core_reexport::ptr::NonNull<Self> { - use ::zerocopy::{KnownLayout}; - let trailing = <#trailing_field as KnownLayout>::raw_from_ptr_len(bytes, elems); - let slf = trailing.as_ptr() as *mut Self; - // SAFETY: Constructed from `trailing`, which is non-null. - unsafe { ::zerocopy::macro_util::core_reexport::ptr::NonNull::new_unchecked(slf) } - } - ), - ) - } else { - // For enums, unions, and non-`repr(C)` structs, we require that - // `Self` is sized, and as a result don't need to reason about the - // internals of the type. - ( - true, - quote!( - // SAFETY: `LAYOUT` is guaranteed to accurately describe the - // layout of `Self`, because that is the documented safety - // contract of `DstLayout::for_type`. - const LAYOUT: ::zerocopy::DstLayout = ::zerocopy::DstLayout::for_type::<Self>(); - - // SAFETY: `.cast` preserves address and provenance. - // - // TODO(#429): Add documentation to `.cast` that promises that - // it preserves provenance. - #[inline(always)] - fn raw_from_ptr_len( - bytes: ::zerocopy::macro_util::core_reexport::ptr::NonNull<u8>, - _elems: usize, - ) -> ::zerocopy::macro_util::core_reexport::ptr::NonNull<Self> { - bytes.cast::<Self>() - } - ), - ) - }; - - match &ast.data { - Data::Struct(strct) => { - let require_trait_bound_on_field_types = if require_self_sized { - RequireBoundedFields::No - } else { - RequireBoundedFields::Trailing - }; - - // A bound on the trailing field is required, since structs are - // unsized if their trailing field is unsized. Reflecting the layout - // of an usized trailing field requires that the field is - // `KnownLayout`. - impl_block( - &ast, - strct, - Trait::KnownLayout, - require_trait_bound_on_field_types, - require_self_sized, - None, - Some(extras), - ) - } - Data::Enum(enm) => { - // A bound on the trailing field is not required, since enums cannot - // currently be unsized. - impl_block( - &ast, - enm, - Trait::KnownLayout, - RequireBoundedFields::No, - true, - None, - Some(extras), - ) - } - Data::Union(unn) => { - // A bound on the trailing field is not required, since unions - // cannot currently be unsized. - impl_block( - &ast, - unn, - Trait::KnownLayout, - RequireBoundedFields::No, - true, - None, - Some(extras), - ) - } - } - .into() -} - -#[proc_macro_derive(FromZeroes)] -pub fn derive_from_zeroes(ts: proc_macro::TokenStream) -> proc_macro::TokenStream { - let ast = syn::parse_macro_input!(ts as DeriveInput); - match &ast.data { - Data::Struct(strct) => derive_from_zeroes_struct(&ast, strct), - Data::Enum(enm) => derive_from_zeroes_enum(&ast, enm), - Data::Union(unn) => derive_from_zeroes_union(&ast, unn), - } - .into() -} - -#[proc_macro_derive(FromBytes)] -pub fn derive_from_bytes(ts: proc_macro::TokenStream) -> proc_macro::TokenStream { - let ast = syn::parse_macro_input!(ts as DeriveInput); - match &ast.data { - Data::Struct(strct) => derive_from_bytes_struct(&ast, strct), - Data::Enum(enm) => derive_from_bytes_enum(&ast, enm), - Data::Union(unn) => derive_from_bytes_union(&ast, unn), - } - .into() -} - -#[proc_macro_derive(AsBytes)] -pub fn derive_as_bytes(ts: proc_macro::TokenStream) -> proc_macro::TokenStream { - let ast = syn::parse_macro_input!(ts as DeriveInput); - match &ast.data { - Data::Struct(strct) => derive_as_bytes_struct(&ast, strct), - Data::Enum(enm) => derive_as_bytes_enum(&ast, enm), - Data::Union(unn) => derive_as_bytes_union(&ast, unn), - } - .into() -} - -#[proc_macro_derive(Unaligned)] -pub fn derive_unaligned(ts: proc_macro::TokenStream) -> proc_macro::TokenStream { - let ast = syn::parse_macro_input!(ts as DeriveInput); - match &ast.data { - Data::Struct(strct) => derive_unaligned_struct(&ast, strct), - Data::Enum(enm) => derive_unaligned_enum(&ast, enm), - Data::Union(unn) => derive_unaligned_union(&ast, unn), - } - .into() -} - -const STRUCT_UNION_ALLOWED_REPR_COMBINATIONS: &[&[StructRepr]] = &[ - &[StructRepr::C], - &[StructRepr::Transparent], - &[StructRepr::Packed], - &[StructRepr::C, StructRepr::Packed], -]; - -// A struct is `FromZeroes` if: -// - all fields are `FromZeroes` - -fn derive_from_zeroes_struct(ast: &DeriveInput, strct: &DataStruct) -> proc_macro2::TokenStream { - impl_block(ast, strct, Trait::FromZeroes, RequireBoundedFields::Yes, false, None, None) -} - -// An enum is `FromZeroes` if: -// - all of its variants are fieldless -// - one of the variants has a discriminant of `0` - -fn derive_from_zeroes_enum(ast: &DeriveInput, enm: &DataEnum) -> proc_macro2::TokenStream { - if !enm.is_c_like() { - return Error::new_spanned(ast, "only C-like enums can implement FromZeroes") - .to_compile_error(); - } - - let has_explicit_zero_discriminant = - enm.variants.iter().filter_map(|v| v.discriminant.as_ref()).any(|(_, e)| { - if let Expr::Lit(ExprLit { lit: Lit::Int(i), .. }) = e { - i.base10_parse::<usize>().ok() == Some(0) - } else { - false - } - }); - // If the first variant of an enum does not specify its discriminant, it is set to zero: - // https://doc.rust-lang.org/reference/items/enumerations.html#custom-discriminant-values-for-fieldless-enumerations - let has_implicit_zero_discriminant = - enm.variants.iter().next().map(|v| v.discriminant.is_none()) == Some(true); - - if !has_explicit_zero_discriminant && !has_implicit_zero_discriminant { - return Error::new_spanned( - ast, - "FromZeroes only supported on enums with a variant that has a discriminant of `0`", - ) - .to_compile_error(); - } - - impl_block(ast, enm, Trait::FromZeroes, RequireBoundedFields::Yes, false, None, None) -} - -// Like structs, unions are `FromZeroes` if -// - all fields are `FromZeroes` - -fn derive_from_zeroes_union(ast: &DeriveInput, unn: &DataUnion) -> proc_macro2::TokenStream { - impl_block(ast, unn, Trait::FromZeroes, RequireBoundedFields::Yes, false, None, None) -} - -// A struct is `FromBytes` if: -// - all fields are `FromBytes` - -fn derive_from_bytes_struct(ast: &DeriveInput, strct: &DataStruct) -> proc_macro2::TokenStream { - impl_block(ast, strct, Trait::FromBytes, RequireBoundedFields::Yes, false, None, None) -} - -// An enum is `FromBytes` if: -// - Every possible bit pattern must be valid, which means that every bit -// pattern must correspond to a different enum variant. Thus, for an enum -// whose layout takes up N bytes, there must be 2^N variants. -// - Since we must know N, only representations which guarantee the layout's -// size are allowed. These are `repr(uN)` and `repr(iN)` (`repr(C)` implies an -// implementation-defined size). `usize` and `isize` technically guarantee the -// layout's size, but would require us to know how large those are on the -// target platform. This isn't terribly difficult - we could emit a const -// expression that could call `core::mem::size_of` in order to determine the -// size and check against the number of enum variants, but a) this would be -// platform-specific and, b) even on Rust's smallest bit width platform (32), -// this would require ~4 billion enum variants, which obviously isn't a thing. - -fn derive_from_bytes_enum(ast: &DeriveInput, enm: &DataEnum) -> proc_macro2::TokenStream { - if !enm.is_c_like() { - return Error::new_spanned(ast, "only C-like enums can implement FromBytes") - .to_compile_error(); - } - - let reprs = try_or_print!(ENUM_FROM_BYTES_CFG.validate_reprs(ast)); - - let variants_required = match reprs.as_slice() { - [EnumRepr::U8] | [EnumRepr::I8] => 1usize << 8, - [EnumRepr::U16] | [EnumRepr::I16] => 1usize << 16, - // `validate_reprs` has already validated that it's one of the preceding - // patterns. - _ => unreachable!(), - }; - if enm.variants.len() != variants_required { - return Error::new_spanned( - ast, - format!( - "FromBytes only supported on {} enum with {} variants", - reprs[0], variants_required - ), - ) - .to_compile_error(); - } - - impl_block(ast, enm, Trait::FromBytes, RequireBoundedFields::Yes, false, None, None) -} - -#[rustfmt::skip] -const ENUM_FROM_BYTES_CFG: Config<EnumRepr> = { - use EnumRepr::*; - Config { - allowed_combinations_message: r#"FromBytes requires repr of "u8", "u16", "i8", or "i16""#, - derive_unaligned: false, - allowed_combinations: &[ - &[U8], - &[U16], - &[I8], - &[I16], - ], - disallowed_but_legal_combinations: &[ - &[C], - &[U32], - &[I32], - &[U64], - &[I64], - &[Usize], - &[Isize], - ], - } -}; - -// Like structs, unions are `FromBytes` if -// - all fields are `FromBytes` - -fn derive_from_bytes_union(ast: &DeriveInput, unn: &DataUnion) -> proc_macro2::TokenStream { - impl_block(ast, unn, Trait::FromBytes, RequireBoundedFields::Yes, false, None, None) -} - -// A struct is `AsBytes` if: -// - all fields are `AsBytes` -// - `repr(C)` or `repr(transparent)` and -// - no padding (size of struct equals sum of size of field types) -// - `repr(packed)` - -fn derive_as_bytes_struct(ast: &DeriveInput, strct: &DataStruct) -> proc_macro2::TokenStream { - let reprs = try_or_print!(STRUCT_UNION_AS_BYTES_CFG.validate_reprs(ast)); - let is_transparent = reprs.contains(&StructRepr::Transparent); - let is_packed = reprs.contains(&StructRepr::Packed); - - // TODO(#10): Support type parameters for non-transparent, non-packed - // structs. - if !ast.generics.params.is_empty() && !is_transparent && !is_packed { - return Error::new( - Span::call_site(), - "unsupported on generic structs that are not repr(transparent) or repr(packed)", - ) - .to_compile_error(); - } - - // We don't need a padding check if the struct is repr(transparent) or - // repr(packed). - // - repr(transparent): The layout and ABI of the whole struct is the same - // as its only non-ZST field (meaning there's no padding outside of that - // field) and we require that field to be `AsBytes` (meaning there's no - // padding in that field). - // - repr(packed): Any inter-field padding bytes are removed, meaning that - // any padding bytes would need to come from the fields, all of which - // we require to be `AsBytes` (meaning they don't have any padding). - let padding_check = if is_transparent || is_packed { None } else { Some(PaddingCheck::Struct) }; - impl_block(ast, strct, Trait::AsBytes, RequireBoundedFields::Yes, false, padding_check, None) -} - -const STRUCT_UNION_AS_BYTES_CFG: Config<StructRepr> = Config { - // Since `disallowed_but_legal_combinations` is empty, this message will - // never actually be emitted. - allowed_combinations_message: r#"AsBytes requires either a) repr "C" or "transparent" with all fields implementing AsBytes or, b) repr "packed""#, - derive_unaligned: false, - allowed_combinations: STRUCT_UNION_ALLOWED_REPR_COMBINATIONS, - disallowed_but_legal_combinations: &[], -}; - -// An enum is `AsBytes` if it is C-like and has a defined repr. - -fn derive_as_bytes_enum(ast: &DeriveInput, enm: &DataEnum) -> proc_macro2::TokenStream { - if !enm.is_c_like() { - return Error::new_spanned(ast, "only C-like enums can implement AsBytes") - .to_compile_error(); - } - - // We don't care what the repr is; we only care that it is one of the - // allowed ones. - let _: Vec<repr::EnumRepr> = try_or_print!(ENUM_AS_BYTES_CFG.validate_reprs(ast)); - impl_block(ast, enm, Trait::AsBytes, RequireBoundedFields::No, false, None, None) -} - -#[rustfmt::skip] -const ENUM_AS_BYTES_CFG: Config<EnumRepr> = { - use EnumRepr::*; - Config { - // Since `disallowed_but_legal_combinations` is empty, this message will - // never actually be emitted. - allowed_combinations_message: r#"AsBytes requires repr of "C", "u8", "u16", "u32", "u64", "usize", "i8", "i16", "i32", "i64", or "isize""#, - derive_unaligned: false, - allowed_combinations: &[ - &[C], - &[U8], - &[U16], - &[I8], - &[I16], - &[U32], - &[I32], - &[U64], - &[I64], - &[Usize], - &[Isize], - ], - disallowed_but_legal_combinations: &[], - } -}; - -// A union is `AsBytes` if: -// - all fields are `AsBytes` -// - `repr(C)`, `repr(transparent)`, or `repr(packed)` -// - no padding (size of union equals size of each field type) - -fn derive_as_bytes_union(ast: &DeriveInput, unn: &DataUnion) -> proc_macro2::TokenStream { - // TODO(#10): Support type parameters. - if !ast.generics.params.is_empty() { - return Error::new(Span::call_site(), "unsupported on types with type parameters") - .to_compile_error(); - } - - try_or_print!(STRUCT_UNION_AS_BYTES_CFG.validate_reprs(ast)); - - impl_block( - ast, - unn, - Trait::AsBytes, - RequireBoundedFields::Yes, - false, - Some(PaddingCheck::Union), - None, - ) -} - -// A struct is `Unaligned` if: -// - `repr(align)` is no more than 1 and either -// - `repr(C)` or `repr(transparent)` and -// - all fields `Unaligned` -// - `repr(packed)` - -fn derive_unaligned_struct(ast: &DeriveInput, strct: &DataStruct) -> proc_macro2::TokenStream { - let reprs = try_or_print!(STRUCT_UNION_UNALIGNED_CFG.validate_reprs(ast)); - let require_trait_bounds_on_field_types = (!reprs.contains(&StructRepr::Packed)).into(); - - impl_block(ast, strct, Trait::Unaligned, require_trait_bounds_on_field_types, false, None, None) -} - -const STRUCT_UNION_UNALIGNED_CFG: Config<StructRepr> = Config { - // Since `disallowed_but_legal_combinations` is empty, this message will - // never actually be emitted. - allowed_combinations_message: r#"Unaligned requires either a) repr "C" or "transparent" with all fields implementing Unaligned or, b) repr "packed""#, - derive_unaligned: true, - allowed_combinations: STRUCT_UNION_ALLOWED_REPR_COMBINATIONS, - disallowed_but_legal_combinations: &[], -}; - -// An enum is `Unaligned` if: -// - No `repr(align(N > 1))` -// - `repr(u8)` or `repr(i8)` - -fn derive_unaligned_enum(ast: &DeriveInput, enm: &DataEnum) -> proc_macro2::TokenStream { - if !enm.is_c_like() { - return Error::new_spanned(ast, "only C-like enums can implement Unaligned") - .to_compile_error(); - } - - // The only valid reprs are `u8` and `i8`, and optionally `align(1)`. We - // don't actually care what the reprs are so long as they satisfy that - // requirement. - let _: Vec<repr::EnumRepr> = try_or_print!(ENUM_UNALIGNED_CFG.validate_reprs(ast)); - - // C-like enums cannot currently have type parameters, so this value of true - // for `require_trait_bound_on_field_types` doesn't really do anything. But - // it's marginally more future-proof in case that restriction is lifted in - // the future. - impl_block(ast, enm, Trait::Unaligned, RequireBoundedFields::Yes, false, None, None) -} - -#[rustfmt::skip] -const ENUM_UNALIGNED_CFG: Config<EnumRepr> = { - use EnumRepr::*; - Config { - allowed_combinations_message: - r#"Unaligned requires repr of "u8" or "i8", and no alignment (i.e., repr(align(N > 1)))"#, - derive_unaligned: true, - allowed_combinations: &[ - &[U8], - &[I8], - ], - disallowed_but_legal_combinations: &[ - &[C], - &[U16], - &[U32], - &[U64], - &[Usize], - &[I16], - &[I32], - &[I64], - &[Isize], - ], - } -}; - -// Like structs, a union is `Unaligned` if: -// - `repr(align)` is no more than 1 and either -// - `repr(C)` or `repr(transparent)` and -// - all fields `Unaligned` -// - `repr(packed)` - -fn derive_unaligned_union(ast: &DeriveInput, unn: &DataUnion) -> proc_macro2::TokenStream { - let reprs = try_or_print!(STRUCT_UNION_UNALIGNED_CFG.validate_reprs(ast)); - let require_trait_bound_on_field_types = (!reprs.contains(&StructRepr::Packed)).into(); - - impl_block(ast, unn, Trait::Unaligned, require_trait_bound_on_field_types, false, None, None) -} - -// This enum describes what kind of padding check needs to be generated for the -// associated impl. -enum PaddingCheck { - // Check that the sum of the fields' sizes exactly equals the struct's size. - Struct, - // Check that the size of each field exactly equals the union's size. - Union, -} - -impl PaddingCheck { - /// Returns the ident of the macro to call in order to validate that a type - /// passes the padding check encoded by `PaddingCheck`. - fn validator_macro_ident(&self) -> Ident { - let s = match self { - PaddingCheck::Struct => "struct_has_padding", - PaddingCheck::Union => "union_has_padding", - }; - - Ident::new(s, Span::call_site()) - } -} - -#[derive(Debug, Eq, PartialEq)] -enum Trait { - KnownLayout, - FromZeroes, - FromBytes, - AsBytes, - Unaligned, -} - -impl Trait { - fn ident(&self) -> Ident { - Ident::new(format!("{:?}", self).as_str(), Span::call_site()) - } -} - -#[derive(Debug, Eq, PartialEq)] -enum RequireBoundedFields { - No, - Yes, - Trailing, -} - -impl From<bool> for RequireBoundedFields { - fn from(do_require: bool) -> Self { - match do_require { - true => Self::Yes, - false => Self::No, - } - } -} - -fn impl_block<D: DataExt>( - input: &DeriveInput, - data: &D, - trt: Trait, - require_trait_bound_on_field_types: RequireBoundedFields, - require_self_sized: bool, - padding_check: Option<PaddingCheck>, - extras: Option<proc_macro2::TokenStream>, -) -> proc_macro2::TokenStream { - // In this documentation, we will refer to this hypothetical struct: - // - // #[derive(FromBytes)] - // struct Foo<T, I: Iterator> - // where - // T: Copy, - // I: Clone, - // I::Item: Clone, - // { - // a: u8, - // b: T, - // c: I::Item, - // } - // - // We extract the field types, which in this case are `u8`, `T`, and - // `I::Item`. We re-use the existing parameters and where clauses. If - // `require_trait_bound == true` (as it is for `FromBytes), we add where - // bounds for each field's type: - // - // impl<T, I: Iterator> FromBytes for Foo<T, I> - // where - // T: Copy, - // I: Clone, - // I::Item: Clone, - // T: FromBytes, - // I::Item: FromBytes, - // { - // } - // - // NOTE: It is standard practice to only emit bounds for the type parameters - // themselves, not for field types based on those parameters (e.g., `T` vs - // `T::Foo`). For a discussion of why this is standard practice, see - // https://github.com/rust-lang/rust/issues/26925. - // - // The reason we diverge from this standard is that doing it that way for us - // would be unsound. E.g., consider a type, `T` where `T: FromBytes` but - // `T::Foo: !FromBytes`. It would not be sound for us to accept a type with - // a `T::Foo` field as `FromBytes` simply because `T: FromBytes`. - // - // While there's no getting around this requirement for us, it does have the - // pretty serious downside that, when lifetimes are involved, the trait - // solver ties itself in knots: - // - // #[derive(Unaligned)] - // #[repr(C)] - // struct Dup<'a, 'b> { - // a: PhantomData<&'a u8>, - // b: PhantomData<&'b u8>, - // } - // - // error[E0283]: type annotations required: cannot resolve `core::marker::PhantomData<&'a u8>: zerocopy::Unaligned` - // --> src/main.rs:6:10 - // | - // 6 | #[derive(Unaligned)] - // | ^^^^^^^^^ - // | - // = note: required by `zerocopy::Unaligned` - - let type_ident = &input.ident; - let trait_ident = trt.ident(); - let field_types = data.field_types(); - - let bound_tt = |ty| parse_quote!(#ty: ::zerocopy::#trait_ident); - let field_type_bounds: Vec<_> = match (require_trait_bound_on_field_types, &field_types[..]) { - (RequireBoundedFields::Yes, _) => field_types.iter().map(bound_tt).collect(), - (RequireBoundedFields::No, _) | (RequireBoundedFields::Trailing, []) => vec![], - (RequireBoundedFields::Trailing, [.., last]) => vec![bound_tt(last)], - }; - - // Don't bother emitting a padding check if there are no fields. - #[allow( - unstable_name_collisions, // See `BoolExt` below - clippy::incompatible_msrv, // https://github.com/rust-lang/rust-clippy/issues/12280 - )] - let padding_check_bound = padding_check.and_then(|check| (!field_types.is_empty()).then_some(check)).map(|check| { - let fields = field_types.iter(); - let validator_macro = check.validator_macro_ident(); - parse_quote!( - ::zerocopy::macro_util::HasPadding<#type_ident, {::zerocopy::#validator_macro!(#type_ident, #(#fields),*)}>: - ::zerocopy::macro_util::ShouldBe<false> - ) - }); - - let self_sized_bound = if require_self_sized { Some(parse_quote!(Self: Sized)) } else { None }; - - let bounds = input - .generics - .where_clause - .as_ref() - .map(|where_clause| where_clause.predicates.iter()) - .into_iter() - .flatten() - .chain(field_type_bounds.iter()) - .chain(padding_check_bound.iter()) - .chain(self_sized_bound.iter()); - - // The parameters with trait bounds, but without type defaults. - let params = input.generics.params.clone().into_iter().map(|mut param| { - match &mut param { - GenericParam::Type(ty) => ty.default = None, - GenericParam::Const(cnst) => cnst.default = None, - GenericParam::Lifetime(_) => {} - } - quote!(#param) - }); - - // The identifiers of the parameters without trait bounds or type defaults. - let param_idents = input.generics.params.iter().map(|param| match param { - GenericParam::Type(ty) => { - let ident = &ty.ident; - quote!(#ident) - } - GenericParam::Lifetime(l) => { - let ident = &l.lifetime; - quote!(#ident) - } - GenericParam::Const(cnst) => { - let ident = &cnst.ident; - quote!({#ident}) - } - }); - - quote! { - // TODO(#553): Add a test that generates a warning when - // `#[allow(deprecated)]` isn't present. - #[allow(deprecated)] - unsafe impl < #(#params),* > ::zerocopy::#trait_ident for #type_ident < #(#param_idents),* > - where - #(#bounds,)* - { - fn only_derive_is_allowed_to_implement_this_trait() {} - - #extras - } - } -} - -fn print_all_errors(errors: Vec<Error>) -> proc_macro2::TokenStream { - errors.iter().map(Error::to_compile_error).collect() -} - -// A polyfill for `Option::then_some`, which was added after our MSRV. -// -// TODO(#67): Remove this once our MSRV is >= 1.62. -#[allow(unused)] -trait BoolExt { - fn then_some<T>(self, t: T) -> Option<T>; -} - -#[allow(unused)] -impl BoolExt for bool { - fn then_some<T>(self, t: T) -> Option<T> { - if self { - Some(t) - } else { - None - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_config_repr_orderings() { - // Validate that the repr lists in the various configs are in the - // canonical order. If they aren't, then our algorithm to look up in - // those lists won't work. - - // TODO(https://github.com/rust-lang/rust/issues/53485): Remove once - // `Vec::is_sorted` is stabilized. - fn is_sorted_and_deduped<T: Clone + Ord>(ts: &[T]) -> bool { - let mut sorted = ts.to_vec(); - sorted.sort(); - sorted.dedup(); - ts == sorted.as_slice() - } - - fn elements_are_sorted_and_deduped<T: Clone + Ord>(lists: &[&[T]]) -> bool { - lists.iter().all(|list| is_sorted_and_deduped(list)) - } - - fn config_is_sorted<T: KindRepr + Clone>(config: &Config<T>) -> bool { - elements_are_sorted_and_deduped(config.allowed_combinations) - && elements_are_sorted_and_deduped(config.disallowed_but_legal_combinations) - } - - assert!(config_is_sorted(&STRUCT_UNION_UNALIGNED_CFG)); - assert!(config_is_sorted(&ENUM_FROM_BYTES_CFG)); - assert!(config_is_sorted(&ENUM_UNALIGNED_CFG)); - } - - #[test] - fn test_config_repr_no_overlap() { - // Validate that no set of reprs appears in both the - // `allowed_combinations` and `disallowed_but_legal_combinations` lists. - - fn overlap<T: Eq>(a: &[T], b: &[T]) -> bool { - a.iter().any(|elem| b.contains(elem)) - } - - fn config_overlaps<T: KindRepr + Eq>(config: &Config<T>) -> bool { - overlap(config.allowed_combinations, config.disallowed_but_legal_combinations) - } - - assert!(!config_overlaps(&STRUCT_UNION_UNALIGNED_CFG)); - assert!(!config_overlaps(&ENUM_FROM_BYTES_CFG)); - assert!(!config_overlaps(&ENUM_UNALIGNED_CFG)); - } -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/src/repr.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/src/repr.rs deleted file mode 100644 index f4f2788..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/src/repr.rs +++ /dev/null
@@ -1,311 +0,0 @@ -// Copyright 2019 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -use core::fmt::{self, Display, Formatter}; - -use { - proc_macro2::Span, - syn::punctuated::Punctuated, - syn::spanned::Spanned, - syn::token::Comma, - syn::{Attribute, DeriveInput, Error, LitInt, Meta}, -}; - -pub struct Config<Repr: KindRepr> { - // A human-readable message describing what combinations of representations - // are allowed. This will be printed to the user if they use an invalid - // combination. - pub allowed_combinations_message: &'static str, - // Whether we're checking as part of `derive(Unaligned)`. If not, we can - // ignore `repr(align)`, which makes the code (and the list of valid repr - // combinations we have to enumerate) somewhat simpler. If we're checking - // for `Unaligned`, then in addition to checking against illegal - // combinations, we also check to see if there exists a `repr(align(N > 1))` - // attribute. - pub derive_unaligned: bool, - // Combinations which are valid for the trait. - pub allowed_combinations: &'static [&'static [Repr]], - // Combinations which are not valid for the trait, but are legal according - // to Rust. Any combination not in this or `allowed_combinations` is either - // illegal according to Rust or the behavior is unspecified. If the behavior - // is unspecified, it might become specified in the future, and that - // specification might not play nicely with our requirements. Thus, we - // reject combinations with unspecified behavior in addition to illegal - // combinations. - pub disallowed_but_legal_combinations: &'static [&'static [Repr]], -} - -impl<R: KindRepr> Config<R> { - /// Validate that `input`'s representation attributes conform to the - /// requirements specified by this `Config`. - /// - /// `validate_reprs` extracts the `repr` attributes, validates that they - /// conform to the requirements of `self`, and returns them. Regardless of - /// whether `align` attributes are considered during validation, they are - /// stripped out of the returned value since no callers care about them. - pub fn validate_reprs(&self, input: &DeriveInput) -> Result<Vec<R>, Vec<Error>> { - let mut metas_reprs = reprs(&input.attrs)?; - metas_reprs.sort_by(|a: &(_, R), b| a.1.partial_cmp(&b.1).unwrap()); - - if self.derive_unaligned { - if let Some((meta, _)) = - metas_reprs.iter().find(|&repr: &&(_, R)| repr.1.is_align_gt_one()) - { - return Err(vec![Error::new_spanned( - meta, - "cannot derive Unaligned with repr(align(N > 1))", - )]); - } - } - - let mut metas = Vec::new(); - let mut reprs = Vec::new(); - metas_reprs.into_iter().filter(|(_, repr)| !repr.is_align()).for_each(|(meta, repr)| { - metas.push(meta); - reprs.push(repr) - }); - - if reprs.is_empty() { - // Use `Span::call_site` to report this error on the - // `#[derive(...)]` itself. - return Err(vec![Error::new(Span::call_site(), "must have a non-align #[repr(...)] attribute in order to guarantee this type's memory layout")]); - } - - let initial_sp = metas[0].span(); - let err_span = metas.iter().skip(1).try_fold(initial_sp, |sp, meta| sp.join(meta.span())); - - if self.allowed_combinations.contains(&reprs.as_slice()) { - Ok(reprs) - } else if self.disallowed_but_legal_combinations.contains(&reprs.as_slice()) { - Err(vec![Error::new( - err_span.unwrap_or_else(|| input.span()), - self.allowed_combinations_message, - )]) - } else { - Err(vec![Error::new( - err_span.unwrap_or_else(|| input.span()), - "conflicting representation hints", - )]) - } - } -} - -// The type of valid reprs for a particular kind (enum, struct, union). -pub trait KindRepr: 'static + Sized + Ord { - fn is_align(&self) -> bool; - fn is_align_gt_one(&self) -> bool; - fn parse(meta: &Meta) -> syn::Result<Self>; -} - -// Defines an enum for reprs which are valid for a given kind (structs, enums, -// etc), and provide implementations of `KindRepr`, `Ord`, and `Display`, and -// those traits' super-traits. -macro_rules! define_kind_specific_repr { - ($type_name:expr, $repr_name:ident, [ $($repr_variant:ident),* ] , [ $($repr_variant_aligned:ident),* ]) => { - #[derive(Copy, Clone, Debug, Eq, PartialEq)] - pub enum $repr_name { - $($repr_variant,)* - $($repr_variant_aligned(u64),)* - } - - impl KindRepr for $repr_name { - fn is_align(&self) -> bool { - match self { - $($repr_name::$repr_variant_aligned(_) => true,)* - _ => false, - } - } - - fn is_align_gt_one(&self) -> bool { - match self { - // `packed(n)` only lowers alignment - $repr_name::Align(n) => n > &1, - _ => false, - } - } - - fn parse(meta: &Meta) -> syn::Result<$repr_name> { - match Repr::from_meta(meta)? { - $(Repr::$repr_variant => Ok($repr_name::$repr_variant),)* - $(Repr::$repr_variant_aligned(u) => Ok($repr_name::$repr_variant_aligned(u)),)* - _ => Err(Error::new_spanned(meta, concat!("unsupported representation for deriving FromBytes, AsBytes, or Unaligned on ", $type_name))) - } - } - } - - // Define a stable ordering so we can canonicalize lists of reprs. The - // ordering itself doesn't matter so long as it's stable. - impl PartialOrd for $repr_name { - fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> { - Some(self.cmp(other)) - } - } - - impl Ord for $repr_name { - fn cmp(&self, other: &Self) -> core::cmp::Ordering { - format!("{:?}", self).cmp(&format!("{:?}", other)) - } - } - - impl core::fmt::Display for $repr_name { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - match self { - $($repr_name::$repr_variant => Repr::$repr_variant,)* - $($repr_name::$repr_variant_aligned(u) => Repr::$repr_variant_aligned(*u),)* - }.fmt(f) - } - } - } -} - -define_kind_specific_repr!("a struct", StructRepr, [C, Transparent, Packed], [Align, PackedN]); -define_kind_specific_repr!( - "an enum", - EnumRepr, - [C, U8, U16, U32, U64, Usize, I8, I16, I32, I64, Isize], - [Align] -); - -// All representations known to Rust. -#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd)] -pub enum Repr { - U8, - U16, - U32, - U64, - Usize, - I8, - I16, - I32, - I64, - Isize, - C, - Transparent, - Packed, - PackedN(u64), - Align(u64), -} - -impl Repr { - fn from_meta(meta: &Meta) -> Result<Repr, Error> { - let (path, list) = match meta { - Meta::Path(path) => (path, None), - Meta::List(list) => (&list.path, Some(list)), - _ => return Err(Error::new_spanned(meta, "unrecognized representation hint")), - }; - - let ident = path - .get_ident() - .ok_or_else(|| Error::new_spanned(meta, "unrecognized representation hint"))?; - - Ok(match (ident.to_string().as_str(), list) { - ("u8", None) => Repr::U8, - ("u16", None) => Repr::U16, - ("u32", None) => Repr::U32, - ("u64", None) => Repr::U64, - ("usize", None) => Repr::Usize, - ("i8", None) => Repr::I8, - ("i16", None) => Repr::I16, - ("i32", None) => Repr::I32, - ("i64", None) => Repr::I64, - ("isize", None) => Repr::Isize, - ("C", None) => Repr::C, - ("transparent", None) => Repr::Transparent, - ("packed", None) => Repr::Packed, - ("packed", Some(list)) => { - Repr::PackedN(list.parse_args::<LitInt>()?.base10_parse::<u64>()?) - } - ("align", Some(list)) => { - Repr::Align(list.parse_args::<LitInt>()?.base10_parse::<u64>()?) - } - _ => return Err(Error::new_spanned(meta, "unrecognized representation hint")), - }) - } -} - -impl KindRepr for Repr { - fn is_align(&self) -> bool { - false - } - - fn is_align_gt_one(&self) -> bool { - false - } - - fn parse(meta: &Meta) -> syn::Result<Self> { - Self::from_meta(meta) - } -} - -impl Display for Repr { - fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> { - if let Repr::Align(n) = self { - return write!(f, "repr(align({}))", n); - } - if let Repr::PackedN(n) = self { - return write!(f, "repr(packed({}))", n); - } - write!( - f, - "repr({})", - match self { - Repr::U8 => "u8", - Repr::U16 => "u16", - Repr::U32 => "u32", - Repr::U64 => "u64", - Repr::Usize => "usize", - Repr::I8 => "i8", - Repr::I16 => "i16", - Repr::I32 => "i32", - Repr::I64 => "i64", - Repr::Isize => "isize", - Repr::C => "C", - Repr::Transparent => "transparent", - Repr::Packed => "packed", - _ => unreachable!(), - } - ) - } -} - -pub(crate) fn reprs<R: KindRepr>(attrs: &[Attribute]) -> Result<Vec<(Meta, R)>, Vec<Error>> { - let mut reprs = Vec::new(); - let mut errors = Vec::new(); - for attr in attrs { - // Ignore documentation attributes. - if attr.path().is_ident("doc") { - continue; - } - if let Meta::List(ref meta_list) = attr.meta { - if meta_list.path.is_ident("repr") { - let parsed: Punctuated<Meta, Comma> = - match meta_list.parse_args_with(Punctuated::parse_terminated) { - Ok(parsed) => parsed, - Err(_) => { - errors.push(Error::new_spanned( - &meta_list.tokens, - "unrecognized representation hint", - )); - continue; - } - }; - for meta in parsed { - match R::parse(&meta) { - Ok(repr) => reprs.push((meta, repr)), - Err(err) => errors.push(err), - } - } - } - } - } - - if !errors.is_empty() { - return Err(errors); - } - Ok(reprs) -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/enum_as_bytes.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/enum_as_bytes.rs deleted file mode 100644 index e305bc4c..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/enum_as_bytes.rs +++ /dev/null
@@ -1,101 +0,0 @@ -// Copyright 2019 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -#![allow(warnings)] - -use {static_assertions::assert_impl_all, zerocopy::AsBytes}; - -// An enum is `AsBytes` if if has a defined repr. - -#[derive(AsBytes)] -#[repr(C)] -enum C { - A, -} - -assert_impl_all!(C: AsBytes); - -#[derive(AsBytes)] -#[repr(u8)] -enum U8 { - A, -} - -assert_impl_all!(U8: AsBytes); - -#[derive(AsBytes)] -#[repr(u16)] -enum U16 { - A, -} - -assert_impl_all!(U16: AsBytes); - -#[derive(AsBytes)] -#[repr(u32)] -enum U32 { - A, -} - -assert_impl_all!(U32: AsBytes); - -#[derive(AsBytes)] -#[repr(u64)] -enum U64 { - A, -} - -assert_impl_all!(U64: AsBytes); - -#[derive(AsBytes)] -#[repr(usize)] -enum Usize { - A, -} - -assert_impl_all!(Usize: AsBytes); - -#[derive(AsBytes)] -#[repr(i8)] -enum I8 { - A, -} - -assert_impl_all!(I8: AsBytes); - -#[derive(AsBytes)] -#[repr(i16)] -enum I16 { - A, -} - -assert_impl_all!(I16: AsBytes); - -#[derive(AsBytes)] -#[repr(i32)] -enum I32 { - A, -} - -assert_impl_all!(I32: AsBytes); - -#[derive(AsBytes)] -#[repr(i64)] -enum I64 { - A, -} - -assert_impl_all!(I64: AsBytes); - -#[derive(AsBytes)] -#[repr(isize)] -enum Isize { - A, -} - -assert_impl_all!(Isize: AsBytes);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/enum_from_zeroes.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/enum_from_zeroes.rs deleted file mode 100644 index c6bb675..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/enum_from_zeroes.rs +++ /dev/null
@@ -1,35 +0,0 @@ -// Copyright 2019 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -#![allow(warnings)] - -mod util; - -use {static_assertions::assert_impl_all, zerocopy::FromZeroes}; - -#[derive(FromZeroes)] -enum Foo { - A, -} - -assert_impl_all!(Foo: FromZeroes); - -#[derive(FromZeroes)] -enum Bar { - A = 0, -} - -assert_impl_all!(Bar: FromZeroes); - -#[derive(FromZeroes)] -enum Baz { - A = 1, - B = 0, -} - -assert_impl_all!(Baz: FromZeroes);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/enum_known_layout.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/enum_known_layout.rs deleted file mode 100644 index 49a6765..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/enum_known_layout.rs +++ /dev/null
@@ -1,46 +0,0 @@ -// Copyright 2022 The Fuchsia Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#![allow(warnings)] - -mod util; - -use {core::marker::PhantomData, static_assertions::assert_impl_all, zerocopy::KnownLayout}; - -#[derive(KnownLayout)] -enum Foo { - A, -} - -assert_impl_all!(Foo: KnownLayout); - -#[derive(KnownLayout)] -enum Bar { - A = 0, -} - -assert_impl_all!(Bar: KnownLayout); - -#[derive(KnownLayout)] -enum Baz { - A = 1, - B = 0, -} - -assert_impl_all!(Baz: KnownLayout); - -// Deriving `KnownLayout` should work if the enum has bounded parameters. - -#[derive(KnownLayout)] -#[repr(C)] -enum WithParams<'a: 'b, 'b: 'a, const N: usize, T: 'a + 'b + KnownLayout> -where - 'a: 'b, - 'b: 'a, - T: 'a + 'b + KnownLayout, -{ - Variant([T; N], PhantomData<&'a &'b ()>), -} - -assert_impl_all!(WithParams<'static, 'static, 42, u8>: KnownLayout);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/enum_unaligned.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/enum_unaligned.rs deleted file mode 100644 index 152ce27..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/enum_unaligned.rs +++ /dev/null
@@ -1,47 +0,0 @@ -// Copyright 2019 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -#![allow(warnings)] - -use {static_assertions::assert_impl_all, zerocopy::Unaligned}; - -// An enum is `Unaligned` if: -// - No `repr(align(N > 1))` -// - `repr(u8)` or `repr(i8)` - -#[derive(Unaligned)] -#[repr(u8)] -enum Foo { - A, -} - -assert_impl_all!(Foo: Unaligned); - -#[derive(Unaligned)] -#[repr(i8)] -enum Bar { - A, -} - -assert_impl_all!(Bar: Unaligned); - -#[derive(Unaligned)] -#[repr(u8, align(1))] -enum Baz { - A, -} - -assert_impl_all!(Baz: Unaligned); - -#[derive(Unaligned)] -#[repr(i8, align(1))] -enum Blah { - B, -} - -assert_impl_all!(Blah: Unaligned);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/hygiene.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/hygiene.rs deleted file mode 100644 index b7b838d6..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/hygiene.rs +++ /dev/null
@@ -1,43 +0,0 @@ -// Copyright 2019 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -// Make sure that macro hygiene will ensure that when we reference "zerocopy", -// that will work properly even if they've renamed the crate and have not -// imported its traits. - -#![allow(warnings)] - -extern crate zerocopy as _zerocopy; - -#[macro_use] -mod util; - -use std::{marker::PhantomData, option::IntoIter}; - -use static_assertions::assert_impl_all; - -#[derive( - _zerocopy::KnownLayout, _zerocopy::FromZeroes, _zerocopy::FromBytes, _zerocopy::Unaligned, -)] -#[repr(C)] -struct TypeParams<'a, T, I: Iterator> { - a: T, - c: I::Item, - d: u8, - e: PhantomData<&'a [u8]>, - f: PhantomData<&'static str>, - g: PhantomData<String>, -} - -assert_impl_all!( - TypeParams<'static, (), IntoIter<()>>: - _zerocopy::KnownLayout, - _zerocopy::FromZeroes, - _zerocopy::FromBytes, - _zerocopy::Unaligned -);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/paths_and_modules.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/paths_and_modules.rs deleted file mode 100644 index a01983b..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/paths_and_modules.rs +++ /dev/null
@@ -1,38 +0,0 @@ -// Copyright 2019 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -#![allow(warnings)] - -use zerocopy::{AsBytes, FromBytes, FromZeroes, Unaligned}; - -// Ensure that types that are use'd and types that are referenced by path work. - -mod foo { - use zerocopy::{AsBytes, FromBytes, FromZeroes, Unaligned}; - - #[derive(FromZeroes, FromBytes, AsBytes, Unaligned)] - #[repr(C)] - pub struct Foo { - foo: u8, - } - - #[derive(FromZeroes, FromBytes, AsBytes, Unaligned)] - #[repr(C)] - pub struct Bar { - bar: u8, - } -} - -use foo::Foo; - -#[derive(FromZeroes, FromBytes, AsBytes, Unaligned)] -#[repr(C)] -struct Baz { - foo: Foo, - bar: foo::Bar, -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/priv_in_pub.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/priv_in_pub.rs deleted file mode 100644 index 5f7d874..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/priv_in_pub.rs +++ /dev/null
@@ -1,24 +0,0 @@ -// Copyright 2019 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -use zerocopy::{AsBytes, FromBytes, FromZeroes, KnownLayout, Unaligned}; - -// These derives do not result in E0446 as of Rust 1.59.0, because of -// https://github.com/rust-lang/rust/pull/90586. -// -// This change eliminates one of the major downsides of emitting `where` -// bounds for field types (i.e., the emission of E0446 for private field -// types). - -#[derive(KnownLayout, AsBytes, FromZeroes, FromBytes, Unaligned)] -#[repr(C)] -pub struct Public(Private); - -#[derive(KnownLayout, AsBytes, FromZeroes, FromBytes, Unaligned)] -#[repr(C)] -struct Private(());
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/struct_as_bytes.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/struct_as_bytes.rs deleted file mode 100644 index 3c71bf0..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/struct_as_bytes.rs +++ /dev/null
@@ -1,161 +0,0 @@ -// Copyright 2019 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -#![allow(warnings)] - -mod util; - -use std::{marker::PhantomData, mem::ManuallyDrop, option::IntoIter}; - -use {static_assertions::assert_impl_all, zerocopy::AsBytes}; - -use self::util::AU16; - -// A struct is `AsBytes` if: -// - all fields are `AsBytes` -// - `repr(C)` or `repr(transparent)` and -// - no padding (size of struct equals sum of size of field types) -// - `repr(packed)` - -#[derive(AsBytes)] -#[repr(C)] -struct CZst; - -assert_impl_all!(CZst: AsBytes); - -#[derive(AsBytes)] -#[repr(C)] -struct C { - a: u8, - b: u8, - c: AU16, -} - -assert_impl_all!(C: AsBytes); - -#[derive(AsBytes)] -#[repr(transparent)] -struct Transparent { - a: u8, - b: CZst, -} - -assert_impl_all!(Transparent: AsBytes); - -#[derive(AsBytes)] -#[repr(transparent)] -struct TransparentGeneric<T: ?Sized> { - a: CZst, - b: T, -} - -assert_impl_all!(TransparentGeneric<u64>: AsBytes); -assert_impl_all!(TransparentGeneric<[u64]>: AsBytes); - -#[derive(AsBytes)] -#[repr(C, packed)] -struct CZstPacked; - -assert_impl_all!(CZstPacked: AsBytes); - -#[derive(AsBytes)] -#[repr(C, packed)] -struct CPacked { - a: u8, - // NOTE: The `u16` type is not guaranteed to have alignment 2, although it - // does on many platforms. However, to fix this would require a custom type - // with a `#[repr(align(2))]` attribute, and `#[repr(packed)]` types are not - // allowed to transitively contain `#[repr(align(...))]` types. Thus, we - // have no choice but to use `u16` here. Luckily, these tests run in CI on - // platforms on which `u16` has alignment 2, so this isn't that big of a - // deal. - b: u16, -} - -assert_impl_all!(CPacked: AsBytes); - -#[derive(AsBytes)] -#[repr(C, packed(2))] -// The same caveats as for CPacked apply - we're assuming u64 is at least -// 4-byte aligned by default. Without packed(2), this should fail, as there -// would be padding between a/b assuming u64 is 4+ byte aligned. -struct CPacked2 { - a: u16, - b: u64, -} - -assert_impl_all!(CPacked2: AsBytes); - -#[derive(AsBytes)] -#[repr(C, packed)] -struct CPackedGeneric<T, U: ?Sized> { - t: T, - // Unsized types stored in `repr(packed)` structs must not be dropped - // because dropping them in-place might be unsound depending on the - // alignment of the outer struct. Sized types can be dropped by first being - // moved to an aligned stack variable, but this isn't possible with unsized - // types. - u: ManuallyDrop<U>, -} - -assert_impl_all!(CPackedGeneric<u8, AU16>: AsBytes); -assert_impl_all!(CPackedGeneric<u8, [AU16]>: AsBytes); - -#[derive(AsBytes)] -#[repr(packed)] -struct Packed { - a: u8, - // NOTE: The `u16` type is not guaranteed to have alignment 2, although it - // does on many platforms. However, to fix this would require a custom type - // with a `#[repr(align(2))]` attribute, and `#[repr(packed)]` types are not - // allowed to transitively contain `#[repr(align(...))]` types. Thus, we - // have no choice but to use `u16` here. Luckily, these tests run in CI on - // platforms on which `u16` has alignment 2, so this isn't that big of a - // deal. - b: u16, -} - -assert_impl_all!(Packed: AsBytes); - -#[derive(AsBytes)] -#[repr(packed)] -struct PackedGeneric<T, U: ?Sized> { - t: T, - // Unsized types stored in `repr(packed)` structs must not be dropped - // because dropping them in-place might be unsound depending on the - // alignment of the outer struct. Sized types can be dropped by first being - // moved to an aligned stack variable, but this isn't possible with unsized - // types. - u: ManuallyDrop<U>, -} - -assert_impl_all!(PackedGeneric<u8, AU16>: AsBytes); -assert_impl_all!(PackedGeneric<u8, [AU16]>: AsBytes); - -#[derive(AsBytes)] -#[repr(transparent)] -struct Unsized { - a: [u8], -} - -assert_impl_all!(Unsized: AsBytes); - -// Deriving `AsBytes` should work if the struct has bounded parameters. - -#[derive(AsBytes)] -#[repr(transparent)] -struct WithParams<'a: 'b, 'b: 'a, const N: usize, T: 'a + 'b + AsBytes>( - [T; N], - PhantomData<&'a &'b ()>, -) -where - 'a: 'b, - 'b: 'a, - T: 'a + 'b + AsBytes; - -assert_impl_all!(WithParams<'static, 'static, 42, u8>: AsBytes);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/struct_from_bytes.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/struct_from_bytes.rs deleted file mode 100644 index 98f03d1..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/struct_from_bytes.rs +++ /dev/null
@@ -1,79 +0,0 @@ -// Copyright 2019 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -#![allow(warnings)] - -mod util; - -use std::{marker::PhantomData, option::IntoIter}; - -use { - static_assertions::assert_impl_all, - zerocopy::{FromBytes, FromZeroes}, -}; - -use crate::util::AU16; - -// A struct is `FromBytes` if: -// - all fields are `FromBytes` - -#[derive(FromZeroes, FromBytes)] -struct Zst; - -assert_impl_all!(Zst: FromBytes); - -#[derive(FromZeroes, FromBytes)] -struct One { - a: u8, -} - -assert_impl_all!(One: FromBytes); - -#[derive(FromZeroes, FromBytes)] -struct Two { - a: u8, - b: Zst, -} - -assert_impl_all!(Two: FromBytes); - -#[derive(FromZeroes, FromBytes)] -struct Unsized { - a: [u8], -} - -assert_impl_all!(Unsized: FromBytes); - -#[derive(FromZeroes, FromBytes)] -struct TypeParams<'a, T: ?Sized, I: Iterator> { - a: I::Item, - b: u8, - c: PhantomData<&'a [u8]>, - d: PhantomData<&'static str>, - e: PhantomData<String>, - f: T, -} - -assert_impl_all!(TypeParams<'static, (), IntoIter<()>>: FromBytes); -assert_impl_all!(TypeParams<'static, AU16, IntoIter<()>>: FromBytes); -assert_impl_all!(TypeParams<'static, [AU16], IntoIter<()>>: FromBytes); - -// Deriving `FromBytes` should work if the struct has bounded parameters. - -#[derive(FromZeroes, FromBytes)] -#[repr(transparent)] -struct WithParams<'a: 'b, 'b: 'a, const N: usize, T: 'a + 'b + FromBytes>( - [T; N], - PhantomData<&'a &'b ()>, -) -where - 'a: 'b, - 'b: 'a, - T: 'a + 'b + FromBytes; - -assert_impl_all!(WithParams<'static, 'static, 42, u8>: FromBytes);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/struct_from_zeroes.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/struct_from_zeroes.rs deleted file mode 100644 index 75d8245..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/struct_from_zeroes.rs +++ /dev/null
@@ -1,77 +0,0 @@ -// Copyright 2019 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -#![allow(warnings)] - -#[macro_use] -mod util; - -use std::{marker::PhantomData, option::IntoIter}; - -use {static_assertions::assert_impl_all, zerocopy::FromZeroes}; - -use crate::util::AU16; - -// A struct is `FromZeroes` if: -// - all fields are `FromZeroes` - -#[derive(FromZeroes)] -struct Zst; - -assert_impl_all!(Zst: FromZeroes); - -#[derive(FromZeroes)] -struct One { - a: bool, -} - -assert_impl_all!(One: FromZeroes); - -#[derive(FromZeroes)] -struct Two { - a: bool, - b: Zst, -} - -assert_impl_all!(Two: FromZeroes); - -#[derive(FromZeroes)] -struct Unsized { - a: [u8], -} - -assert_impl_all!(Unsized: FromZeroes); - -#[derive(FromZeroes)] -struct TypeParams<'a, T: ?Sized, I: Iterator> { - a: I::Item, - b: u8, - c: PhantomData<&'a [u8]>, - d: PhantomData<&'static str>, - e: PhantomData<String>, - f: T, -} - -assert_impl_all!(TypeParams<'static, (), IntoIter<()>>: FromZeroes); -assert_impl_all!(TypeParams<'static, AU16, IntoIter<()>>: FromZeroes); -assert_impl_all!(TypeParams<'static, [AU16], IntoIter<()>>: FromZeroes); - -// Deriving `FromZeroes` should work if the struct has bounded parameters. - -#[derive(FromZeroes)] -#[repr(transparent)] -struct WithParams<'a: 'b, 'b: 'a, const N: usize, T: 'a + 'b + FromZeroes>( - [T; N], - PhantomData<&'a &'b ()>, -) -where - 'a: 'b, - 'b: 'a, - T: 'a + 'b + FromZeroes; - -assert_impl_all!(WithParams<'static, 'static, 42, u8>: FromZeroes);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/struct_known_layout.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/struct_known_layout.rs deleted file mode 100644 index 68d1284d..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/struct_known_layout.rs +++ /dev/null
@@ -1,65 +0,0 @@ -// Copyright 2022 The Fuchsia Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#![allow(warnings)] - -#[macro_use] -mod util; - -use std::{marker::PhantomData, option::IntoIter}; - -use { - static_assertions::assert_impl_all, - zerocopy::{DstLayout, KnownLayout}, -}; - -use crate::util::AU16; - -#[derive(KnownLayout)] -struct Zst; - -assert_impl_all!(Zst: KnownLayout); - -#[derive(KnownLayout)] -struct One { - a: bool, -} - -assert_impl_all!(One: KnownLayout); - -#[derive(KnownLayout)] -struct Two { - a: bool, - b: Zst, -} - -assert_impl_all!(Two: KnownLayout); - -#[derive(KnownLayout)] -struct TypeParams<'a, T, I: Iterator> { - a: I::Item, - b: u8, - c: PhantomData<&'a [u8]>, - d: PhantomData<&'static str>, - e: PhantomData<String>, - f: T, -} - -assert_impl_all!(TypeParams<'static, (), IntoIter<()>>: KnownLayout); -assert_impl_all!(TypeParams<'static, AU16, IntoIter<()>>: KnownLayout); - -// Deriving `KnownLayout` should work if the struct has bounded parameters. - -#[derive(KnownLayout)] -#[repr(C)] -struct WithParams<'a: 'b, 'b: 'a, const N: usize, T: 'a + 'b + KnownLayout>( - [T; N], - PhantomData<&'a &'b ()>, -) -where - 'a: 'b, - 'b: 'a, - T: 'a + 'b + KnownLayout; - -assert_impl_all!(WithParams<'static, 'static, 42, u8>: KnownLayout);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/struct_unaligned.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/struct_unaligned.rs deleted file mode 100644 index a7db432..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/struct_unaligned.rs +++ /dev/null
@@ -1,100 +0,0 @@ -// Copyright 2019 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -#![allow(warnings)] - -mod util; - -use std::{marker::PhantomData, option::IntoIter}; - -use {static_assertions::assert_impl_all, zerocopy::Unaligned}; - -use crate::util::AU16; - -// A struct is `Unaligned` if: -// - `repr(align)` is no more than 1 and either -// - `repr(C)` or `repr(transparent)` and -// - all fields Unaligned -// - `repr(packed)` - -#[derive(Unaligned)] -#[repr(C)] -struct Foo { - a: u8, -} - -assert_impl_all!(Foo: Unaligned); - -#[derive(Unaligned)] -#[repr(transparent)] -struct Bar { - a: u8, -} - -assert_impl_all!(Bar: Unaligned); - -#[derive(Unaligned)] -#[repr(packed)] -struct Baz { - // NOTE: The `u16` type is not guaranteed to have alignment 2, although it - // does on many platforms. However, to fix this would require a custom type - // with a `#[repr(align(2))]` attribute, and `#[repr(packed)]` types are not - // allowed to transitively contain `#[repr(align(...))]` types. Thus, we - // have no choice but to use `u16` here. Luckily, these tests run in CI on - // platforms on which `u16` has alignment 2, so this isn't that big of a - // deal. - a: u16, -} - -assert_impl_all!(Baz: Unaligned); - -#[derive(Unaligned)] -#[repr(C, align(1))] -struct FooAlign { - a: u8, -} - -assert_impl_all!(FooAlign: Unaligned); - -#[derive(Unaligned)] -#[repr(transparent)] -struct Unsized { - a: [u8], -} - -assert_impl_all!(Unsized: Unaligned); - -#[derive(Unaligned)] -#[repr(C)] -struct TypeParams<'a, T: ?Sized, I: Iterator> { - a: I::Item, - b: u8, - c: PhantomData<&'a [u8]>, - d: PhantomData<&'static str>, - e: PhantomData<String>, - f: T, -} - -assert_impl_all!(TypeParams<'static, (), IntoIter<()>>: Unaligned); -assert_impl_all!(TypeParams<'static, u8, IntoIter<()>>: Unaligned); -assert_impl_all!(TypeParams<'static, [u8], IntoIter<()>>: Unaligned); - -// Deriving `Unaligned` should work if the struct has bounded parameters. - -#[derive(Unaligned)] -#[repr(transparent)] -struct WithParams<'a: 'b, 'b: 'a, const N: usize, T: 'a + 'b + Unaligned>( - [T; N], - PhantomData<&'a &'b ()>, -) -where - 'a: 'b, - 'b: 'a, - T: 'a + 'b + Unaligned; - -assert_impl_all!(WithParams<'static, 'static, 42, u8>: Unaligned);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/trybuild.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/trybuild.rs deleted file mode 100644 index 3ea1c3b..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/trybuild.rs +++ /dev/null
@@ -1,19 +0,0 @@ -// Copyright 2019 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -#[test] -#[cfg_attr(miri, ignore)] -fn ui() { - let version = testutil::ToolchainVersion::extract_from_pwd().unwrap(); - // See the doc comment on this method for an explanation of what this does - // and why we store source files in different directories. - let source_files_dirname = version.get_ui_source_files_dirname_and_maybe_print_warning(); - - let t = trybuild::TestCases::new(); - t.compile_fail(format!("tests/{source_files_dirname}/*.rs")); -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-msrv/derive_transparent.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-msrv/derive_transparent.rs deleted file mode 100644 index 2084d92..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-msrv/derive_transparent.rs +++ /dev/null
@@ -1,40 +0,0 @@ -// Copyright 2019 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -#[path = "../util.rs"] -mod util; - -use core::marker::PhantomData; - -use { - static_assertions::assert_impl_all, - zerocopy::{AsBytes, FromBytes, FromZeroes, Unaligned}, -}; - -use self::util::NotZerocopy; - -fn main() {} - -// Test generic transparent structs - -#[derive(AsBytes, FromZeroes, FromBytes, Unaligned)] -#[repr(transparent)] -struct TransparentStruct<T> { - inner: T, - _phantom: PhantomData<()>, -} - -// It should be legal to derive these traits on a transparent struct, but it -// must also ensure the traits are only implemented when the inner type -// implements them. -assert_impl_all!(TransparentStruct<NotZerocopy>: FromZeroes); -assert_impl_all!(TransparentStruct<NotZerocopy>: FromBytes); -assert_impl_all!(TransparentStruct<NotZerocopy>: AsBytes); -assert_impl_all!(TransparentStruct<NotZerocopy>: Unaligned);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-msrv/derive_transparent.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-msrv/derive_transparent.stderr deleted file mode 100644 index 3b228b1..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-msrv/derive_transparent.stderr +++ /dev/null
@@ -1,71 +0,0 @@ -error[E0277]: the trait bound `NotZerocopy: FromZeroes` is not satisfied - --> tests/ui-msrv/derive_transparent.rs:37:1 - | -37 | assert_impl_all!(TransparentStruct<NotZerocopy>: FromZeroes); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `FromZeroes` is not implemented for `NotZerocopy` - | -note: required because of the requirements on the impl of `FromZeroes` for `TransparentStruct<NotZerocopy>` - --> tests/ui-msrv/derive_transparent.rs:27:19 - | -27 | #[derive(AsBytes, FromZeroes, FromBytes, Unaligned)] - | ^^^^^^^^^^ -note: required by a bound in `_::{closure#0}::assert_impl_all` - --> tests/ui-msrv/derive_transparent.rs:37:1 - | -37 | assert_impl_all!(TransparentStruct<NotZerocopy>: FromZeroes); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `_::{closure#0}::assert_impl_all` - = note: this error originates in the macro `assert_impl_all` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `NotZerocopy: FromBytes` is not satisfied - --> tests/ui-msrv/derive_transparent.rs:38:1 - | -38 | assert_impl_all!(TransparentStruct<NotZerocopy>: FromBytes); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `FromBytes` is not implemented for `NotZerocopy` - | -note: required because of the requirements on the impl of `FromBytes` for `TransparentStruct<NotZerocopy>` - --> tests/ui-msrv/derive_transparent.rs:27:31 - | -27 | #[derive(AsBytes, FromZeroes, FromBytes, Unaligned)] - | ^^^^^^^^^ -note: required by a bound in `_::{closure#0}::assert_impl_all` - --> tests/ui-msrv/derive_transparent.rs:38:1 - | -38 | assert_impl_all!(TransparentStruct<NotZerocopy>: FromBytes); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `_::{closure#0}::assert_impl_all` - = note: this error originates in the macro `assert_impl_all` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `NotZerocopy: AsBytes` is not satisfied - --> tests/ui-msrv/derive_transparent.rs:39:1 - | -39 | assert_impl_all!(TransparentStruct<NotZerocopy>: AsBytes); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `AsBytes` is not implemented for `NotZerocopy` - | -note: required because of the requirements on the impl of `AsBytes` for `TransparentStruct<NotZerocopy>` - --> tests/ui-msrv/derive_transparent.rs:27:10 - | -27 | #[derive(AsBytes, FromZeroes, FromBytes, Unaligned)] - | ^^^^^^^ -note: required by a bound in `_::{closure#0}::assert_impl_all` - --> tests/ui-msrv/derive_transparent.rs:39:1 - | -39 | assert_impl_all!(TransparentStruct<NotZerocopy>: AsBytes); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `_::{closure#0}::assert_impl_all` - = note: this error originates in the macro `assert_impl_all` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `NotZerocopy: Unaligned` is not satisfied - --> tests/ui-msrv/derive_transparent.rs:40:1 - | -40 | assert_impl_all!(TransparentStruct<NotZerocopy>: Unaligned); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Unaligned` is not implemented for `NotZerocopy` - | -note: required because of the requirements on the impl of `Unaligned` for `TransparentStruct<NotZerocopy>` - --> tests/ui-msrv/derive_transparent.rs:27:42 - | -27 | #[derive(AsBytes, FromZeroes, FromBytes, Unaligned)] - | ^^^^^^^^^ -note: required by a bound in `_::{closure#0}::assert_impl_all` - --> tests/ui-msrv/derive_transparent.rs:40:1 - | -40 | assert_impl_all!(TransparentStruct<NotZerocopy>: Unaligned); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `_::{closure#0}::assert_impl_all` - = note: this error originates in the macro `assert_impl_all` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-msrv/enum.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-msrv/enum.rs deleted file mode 100644 index 31d5679..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-msrv/enum.rs +++ /dev/null
@@ -1,194 +0,0 @@ -// Copyright 2019 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -#[macro_use] -extern crate zerocopy; - -fn main() {} - -// -// Generic errors -// - -#[derive(FromZeroes, FromBytes)] -#[repr("foo")] -enum Generic1 { - A, -} - -#[derive(FromZeroes, FromBytes)] -#[repr(foo)] -enum Generic2 { - A, -} - -#[derive(FromZeroes, FromBytes)] -#[repr(transparent)] -enum Generic3 { - A, -} - -#[derive(FromZeroes, FromBytes)] -#[repr(u8, u16)] -enum Generic4 { - A, -} - -#[derive(FromZeroes, FromBytes)] -enum Generic5 { - A, -} - -// -// FromZeroes errors -// - -#[derive(FromZeroes)] -enum FromZeroes1 { - A(u8), -} - -#[derive(FromZeroes)] -enum FromZeroes2 { - A, - B(u8), -} - -#[derive(FromZeroes)] -enum FromZeroes3 { - A = 1, - B, -} - -// -// FromBytes errors -// - -#[derive(FromZeroes, FromBytes)] -#[repr(C)] -enum FromBytes1 { - A, -} - -#[derive(FromZeroes, FromBytes)] -#[repr(usize)] -enum FromBytes2 { - A, -} - -#[derive(FromZeroes, FromBytes)] -#[repr(isize)] -enum FromBytes3 { - A, -} - -#[derive(FromZeroes, FromBytes)] -#[repr(u32)] -enum FromBytes4 { - A, -} - -#[derive(FromZeroes, FromBytes)] -#[repr(i32)] -enum FromBytes5 { - A, -} - -#[derive(FromZeroes, FromBytes)] -#[repr(u64)] -enum FromBytes6 { - A, -} - -#[derive(FromZeroes, FromBytes)] -#[repr(i64)] -enum FromBytes7 { - A, -} - -// -// Unaligned errors -// - -#[derive(Unaligned)] -#[repr(C)] -enum Unaligned1 { - A, -} - -#[derive(Unaligned)] -#[repr(u16)] -enum Unaligned2 { - A, -} - -#[derive(Unaligned)] -#[repr(i16)] -enum Unaligned3 { - A, -} - -#[derive(Unaligned)] -#[repr(u32)] -enum Unaligned4 { - A, -} - -#[derive(Unaligned)] -#[repr(i32)] -enum Unaligned5 { - A, -} - -#[derive(Unaligned)] -#[repr(u64)] -enum Unaligned6 { - A, -} - -#[derive(Unaligned)] -#[repr(i64)] -enum Unaligned7 { - A, -} - -#[derive(Unaligned)] -#[repr(usize)] -enum Unaligned8 { - A, -} - -#[derive(Unaligned)] -#[repr(isize)] -enum Unaligned9 { - A, -} - -#[derive(Unaligned)] -#[repr(u8, align(2))] -enum Unaligned10 { - A, -} - -#[derive(Unaligned)] -#[repr(i8, align(2))] -enum Unaligned11 { - A, -} - -#[derive(Unaligned)] -#[repr(align(1), align(2))] -enum Unaligned12 { - A, -} - -#[derive(Unaligned)] -#[repr(align(2), align(4))] -enum Unaligned13 { - A, -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-msrv/enum.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-msrv/enum.stderr deleted file mode 100644 index 39bde3f9..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-msrv/enum.stderr +++ /dev/null
@@ -1,199 +0,0 @@ -error: unrecognized representation hint - --> tests/ui-msrv/enum.rs:19:8 - | -19 | #[repr("foo")] - | ^^^^^ - -error: unrecognized representation hint - --> tests/ui-msrv/enum.rs:25:8 - | -25 | #[repr(foo)] - | ^^^ - -error: unsupported representation for deriving FromBytes, AsBytes, or Unaligned on an enum - --> tests/ui-msrv/enum.rs:31:8 - | -31 | #[repr(transparent)] - | ^^^^^^^^^^^ - -error: conflicting representation hints - --> tests/ui-msrv/enum.rs:37:1 - | -37 | #[repr(u8, u16)] - | ^ - -error: must have a non-align #[repr(...)] attribute in order to guarantee this type's memory layout - --> tests/ui-msrv/enum.rs:42:22 - | -42 | #[derive(FromZeroes, FromBytes)] - | ^^^^^^^^^ - | - = note: this error originates in the derive macro `FromBytes` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: only C-like enums can implement FromZeroes - --> tests/ui-msrv/enum.rs:52:1 - | -52 | / enum FromZeroes1 { -53 | | A(u8), -54 | | } - | |_^ - -error: only C-like enums can implement FromZeroes - --> tests/ui-msrv/enum.rs:57:1 - | -57 | / enum FromZeroes2 { -58 | | A, -59 | | B(u8), -60 | | } - | |_^ - -error: FromZeroes only supported on enums with a variant that has a discriminant of `0` - --> tests/ui-msrv/enum.rs:63:1 - | -63 | / enum FromZeroes3 { -64 | | A = 1, -65 | | B, -66 | | } - | |_^ - -error: FromBytes requires repr of "u8", "u16", "i8", or "i16" - --> tests/ui-msrv/enum.rs:73:8 - | -73 | #[repr(C)] - | ^ - -error: FromBytes requires repr of "u8", "u16", "i8", or "i16" - --> tests/ui-msrv/enum.rs:79:8 - | -79 | #[repr(usize)] - | ^^^^^ - -error: FromBytes requires repr of "u8", "u16", "i8", or "i16" - --> tests/ui-msrv/enum.rs:85:8 - | -85 | #[repr(isize)] - | ^^^^^ - -error: FromBytes requires repr of "u8", "u16", "i8", or "i16" - --> tests/ui-msrv/enum.rs:91:8 - | -91 | #[repr(u32)] - | ^^^ - -error: FromBytes requires repr of "u8", "u16", "i8", or "i16" - --> tests/ui-msrv/enum.rs:97:8 - | -97 | #[repr(i32)] - | ^^^ - -error: FromBytes requires repr of "u8", "u16", "i8", or "i16" - --> tests/ui-msrv/enum.rs:103:8 - | -103 | #[repr(u64)] - | ^^^ - -error: FromBytes requires repr of "u8", "u16", "i8", or "i16" - --> tests/ui-msrv/enum.rs:109:8 - | -109 | #[repr(i64)] - | ^^^ - -error: Unaligned requires repr of "u8" or "i8", and no alignment (i.e., repr(align(N > 1))) - --> tests/ui-msrv/enum.rs:119:8 - | -119 | #[repr(C)] - | ^ - -error: Unaligned requires repr of "u8" or "i8", and no alignment (i.e., repr(align(N > 1))) - --> tests/ui-msrv/enum.rs:125:8 - | -125 | #[repr(u16)] - | ^^^ - -error: Unaligned requires repr of "u8" or "i8", and no alignment (i.e., repr(align(N > 1))) - --> tests/ui-msrv/enum.rs:131:8 - | -131 | #[repr(i16)] - | ^^^ - -error: Unaligned requires repr of "u8" or "i8", and no alignment (i.e., repr(align(N > 1))) - --> tests/ui-msrv/enum.rs:137:8 - | -137 | #[repr(u32)] - | ^^^ - -error: Unaligned requires repr of "u8" or "i8", and no alignment (i.e., repr(align(N > 1))) - --> tests/ui-msrv/enum.rs:143:8 - | -143 | #[repr(i32)] - | ^^^ - -error: Unaligned requires repr of "u8" or "i8", and no alignment (i.e., repr(align(N > 1))) - --> tests/ui-msrv/enum.rs:149:8 - | -149 | #[repr(u64)] - | ^^^ - -error: Unaligned requires repr of "u8" or "i8", and no alignment (i.e., repr(align(N > 1))) - --> tests/ui-msrv/enum.rs:155:8 - | -155 | #[repr(i64)] - | ^^^ - -error: Unaligned requires repr of "u8" or "i8", and no alignment (i.e., repr(align(N > 1))) - --> tests/ui-msrv/enum.rs:161:8 - | -161 | #[repr(usize)] - | ^^^^^ - -error: Unaligned requires repr of "u8" or "i8", and no alignment (i.e., repr(align(N > 1))) - --> tests/ui-msrv/enum.rs:167:8 - | -167 | #[repr(isize)] - | ^^^^^ - -error: cannot derive Unaligned with repr(align(N > 1)) - --> tests/ui-msrv/enum.rs:173:12 - | -173 | #[repr(u8, align(2))] - | ^^^^^^^^ - -error: cannot derive Unaligned with repr(align(N > 1)) - --> tests/ui-msrv/enum.rs:179:12 - | -179 | #[repr(i8, align(2))] - | ^^^^^^^^ - -error: cannot derive Unaligned with repr(align(N > 1)) - --> tests/ui-msrv/enum.rs:185:18 - | -185 | #[repr(align(1), align(2))] - | ^^^^^^^^ - -error: cannot derive Unaligned with repr(align(N > 1)) - --> tests/ui-msrv/enum.rs:191:8 - | -191 | #[repr(align(2), align(4))] - | ^^^^^^^^ - -error[E0565]: meta item in `repr` must be an identifier - --> tests/ui-msrv/enum.rs:19:8 - | -19 | #[repr("foo")] - | ^^^^^ - -error[E0552]: unrecognized representation hint - --> tests/ui-msrv/enum.rs:25:8 - | -25 | #[repr(foo)] - | ^^^ - -error[E0566]: conflicting representation hints - --> tests/ui-msrv/enum.rs:37:8 - | -37 | #[repr(u8, u16)] - | ^^ ^^^ - | - = note: `#[deny(conflicting_repr_hints)]` on by default - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - = note: for more information, see issue #68585 <https://github.com/rust-lang/rust/issues/68585>
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-msrv/enum_from_bytes_u8_too_few.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-msrv/enum_from_bytes_u8_too_few.rs deleted file mode 100644 index 1b1bed3..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-msrv/enum_from_bytes_u8_too_few.rs +++ /dev/null
@@ -1,272 +0,0 @@ -// Copyright 2019 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -#[macro_use] -extern crate zerocopy; - -fn main() {} - -#[derive(FromBytes)] -#[repr(u8)] -enum Foo { - Variant0, - Variant1, - Variant2, - Variant3, - Variant4, - Variant5, - Variant6, - Variant7, - Variant8, - Variant9, - Variant10, - Variant11, - Variant12, - Variant13, - Variant14, - Variant15, - Variant16, - Variant17, - Variant18, - Variant19, - Variant20, - Variant21, - Variant22, - Variant23, - Variant24, - Variant25, - Variant26, - Variant27, - Variant28, - Variant29, - Variant30, - Variant31, - Variant32, - Variant33, - Variant34, - Variant35, - Variant36, - Variant37, - Variant38, - Variant39, - Variant40, - Variant41, - Variant42, - Variant43, - Variant44, - Variant45, - Variant46, - Variant47, - Variant48, - Variant49, - Variant50, - Variant51, - Variant52, - Variant53, - Variant54, - Variant55, - Variant56, - Variant57, - Variant58, - Variant59, - Variant60, - Variant61, - Variant62, - Variant63, - Variant64, - Variant65, - Variant66, - Variant67, - Variant68, - Variant69, - Variant70, - Variant71, - Variant72, - Variant73, - Variant74, - Variant75, - Variant76, - Variant77, - Variant78, - Variant79, - Variant80, - Variant81, - Variant82, - Variant83, - Variant84, - Variant85, - Variant86, - Variant87, - Variant88, - Variant89, - Variant90, - Variant91, - Variant92, - Variant93, - Variant94, - Variant95, - Variant96, - Variant97, - Variant98, - Variant99, - Variant100, - Variant101, - Variant102, - Variant103, - Variant104, - Variant105, - Variant106, - Variant107, - Variant108, - Variant109, - Variant110, - Variant111, - Variant112, - Variant113, - Variant114, - Variant115, - Variant116, - Variant117, - Variant118, - Variant119, - Variant120, - Variant121, - Variant122, - Variant123, - Variant124, - Variant125, - Variant126, - Variant127, - Variant128, - Variant129, - Variant130, - Variant131, - Variant132, - Variant133, - Variant134, - Variant135, - Variant136, - Variant137, - Variant138, - Variant139, - Variant140, - Variant141, - Variant142, - Variant143, - Variant144, - Variant145, - Variant146, - Variant147, - Variant148, - Variant149, - Variant150, - Variant151, - Variant152, - Variant153, - Variant154, - Variant155, - Variant156, - Variant157, - Variant158, - Variant159, - Variant160, - Variant161, - Variant162, - Variant163, - Variant164, - Variant165, - Variant166, - Variant167, - Variant168, - Variant169, - Variant170, - Variant171, - Variant172, - Variant173, - Variant174, - Variant175, - Variant176, - Variant177, - Variant178, - Variant179, - Variant180, - Variant181, - Variant182, - Variant183, - Variant184, - Variant185, - Variant186, - Variant187, - Variant188, - Variant189, - Variant190, - Variant191, - Variant192, - Variant193, - Variant194, - Variant195, - Variant196, - Variant197, - Variant198, - Variant199, - Variant200, - Variant201, - Variant202, - Variant203, - Variant204, - Variant205, - Variant206, - Variant207, - Variant208, - Variant209, - Variant210, - Variant211, - Variant212, - Variant213, - Variant214, - Variant215, - Variant216, - Variant217, - Variant218, - Variant219, - Variant220, - Variant221, - Variant222, - Variant223, - Variant224, - Variant225, - Variant226, - Variant227, - Variant228, - Variant229, - Variant230, - Variant231, - Variant232, - Variant233, - Variant234, - Variant235, - Variant236, - Variant237, - Variant238, - Variant239, - Variant240, - Variant241, - Variant242, - Variant243, - Variant244, - Variant245, - Variant246, - Variant247, - Variant248, - Variant249, - Variant250, - Variant251, - Variant252, - Variant253, - Variant254, -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-msrv/enum_from_bytes_u8_too_few.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-msrv/enum_from_bytes_u8_too_few.stderr deleted file mode 100644 index ff828dc..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-msrv/enum_from_bytes_u8_too_few.stderr +++ /dev/null
@@ -1,11 +0,0 @@ -error: FromBytes only supported on repr(u8) enum with 256 variants - --> tests/ui-msrv/enum_from_bytes_u8_too_few.rs:15:1 - | -15 | / #[repr(u8)] -16 | | enum Foo { -17 | | Variant0, -18 | | Variant1, -... | -271 | | Variant254, -272 | | } - | |_^
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-msrv/late_compile_pass.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-msrv/late_compile_pass.rs deleted file mode 100644 index cd65a6e..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-msrv/late_compile_pass.rs +++ /dev/null
@@ -1,75 +0,0 @@ -// Copyright 2019 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -#[macro_use] -extern crate zerocopy; - -#[path = "../util.rs"] -mod util; - -use self::util::{NotZerocopy, AU16}; -use zerocopy::KnownLayout; - -fn main() {} - -// These tests cause errors which are generated by a later compilation pass than -// the other errors we generate, and so if they're compiled in the same file, -// the compiler will never get to that pass, and so we won't get the errors. - -// -// FromZeroes errors -// - -#[derive(FromZeroes)] -struct FromZeroes1 { - value: NotZerocopy, -} - -// -// FromBytes errors -// - -#[derive(FromBytes)] -struct FromBytes1 { - value: NotZerocopy, -} - -// -// AsBytes errors -// - -#[derive(AsBytes)] -#[repr(C)] -struct AsBytes1 { - value: NotZerocopy, -} - -// -// Unaligned errors -// - -#[derive(Unaligned)] -#[repr(C)] -struct Unaligned1 { - aligned: AU16, -} - -// This specifically tests a bug we had in an old version of the code in which -// the trait bound would only be enforced for the first field's type. -#[derive(Unaligned)] -#[repr(C)] -struct Unaligned2 { - unaligned: u8, - aligned: AU16, -} - -#[derive(Unaligned)] -#[repr(transparent)] -struct Unaligned3 { - aligned: AU16, -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-msrv/late_compile_pass.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-msrv/late_compile_pass.stderr deleted file mode 100644 index 39dbcd18..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-msrv/late_compile_pass.stderr +++ /dev/null
@@ -1,74 +0,0 @@ -warning: unused import: `zerocopy::KnownLayout` - --> tests/ui-msrv/late_compile_pass.rs:16:5 - | -16 | use zerocopy::KnownLayout; - | ^^^^^^^^^^^^^^^^^^^^^ - | - = note: `#[warn(unused_imports)]` on by default - -error[E0277]: the trait bound `NotZerocopy: FromZeroes` is not satisfied - --> tests/ui-msrv/late_compile_pass.rs:28:10 - | -28 | #[derive(FromZeroes)] - | ^^^^^^^^^^ the trait `FromZeroes` is not implemented for `NotZerocopy` - | - = help: see issue #48214 - = note: this error originates in the derive macro `FromZeroes` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `NotZerocopy: FromBytes` is not satisfied - --> tests/ui-msrv/late_compile_pass.rs:37:10 - | -37 | #[derive(FromBytes)] - | ^^^^^^^^^ the trait `FromBytes` is not implemented for `NotZerocopy` - | - = help: see issue #48214 - = note: this error originates in the derive macro `FromBytes` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `FromBytes1: FromZeroes` is not satisfied - --> tests/ui-msrv/late_compile_pass.rs:37:10 - | -37 | #[derive(FromBytes)] - | ^^^^^^^^^ the trait `FromZeroes` is not implemented for `FromBytes1` - | -note: required by a bound in `FromBytes` - --> $WORKSPACE/src/lib.rs - | - | pub unsafe trait FromBytes: FromZeroes { - | ^^^^^^^^^^ required by this bound in `FromBytes` - = note: this error originates in the derive macro `FromBytes` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `NotZerocopy: AsBytes` is not satisfied - --> tests/ui-msrv/late_compile_pass.rs:46:10 - | -46 | #[derive(AsBytes)] - | ^^^^^^^ the trait `AsBytes` is not implemented for `NotZerocopy` - | - = help: see issue #48214 - = note: this error originates in the derive macro `AsBytes` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `AU16: Unaligned` is not satisfied - --> tests/ui-msrv/late_compile_pass.rs:56:10 - | -56 | #[derive(Unaligned)] - | ^^^^^^^^^ the trait `Unaligned` is not implemented for `AU16` - | - = help: see issue #48214 - = note: this error originates in the derive macro `Unaligned` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `AU16: Unaligned` is not satisfied - --> tests/ui-msrv/late_compile_pass.rs:64:10 - | -64 | #[derive(Unaligned)] - | ^^^^^^^^^ the trait `Unaligned` is not implemented for `AU16` - | - = help: see issue #48214 - = note: this error originates in the derive macro `Unaligned` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `AU16: Unaligned` is not satisfied - --> tests/ui-msrv/late_compile_pass.rs:71:10 - | -71 | #[derive(Unaligned)] - | ^^^^^^^^^ the trait `Unaligned` is not implemented for `AU16` - | - = help: see issue #48214 - = note: this error originates in the derive macro `Unaligned` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-msrv/mid_compile_pass.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-msrv/mid_compile_pass.rs deleted file mode 100644 index e0c4bc57..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-msrv/mid_compile_pass.rs +++ /dev/null
@@ -1,61 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::KnownLayout; - -fn main() {} - -// These tests cause errors which are generated by a later compilation pass than -// the other errors we generate, and so if they're compiled in the same file, -// the compiler will never get to that pass, and so we won't get the errors. - -// -// KnownLayout errors -// - -fn assert_kl<T: ?Sized + KnownLayout>(_: &T) {} - -// | `repr(C)`? | generic? | `KnownLayout`? | `Sized`? | Type Name | -// | N | Y | N | N | KL04 | -#[derive(KnownLayout)] -struct KL04<T: ?Sized>(u8, T); - -fn test_kl04<T: ?Sized>(kl: &KL04<T>) { - assert_kl(kl); -} - -// | `repr(C)`? | generic? | `KnownLayout`? | `Sized`? | Type Name | -// | N | Y | Y | N | KL06 | -#[derive(KnownLayout)] -struct KL06<T: ?Sized + KnownLayout>(u8, T); - -fn test_kl06<T: ?Sized + KnownLayout>(kl: &KL06<T>) { - assert_kl(kl); -} - -// | `repr(C)`? | generic? | `KnownLayout`? | `Sized`? | Type Name | -// | Y | Y | N | N | KL12 | -#[derive(KnownLayout)] -#[repr(C)] -struct KL12<T: ?Sized>(u8, T); - -fn test_kl12<T: ?Sized>(kl: &KL12<T>) { - assert_kl(kl) -} - -// | `repr(C)`? | generic? | `KnownLayout`? | `Sized`? | Type Name | -// | Y | Y | N | Y | KL13 | -#[derive(KnownLayout)] -#[repr(C)] -struct KL13<T>(u8, T); - -fn test_kl13<T>(t: T) -> impl KnownLayout { - KL13(0u8, t) -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-msrv/mid_compile_pass.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-msrv/mid_compile_pass.stderr deleted file mode 100644 index 5aa2cde..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-msrv/mid_compile_pass.stderr +++ /dev/null
@@ -1,104 +0,0 @@ -error[E0277]: the trait bound `T: KnownLayout` is not satisfied - --> tests/ui-msrv/mid_compile_pass.rs:59:26 - | -59 | fn test_kl13<T>(t: T) -> impl KnownLayout { - | ^^^^^^^^^^^^^^^^ the trait `KnownLayout` is not implemented for `T` - | -note: required because of the requirements on the impl of `KnownLayout` for `KL13<T>` - --> tests/ui-msrv/mid_compile_pass.rs:55:10 - | -55 | #[derive(KnownLayout)] - | ^^^^^^^^^^^ - = note: this error originates in the derive macro `KnownLayout` (in Nightly builds, run with -Z macro-backtrace for more info) -help: consider restricting type parameter `T` - | -59 | fn test_kl13<T: zerocopy::KnownLayout>(t: T) -> impl KnownLayout { - | +++++++++++++++++++++++ - -error[E0277]: the size for values of type `T` cannot be known at compilation time - --> tests/ui-msrv/mid_compile_pass.rs:31:15 - | -30 | fn test_kl04<T: ?Sized>(kl: &KL04<T>) { - | - this type parameter needs to be `std::marker::Sized` -31 | assert_kl(kl); - | --------- ^^ doesn't have a size known at compile-time - | | - | required by a bound introduced by this call - | -note: required because it appears within the type `KL04<T>` - --> tests/ui-msrv/mid_compile_pass.rs:28:8 - | -28 | struct KL04<T: ?Sized>(u8, T); - | ^^^^ -note: required because of the requirements on the impl of `KnownLayout` for `KL04<T>` - --> tests/ui-msrv/mid_compile_pass.rs:27:10 - | -27 | #[derive(KnownLayout)] - | ^^^^^^^^^^^ -note: required by a bound in `assert_kl` - --> tests/ui-msrv/mid_compile_pass.rs:23:26 - | -23 | fn assert_kl<T: ?Sized + KnownLayout>(_: &T) {} - | ^^^^^^^^^^^ required by this bound in `assert_kl` - = note: this error originates in the derive macro `KnownLayout` (in Nightly builds, run with -Z macro-backtrace for more info) -help: consider removing the `?Sized` bound to make the type parameter `Sized` - | -30 - fn test_kl04<T: ?Sized>(kl: &KL04<T>) { -30 + fn test_kl04<T>(kl: &KL04<T>) { - | - -error[E0277]: the size for values of type `T` cannot be known at compilation time - --> tests/ui-msrv/mid_compile_pass.rs:40:15 - | -39 | fn test_kl06<T: ?Sized + KnownLayout>(kl: &KL06<T>) { - | - this type parameter needs to be `std::marker::Sized` -40 | assert_kl(kl); - | --------- ^^ doesn't have a size known at compile-time - | | - | required by a bound introduced by this call - | -note: required because it appears within the type `KL06<T>` - --> tests/ui-msrv/mid_compile_pass.rs:37:8 - | -37 | struct KL06<T: ?Sized + KnownLayout>(u8, T); - | ^^^^ -note: required because of the requirements on the impl of `KnownLayout` for `KL06<T>` - --> tests/ui-msrv/mid_compile_pass.rs:36:10 - | -36 | #[derive(KnownLayout)] - | ^^^^^^^^^^^ -note: required by a bound in `assert_kl` - --> tests/ui-msrv/mid_compile_pass.rs:23:26 - | -23 | fn assert_kl<T: ?Sized + KnownLayout>(_: &T) {} - | ^^^^^^^^^^^ required by this bound in `assert_kl` - = note: this error originates in the derive macro `KnownLayout` (in Nightly builds, run with -Z macro-backtrace for more info) -help: consider removing the `?Sized` bound to make the type parameter `Sized` - | -39 - fn test_kl06<T: ?Sized + KnownLayout>(kl: &KL06<T>) { -39 + fn test_kl06<T: KnownLayout>(kl: &KL06<T>) { - | - -error[E0277]: the trait bound `T: KnownLayout` is not satisfied - --> tests/ui-msrv/mid_compile_pass.rs:50:15 - | -50 | assert_kl(kl) - | --------- ^^ the trait `KnownLayout` is not implemented for `T` - | | - | required by a bound introduced by this call - | -note: required because of the requirements on the impl of `KnownLayout` for `KL12<T>` - --> tests/ui-msrv/mid_compile_pass.rs:45:10 - | -45 | #[derive(KnownLayout)] - | ^^^^^^^^^^^ -note: required by a bound in `assert_kl` - --> tests/ui-msrv/mid_compile_pass.rs:23:26 - | -23 | fn assert_kl<T: ?Sized + KnownLayout>(_: &T) {} - | ^^^^^^^^^^^ required by this bound in `assert_kl` - = note: this error originates in the derive macro `KnownLayout` (in Nightly builds, run with -Z macro-backtrace for more info) -help: consider further restricting this bound - | -49 | fn test_kl12<T: ?Sized + zerocopy::KnownLayout>(kl: &KL12<T>) { - | +++++++++++++++++++++++
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-msrv/struct.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-msrv/struct.rs deleted file mode 100644 index c76dc7f9..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-msrv/struct.rs +++ /dev/null
@@ -1,99 +0,0 @@ -// Copyright 2019 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -#[macro_use] -extern crate zerocopy; - -#[path = "../util.rs"] -mod util; - -use zerocopy::KnownLayout; - -use self::util::AU16; - -fn main() {} - -// -// KnownLayout errors -// - -struct NotKnownLayout; - -struct NotKnownLayoutDst([u8]); - -// | `repr(C)`? | generic? | `KnownLayout`? | `Sized`? | Type Name | -// | N | N | N | N | KL00 | -#[derive(KnownLayout)] -struct KL00(u8, NotKnownLayoutDst); - -// | `repr(C)`? | generic? | `KnownLayout`? | `Sized`? | Type Name | -// | N | N | Y | N | KL02 | -#[derive(KnownLayout)] -struct KL02(u8, [u8]); - -// | `repr(C)`? | generic? | `KnownLayout`? | `Sized`? | Type Name | -// | Y | N | N | N | KL08 | -#[derive(KnownLayout)] -#[repr(C)] -struct KL08(u8, NotKnownLayoutDst); - -// | `repr(C)`? | generic? | `KnownLayout`? | `Sized`? | Type Name | -// | Y | N | N | Y | KL09 | -#[derive(KnownLayout)] -#[repr(C)] -struct KL09(NotKnownLayout, NotKnownLayout); - -// -// AsBytes errors -// - -#[derive(AsBytes)] -#[repr(C)] -struct AsBytes1<T>(T); - -#[derive(AsBytes)] -#[repr(C)] -struct AsBytes2 { - foo: u8, - bar: AU16, -} - -#[derive(AsBytes)] -#[repr(C, packed(2))] -struct AsBytes3 { - foo: u8, - // We'd prefer to use AU64 here, but you can't use aligned types in - // packed structs. - bar: u64, -} - -// -// Unaligned errors -// - -#[derive(Unaligned)] -#[repr(C, align(2))] -struct Unaligned1; - -#[derive(Unaligned)] -#[repr(transparent, align(2))] -struct Unaligned2 { - foo: u8, -} - -#[derive(Unaligned)] -#[repr(packed, align(2))] -struct Unaligned3; - -#[derive(Unaligned)] -#[repr(align(1), align(2))] -struct Unaligned4; - -#[derive(Unaligned)] -#[repr(align(2), align(4))] -struct Unaligned5;
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-msrv/struct.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-msrv/struct.stderr deleted file mode 100644 index f4a435d..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-msrv/struct.stderr +++ /dev/null
@@ -1,113 +0,0 @@ -error: unsupported on generic structs that are not repr(transparent) or repr(packed) - --> tests/ui-msrv/struct.rs:55:10 - | -55 | #[derive(AsBytes)] - | ^^^^^^^ - | - = note: this error originates in the derive macro `AsBytes` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: cannot derive Unaligned with repr(align(N > 1)) - --> tests/ui-msrv/struct.rs:80:11 - | -80 | #[repr(C, align(2))] - | ^^^^^^^^ - -error: cannot derive Unaligned with repr(align(N > 1)) - --> tests/ui-msrv/struct.rs:84:21 - | -84 | #[repr(transparent, align(2))] - | ^^^^^^^^ - -error: cannot derive Unaligned with repr(align(N > 1)) - --> tests/ui-msrv/struct.rs:90:16 - | -90 | #[repr(packed, align(2))] - | ^^^^^^^^ - -error: cannot derive Unaligned with repr(align(N > 1)) - --> tests/ui-msrv/struct.rs:94:18 - | -94 | #[repr(align(1), align(2))] - | ^^^^^^^^ - -error: cannot derive Unaligned with repr(align(N > 1)) - --> tests/ui-msrv/struct.rs:98:8 - | -98 | #[repr(align(2), align(4))] - | ^^^^^^^^ - -error[E0692]: transparent struct cannot have other repr hints - --> tests/ui-msrv/struct.rs:84:8 - | -84 | #[repr(transparent, align(2))] - | ^^^^^^^^^^^ ^^^^^^^^ - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/struct.rs:31:10 - | -31 | #[derive(KnownLayout)] - | ^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: within `KL00`, the trait `Sized` is not implemented for `[u8]` -note: required because it appears within the type `KL00` - --> tests/ui-msrv/struct.rs:32:8 - | -32 | struct KL00(u8, NotKnownLayoutDst); - | ^^^^ - = help: see issue #48214 - = note: this error originates in the derive macro `KnownLayout` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-msrv/struct.rs:36:10 - | -36 | #[derive(KnownLayout)] - | ^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: within `KL02`, the trait `Sized` is not implemented for `[u8]` -note: required because it appears within the type `KL02` - --> tests/ui-msrv/struct.rs:37:8 - | -37 | struct KL02(u8, [u8]); - | ^^^^ - = help: see issue #48214 - = note: this error originates in the derive macro `KnownLayout` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `NotKnownLayoutDst: KnownLayout` is not satisfied - --> tests/ui-msrv/struct.rs:41:10 - | -41 | #[derive(KnownLayout)] - | ^^^^^^^^^^^ the trait `KnownLayout` is not implemented for `NotKnownLayoutDst` - | - = help: see issue #48214 - = note: this error originates in the derive macro `KnownLayout` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `NotKnownLayout: KnownLayout` is not satisfied - --> tests/ui-msrv/struct.rs:47:10 - | -47 | #[derive(KnownLayout)] - | ^^^^^^^^^^^ the trait `KnownLayout` is not implemented for `NotKnownLayout` - | - = help: see issue #48214 - = note: this error originates in the derive macro `KnownLayout` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `HasPadding<AsBytes2, true>: ShouldBe<false>` is not satisfied - --> tests/ui-msrv/struct.rs:59:10 - | -59 | #[derive(AsBytes)] - | ^^^^^^^ the trait `ShouldBe<false>` is not implemented for `HasPadding<AsBytes2, true>` - | - = help: the following implementations were found: - <HasPadding<T, VALUE> as ShouldBe<VALUE>> - = help: see issue #48214 - = note: this error originates in the derive macro `AsBytes` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `HasPadding<AsBytes3, true>: ShouldBe<false>` is not satisfied - --> tests/ui-msrv/struct.rs:66:10 - | -66 | #[derive(AsBytes)] - | ^^^^^^^ the trait `ShouldBe<false>` is not implemented for `HasPadding<AsBytes3, true>` - | - = help: the following implementations were found: - <HasPadding<T, VALUE> as ShouldBe<VALUE>> - = help: see issue #48214 - = note: this error originates in the derive macro `AsBytes` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-msrv/union.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-msrv/union.rs deleted file mode 100644 index 8938e78..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-msrv/union.rs +++ /dev/null
@@ -1,73 +0,0 @@ -// Copyright 2019 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -#[macro_use] -extern crate zerocopy; - -#[path = "../util.rs"] -mod util; - -use self::util::AU16; -use std::mem::ManuallyDrop; - -fn main() {} - -// -// AsBytes errors -// - -#[derive(AsBytes)] -#[repr(C)] -union AsBytes1<T> { - foo: ManuallyDrop<T>, -} - -#[derive(AsBytes)] -#[repr(C)] -union AsBytes2 { - foo: u8, - bar: [u8; 2], -} - -// -// Unaligned errors -// - -#[derive(Unaligned)] -#[repr(C, align(2))] -union Unaligned1 { - foo: i16, - bar: AU16, -} - -// Transparent unions are unstable; see issue #60405 -// <https://github.com/rust-lang/rust/issues/60405> for more information. - -// #[derive(Unaligned)] -// #[repr(transparent, align(2))] -// union Unaligned2 { -// foo: u8, -// } - -#[derive(Unaligned)] -#[repr(packed, align(2))] -union Unaligned3 { - foo: u8, -} - -#[derive(Unaligned)] -#[repr(align(1), align(2))] -struct Unaligned4 { - foo: u8, -} - -#[derive(Unaligned)] -#[repr(align(2), align(4))] -struct Unaligned5 { - foo: u8, -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-msrv/union.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-msrv/union.stderr deleted file mode 100644 index 3e13059..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-msrv/union.stderr +++ /dev/null
@@ -1,42 +0,0 @@ -error: unsupported on types with type parameters - --> tests/ui-msrv/union.rs:24:10 - | -24 | #[derive(AsBytes)] - | ^^^^^^^ - | - = note: this error originates in the derive macro `AsBytes` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: cannot derive Unaligned with repr(align(N > 1)) - --> tests/ui-msrv/union.rs:42:11 - | -42 | #[repr(C, align(2))] - | ^^^^^^^^ - -error: cannot derive Unaligned with repr(align(N > 1)) - --> tests/ui-msrv/union.rs:58:16 - | -58 | #[repr(packed, align(2))] - | ^^^^^^^^ - -error: cannot derive Unaligned with repr(align(N > 1)) - --> tests/ui-msrv/union.rs:64:18 - | -64 | #[repr(align(1), align(2))] - | ^^^^^^^^ - -error: cannot derive Unaligned with repr(align(N > 1)) - --> tests/ui-msrv/union.rs:70:8 - | -70 | #[repr(align(2), align(4))] - | ^^^^^^^^ - -error[E0277]: the trait bound `HasPadding<AsBytes2, true>: ShouldBe<false>` is not satisfied - --> tests/ui-msrv/union.rs:30:10 - | -30 | #[derive(AsBytes)] - | ^^^^^^^ the trait `ShouldBe<false>` is not implemented for `HasPadding<AsBytes2, true>` - | - = help: the following implementations were found: - <HasPadding<T, VALUE> as ShouldBe<VALUE>> - = help: see issue #48214 - = note: this error originates in the derive macro `AsBytes` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-nightly/derive_transparent.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-nightly/derive_transparent.rs deleted file mode 100644 index 2084d92..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-nightly/derive_transparent.rs +++ /dev/null
@@ -1,40 +0,0 @@ -// Copyright 2019 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -#[path = "../util.rs"] -mod util; - -use core::marker::PhantomData; - -use { - static_assertions::assert_impl_all, - zerocopy::{AsBytes, FromBytes, FromZeroes, Unaligned}, -}; - -use self::util::NotZerocopy; - -fn main() {} - -// Test generic transparent structs - -#[derive(AsBytes, FromZeroes, FromBytes, Unaligned)] -#[repr(transparent)] -struct TransparentStruct<T> { - inner: T, - _phantom: PhantomData<()>, -} - -// It should be legal to derive these traits on a transparent struct, but it -// must also ensure the traits are only implemented when the inner type -// implements them. -assert_impl_all!(TransparentStruct<NotZerocopy>: FromZeroes); -assert_impl_all!(TransparentStruct<NotZerocopy>: FromBytes); -assert_impl_all!(TransparentStruct<NotZerocopy>: AsBytes); -assert_impl_all!(TransparentStruct<NotZerocopy>: Unaligned);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-nightly/derive_transparent.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-nightly/derive_transparent.stderr deleted file mode 100644 index 86533b23..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-nightly/derive_transparent.stderr +++ /dev/null
@@ -1,111 +0,0 @@ -error[E0277]: the trait bound `NotZerocopy: FromZeroes` is not satisfied - --> tests/ui-nightly/derive_transparent.rs:37:18 - | -37 | assert_impl_all!(TransparentStruct<NotZerocopy>: FromZeroes); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `FromZeroes` is not implemented for `NotZerocopy`, which is required by `TransparentStruct<NotZerocopy>: FromZeroes` - | - = help: the following other types implement trait `FromZeroes`: - () - *const T - *mut T - AU16 - F32<O> - F64<O> - I128<O> - I16<O> - and $N others -note: required for `TransparentStruct<NotZerocopy>` to implement `FromZeroes` - --> tests/ui-nightly/derive_transparent.rs:27:19 - | -27 | #[derive(AsBytes, FromZeroes, FromBytes, Unaligned)] - | ^^^^^^^^^^ unsatisfied trait bound introduced in this `derive` macro -note: required by a bound in `_::{closure#0}::assert_impl_all` - --> tests/ui-nightly/derive_transparent.rs:37:1 - | -37 | assert_impl_all!(TransparentStruct<NotZerocopy>: FromZeroes); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `assert_impl_all` - = note: this error originates in the derive macro `FromZeroes` which comes from the expansion of the macro `assert_impl_all` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `NotZerocopy: FromBytes` is not satisfied - --> tests/ui-nightly/derive_transparent.rs:38:18 - | -38 | assert_impl_all!(TransparentStruct<NotZerocopy>: FromBytes); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `FromBytes` is not implemented for `NotZerocopy`, which is required by `TransparentStruct<NotZerocopy>: FromBytes` - | - = help: the following other types implement trait `FromBytes`: - () - AU16 - F32<O> - F64<O> - I128<O> - I16<O> - I32<O> - I64<O> - and $N others -note: required for `TransparentStruct<NotZerocopy>` to implement `FromBytes` - --> tests/ui-nightly/derive_transparent.rs:27:31 - | -27 | #[derive(AsBytes, FromZeroes, FromBytes, Unaligned)] - | ^^^^^^^^^ unsatisfied trait bound introduced in this `derive` macro -note: required by a bound in `_::{closure#0}::assert_impl_all` - --> tests/ui-nightly/derive_transparent.rs:38:1 - | -38 | assert_impl_all!(TransparentStruct<NotZerocopy>: FromBytes); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `assert_impl_all` - = note: this error originates in the derive macro `FromBytes` which comes from the expansion of the macro `assert_impl_all` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `NotZerocopy: AsBytes` is not satisfied - --> tests/ui-nightly/derive_transparent.rs:39:18 - | -39 | assert_impl_all!(TransparentStruct<NotZerocopy>: AsBytes); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `AsBytes` is not implemented for `NotZerocopy`, which is required by `TransparentStruct<NotZerocopy>: AsBytes` - | - = help: the following other types implement trait `AsBytes`: - () - AU16 - F32<O> - F64<O> - I128<O> - I16<O> - I32<O> - I64<O> - and $N others -note: required for `TransparentStruct<NotZerocopy>` to implement `AsBytes` - --> tests/ui-nightly/derive_transparent.rs:27:10 - | -27 | #[derive(AsBytes, FromZeroes, FromBytes, Unaligned)] - | ^^^^^^^ unsatisfied trait bound introduced in this `derive` macro -note: required by a bound in `_::{closure#0}::assert_impl_all` - --> tests/ui-nightly/derive_transparent.rs:39:1 - | -39 | assert_impl_all!(TransparentStruct<NotZerocopy>: AsBytes); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `assert_impl_all` - = note: this error originates in the derive macro `AsBytes` which comes from the expansion of the macro `assert_impl_all` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `NotZerocopy: Unaligned` is not satisfied - --> tests/ui-nightly/derive_transparent.rs:40:18 - | -40 | assert_impl_all!(TransparentStruct<NotZerocopy>: Unaligned); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Unaligned` is not implemented for `NotZerocopy`, which is required by `TransparentStruct<NotZerocopy>: Unaligned` - | - = help: the following other types implement trait `Unaligned`: - () - F32<O> - F64<O> - I128<O> - I16<O> - I32<O> - I64<O> - ManuallyDrop<T> - and $N others -note: required for `TransparentStruct<NotZerocopy>` to implement `Unaligned` - --> tests/ui-nightly/derive_transparent.rs:27:42 - | -27 | #[derive(AsBytes, FromZeroes, FromBytes, Unaligned)] - | ^^^^^^^^^ unsatisfied trait bound introduced in this `derive` macro -note: required by a bound in `_::{closure#0}::assert_impl_all` - --> tests/ui-nightly/derive_transparent.rs:40:1 - | -40 | assert_impl_all!(TransparentStruct<NotZerocopy>: Unaligned); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `assert_impl_all` - = note: this error originates in the derive macro `Unaligned` which comes from the expansion of the macro `assert_impl_all` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-nightly/enum.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-nightly/enum.rs deleted file mode 100644 index 31d5679..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-nightly/enum.rs +++ /dev/null
@@ -1,194 +0,0 @@ -// Copyright 2019 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -#[macro_use] -extern crate zerocopy; - -fn main() {} - -// -// Generic errors -// - -#[derive(FromZeroes, FromBytes)] -#[repr("foo")] -enum Generic1 { - A, -} - -#[derive(FromZeroes, FromBytes)] -#[repr(foo)] -enum Generic2 { - A, -} - -#[derive(FromZeroes, FromBytes)] -#[repr(transparent)] -enum Generic3 { - A, -} - -#[derive(FromZeroes, FromBytes)] -#[repr(u8, u16)] -enum Generic4 { - A, -} - -#[derive(FromZeroes, FromBytes)] -enum Generic5 { - A, -} - -// -// FromZeroes errors -// - -#[derive(FromZeroes)] -enum FromZeroes1 { - A(u8), -} - -#[derive(FromZeroes)] -enum FromZeroes2 { - A, - B(u8), -} - -#[derive(FromZeroes)] -enum FromZeroes3 { - A = 1, - B, -} - -// -// FromBytes errors -// - -#[derive(FromZeroes, FromBytes)] -#[repr(C)] -enum FromBytes1 { - A, -} - -#[derive(FromZeroes, FromBytes)] -#[repr(usize)] -enum FromBytes2 { - A, -} - -#[derive(FromZeroes, FromBytes)] -#[repr(isize)] -enum FromBytes3 { - A, -} - -#[derive(FromZeroes, FromBytes)] -#[repr(u32)] -enum FromBytes4 { - A, -} - -#[derive(FromZeroes, FromBytes)] -#[repr(i32)] -enum FromBytes5 { - A, -} - -#[derive(FromZeroes, FromBytes)] -#[repr(u64)] -enum FromBytes6 { - A, -} - -#[derive(FromZeroes, FromBytes)] -#[repr(i64)] -enum FromBytes7 { - A, -} - -// -// Unaligned errors -// - -#[derive(Unaligned)] -#[repr(C)] -enum Unaligned1 { - A, -} - -#[derive(Unaligned)] -#[repr(u16)] -enum Unaligned2 { - A, -} - -#[derive(Unaligned)] -#[repr(i16)] -enum Unaligned3 { - A, -} - -#[derive(Unaligned)] -#[repr(u32)] -enum Unaligned4 { - A, -} - -#[derive(Unaligned)] -#[repr(i32)] -enum Unaligned5 { - A, -} - -#[derive(Unaligned)] -#[repr(u64)] -enum Unaligned6 { - A, -} - -#[derive(Unaligned)] -#[repr(i64)] -enum Unaligned7 { - A, -} - -#[derive(Unaligned)] -#[repr(usize)] -enum Unaligned8 { - A, -} - -#[derive(Unaligned)] -#[repr(isize)] -enum Unaligned9 { - A, -} - -#[derive(Unaligned)] -#[repr(u8, align(2))] -enum Unaligned10 { - A, -} - -#[derive(Unaligned)] -#[repr(i8, align(2))] -enum Unaligned11 { - A, -} - -#[derive(Unaligned)] -#[repr(align(1), align(2))] -enum Unaligned12 { - A, -} - -#[derive(Unaligned)] -#[repr(align(2), align(4))] -enum Unaligned13 { - A, -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-nightly/enum.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-nightly/enum.stderr deleted file mode 100644 index a4d5edf..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-nightly/enum.stderr +++ /dev/null
@@ -1,201 +0,0 @@ -error: unrecognized representation hint - --> tests/ui-nightly/enum.rs:19:8 - | -19 | #[repr("foo")] - | ^^^^^ - -error: unrecognized representation hint - --> tests/ui-nightly/enum.rs:25:8 - | -25 | #[repr(foo)] - | ^^^ - -error: unsupported representation for deriving FromBytes, AsBytes, or Unaligned on an enum - --> tests/ui-nightly/enum.rs:31:8 - | -31 | #[repr(transparent)] - | ^^^^^^^^^^^ - -error: conflicting representation hints - --> tests/ui-nightly/enum.rs:37:8 - | -37 | #[repr(u8, u16)] - | ^^^^^^^ - -error: must have a non-align #[repr(...)] attribute in order to guarantee this type's memory layout - --> tests/ui-nightly/enum.rs:42:22 - | -42 | #[derive(FromZeroes, FromBytes)] - | ^^^^^^^^^ - | - = note: this error originates in the derive macro `FromBytes` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: only C-like enums can implement FromZeroes - --> tests/ui-nightly/enum.rs:52:1 - | -52 | / enum FromZeroes1 { -53 | | A(u8), -54 | | } - | |_^ - -error: only C-like enums can implement FromZeroes - --> tests/ui-nightly/enum.rs:57:1 - | -57 | / enum FromZeroes2 { -58 | | A, -59 | | B(u8), -60 | | } - | |_^ - -error: FromZeroes only supported on enums with a variant that has a discriminant of `0` - --> tests/ui-nightly/enum.rs:63:1 - | -63 | / enum FromZeroes3 { -64 | | A = 1, -65 | | B, -66 | | } - | |_^ - -error: FromBytes requires repr of "u8", "u16", "i8", or "i16" - --> tests/ui-nightly/enum.rs:73:8 - | -73 | #[repr(C)] - | ^ - -error: FromBytes requires repr of "u8", "u16", "i8", or "i16" - --> tests/ui-nightly/enum.rs:79:8 - | -79 | #[repr(usize)] - | ^^^^^ - -error: FromBytes requires repr of "u8", "u16", "i8", or "i16" - --> tests/ui-nightly/enum.rs:85:8 - | -85 | #[repr(isize)] - | ^^^^^ - -error: FromBytes requires repr of "u8", "u16", "i8", or "i16" - --> tests/ui-nightly/enum.rs:91:8 - | -91 | #[repr(u32)] - | ^^^ - -error: FromBytes requires repr of "u8", "u16", "i8", or "i16" - --> tests/ui-nightly/enum.rs:97:8 - | -97 | #[repr(i32)] - | ^^^ - -error: FromBytes requires repr of "u8", "u16", "i8", or "i16" - --> tests/ui-nightly/enum.rs:103:8 - | -103 | #[repr(u64)] - | ^^^ - -error: FromBytes requires repr of "u8", "u16", "i8", or "i16" - --> tests/ui-nightly/enum.rs:109:8 - | -109 | #[repr(i64)] - | ^^^ - -error: Unaligned requires repr of "u8" or "i8", and no alignment (i.e., repr(align(N > 1))) - --> tests/ui-nightly/enum.rs:119:8 - | -119 | #[repr(C)] - | ^ - -error: Unaligned requires repr of "u8" or "i8", and no alignment (i.e., repr(align(N > 1))) - --> tests/ui-nightly/enum.rs:125:8 - | -125 | #[repr(u16)] - | ^^^ - -error: Unaligned requires repr of "u8" or "i8", and no alignment (i.e., repr(align(N > 1))) - --> tests/ui-nightly/enum.rs:131:8 - | -131 | #[repr(i16)] - | ^^^ - -error: Unaligned requires repr of "u8" or "i8", and no alignment (i.e., repr(align(N > 1))) - --> tests/ui-nightly/enum.rs:137:8 - | -137 | #[repr(u32)] - | ^^^ - -error: Unaligned requires repr of "u8" or "i8", and no alignment (i.e., repr(align(N > 1))) - --> tests/ui-nightly/enum.rs:143:8 - | -143 | #[repr(i32)] - | ^^^ - -error: Unaligned requires repr of "u8" or "i8", and no alignment (i.e., repr(align(N > 1))) - --> tests/ui-nightly/enum.rs:149:8 - | -149 | #[repr(u64)] - | ^^^ - -error: Unaligned requires repr of "u8" or "i8", and no alignment (i.e., repr(align(N > 1))) - --> tests/ui-nightly/enum.rs:155:8 - | -155 | #[repr(i64)] - | ^^^ - -error: Unaligned requires repr of "u8" or "i8", and no alignment (i.e., repr(align(N > 1))) - --> tests/ui-nightly/enum.rs:161:8 - | -161 | #[repr(usize)] - | ^^^^^ - -error: Unaligned requires repr of "u8" or "i8", and no alignment (i.e., repr(align(N > 1))) - --> tests/ui-nightly/enum.rs:167:8 - | -167 | #[repr(isize)] - | ^^^^^ - -error: cannot derive Unaligned with repr(align(N > 1)) - --> tests/ui-nightly/enum.rs:173:12 - | -173 | #[repr(u8, align(2))] - | ^^^^^^^^ - -error: cannot derive Unaligned with repr(align(N > 1)) - --> tests/ui-nightly/enum.rs:179:12 - | -179 | #[repr(i8, align(2))] - | ^^^^^^^^ - -error: cannot derive Unaligned with repr(align(N > 1)) - --> tests/ui-nightly/enum.rs:185:18 - | -185 | #[repr(align(1), align(2))] - | ^^^^^^^^ - -error: cannot derive Unaligned with repr(align(N > 1)) - --> tests/ui-nightly/enum.rs:191:8 - | -191 | #[repr(align(2), align(4))] - | ^^^^^^^^ - -error[E0565]: meta item in `repr` must be an identifier - --> tests/ui-nightly/enum.rs:19:8 - | -19 | #[repr("foo")] - | ^^^^^ - -error[E0552]: unrecognized representation hint - --> tests/ui-nightly/enum.rs:25:8 - | -25 | #[repr(foo)] - | ^^^ - | - = help: valid reprs are `Rust` (default), `C`, `align`, `packed`, `transparent`, `simd`, `i8`, `u8`, `i16`, `u16`, `i32`, `u32`, `i64`, `u64`, `i128`, `u128`, `isize`, `usize` - -error[E0566]: conflicting representation hints - --> tests/ui-nightly/enum.rs:37:8 - | -37 | #[repr(u8, u16)] - | ^^ ^^^ - | - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - = note: for more information, see issue #68585 <https://github.com/rust-lang/rust/issues/68585> - = note: `#[deny(conflicting_repr_hints)]` on by default
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-nightly/enum_from_bytes_u8_too_few.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-nightly/enum_from_bytes_u8_too_few.rs deleted file mode 100644 index 1b1bed3..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-nightly/enum_from_bytes_u8_too_few.rs +++ /dev/null
@@ -1,272 +0,0 @@ -// Copyright 2019 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -#[macro_use] -extern crate zerocopy; - -fn main() {} - -#[derive(FromBytes)] -#[repr(u8)] -enum Foo { - Variant0, - Variant1, - Variant2, - Variant3, - Variant4, - Variant5, - Variant6, - Variant7, - Variant8, - Variant9, - Variant10, - Variant11, - Variant12, - Variant13, - Variant14, - Variant15, - Variant16, - Variant17, - Variant18, - Variant19, - Variant20, - Variant21, - Variant22, - Variant23, - Variant24, - Variant25, - Variant26, - Variant27, - Variant28, - Variant29, - Variant30, - Variant31, - Variant32, - Variant33, - Variant34, - Variant35, - Variant36, - Variant37, - Variant38, - Variant39, - Variant40, - Variant41, - Variant42, - Variant43, - Variant44, - Variant45, - Variant46, - Variant47, - Variant48, - Variant49, - Variant50, - Variant51, - Variant52, - Variant53, - Variant54, - Variant55, - Variant56, - Variant57, - Variant58, - Variant59, - Variant60, - Variant61, - Variant62, - Variant63, - Variant64, - Variant65, - Variant66, - Variant67, - Variant68, - Variant69, - Variant70, - Variant71, - Variant72, - Variant73, - Variant74, - Variant75, - Variant76, - Variant77, - Variant78, - Variant79, - Variant80, - Variant81, - Variant82, - Variant83, - Variant84, - Variant85, - Variant86, - Variant87, - Variant88, - Variant89, - Variant90, - Variant91, - Variant92, - Variant93, - Variant94, - Variant95, - Variant96, - Variant97, - Variant98, - Variant99, - Variant100, - Variant101, - Variant102, - Variant103, - Variant104, - Variant105, - Variant106, - Variant107, - Variant108, - Variant109, - Variant110, - Variant111, - Variant112, - Variant113, - Variant114, - Variant115, - Variant116, - Variant117, - Variant118, - Variant119, - Variant120, - Variant121, - Variant122, - Variant123, - Variant124, - Variant125, - Variant126, - Variant127, - Variant128, - Variant129, - Variant130, - Variant131, - Variant132, - Variant133, - Variant134, - Variant135, - Variant136, - Variant137, - Variant138, - Variant139, - Variant140, - Variant141, - Variant142, - Variant143, - Variant144, - Variant145, - Variant146, - Variant147, - Variant148, - Variant149, - Variant150, - Variant151, - Variant152, - Variant153, - Variant154, - Variant155, - Variant156, - Variant157, - Variant158, - Variant159, - Variant160, - Variant161, - Variant162, - Variant163, - Variant164, - Variant165, - Variant166, - Variant167, - Variant168, - Variant169, - Variant170, - Variant171, - Variant172, - Variant173, - Variant174, - Variant175, - Variant176, - Variant177, - Variant178, - Variant179, - Variant180, - Variant181, - Variant182, - Variant183, - Variant184, - Variant185, - Variant186, - Variant187, - Variant188, - Variant189, - Variant190, - Variant191, - Variant192, - Variant193, - Variant194, - Variant195, - Variant196, - Variant197, - Variant198, - Variant199, - Variant200, - Variant201, - Variant202, - Variant203, - Variant204, - Variant205, - Variant206, - Variant207, - Variant208, - Variant209, - Variant210, - Variant211, - Variant212, - Variant213, - Variant214, - Variant215, - Variant216, - Variant217, - Variant218, - Variant219, - Variant220, - Variant221, - Variant222, - Variant223, - Variant224, - Variant225, - Variant226, - Variant227, - Variant228, - Variant229, - Variant230, - Variant231, - Variant232, - Variant233, - Variant234, - Variant235, - Variant236, - Variant237, - Variant238, - Variant239, - Variant240, - Variant241, - Variant242, - Variant243, - Variant244, - Variant245, - Variant246, - Variant247, - Variant248, - Variant249, - Variant250, - Variant251, - Variant252, - Variant253, - Variant254, -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-nightly/enum_from_bytes_u8_too_few.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-nightly/enum_from_bytes_u8_too_few.stderr deleted file mode 100644 index 50cf0e7c..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-nightly/enum_from_bytes_u8_too_few.stderr +++ /dev/null
@@ -1,11 +0,0 @@ -error: FromBytes only supported on repr(u8) enum with 256 variants - --> tests/ui-nightly/enum_from_bytes_u8_too_few.rs:15:1 - | -15 | / #[repr(u8)] -16 | | enum Foo { -17 | | Variant0, -18 | | Variant1, -... | -271 | | Variant254, -272 | | } - | |_^
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-nightly/late_compile_pass.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-nightly/late_compile_pass.rs deleted file mode 100644 index cd65a6e..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-nightly/late_compile_pass.rs +++ /dev/null
@@ -1,75 +0,0 @@ -// Copyright 2019 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -#[macro_use] -extern crate zerocopy; - -#[path = "../util.rs"] -mod util; - -use self::util::{NotZerocopy, AU16}; -use zerocopy::KnownLayout; - -fn main() {} - -// These tests cause errors which are generated by a later compilation pass than -// the other errors we generate, and so if they're compiled in the same file, -// the compiler will never get to that pass, and so we won't get the errors. - -// -// FromZeroes errors -// - -#[derive(FromZeroes)] -struct FromZeroes1 { - value: NotZerocopy, -} - -// -// FromBytes errors -// - -#[derive(FromBytes)] -struct FromBytes1 { - value: NotZerocopy, -} - -// -// AsBytes errors -// - -#[derive(AsBytes)] -#[repr(C)] -struct AsBytes1 { - value: NotZerocopy, -} - -// -// Unaligned errors -// - -#[derive(Unaligned)] -#[repr(C)] -struct Unaligned1 { - aligned: AU16, -} - -// This specifically tests a bug we had in an old version of the code in which -// the trait bound would only be enforced for the first field's type. -#[derive(Unaligned)] -#[repr(C)] -struct Unaligned2 { - unaligned: u8, - aligned: AU16, -} - -#[derive(Unaligned)] -#[repr(transparent)] -struct Unaligned3 { - aligned: AU16, -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-nightly/late_compile_pass.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-nightly/late_compile_pass.stderr deleted file mode 100644 index 8d4e3389..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-nightly/late_compile_pass.stderr +++ /dev/null
@@ -1,168 +0,0 @@ -warning: unused import: `zerocopy::KnownLayout` - --> tests/ui-nightly/late_compile_pass.rs:16:5 - | -16 | use zerocopy::KnownLayout; - | ^^^^^^^^^^^^^^^^^^^^^ - | - = note: `#[warn(unused_imports)]` on by default - -error[E0277]: the trait bound `NotZerocopy: FromZeroes` is not satisfied - --> tests/ui-nightly/late_compile_pass.rs:28:10 - | -28 | #[derive(FromZeroes)] - | ^^^^^^^^^^ the trait `FromZeroes` is not implemented for `NotZerocopy` - | - = help: the following other types implement trait `FromZeroes`: - () - *const T - *mut T - AU16 - F32<O> - F64<O> - FromZeroes1 - I128<O> - and $N others - = help: see issue #48214 - = note: this error originates in the derive macro `FromZeroes` (in Nightly builds, run with -Z macro-backtrace for more info) -help: add `#![feature(trivial_bounds)]` to the crate attributes to enable - | -9 + #![feature(trivial_bounds)] - | - -error[E0277]: the trait bound `NotZerocopy: FromBytes` is not satisfied - --> tests/ui-nightly/late_compile_pass.rs:37:10 - | -37 | #[derive(FromBytes)] - | ^^^^^^^^^ the trait `FromBytes` is not implemented for `NotZerocopy` - | - = help: the following other types implement trait `FromBytes`: - () - AU16 - F32<O> - F64<O> - FromBytes1 - I128<O> - I16<O> - I32<O> - and $N others - = help: see issue #48214 - = note: this error originates in the derive macro `FromBytes` (in Nightly builds, run with -Z macro-backtrace for more info) -help: add `#![feature(trivial_bounds)]` to the crate attributes to enable - | -9 + #![feature(trivial_bounds)] - | - -error[E0277]: the trait bound `FromBytes1: FromZeroes` is not satisfied - --> tests/ui-nightly/late_compile_pass.rs:37:10 - | -37 | #[derive(FromBytes)] - | ^^^^^^^^^ the trait `FromZeroes` is not implemented for `FromBytes1` - | - = help: the following other types implement trait `FromZeroes`: - () - *const T - *mut T - AU16 - F32<O> - F64<O> - FromZeroes1 - I128<O> - and $N others -note: required by a bound in `FromBytes` - --> $WORKSPACE/src/lib.rs - | - | pub unsafe trait FromBytes: FromZeroes { - | ^^^^^^^^^^ required by this bound in `FromBytes` - = note: this error originates in the derive macro `FromBytes` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `NotZerocopy: AsBytes` is not satisfied - --> tests/ui-nightly/late_compile_pass.rs:46:10 - | -46 | #[derive(AsBytes)] - | ^^^^^^^ the trait `AsBytes` is not implemented for `NotZerocopy` - | - = help: the following other types implement trait `AsBytes`: - () - AU16 - AsBytes1 - F32<O> - F64<O> - I128<O> - I16<O> - I32<O> - and $N others - = help: see issue #48214 - = note: this error originates in the derive macro `AsBytes` (in Nightly builds, run with -Z macro-backtrace for more info) -help: add `#![feature(trivial_bounds)]` to the crate attributes to enable - | -9 + #![feature(trivial_bounds)] - | - -error[E0277]: the trait bound `AU16: Unaligned` is not satisfied - --> tests/ui-nightly/late_compile_pass.rs:56:10 - | -56 | #[derive(Unaligned)] - | ^^^^^^^^^ the trait `Unaligned` is not implemented for `AU16` - | - = help: the following other types implement trait `Unaligned`: - () - F32<O> - F64<O> - I128<O> - I16<O> - I32<O> - I64<O> - ManuallyDrop<T> - and $N others - = help: see issue #48214 - = note: this error originates in the derive macro `Unaligned` (in Nightly builds, run with -Z macro-backtrace for more info) -help: add `#![feature(trivial_bounds)]` to the crate attributes to enable - | -9 + #![feature(trivial_bounds)] - | - -error[E0277]: the trait bound `AU16: Unaligned` is not satisfied - --> tests/ui-nightly/late_compile_pass.rs:64:10 - | -64 | #[derive(Unaligned)] - | ^^^^^^^^^ the trait `Unaligned` is not implemented for `AU16` - | - = help: the following other types implement trait `Unaligned`: - () - F32<O> - F64<O> - I128<O> - I16<O> - I32<O> - I64<O> - ManuallyDrop<T> - and $N others - = help: see issue #48214 - = note: this error originates in the derive macro `Unaligned` (in Nightly builds, run with -Z macro-backtrace for more info) -help: add `#![feature(trivial_bounds)]` to the crate attributes to enable - | -9 + #![feature(trivial_bounds)] - | - -error[E0277]: the trait bound `AU16: Unaligned` is not satisfied - --> tests/ui-nightly/late_compile_pass.rs:71:10 - | -71 | #[derive(Unaligned)] - | ^^^^^^^^^ the trait `Unaligned` is not implemented for `AU16` - | - = help: the following other types implement trait `Unaligned`: - () - F32<O> - F64<O> - I128<O> - I16<O> - I32<O> - I64<O> - ManuallyDrop<T> - and $N others - = help: see issue #48214 - = note: this error originates in the derive macro `Unaligned` (in Nightly builds, run with -Z macro-backtrace for more info) -help: add `#![feature(trivial_bounds)]` to the crate attributes to enable - | -9 + #![feature(trivial_bounds)] - |
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-nightly/mid_compile_pass.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-nightly/mid_compile_pass.rs deleted file mode 100644 index e0c4bc57..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-nightly/mid_compile_pass.rs +++ /dev/null
@@ -1,61 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::KnownLayout; - -fn main() {} - -// These tests cause errors which are generated by a later compilation pass than -// the other errors we generate, and so if they're compiled in the same file, -// the compiler will never get to that pass, and so we won't get the errors. - -// -// KnownLayout errors -// - -fn assert_kl<T: ?Sized + KnownLayout>(_: &T) {} - -// | `repr(C)`? | generic? | `KnownLayout`? | `Sized`? | Type Name | -// | N | Y | N | N | KL04 | -#[derive(KnownLayout)] -struct KL04<T: ?Sized>(u8, T); - -fn test_kl04<T: ?Sized>(kl: &KL04<T>) { - assert_kl(kl); -} - -// | `repr(C)`? | generic? | `KnownLayout`? | `Sized`? | Type Name | -// | N | Y | Y | N | KL06 | -#[derive(KnownLayout)] -struct KL06<T: ?Sized + KnownLayout>(u8, T); - -fn test_kl06<T: ?Sized + KnownLayout>(kl: &KL06<T>) { - assert_kl(kl); -} - -// | `repr(C)`? | generic? | `KnownLayout`? | `Sized`? | Type Name | -// | Y | Y | N | N | KL12 | -#[derive(KnownLayout)] -#[repr(C)] -struct KL12<T: ?Sized>(u8, T); - -fn test_kl12<T: ?Sized>(kl: &KL12<T>) { - assert_kl(kl) -} - -// | `repr(C)`? | generic? | `KnownLayout`? | `Sized`? | Type Name | -// | Y | Y | N | Y | KL13 | -#[derive(KnownLayout)] -#[repr(C)] -struct KL13<T>(u8, T); - -fn test_kl13<T>(t: T) -> impl KnownLayout { - KL13(0u8, t) -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-nightly/mid_compile_pass.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-nightly/mid_compile_pass.stderr deleted file mode 100644 index 591727502..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-nightly/mid_compile_pass.stderr +++ /dev/null
@@ -1,104 +0,0 @@ -error[E0277]: the trait bound `T: KnownLayout` is not satisfied - --> tests/ui-nightly/mid_compile_pass.rs:59:26 - | -59 | fn test_kl13<T>(t: T) -> impl KnownLayout { - | ^^^^^^^^^^^^^^^^ the trait `KnownLayout` is not implemented for `T`, which is required by `KL13<T>: KnownLayout` - | -note: required for `KL13<T>` to implement `KnownLayout` - --> tests/ui-nightly/mid_compile_pass.rs:55:10 - | -55 | #[derive(KnownLayout)] - | ^^^^^^^^^^^ unsatisfied trait bound introduced in this `derive` macro - = note: this error originates in the derive macro `KnownLayout` (in Nightly builds, run with -Z macro-backtrace for more info) -help: consider restricting type parameter `T` - | -59 | fn test_kl13<T: zerocopy::KnownLayout>(t: T) -> impl KnownLayout { - | +++++++++++++++++++++++ - -error[E0277]: the size for values of type `T` cannot be known at compilation time - --> tests/ui-nightly/mid_compile_pass.rs:31:15 - | -30 | fn test_kl04<T: ?Sized>(kl: &KL04<T>) { - | - this type parameter needs to be `Sized` -31 | assert_kl(kl); - | --------- ^^ doesn't have a size known at compile-time - | | - | required by a bound introduced by this call - | -note: required because it appears within the type `KL04<T>` - --> tests/ui-nightly/mid_compile_pass.rs:28:8 - | -28 | struct KL04<T: ?Sized>(u8, T); - | ^^^^ -note: required for `KL04<T>` to implement `KnownLayout` - --> tests/ui-nightly/mid_compile_pass.rs:27:10 - | -27 | #[derive(KnownLayout)] - | ^^^^^^^^^^^ unsatisfied trait bound introduced in this `derive` macro -note: required by a bound in `assert_kl` - --> tests/ui-nightly/mid_compile_pass.rs:23:26 - | -23 | fn assert_kl<T: ?Sized + KnownLayout>(_: &T) {} - | ^^^^^^^^^^^ required by this bound in `assert_kl` - = note: this error originates in the derive macro `KnownLayout` (in Nightly builds, run with -Z macro-backtrace for more info) -help: consider removing the `?Sized` bound to make the type parameter `Sized` - | -30 - fn test_kl04<T: ?Sized>(kl: &KL04<T>) { -30 + fn test_kl04<T>(kl: &KL04<T>) { - | - -error[E0277]: the size for values of type `T` cannot be known at compilation time - --> tests/ui-nightly/mid_compile_pass.rs:40:15 - | -39 | fn test_kl06<T: ?Sized + KnownLayout>(kl: &KL06<T>) { - | - this type parameter needs to be `Sized` -40 | assert_kl(kl); - | --------- ^^ doesn't have a size known at compile-time - | | - | required by a bound introduced by this call - | -note: required because it appears within the type `KL06<T>` - --> tests/ui-nightly/mid_compile_pass.rs:37:8 - | -37 | struct KL06<T: ?Sized + KnownLayout>(u8, T); - | ^^^^ -note: required for `KL06<T>` to implement `KnownLayout` - --> tests/ui-nightly/mid_compile_pass.rs:36:10 - | -36 | #[derive(KnownLayout)] - | ^^^^^^^^^^^ unsatisfied trait bound introduced in this `derive` macro -note: required by a bound in `assert_kl` - --> tests/ui-nightly/mid_compile_pass.rs:23:26 - | -23 | fn assert_kl<T: ?Sized + KnownLayout>(_: &T) {} - | ^^^^^^^^^^^ required by this bound in `assert_kl` - = note: this error originates in the derive macro `KnownLayout` (in Nightly builds, run with -Z macro-backtrace for more info) -help: consider removing the `?Sized` bound to make the type parameter `Sized` - | -39 - fn test_kl06<T: ?Sized + KnownLayout>(kl: &KL06<T>) { -39 + fn test_kl06<T: KnownLayout>(kl: &KL06<T>) { - | - -error[E0277]: the trait bound `T: KnownLayout` is not satisfied - --> tests/ui-nightly/mid_compile_pass.rs:50:15 - | -50 | assert_kl(kl) - | --------- ^^ the trait `KnownLayout` is not implemented for `T`, which is required by `KL12<T>: KnownLayout` - | | - | required by a bound introduced by this call - | -note: required for `KL12<T>` to implement `KnownLayout` - --> tests/ui-nightly/mid_compile_pass.rs:45:10 - | -45 | #[derive(KnownLayout)] - | ^^^^^^^^^^^ unsatisfied trait bound introduced in this `derive` macro -note: required by a bound in `assert_kl` - --> tests/ui-nightly/mid_compile_pass.rs:23:26 - | -23 | fn assert_kl<T: ?Sized + KnownLayout>(_: &T) {} - | ^^^^^^^^^^^ required by this bound in `assert_kl` - = note: this error originates in the derive macro `KnownLayout` (in Nightly builds, run with -Z macro-backtrace for more info) -help: consider further restricting this bound - | -49 | fn test_kl12<T: ?Sized + zerocopy::KnownLayout>(kl: &KL12<T>) { - | +++++++++++++++++++++++
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-nightly/struct.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-nightly/struct.rs deleted file mode 100644 index c76dc7f9..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-nightly/struct.rs +++ /dev/null
@@ -1,99 +0,0 @@ -// Copyright 2019 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -#[macro_use] -extern crate zerocopy; - -#[path = "../util.rs"] -mod util; - -use zerocopy::KnownLayout; - -use self::util::AU16; - -fn main() {} - -// -// KnownLayout errors -// - -struct NotKnownLayout; - -struct NotKnownLayoutDst([u8]); - -// | `repr(C)`? | generic? | `KnownLayout`? | `Sized`? | Type Name | -// | N | N | N | N | KL00 | -#[derive(KnownLayout)] -struct KL00(u8, NotKnownLayoutDst); - -// | `repr(C)`? | generic? | `KnownLayout`? | `Sized`? | Type Name | -// | N | N | Y | N | KL02 | -#[derive(KnownLayout)] -struct KL02(u8, [u8]); - -// | `repr(C)`? | generic? | `KnownLayout`? | `Sized`? | Type Name | -// | Y | N | N | N | KL08 | -#[derive(KnownLayout)] -#[repr(C)] -struct KL08(u8, NotKnownLayoutDst); - -// | `repr(C)`? | generic? | `KnownLayout`? | `Sized`? | Type Name | -// | Y | N | N | Y | KL09 | -#[derive(KnownLayout)] -#[repr(C)] -struct KL09(NotKnownLayout, NotKnownLayout); - -// -// AsBytes errors -// - -#[derive(AsBytes)] -#[repr(C)] -struct AsBytes1<T>(T); - -#[derive(AsBytes)] -#[repr(C)] -struct AsBytes2 { - foo: u8, - bar: AU16, -} - -#[derive(AsBytes)] -#[repr(C, packed(2))] -struct AsBytes3 { - foo: u8, - // We'd prefer to use AU64 here, but you can't use aligned types in - // packed structs. - bar: u64, -} - -// -// Unaligned errors -// - -#[derive(Unaligned)] -#[repr(C, align(2))] -struct Unaligned1; - -#[derive(Unaligned)] -#[repr(transparent, align(2))] -struct Unaligned2 { - foo: u8, -} - -#[derive(Unaligned)] -#[repr(packed, align(2))] -struct Unaligned3; - -#[derive(Unaligned)] -#[repr(align(1), align(2))] -struct Unaligned4; - -#[derive(Unaligned)] -#[repr(align(2), align(4))] -struct Unaligned5;
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-nightly/struct.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-nightly/struct.stderr deleted file mode 100644 index 77e0d9e..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-nightly/struct.stderr +++ /dev/null
@@ -1,161 +0,0 @@ -error: unsupported on generic structs that are not repr(transparent) or repr(packed) - --> tests/ui-nightly/struct.rs:55:10 - | -55 | #[derive(AsBytes)] - | ^^^^^^^ - | - = note: this error originates in the derive macro `AsBytes` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: cannot derive Unaligned with repr(align(N > 1)) - --> tests/ui-nightly/struct.rs:80:11 - | -80 | #[repr(C, align(2))] - | ^^^^^^^^ - -error: cannot derive Unaligned with repr(align(N > 1)) - --> tests/ui-nightly/struct.rs:84:21 - | -84 | #[repr(transparent, align(2))] - | ^^^^^^^^ - -error: cannot derive Unaligned with repr(align(N > 1)) - --> tests/ui-nightly/struct.rs:90:16 - | -90 | #[repr(packed, align(2))] - | ^^^^^^^^ - -error: cannot derive Unaligned with repr(align(N > 1)) - --> tests/ui-nightly/struct.rs:94:18 - | -94 | #[repr(align(1), align(2))] - | ^^^^^^^^ - -error: cannot derive Unaligned with repr(align(N > 1)) - --> tests/ui-nightly/struct.rs:98:8 - | -98 | #[repr(align(2), align(4))] - | ^^^^^^^^ - -error[E0692]: transparent struct cannot have other repr hints - --> tests/ui-nightly/struct.rs:84:8 - | -84 | #[repr(transparent, align(2))] - | ^^^^^^^^^^^ ^^^^^^^^ - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/struct.rs:31:10 - | -31 | #[derive(KnownLayout)] - | ^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: within `KL00`, the trait `Sized` is not implemented for `[u8]`, which is required by `KL00: Sized` -note: required because it appears within the type `KL00` - --> tests/ui-nightly/struct.rs:32:8 - | -32 | struct KL00(u8, NotKnownLayoutDst); - | ^^^^ - = help: see issue #48214 - = note: this error originates in the derive macro `KnownLayout` (in Nightly builds, run with -Z macro-backtrace for more info) -help: add `#![feature(trivial_bounds)]` to the crate attributes to enable - | -9 + #![feature(trivial_bounds)] - | - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-nightly/struct.rs:36:10 - | -36 | #[derive(KnownLayout)] - | ^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: within `KL02`, the trait `Sized` is not implemented for `[u8]`, which is required by `KL02: Sized` -note: required because it appears within the type `KL02` - --> tests/ui-nightly/struct.rs:37:8 - | -37 | struct KL02(u8, [u8]); - | ^^^^ - = help: see issue #48214 - = note: this error originates in the derive macro `KnownLayout` (in Nightly builds, run with -Z macro-backtrace for more info) -help: add `#![feature(trivial_bounds)]` to the crate attributes to enable - | -9 + #![feature(trivial_bounds)] - | - -error[E0277]: the trait bound `NotKnownLayoutDst: KnownLayout` is not satisfied - --> tests/ui-nightly/struct.rs:41:10 - | -41 | #[derive(KnownLayout)] - | ^^^^^^^^^^^ the trait `KnownLayout` is not implemented for `NotKnownLayoutDst` - | - = help: the following other types implement trait `KnownLayout`: - () - *const T - *mut T - AU16 - F32<O> - F64<O> - I128<O> - I16<O> - and $N others - = help: see issue #48214 - = note: this error originates in the derive macro `KnownLayout` (in Nightly builds, run with -Z macro-backtrace for more info) -help: add `#![feature(trivial_bounds)]` to the crate attributes to enable - | -9 + #![feature(trivial_bounds)] - | - -error[E0277]: the trait bound `NotKnownLayout: KnownLayout` is not satisfied - --> tests/ui-nightly/struct.rs:47:10 - | -47 | #[derive(KnownLayout)] - | ^^^^^^^^^^^ the trait `KnownLayout` is not implemented for `NotKnownLayout` - | - = help: the following other types implement trait `KnownLayout`: - () - *const T - *mut T - AU16 - F32<O> - F64<O> - I128<O> - I16<O> - and $N others - = help: see issue #48214 - = note: this error originates in the derive macro `KnownLayout` (in Nightly builds, run with -Z macro-backtrace for more info) -help: add `#![feature(trivial_bounds)]` to the crate attributes to enable - | -9 + #![feature(trivial_bounds)] - | - -error[E0277]: the trait bound `HasPadding<AsBytes2, true>: ShouldBe<false>` is not satisfied - --> tests/ui-nightly/struct.rs:59:10 - | -59 | #[derive(AsBytes)] - | ^^^^^^^ the trait `ShouldBe<false>` is not implemented for `HasPadding<AsBytes2, true>` - | - = help: the trait `ShouldBe<true>` is implemented for `HasPadding<AsBytes2, true>` - = help: see issue #48214 - = note: this error originates in the derive macro `AsBytes` (in Nightly builds, run with -Z macro-backtrace for more info) -help: add `#![feature(trivial_bounds)]` to the crate attributes to enable - | -9 + #![feature(trivial_bounds)] - | - -error[E0277]: the trait bound `HasPadding<AsBytes3, true>: ShouldBe<false>` is not satisfied - --> tests/ui-nightly/struct.rs:66:10 - | -66 | #[derive(AsBytes)] - | ^^^^^^^ the trait `ShouldBe<false>` is not implemented for `HasPadding<AsBytes3, true>` - | - = help: the trait `ShouldBe<true>` is implemented for `HasPadding<AsBytes3, true>` - = help: see issue #48214 - = note: this error originates in the derive macro `AsBytes` (in Nightly builds, run with -Z macro-backtrace for more info) -help: add `#![feature(trivial_bounds)]` to the crate attributes to enable - | -9 + #![feature(trivial_bounds)] - | - -error[E0587]: type has conflicting packed and align representation hints - --> tests/ui-nightly/struct.rs:91:1 - | -91 | struct Unaligned3; - | ^^^^^^^^^^^^^^^^^
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-nightly/union.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-nightly/union.rs deleted file mode 100644 index 8938e78..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-nightly/union.rs +++ /dev/null
@@ -1,73 +0,0 @@ -// Copyright 2019 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -#[macro_use] -extern crate zerocopy; - -#[path = "../util.rs"] -mod util; - -use self::util::AU16; -use std::mem::ManuallyDrop; - -fn main() {} - -// -// AsBytes errors -// - -#[derive(AsBytes)] -#[repr(C)] -union AsBytes1<T> { - foo: ManuallyDrop<T>, -} - -#[derive(AsBytes)] -#[repr(C)] -union AsBytes2 { - foo: u8, - bar: [u8; 2], -} - -// -// Unaligned errors -// - -#[derive(Unaligned)] -#[repr(C, align(2))] -union Unaligned1 { - foo: i16, - bar: AU16, -} - -// Transparent unions are unstable; see issue #60405 -// <https://github.com/rust-lang/rust/issues/60405> for more information. - -// #[derive(Unaligned)] -// #[repr(transparent, align(2))] -// union Unaligned2 { -// foo: u8, -// } - -#[derive(Unaligned)] -#[repr(packed, align(2))] -union Unaligned3 { - foo: u8, -} - -#[derive(Unaligned)] -#[repr(align(1), align(2))] -struct Unaligned4 { - foo: u8, -} - -#[derive(Unaligned)] -#[repr(align(2), align(4))] -struct Unaligned5 { - foo: u8, -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-nightly/union.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-nightly/union.stderr deleted file mode 100644 index ae510e83..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-nightly/union.stderr +++ /dev/null
@@ -1,51 +0,0 @@ -error: unsupported on types with type parameters - --> tests/ui-nightly/union.rs:24:10 - | -24 | #[derive(AsBytes)] - | ^^^^^^^ - | - = note: this error originates in the derive macro `AsBytes` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: cannot derive Unaligned with repr(align(N > 1)) - --> tests/ui-nightly/union.rs:42:11 - | -42 | #[repr(C, align(2))] - | ^^^^^^^^ - -error: cannot derive Unaligned with repr(align(N > 1)) - --> tests/ui-nightly/union.rs:58:16 - | -58 | #[repr(packed, align(2))] - | ^^^^^^^^ - -error: cannot derive Unaligned with repr(align(N > 1)) - --> tests/ui-nightly/union.rs:64:18 - | -64 | #[repr(align(1), align(2))] - | ^^^^^^^^ - -error: cannot derive Unaligned with repr(align(N > 1)) - --> tests/ui-nightly/union.rs:70:8 - | -70 | #[repr(align(2), align(4))] - | ^^^^^^^^ - -error[E0277]: the trait bound `HasPadding<AsBytes2, true>: ShouldBe<false>` is not satisfied - --> tests/ui-nightly/union.rs:30:10 - | -30 | #[derive(AsBytes)] - | ^^^^^^^ the trait `ShouldBe<false>` is not implemented for `HasPadding<AsBytes2, true>` - | - = help: the trait `ShouldBe<true>` is implemented for `HasPadding<AsBytes2, true>` - = help: see issue #48214 - = note: this error originates in the derive macro `AsBytes` (in Nightly builds, run with -Z macro-backtrace for more info) -help: add `#![feature(trivial_bounds)]` to the crate attributes to enable - | -9 + #![feature(trivial_bounds)] - | - -error[E0587]: type has conflicting packed and align representation hints - --> tests/ui-nightly/union.rs:59:1 - | -59 | union Unaligned3 { - | ^^^^^^^^^^^^^^^^
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-stable/derive_transparent.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-stable/derive_transparent.rs deleted file mode 100644 index 2084d92..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-stable/derive_transparent.rs +++ /dev/null
@@ -1,40 +0,0 @@ -// Copyright 2019 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -#[path = "../util.rs"] -mod util; - -use core::marker::PhantomData; - -use { - static_assertions::assert_impl_all, - zerocopy::{AsBytes, FromBytes, FromZeroes, Unaligned}, -}; - -use self::util::NotZerocopy; - -fn main() {} - -// Test generic transparent structs - -#[derive(AsBytes, FromZeroes, FromBytes, Unaligned)] -#[repr(transparent)] -struct TransparentStruct<T> { - inner: T, - _phantom: PhantomData<()>, -} - -// It should be legal to derive these traits on a transparent struct, but it -// must also ensure the traits are only implemented when the inner type -// implements them. -assert_impl_all!(TransparentStruct<NotZerocopy>: FromZeroes); -assert_impl_all!(TransparentStruct<NotZerocopy>: FromBytes); -assert_impl_all!(TransparentStruct<NotZerocopy>: AsBytes); -assert_impl_all!(TransparentStruct<NotZerocopy>: Unaligned);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-stable/derive_transparent.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-stable/derive_transparent.stderr deleted file mode 100644 index 57d34cbf..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-stable/derive_transparent.stderr +++ /dev/null
@@ -1,111 +0,0 @@ -error[E0277]: the trait bound `NotZerocopy: FromZeroes` is not satisfied - --> tests/ui-stable/derive_transparent.rs:37:18 - | -37 | assert_impl_all!(TransparentStruct<NotZerocopy>: FromZeroes); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `FromZeroes` is not implemented for `NotZerocopy`, which is required by `TransparentStruct<NotZerocopy>: FromZeroes` - | - = help: the following other types implement trait `FromZeroes`: - () - *const T - *mut T - AU16 - F32<O> - F64<O> - I128<O> - I16<O> - and $N others -note: required for `TransparentStruct<NotZerocopy>` to implement `FromZeroes` - --> tests/ui-stable/derive_transparent.rs:27:19 - | -27 | #[derive(AsBytes, FromZeroes, FromBytes, Unaligned)] - | ^^^^^^^^^^ unsatisfied trait bound introduced in this `derive` macro -note: required by a bound in `_::{closure#0}::assert_impl_all` - --> tests/ui-stable/derive_transparent.rs:37:1 - | -37 | assert_impl_all!(TransparentStruct<NotZerocopy>: FromZeroes); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `assert_impl_all` - = note: this error originates in the derive macro `FromZeroes` which comes from the expansion of the macro `assert_impl_all` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `NotZerocopy: FromBytes` is not satisfied - --> tests/ui-stable/derive_transparent.rs:38:18 - | -38 | assert_impl_all!(TransparentStruct<NotZerocopy>: FromBytes); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `FromBytes` is not implemented for `NotZerocopy`, which is required by `TransparentStruct<NotZerocopy>: FromBytes` - | - = help: the following other types implement trait `FromBytes`: - () - AU16 - F32<O> - F64<O> - I128<O> - I16<O> - I32<O> - I64<O> - and $N others -note: required for `TransparentStruct<NotZerocopy>` to implement `FromBytes` - --> tests/ui-stable/derive_transparent.rs:27:31 - | -27 | #[derive(AsBytes, FromZeroes, FromBytes, Unaligned)] - | ^^^^^^^^^ unsatisfied trait bound introduced in this `derive` macro -note: required by a bound in `_::{closure#0}::assert_impl_all` - --> tests/ui-stable/derive_transparent.rs:38:1 - | -38 | assert_impl_all!(TransparentStruct<NotZerocopy>: FromBytes); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `assert_impl_all` - = note: this error originates in the derive macro `FromBytes` which comes from the expansion of the macro `assert_impl_all` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `NotZerocopy: AsBytes` is not satisfied - --> tests/ui-stable/derive_transparent.rs:39:18 - | -39 | assert_impl_all!(TransparentStruct<NotZerocopy>: AsBytes); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `AsBytes` is not implemented for `NotZerocopy`, which is required by `TransparentStruct<NotZerocopy>: AsBytes` - | - = help: the following other types implement trait `AsBytes`: - () - AU16 - F32<O> - F64<O> - I128<O> - I16<O> - I32<O> - I64<O> - and $N others -note: required for `TransparentStruct<NotZerocopy>` to implement `AsBytes` - --> tests/ui-stable/derive_transparent.rs:27:10 - | -27 | #[derive(AsBytes, FromZeroes, FromBytes, Unaligned)] - | ^^^^^^^ unsatisfied trait bound introduced in this `derive` macro -note: required by a bound in `_::{closure#0}::assert_impl_all` - --> tests/ui-stable/derive_transparent.rs:39:1 - | -39 | assert_impl_all!(TransparentStruct<NotZerocopy>: AsBytes); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `assert_impl_all` - = note: this error originates in the derive macro `AsBytes` which comes from the expansion of the macro `assert_impl_all` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `NotZerocopy: Unaligned` is not satisfied - --> tests/ui-stable/derive_transparent.rs:40:18 - | -40 | assert_impl_all!(TransparentStruct<NotZerocopy>: Unaligned); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Unaligned` is not implemented for `NotZerocopy`, which is required by `TransparentStruct<NotZerocopy>: Unaligned` - | - = help: the following other types implement trait `Unaligned`: - () - F32<O> - F64<O> - I128<O> - I16<O> - I32<O> - I64<O> - ManuallyDrop<T> - and $N others -note: required for `TransparentStruct<NotZerocopy>` to implement `Unaligned` - --> tests/ui-stable/derive_transparent.rs:27:42 - | -27 | #[derive(AsBytes, FromZeroes, FromBytes, Unaligned)] - | ^^^^^^^^^ unsatisfied trait bound introduced in this `derive` macro -note: required by a bound in `_::{closure#0}::assert_impl_all` - --> tests/ui-stable/derive_transparent.rs:40:1 - | -40 | assert_impl_all!(TransparentStruct<NotZerocopy>: Unaligned); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `assert_impl_all` - = note: this error originates in the derive macro `Unaligned` which comes from the expansion of the macro `assert_impl_all` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-stable/enum.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-stable/enum.rs deleted file mode 100644 index 31d5679..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-stable/enum.rs +++ /dev/null
@@ -1,194 +0,0 @@ -// Copyright 2019 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -#[macro_use] -extern crate zerocopy; - -fn main() {} - -// -// Generic errors -// - -#[derive(FromZeroes, FromBytes)] -#[repr("foo")] -enum Generic1 { - A, -} - -#[derive(FromZeroes, FromBytes)] -#[repr(foo)] -enum Generic2 { - A, -} - -#[derive(FromZeroes, FromBytes)] -#[repr(transparent)] -enum Generic3 { - A, -} - -#[derive(FromZeroes, FromBytes)] -#[repr(u8, u16)] -enum Generic4 { - A, -} - -#[derive(FromZeroes, FromBytes)] -enum Generic5 { - A, -} - -// -// FromZeroes errors -// - -#[derive(FromZeroes)] -enum FromZeroes1 { - A(u8), -} - -#[derive(FromZeroes)] -enum FromZeroes2 { - A, - B(u8), -} - -#[derive(FromZeroes)] -enum FromZeroes3 { - A = 1, - B, -} - -// -// FromBytes errors -// - -#[derive(FromZeroes, FromBytes)] -#[repr(C)] -enum FromBytes1 { - A, -} - -#[derive(FromZeroes, FromBytes)] -#[repr(usize)] -enum FromBytes2 { - A, -} - -#[derive(FromZeroes, FromBytes)] -#[repr(isize)] -enum FromBytes3 { - A, -} - -#[derive(FromZeroes, FromBytes)] -#[repr(u32)] -enum FromBytes4 { - A, -} - -#[derive(FromZeroes, FromBytes)] -#[repr(i32)] -enum FromBytes5 { - A, -} - -#[derive(FromZeroes, FromBytes)] -#[repr(u64)] -enum FromBytes6 { - A, -} - -#[derive(FromZeroes, FromBytes)] -#[repr(i64)] -enum FromBytes7 { - A, -} - -// -// Unaligned errors -// - -#[derive(Unaligned)] -#[repr(C)] -enum Unaligned1 { - A, -} - -#[derive(Unaligned)] -#[repr(u16)] -enum Unaligned2 { - A, -} - -#[derive(Unaligned)] -#[repr(i16)] -enum Unaligned3 { - A, -} - -#[derive(Unaligned)] -#[repr(u32)] -enum Unaligned4 { - A, -} - -#[derive(Unaligned)] -#[repr(i32)] -enum Unaligned5 { - A, -} - -#[derive(Unaligned)] -#[repr(u64)] -enum Unaligned6 { - A, -} - -#[derive(Unaligned)] -#[repr(i64)] -enum Unaligned7 { - A, -} - -#[derive(Unaligned)] -#[repr(usize)] -enum Unaligned8 { - A, -} - -#[derive(Unaligned)] -#[repr(isize)] -enum Unaligned9 { - A, -} - -#[derive(Unaligned)] -#[repr(u8, align(2))] -enum Unaligned10 { - A, -} - -#[derive(Unaligned)] -#[repr(i8, align(2))] -enum Unaligned11 { - A, -} - -#[derive(Unaligned)] -#[repr(align(1), align(2))] -enum Unaligned12 { - A, -} - -#[derive(Unaligned)] -#[repr(align(2), align(4))] -enum Unaligned13 { - A, -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-stable/enum.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-stable/enum.stderr deleted file mode 100644 index a47ce9c..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-stable/enum.stderr +++ /dev/null
@@ -1,201 +0,0 @@ -error: unrecognized representation hint - --> tests/ui-stable/enum.rs:19:8 - | -19 | #[repr("foo")] - | ^^^^^ - -error: unrecognized representation hint - --> tests/ui-stable/enum.rs:25:8 - | -25 | #[repr(foo)] - | ^^^ - -error: unsupported representation for deriving FromBytes, AsBytes, or Unaligned on an enum - --> tests/ui-stable/enum.rs:31:8 - | -31 | #[repr(transparent)] - | ^^^^^^^^^^^ - -error: conflicting representation hints - --> tests/ui-stable/enum.rs:37:1 - | -37 | #[repr(u8, u16)] - | ^ - -error: must have a non-align #[repr(...)] attribute in order to guarantee this type's memory layout - --> tests/ui-stable/enum.rs:42:22 - | -42 | #[derive(FromZeroes, FromBytes)] - | ^^^^^^^^^ - | - = note: this error originates in the derive macro `FromBytes` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: only C-like enums can implement FromZeroes - --> tests/ui-stable/enum.rs:52:1 - | -52 | / enum FromZeroes1 { -53 | | A(u8), -54 | | } - | |_^ - -error: only C-like enums can implement FromZeroes - --> tests/ui-stable/enum.rs:57:1 - | -57 | / enum FromZeroes2 { -58 | | A, -59 | | B(u8), -60 | | } - | |_^ - -error: FromZeroes only supported on enums with a variant that has a discriminant of `0` - --> tests/ui-stable/enum.rs:63:1 - | -63 | / enum FromZeroes3 { -64 | | A = 1, -65 | | B, -66 | | } - | |_^ - -error: FromBytes requires repr of "u8", "u16", "i8", or "i16" - --> tests/ui-stable/enum.rs:73:8 - | -73 | #[repr(C)] - | ^ - -error: FromBytes requires repr of "u8", "u16", "i8", or "i16" - --> tests/ui-stable/enum.rs:79:8 - | -79 | #[repr(usize)] - | ^^^^^ - -error: FromBytes requires repr of "u8", "u16", "i8", or "i16" - --> tests/ui-stable/enum.rs:85:8 - | -85 | #[repr(isize)] - | ^^^^^ - -error: FromBytes requires repr of "u8", "u16", "i8", or "i16" - --> tests/ui-stable/enum.rs:91:8 - | -91 | #[repr(u32)] - | ^^^ - -error: FromBytes requires repr of "u8", "u16", "i8", or "i16" - --> tests/ui-stable/enum.rs:97:8 - | -97 | #[repr(i32)] - | ^^^ - -error: FromBytes requires repr of "u8", "u16", "i8", or "i16" - --> tests/ui-stable/enum.rs:103:8 - | -103 | #[repr(u64)] - | ^^^ - -error: FromBytes requires repr of "u8", "u16", "i8", or "i16" - --> tests/ui-stable/enum.rs:109:8 - | -109 | #[repr(i64)] - | ^^^ - -error: Unaligned requires repr of "u8" or "i8", and no alignment (i.e., repr(align(N > 1))) - --> tests/ui-stable/enum.rs:119:8 - | -119 | #[repr(C)] - | ^ - -error: Unaligned requires repr of "u8" or "i8", and no alignment (i.e., repr(align(N > 1))) - --> tests/ui-stable/enum.rs:125:8 - | -125 | #[repr(u16)] - | ^^^ - -error: Unaligned requires repr of "u8" or "i8", and no alignment (i.e., repr(align(N > 1))) - --> tests/ui-stable/enum.rs:131:8 - | -131 | #[repr(i16)] - | ^^^ - -error: Unaligned requires repr of "u8" or "i8", and no alignment (i.e., repr(align(N > 1))) - --> tests/ui-stable/enum.rs:137:8 - | -137 | #[repr(u32)] - | ^^^ - -error: Unaligned requires repr of "u8" or "i8", and no alignment (i.e., repr(align(N > 1))) - --> tests/ui-stable/enum.rs:143:8 - | -143 | #[repr(i32)] - | ^^^ - -error: Unaligned requires repr of "u8" or "i8", and no alignment (i.e., repr(align(N > 1))) - --> tests/ui-stable/enum.rs:149:8 - | -149 | #[repr(u64)] - | ^^^ - -error: Unaligned requires repr of "u8" or "i8", and no alignment (i.e., repr(align(N > 1))) - --> tests/ui-stable/enum.rs:155:8 - | -155 | #[repr(i64)] - | ^^^ - -error: Unaligned requires repr of "u8" or "i8", and no alignment (i.e., repr(align(N > 1))) - --> tests/ui-stable/enum.rs:161:8 - | -161 | #[repr(usize)] - | ^^^^^ - -error: Unaligned requires repr of "u8" or "i8", and no alignment (i.e., repr(align(N > 1))) - --> tests/ui-stable/enum.rs:167:8 - | -167 | #[repr(isize)] - | ^^^^^ - -error: cannot derive Unaligned with repr(align(N > 1)) - --> tests/ui-stable/enum.rs:173:12 - | -173 | #[repr(u8, align(2))] - | ^^^^^^^^ - -error: cannot derive Unaligned with repr(align(N > 1)) - --> tests/ui-stable/enum.rs:179:12 - | -179 | #[repr(i8, align(2))] - | ^^^^^^^^ - -error: cannot derive Unaligned with repr(align(N > 1)) - --> tests/ui-stable/enum.rs:185:18 - | -185 | #[repr(align(1), align(2))] - | ^^^^^^^^ - -error: cannot derive Unaligned with repr(align(N > 1)) - --> tests/ui-stable/enum.rs:191:8 - | -191 | #[repr(align(2), align(4))] - | ^^^^^^^^ - -error[E0565]: meta item in `repr` must be an identifier - --> tests/ui-stable/enum.rs:19:8 - | -19 | #[repr("foo")] - | ^^^^^ - -error[E0552]: unrecognized representation hint - --> tests/ui-stable/enum.rs:25:8 - | -25 | #[repr(foo)] - | ^^^ - | - = help: valid reprs are `Rust` (default), `C`, `align`, `packed`, `transparent`, `simd`, `i8`, `u8`, `i16`, `u16`, `i32`, `u32`, `i64`, `u64`, `i128`, `u128`, `isize`, `usize` - -error[E0566]: conflicting representation hints - --> tests/ui-stable/enum.rs:37:8 - | -37 | #[repr(u8, u16)] - | ^^ ^^^ - | - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - = note: for more information, see issue #68585 <https://github.com/rust-lang/rust/issues/68585> - = note: `#[deny(conflicting_repr_hints)]` on by default
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-stable/enum_from_bytes_u8_too_few.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-stable/enum_from_bytes_u8_too_few.rs deleted file mode 100644 index 1b1bed3..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-stable/enum_from_bytes_u8_too_few.rs +++ /dev/null
@@ -1,272 +0,0 @@ -// Copyright 2019 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -#[macro_use] -extern crate zerocopy; - -fn main() {} - -#[derive(FromBytes)] -#[repr(u8)] -enum Foo { - Variant0, - Variant1, - Variant2, - Variant3, - Variant4, - Variant5, - Variant6, - Variant7, - Variant8, - Variant9, - Variant10, - Variant11, - Variant12, - Variant13, - Variant14, - Variant15, - Variant16, - Variant17, - Variant18, - Variant19, - Variant20, - Variant21, - Variant22, - Variant23, - Variant24, - Variant25, - Variant26, - Variant27, - Variant28, - Variant29, - Variant30, - Variant31, - Variant32, - Variant33, - Variant34, - Variant35, - Variant36, - Variant37, - Variant38, - Variant39, - Variant40, - Variant41, - Variant42, - Variant43, - Variant44, - Variant45, - Variant46, - Variant47, - Variant48, - Variant49, - Variant50, - Variant51, - Variant52, - Variant53, - Variant54, - Variant55, - Variant56, - Variant57, - Variant58, - Variant59, - Variant60, - Variant61, - Variant62, - Variant63, - Variant64, - Variant65, - Variant66, - Variant67, - Variant68, - Variant69, - Variant70, - Variant71, - Variant72, - Variant73, - Variant74, - Variant75, - Variant76, - Variant77, - Variant78, - Variant79, - Variant80, - Variant81, - Variant82, - Variant83, - Variant84, - Variant85, - Variant86, - Variant87, - Variant88, - Variant89, - Variant90, - Variant91, - Variant92, - Variant93, - Variant94, - Variant95, - Variant96, - Variant97, - Variant98, - Variant99, - Variant100, - Variant101, - Variant102, - Variant103, - Variant104, - Variant105, - Variant106, - Variant107, - Variant108, - Variant109, - Variant110, - Variant111, - Variant112, - Variant113, - Variant114, - Variant115, - Variant116, - Variant117, - Variant118, - Variant119, - Variant120, - Variant121, - Variant122, - Variant123, - Variant124, - Variant125, - Variant126, - Variant127, - Variant128, - Variant129, - Variant130, - Variant131, - Variant132, - Variant133, - Variant134, - Variant135, - Variant136, - Variant137, - Variant138, - Variant139, - Variant140, - Variant141, - Variant142, - Variant143, - Variant144, - Variant145, - Variant146, - Variant147, - Variant148, - Variant149, - Variant150, - Variant151, - Variant152, - Variant153, - Variant154, - Variant155, - Variant156, - Variant157, - Variant158, - Variant159, - Variant160, - Variant161, - Variant162, - Variant163, - Variant164, - Variant165, - Variant166, - Variant167, - Variant168, - Variant169, - Variant170, - Variant171, - Variant172, - Variant173, - Variant174, - Variant175, - Variant176, - Variant177, - Variant178, - Variant179, - Variant180, - Variant181, - Variant182, - Variant183, - Variant184, - Variant185, - Variant186, - Variant187, - Variant188, - Variant189, - Variant190, - Variant191, - Variant192, - Variant193, - Variant194, - Variant195, - Variant196, - Variant197, - Variant198, - Variant199, - Variant200, - Variant201, - Variant202, - Variant203, - Variant204, - Variant205, - Variant206, - Variant207, - Variant208, - Variant209, - Variant210, - Variant211, - Variant212, - Variant213, - Variant214, - Variant215, - Variant216, - Variant217, - Variant218, - Variant219, - Variant220, - Variant221, - Variant222, - Variant223, - Variant224, - Variant225, - Variant226, - Variant227, - Variant228, - Variant229, - Variant230, - Variant231, - Variant232, - Variant233, - Variant234, - Variant235, - Variant236, - Variant237, - Variant238, - Variant239, - Variant240, - Variant241, - Variant242, - Variant243, - Variant244, - Variant245, - Variant246, - Variant247, - Variant248, - Variant249, - Variant250, - Variant251, - Variant252, - Variant253, - Variant254, -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-stable/enum_from_bytes_u8_too_few.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-stable/enum_from_bytes_u8_too_few.stderr deleted file mode 100644 index 5edbabc..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-stable/enum_from_bytes_u8_too_few.stderr +++ /dev/null
@@ -1,11 +0,0 @@ -error: FromBytes only supported on repr(u8) enum with 256 variants - --> tests/ui-stable/enum_from_bytes_u8_too_few.rs:15:1 - | -15 | / #[repr(u8)] -16 | | enum Foo { -17 | | Variant0, -18 | | Variant1, -... | -271 | | Variant254, -272 | | } - | |_^
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-stable/late_compile_pass.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-stable/late_compile_pass.rs deleted file mode 100644 index cd65a6e..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-stable/late_compile_pass.rs +++ /dev/null
@@ -1,75 +0,0 @@ -// Copyright 2019 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -#[macro_use] -extern crate zerocopy; - -#[path = "../util.rs"] -mod util; - -use self::util::{NotZerocopy, AU16}; -use zerocopy::KnownLayout; - -fn main() {} - -// These tests cause errors which are generated by a later compilation pass than -// the other errors we generate, and so if they're compiled in the same file, -// the compiler will never get to that pass, and so we won't get the errors. - -// -// FromZeroes errors -// - -#[derive(FromZeroes)] -struct FromZeroes1 { - value: NotZerocopy, -} - -// -// FromBytes errors -// - -#[derive(FromBytes)] -struct FromBytes1 { - value: NotZerocopy, -} - -// -// AsBytes errors -// - -#[derive(AsBytes)] -#[repr(C)] -struct AsBytes1 { - value: NotZerocopy, -} - -// -// Unaligned errors -// - -#[derive(Unaligned)] -#[repr(C)] -struct Unaligned1 { - aligned: AU16, -} - -// This specifically tests a bug we had in an old version of the code in which -// the trait bound would only be enforced for the first field's type. -#[derive(Unaligned)] -#[repr(C)] -struct Unaligned2 { - unaligned: u8, - aligned: AU16, -} - -#[derive(Unaligned)] -#[repr(transparent)] -struct Unaligned3 { - aligned: AU16, -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-stable/late_compile_pass.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-stable/late_compile_pass.stderr deleted file mode 100644 index 0c66ae57..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-stable/late_compile_pass.stderr +++ /dev/null
@@ -1,144 +0,0 @@ -warning: unused import: `zerocopy::KnownLayout` - --> tests/ui-stable/late_compile_pass.rs:16:5 - | -16 | use zerocopy::KnownLayout; - | ^^^^^^^^^^^^^^^^^^^^^ - | - = note: `#[warn(unused_imports)]` on by default - -error[E0277]: the trait bound `NotZerocopy: FromZeroes` is not satisfied - --> tests/ui-stable/late_compile_pass.rs:28:10 - | -28 | #[derive(FromZeroes)] - | ^^^^^^^^^^ the trait `FromZeroes` is not implemented for `NotZerocopy` - | - = help: the following other types implement trait `FromZeroes`: - () - *const T - *mut T - AU16 - F32<O> - F64<O> - FromZeroes1 - I128<O> - and $N others - = help: see issue #48214 - = note: this error originates in the derive macro `FromZeroes` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `NotZerocopy: FromBytes` is not satisfied - --> tests/ui-stable/late_compile_pass.rs:37:10 - | -37 | #[derive(FromBytes)] - | ^^^^^^^^^ the trait `FromBytes` is not implemented for `NotZerocopy` - | - = help: the following other types implement trait `FromBytes`: - () - AU16 - F32<O> - F64<O> - FromBytes1 - I128<O> - I16<O> - I32<O> - and $N others - = help: see issue #48214 - = note: this error originates in the derive macro `FromBytes` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `FromBytes1: FromZeroes` is not satisfied - --> tests/ui-stable/late_compile_pass.rs:37:10 - | -37 | #[derive(FromBytes)] - | ^^^^^^^^^ the trait `FromZeroes` is not implemented for `FromBytes1` - | - = help: the following other types implement trait `FromZeroes`: - () - *const T - *mut T - AU16 - F32<O> - F64<O> - FromZeroes1 - I128<O> - and $N others -note: required by a bound in `FromBytes` - --> $WORKSPACE/src/lib.rs - | - | pub unsafe trait FromBytes: FromZeroes { - | ^^^^^^^^^^ required by this bound in `FromBytes` - = note: this error originates in the derive macro `FromBytes` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `NotZerocopy: AsBytes` is not satisfied - --> tests/ui-stable/late_compile_pass.rs:46:10 - | -46 | #[derive(AsBytes)] - | ^^^^^^^ the trait `AsBytes` is not implemented for `NotZerocopy` - | - = help: the following other types implement trait `AsBytes`: - () - AU16 - AsBytes1 - F32<O> - F64<O> - I128<O> - I16<O> - I32<O> - and $N others - = help: see issue #48214 - = note: this error originates in the derive macro `AsBytes` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `AU16: Unaligned` is not satisfied - --> tests/ui-stable/late_compile_pass.rs:56:10 - | -56 | #[derive(Unaligned)] - | ^^^^^^^^^ the trait `Unaligned` is not implemented for `AU16` - | - = help: the following other types implement trait `Unaligned`: - () - F32<O> - F64<O> - I128<O> - I16<O> - I32<O> - I64<O> - ManuallyDrop<T> - and $N others - = help: see issue #48214 - = note: this error originates in the derive macro `Unaligned` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `AU16: Unaligned` is not satisfied - --> tests/ui-stable/late_compile_pass.rs:64:10 - | -64 | #[derive(Unaligned)] - | ^^^^^^^^^ the trait `Unaligned` is not implemented for `AU16` - | - = help: the following other types implement trait `Unaligned`: - () - F32<O> - F64<O> - I128<O> - I16<O> - I32<O> - I64<O> - ManuallyDrop<T> - and $N others - = help: see issue #48214 - = note: this error originates in the derive macro `Unaligned` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `AU16: Unaligned` is not satisfied - --> tests/ui-stable/late_compile_pass.rs:71:10 - | -71 | #[derive(Unaligned)] - | ^^^^^^^^^ the trait `Unaligned` is not implemented for `AU16` - | - = help: the following other types implement trait `Unaligned`: - () - F32<O> - F64<O> - I128<O> - I16<O> - I32<O> - I64<O> - ManuallyDrop<T> - and $N others - = help: see issue #48214 - = note: this error originates in the derive macro `Unaligned` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-stable/mid_compile_pass.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-stable/mid_compile_pass.rs deleted file mode 100644 index e0c4bc57..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-stable/mid_compile_pass.rs +++ /dev/null
@@ -1,61 +0,0 @@ -// Copyright 2023 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -extern crate zerocopy; - -use zerocopy::KnownLayout; - -fn main() {} - -// These tests cause errors which are generated by a later compilation pass than -// the other errors we generate, and so if they're compiled in the same file, -// the compiler will never get to that pass, and so we won't get the errors. - -// -// KnownLayout errors -// - -fn assert_kl<T: ?Sized + KnownLayout>(_: &T) {} - -// | `repr(C)`? | generic? | `KnownLayout`? | `Sized`? | Type Name | -// | N | Y | N | N | KL04 | -#[derive(KnownLayout)] -struct KL04<T: ?Sized>(u8, T); - -fn test_kl04<T: ?Sized>(kl: &KL04<T>) { - assert_kl(kl); -} - -// | `repr(C)`? | generic? | `KnownLayout`? | `Sized`? | Type Name | -// | N | Y | Y | N | KL06 | -#[derive(KnownLayout)] -struct KL06<T: ?Sized + KnownLayout>(u8, T); - -fn test_kl06<T: ?Sized + KnownLayout>(kl: &KL06<T>) { - assert_kl(kl); -} - -// | `repr(C)`? | generic? | `KnownLayout`? | `Sized`? | Type Name | -// | Y | Y | N | N | KL12 | -#[derive(KnownLayout)] -#[repr(C)] -struct KL12<T: ?Sized>(u8, T); - -fn test_kl12<T: ?Sized>(kl: &KL12<T>) { - assert_kl(kl) -} - -// | `repr(C)`? | generic? | `KnownLayout`? | `Sized`? | Type Name | -// | Y | Y | N | Y | KL13 | -#[derive(KnownLayout)] -#[repr(C)] -struct KL13<T>(u8, T); - -fn test_kl13<T>(t: T) -> impl KnownLayout { - KL13(0u8, t) -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-stable/mid_compile_pass.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-stable/mid_compile_pass.stderr deleted file mode 100644 index ee7dcb9..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-stable/mid_compile_pass.stderr +++ /dev/null
@@ -1,104 +0,0 @@ -error[E0277]: the trait bound `T: KnownLayout` is not satisfied - --> tests/ui-stable/mid_compile_pass.rs:59:26 - | -59 | fn test_kl13<T>(t: T) -> impl KnownLayout { - | ^^^^^^^^^^^^^^^^ the trait `KnownLayout` is not implemented for `T`, which is required by `KL13<T>: KnownLayout` - | -note: required for `KL13<T>` to implement `KnownLayout` - --> tests/ui-stable/mid_compile_pass.rs:55:10 - | -55 | #[derive(KnownLayout)] - | ^^^^^^^^^^^ unsatisfied trait bound introduced in this `derive` macro - = note: this error originates in the derive macro `KnownLayout` (in Nightly builds, run with -Z macro-backtrace for more info) -help: consider restricting type parameter `T` - | -59 | fn test_kl13<T: zerocopy::KnownLayout>(t: T) -> impl KnownLayout { - | +++++++++++++++++++++++ - -error[E0277]: the size for values of type `T` cannot be known at compilation time - --> tests/ui-stable/mid_compile_pass.rs:31:15 - | -30 | fn test_kl04<T: ?Sized>(kl: &KL04<T>) { - | - this type parameter needs to be `Sized` -31 | assert_kl(kl); - | --------- ^^ doesn't have a size known at compile-time - | | - | required by a bound introduced by this call - | -note: required because it appears within the type `KL04<T>` - --> tests/ui-stable/mid_compile_pass.rs:28:8 - | -28 | struct KL04<T: ?Sized>(u8, T); - | ^^^^ -note: required for `KL04<T>` to implement `KnownLayout` - --> tests/ui-stable/mid_compile_pass.rs:27:10 - | -27 | #[derive(KnownLayout)] - | ^^^^^^^^^^^ unsatisfied trait bound introduced in this `derive` macro -note: required by a bound in `assert_kl` - --> tests/ui-stable/mid_compile_pass.rs:23:26 - | -23 | fn assert_kl<T: ?Sized + KnownLayout>(_: &T) {} - | ^^^^^^^^^^^ required by this bound in `assert_kl` - = note: this error originates in the derive macro `KnownLayout` (in Nightly builds, run with -Z macro-backtrace for more info) -help: consider removing the `?Sized` bound to make the type parameter `Sized` - | -30 - fn test_kl04<T: ?Sized>(kl: &KL04<T>) { -30 + fn test_kl04<T>(kl: &KL04<T>) { - | - -error[E0277]: the size for values of type `T` cannot be known at compilation time - --> tests/ui-stable/mid_compile_pass.rs:40:15 - | -39 | fn test_kl06<T: ?Sized + KnownLayout>(kl: &KL06<T>) { - | - this type parameter needs to be `Sized` -40 | assert_kl(kl); - | --------- ^^ doesn't have a size known at compile-time - | | - | required by a bound introduced by this call - | -note: required because it appears within the type `KL06<T>` - --> tests/ui-stable/mid_compile_pass.rs:37:8 - | -37 | struct KL06<T: ?Sized + KnownLayout>(u8, T); - | ^^^^ -note: required for `KL06<T>` to implement `KnownLayout` - --> tests/ui-stable/mid_compile_pass.rs:36:10 - | -36 | #[derive(KnownLayout)] - | ^^^^^^^^^^^ unsatisfied trait bound introduced in this `derive` macro -note: required by a bound in `assert_kl` - --> tests/ui-stable/mid_compile_pass.rs:23:26 - | -23 | fn assert_kl<T: ?Sized + KnownLayout>(_: &T) {} - | ^^^^^^^^^^^ required by this bound in `assert_kl` - = note: this error originates in the derive macro `KnownLayout` (in Nightly builds, run with -Z macro-backtrace for more info) -help: consider removing the `?Sized` bound to make the type parameter `Sized` - | -39 - fn test_kl06<T: ?Sized + KnownLayout>(kl: &KL06<T>) { -39 + fn test_kl06<T: KnownLayout>(kl: &KL06<T>) { - | - -error[E0277]: the trait bound `T: KnownLayout` is not satisfied - --> tests/ui-stable/mid_compile_pass.rs:50:15 - | -50 | assert_kl(kl) - | --------- ^^ the trait `KnownLayout` is not implemented for `T`, which is required by `KL12<T>: KnownLayout` - | | - | required by a bound introduced by this call - | -note: required for `KL12<T>` to implement `KnownLayout` - --> tests/ui-stable/mid_compile_pass.rs:45:10 - | -45 | #[derive(KnownLayout)] - | ^^^^^^^^^^^ unsatisfied trait bound introduced in this `derive` macro -note: required by a bound in `assert_kl` - --> tests/ui-stable/mid_compile_pass.rs:23:26 - | -23 | fn assert_kl<T: ?Sized + KnownLayout>(_: &T) {} - | ^^^^^^^^^^^ required by this bound in `assert_kl` - = note: this error originates in the derive macro `KnownLayout` (in Nightly builds, run with -Z macro-backtrace for more info) -help: consider further restricting this bound - | -49 | fn test_kl12<T: ?Sized + zerocopy::KnownLayout>(kl: &KL12<T>) { - | +++++++++++++++++++++++
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-stable/struct.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-stable/struct.rs deleted file mode 100644 index c76dc7f9..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-stable/struct.rs +++ /dev/null
@@ -1,99 +0,0 @@ -// Copyright 2019 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -#[macro_use] -extern crate zerocopy; - -#[path = "../util.rs"] -mod util; - -use zerocopy::KnownLayout; - -use self::util::AU16; - -fn main() {} - -// -// KnownLayout errors -// - -struct NotKnownLayout; - -struct NotKnownLayoutDst([u8]); - -// | `repr(C)`? | generic? | `KnownLayout`? | `Sized`? | Type Name | -// | N | N | N | N | KL00 | -#[derive(KnownLayout)] -struct KL00(u8, NotKnownLayoutDst); - -// | `repr(C)`? | generic? | `KnownLayout`? | `Sized`? | Type Name | -// | N | N | Y | N | KL02 | -#[derive(KnownLayout)] -struct KL02(u8, [u8]); - -// | `repr(C)`? | generic? | `KnownLayout`? | `Sized`? | Type Name | -// | Y | N | N | N | KL08 | -#[derive(KnownLayout)] -#[repr(C)] -struct KL08(u8, NotKnownLayoutDst); - -// | `repr(C)`? | generic? | `KnownLayout`? | `Sized`? | Type Name | -// | Y | N | N | Y | KL09 | -#[derive(KnownLayout)] -#[repr(C)] -struct KL09(NotKnownLayout, NotKnownLayout); - -// -// AsBytes errors -// - -#[derive(AsBytes)] -#[repr(C)] -struct AsBytes1<T>(T); - -#[derive(AsBytes)] -#[repr(C)] -struct AsBytes2 { - foo: u8, - bar: AU16, -} - -#[derive(AsBytes)] -#[repr(C, packed(2))] -struct AsBytes3 { - foo: u8, - // We'd prefer to use AU64 here, but you can't use aligned types in - // packed structs. - bar: u64, -} - -// -// Unaligned errors -// - -#[derive(Unaligned)] -#[repr(C, align(2))] -struct Unaligned1; - -#[derive(Unaligned)] -#[repr(transparent, align(2))] -struct Unaligned2 { - foo: u8, -} - -#[derive(Unaligned)] -#[repr(packed, align(2))] -struct Unaligned3; - -#[derive(Unaligned)] -#[repr(align(1), align(2))] -struct Unaligned4; - -#[derive(Unaligned)] -#[repr(align(2), align(4))] -struct Unaligned5;
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-stable/struct.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-stable/struct.stderr deleted file mode 100644 index c1e95af0..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-stable/struct.stderr +++ /dev/null
@@ -1,137 +0,0 @@ -error: unsupported on generic structs that are not repr(transparent) or repr(packed) - --> tests/ui-stable/struct.rs:55:10 - | -55 | #[derive(AsBytes)] - | ^^^^^^^ - | - = note: this error originates in the derive macro `AsBytes` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: cannot derive Unaligned with repr(align(N > 1)) - --> tests/ui-stable/struct.rs:80:11 - | -80 | #[repr(C, align(2))] - | ^^^^^^^^ - -error: cannot derive Unaligned with repr(align(N > 1)) - --> tests/ui-stable/struct.rs:84:21 - | -84 | #[repr(transparent, align(2))] - | ^^^^^^^^ - -error: cannot derive Unaligned with repr(align(N > 1)) - --> tests/ui-stable/struct.rs:90:16 - | -90 | #[repr(packed, align(2))] - | ^^^^^^^^ - -error: cannot derive Unaligned with repr(align(N > 1)) - --> tests/ui-stable/struct.rs:94:18 - | -94 | #[repr(align(1), align(2))] - | ^^^^^^^^ - -error: cannot derive Unaligned with repr(align(N > 1)) - --> tests/ui-stable/struct.rs:98:8 - | -98 | #[repr(align(2), align(4))] - | ^^^^^^^^ - -error[E0692]: transparent struct cannot have other repr hints - --> tests/ui-stable/struct.rs:84:8 - | -84 | #[repr(transparent, align(2))] - | ^^^^^^^^^^^ ^^^^^^^^ - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/struct.rs:31:10 - | -31 | #[derive(KnownLayout)] - | ^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: within `KL00`, the trait `Sized` is not implemented for `[u8]`, which is required by `KL00: Sized` -note: required because it appears within the type `KL00` - --> tests/ui-stable/struct.rs:32:8 - | -32 | struct KL00(u8, NotKnownLayoutDst); - | ^^^^ - = help: see issue #48214 - = note: this error originates in the derive macro `KnownLayout` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> tests/ui-stable/struct.rs:36:10 - | -36 | #[derive(KnownLayout)] - | ^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: within `KL02`, the trait `Sized` is not implemented for `[u8]`, which is required by `KL02: Sized` -note: required because it appears within the type `KL02` - --> tests/ui-stable/struct.rs:37:8 - | -37 | struct KL02(u8, [u8]); - | ^^^^ - = help: see issue #48214 - = note: this error originates in the derive macro `KnownLayout` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `NotKnownLayoutDst: KnownLayout` is not satisfied - --> tests/ui-stable/struct.rs:41:10 - | -41 | #[derive(KnownLayout)] - | ^^^^^^^^^^^ the trait `KnownLayout` is not implemented for `NotKnownLayoutDst` - | - = help: the following other types implement trait `KnownLayout`: - () - *const T - *mut T - AU16 - F32<O> - F64<O> - I128<O> - I16<O> - and $N others - = help: see issue #48214 - = note: this error originates in the derive macro `KnownLayout` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `NotKnownLayout: KnownLayout` is not satisfied - --> tests/ui-stable/struct.rs:47:10 - | -47 | #[derive(KnownLayout)] - | ^^^^^^^^^^^ the trait `KnownLayout` is not implemented for `NotKnownLayout` - | - = help: the following other types implement trait `KnownLayout`: - () - *const T - *mut T - AU16 - F32<O> - F64<O> - I128<O> - I16<O> - and $N others - = help: see issue #48214 - = note: this error originates in the derive macro `KnownLayout` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `HasPadding<AsBytes2, true>: ShouldBe<false>` is not satisfied - --> tests/ui-stable/struct.rs:59:10 - | -59 | #[derive(AsBytes)] - | ^^^^^^^ the trait `ShouldBe<false>` is not implemented for `HasPadding<AsBytes2, true>` - | - = help: the trait `ShouldBe<true>` is implemented for `HasPadding<AsBytes2, true>` - = help: see issue #48214 - = note: this error originates in the derive macro `AsBytes` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0277]: the trait bound `HasPadding<AsBytes3, true>: ShouldBe<false>` is not satisfied - --> tests/ui-stable/struct.rs:66:10 - | -66 | #[derive(AsBytes)] - | ^^^^^^^ the trait `ShouldBe<false>` is not implemented for `HasPadding<AsBytes3, true>` - | - = help: the trait `ShouldBe<true>` is implemented for `HasPadding<AsBytes3, true>` - = help: see issue #48214 - = note: this error originates in the derive macro `AsBytes` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0587]: type has conflicting packed and align representation hints - --> tests/ui-stable/struct.rs:91:1 - | -91 | struct Unaligned3; - | ^^^^^^^^^^^^^^^^^
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-stable/union.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-stable/union.rs deleted file mode 100644 index 8938e78..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-stable/union.rs +++ /dev/null
@@ -1,73 +0,0 @@ -// Copyright 2019 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -#[macro_use] -extern crate zerocopy; - -#[path = "../util.rs"] -mod util; - -use self::util::AU16; -use std::mem::ManuallyDrop; - -fn main() {} - -// -// AsBytes errors -// - -#[derive(AsBytes)] -#[repr(C)] -union AsBytes1<T> { - foo: ManuallyDrop<T>, -} - -#[derive(AsBytes)] -#[repr(C)] -union AsBytes2 { - foo: u8, - bar: [u8; 2], -} - -// -// Unaligned errors -// - -#[derive(Unaligned)] -#[repr(C, align(2))] -union Unaligned1 { - foo: i16, - bar: AU16, -} - -// Transparent unions are unstable; see issue #60405 -// <https://github.com/rust-lang/rust/issues/60405> for more information. - -// #[derive(Unaligned)] -// #[repr(transparent, align(2))] -// union Unaligned2 { -// foo: u8, -// } - -#[derive(Unaligned)] -#[repr(packed, align(2))] -union Unaligned3 { - foo: u8, -} - -#[derive(Unaligned)] -#[repr(align(1), align(2))] -struct Unaligned4 { - foo: u8, -} - -#[derive(Unaligned)] -#[repr(align(2), align(4))] -struct Unaligned5 { - foo: u8, -}
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-stable/union.stderr b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-stable/union.stderr deleted file mode 100644 index f7d6953..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/ui-stable/union.stderr +++ /dev/null
@@ -1,47 +0,0 @@ -error: unsupported on types with type parameters - --> tests/ui-stable/union.rs:24:10 - | -24 | #[derive(AsBytes)] - | ^^^^^^^ - | - = note: this error originates in the derive macro `AsBytes` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: cannot derive Unaligned with repr(align(N > 1)) - --> tests/ui-stable/union.rs:42:11 - | -42 | #[repr(C, align(2))] - | ^^^^^^^^ - -error: cannot derive Unaligned with repr(align(N > 1)) - --> tests/ui-stable/union.rs:58:16 - | -58 | #[repr(packed, align(2))] - | ^^^^^^^^ - -error: cannot derive Unaligned with repr(align(N > 1)) - --> tests/ui-stable/union.rs:64:18 - | -64 | #[repr(align(1), align(2))] - | ^^^^^^^^ - -error: cannot derive Unaligned with repr(align(N > 1)) - --> tests/ui-stable/union.rs:70:8 - | -70 | #[repr(align(2), align(4))] - | ^^^^^^^^ - -error[E0277]: the trait bound `HasPadding<AsBytes2, true>: ShouldBe<false>` is not satisfied - --> tests/ui-stable/union.rs:30:10 - | -30 | #[derive(AsBytes)] - | ^^^^^^^ the trait `ShouldBe<false>` is not implemented for `HasPadding<AsBytes2, true>` - | - = help: the trait `ShouldBe<true>` is implemented for `HasPadding<AsBytes2, true>` - = help: see issue #48214 - = note: this error originates in the derive macro `AsBytes` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0587]: type has conflicting packed and align representation hints - --> tests/ui-stable/union.rs:59:1 - | -59 | union Unaligned3 { - | ^^^^^^^^^^^^^^^^
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/union_as_bytes.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/union_as_bytes.rs deleted file mode 100644 index 84f51817..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/union_as_bytes.rs +++ /dev/null
@@ -1,75 +0,0 @@ -// Copyright 2019 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -#![allow(warnings)] - -use std::{marker::PhantomData, option::IntoIter}; - -use {static_assertions::assert_impl_all, zerocopy::AsBytes}; - -// A union is `AsBytes` if: -// - all fields are `AsBytes` -// - `repr(C)` or `repr(transparent)` and -// - no padding (size of union equals size of each field type) -// - `repr(packed)` - -#[derive(AsBytes, Clone, Copy)] -#[repr(C)] -union CZst { - a: (), -} - -assert_impl_all!(CZst: AsBytes); - -#[derive(AsBytes)] -#[repr(C)] -union C { - a: u8, - b: u8, -} - -assert_impl_all!(C: AsBytes); - -// Transparent unions are unstable; see issue #60405 -// <https://github.com/rust-lang/rust/issues/60405> for more information. - -// #[derive(AsBytes)] -// #[repr(transparent)] -// union Transparent { -// a: u8, -// b: CZst, -// } - -// is_as_bytes!(Transparent); - -#[derive(AsBytes)] -#[repr(C, packed)] -union CZstPacked { - a: (), -} - -assert_impl_all!(CZstPacked: AsBytes); - -#[derive(AsBytes)] -#[repr(C, packed)] -union CPacked { - a: u8, - b: i8, -} - -assert_impl_all!(CPacked: AsBytes); - -#[derive(AsBytes)] -#[repr(C, packed)] -union CMultibytePacked { - a: i32, - b: u32, - c: f32, -} - -assert_impl_all!(CMultibytePacked: AsBytes);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/union_from_bytes.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/union_from_bytes.rs deleted file mode 100644 index 4635735..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/union_from_bytes.rs +++ /dev/null
@@ -1,72 +0,0 @@ -// Copyright 2019 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -#![allow(warnings)] - -use std::{marker::PhantomData, option::IntoIter}; - -use { - static_assertions::assert_impl_all, - zerocopy::{FromBytes, FromZeroes}, -}; - -// A union is `FromBytes` if: -// - all fields are `FromBytes` - -#[derive(Clone, Copy, FromZeroes, FromBytes)] -union Zst { - a: (), -} - -assert_impl_all!(Zst: FromBytes); - -#[derive(FromZeroes, FromBytes)] -union One { - a: u8, -} - -assert_impl_all!(One: FromBytes); - -#[derive(FromZeroes, FromBytes)] -union Two { - a: u8, - b: Zst, -} - -assert_impl_all!(Two: FromBytes); - -#[derive(FromZeroes, FromBytes)] -union TypeParams<'a, T: Copy, I: Iterator> -where - I::Item: Copy, -{ - a: T, - c: I::Item, - d: u8, - e: PhantomData<&'a [u8]>, - f: PhantomData<&'static str>, - g: PhantomData<String>, -} - -assert_impl_all!(TypeParams<'static, (), IntoIter<()>>: FromBytes); - -// Deriving `FromBytes` should work if the union has bounded parameters. - -#[derive(FromZeroes, FromBytes)] -#[repr(C)] -union WithParams<'a: 'b, 'b: 'a, const N: usize, T: 'a + 'b + FromBytes> -where - 'a: 'b, - 'b: 'a, - T: 'a + 'b + Copy + FromBytes, -{ - a: [T; N], - b: PhantomData<&'a &'b ()>, -} - -assert_impl_all!(WithParams<'static, 'static, 42, u8>: FromBytes);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/union_from_zeroes.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/union_from_zeroes.rs deleted file mode 100644 index 935fc15..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/union_from_zeroes.rs +++ /dev/null
@@ -1,72 +0,0 @@ -// Copyright 2019 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -#![allow(warnings)] - -#[macro_use] -mod util; - -use std::{marker::PhantomData, option::IntoIter}; - -use {static_assertions::assert_impl_all, zerocopy::FromZeroes}; - -// A union is `FromZeroes` if: -// - all fields are `FromZeroes` - -#[derive(Clone, Copy, FromZeroes)] -union Zst { - a: (), -} - -assert_impl_all!(Zst: FromZeroes); - -#[derive(FromZeroes)] -union One { - a: bool, -} - -assert_impl_all!(One: FromZeroes); - -#[derive(FromZeroes)] -union Two { - a: bool, - b: Zst, -} - -assert_impl_all!(Two: FromZeroes); - -#[derive(FromZeroes)] -union TypeParams<'a, T: Copy, I: Iterator> -where - I::Item: Copy, -{ - a: T, - c: I::Item, - d: u8, - e: PhantomData<&'a [u8]>, - f: PhantomData<&'static str>, - g: PhantomData<String>, -} - -assert_impl_all!(TypeParams<'static, (), IntoIter<()>>: FromZeroes); - -// Deriving `FromZeroes` should work if the union has bounded parameters. - -#[derive(FromZeroes)] -#[repr(C)] -union WithParams<'a: 'b, 'b: 'a, const N: usize, T: 'a + 'b + FromZeroes> -where - 'a: 'b, - 'b: 'a, - T: 'a + 'b + Copy + FromZeroes, -{ - a: [T; N], - b: PhantomData<&'a &'b ()>, -} - -assert_impl_all!(WithParams<'static, 'static, 42, u8>: FromZeroes);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/union_known_layout.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/union_known_layout.rs deleted file mode 100644 index 337ab4a..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/union_known_layout.rs +++ /dev/null
@@ -1,65 +0,0 @@ -// Copyright 2022 The Fuchsia Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#![allow(warnings)] - -#[macro_use] -mod util; - -use std::{marker::PhantomData, option::IntoIter}; - -use {static_assertions::assert_impl_all, zerocopy::KnownLayout}; - -#[derive(Clone, Copy, KnownLayout)] -union Zst { - a: (), -} - -assert_impl_all!(Zst: KnownLayout); - -#[derive(KnownLayout)] -union One { - a: bool, -} - -assert_impl_all!(One: KnownLayout); - -#[derive(KnownLayout)] -union Two { - a: bool, - b: Zst, -} - -assert_impl_all!(Two: KnownLayout); - -#[derive(KnownLayout)] -union TypeParams<'a, T: Copy, I: Iterator> -where - I::Item: Copy, -{ - a: T, - c: I::Item, - d: u8, - e: PhantomData<&'a [u8]>, - f: PhantomData<&'static str>, - g: PhantomData<String>, -} - -assert_impl_all!(TypeParams<'static, (), IntoIter<()>>: KnownLayout); - -// Deriving `KnownLayout` should work if the union has bounded parameters. - -#[derive(KnownLayout)] -#[repr(C)] -union WithParams<'a: 'b, 'b: 'a, const N: usize, T: 'a + 'b + KnownLayout> -where - 'a: 'b, - 'b: 'a, - T: 'a + 'b + Copy + KnownLayout, -{ - a: [T; N], - b: PhantomData<&'a &'b ()>, -} - -assert_impl_all!(WithParams<'static, 'static, 42, u8>: KnownLayout);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/union_unaligned.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/union_unaligned.rs deleted file mode 100644 index 5ba3ac7..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/union_unaligned.rs +++ /dev/null
@@ -1,77 +0,0 @@ -// Copyright 2019 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -#![allow(warnings)] - -use std::{marker::PhantomData, option::IntoIter}; - -use {static_assertions::assert_impl_all, zerocopy::Unaligned}; - -// A union is `Unaligned` if: -// - `repr(align)` is no more than 1 and either -// - `repr(C)` or `repr(transparent)` and -// - all fields `Unaligned` -// - `repr(packed)` - -#[derive(Unaligned)] -#[repr(C)] -union Foo { - a: u8, -} - -assert_impl_all!(Foo: Unaligned); - -// Transparent unions are unstable; see issue #60405 -// <https://github.com/rust-lang/rust/issues/60405> for more information. - -// #[derive(Unaligned)] -// #[repr(transparent)] -// union Bar { -// a: u8, -// } - -// is_unaligned!(Bar); - -#[derive(Unaligned)] -#[repr(packed)] -union Baz { - // NOTE: The `u16` type is not guaranteed to have alignment 2, although it - // does on many platforms. However, to fix this would require a custom type - // with a `#[repr(align(2))]` attribute, and `#[repr(packed)]` types are not - // allowed to transitively contain `#[repr(align(...))]` types. Thus, we - // have no choice but to use `u16` here. Luckily, these tests run in CI on - // platforms on which `u16` has alignment 2, so this isn't that big of a - // deal. - a: u16, -} - -assert_impl_all!(Baz: Unaligned); - -#[derive(Unaligned)] -#[repr(C, align(1))] -union FooAlign { - a: u8, -} - -assert_impl_all!(FooAlign: Unaligned); - -#[derive(Unaligned)] -#[repr(C)] -union TypeParams<'a, T: Copy, I: Iterator> -where - I::Item: Copy, -{ - a: T, - c: I::Item, - d: u8, - e: PhantomData<&'a [u8]>, - f: PhantomData<&'static str>, - g: PhantomData<String>, -} - -assert_impl_all!(TypeParams<'static, (), IntoIter<()>>: Unaligned);
diff --git a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/util.rs b/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/util.rs deleted file mode 100644 index a8656fb..0000000 --- a/third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/tests/util.rs +++ /dev/null
@@ -1,20 +0,0 @@ -// Copyright 2019 The Fuchsia Authors -// -// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 -// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT -// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. -// This file may not be copied, modified, or distributed except according to -// those terms. - -use zerocopy::{AsBytes, FromBytes, FromZeroes, KnownLayout}; - -/// A type that doesn't implement any zerocopy traits. -pub struct NotZerocopy<T = ()>(T); - -/// A `u16` with alignment 2. -/// -/// Though `u16` has alignment 2 on some platforms, it's not guaranteed. By -/// contrast, `AU16` is guaranteed to have alignment 2. -#[derive(KnownLayout, FromZeroes, FromBytes, AsBytes, Copy, Clone)] -#[repr(C, align(2))] -pub struct AU16(u16);
diff --git a/third_party/rust/zerocopy/v0_7/BUILD.gn b/third_party/rust/zerocopy/v0_7/BUILD.gn deleted file mode 100644 index 2ad4e525..0000000 --- a/third_party/rust/zerocopy/v0_7/BUILD.gn +++ /dev/null
@@ -1,55 +0,0 @@ -# Copyright 2023 The Chromium Authors -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -# @generated from third_party/rust/chromium_crates_io/BUILD.gn.hbs by -# tools/crates/gnrt. -# Do not edit! - -import("//build/rust/cargo_crate.gni") - -cargo_crate("lib") { - crate_name = "zerocopy" - epoch = "0.7" - crate_type = "rlib" - crate_root = - "//third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/src/lib.rs" - sources = [ - "//third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/src/byteorder.rs", - "//third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/src/lib.rs", - "//third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/src/macro_util.rs", - "//third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/src/macros.rs", - "//third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/src/post_monomorphization_compile_fail_tests.rs", - "//third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/src/third_party/rust/layout.rs", - "//third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/src/util.rs", - "//third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/src/wrappers.rs", - ] - inputs = [] - - build_native_rust_unit_tests = false - edition = "2018" - cargo_pkg_version = "0.7.35" - cargo_pkg_authors = "Joshua Liebow-Feeser <joshlf@google.com>" - cargo_pkg_name = "zerocopy" - cargo_pkg_description = "Utilities for zero-copy parsing and serialization" - library_configs -= [ "//build/config/coverage:default_coverage" ] - library_configs -= [ "//build/config/compiler:chromium_code" ] - library_configs += [ "//build/config/compiler:no_chromium_code" ] - executable_configs -= [ "//build/config/compiler:chromium_code" ] - executable_configs += [ "//build/config/compiler:no_chromium_code" ] - proc_macro_configs -= [ "//build/config/compiler:chromium_code" ] - proc_macro_configs += [ "//build/config/compiler:no_chromium_code" ] - deps = [ - "//third_party/rust/byteorder/v1:lib", - "//third_party/rust/zerocopy_derive/v0_7:lib", - ] - features = [ - "byteorder", - "derive", - "simd", - "zerocopy-derive", - ] - rustflags = [ - "--cap-lints=allow", # Suppress all warnings in crates.io crates - ] -}
diff --git a/third_party/rust/zerocopy/v0_7/README.chromium b/third_party/rust/zerocopy/v0_7/README.chromium deleted file mode 100644 index be199780a..0000000 --- a/third_party/rust/zerocopy/v0_7/README.chromium +++ /dev/null
@@ -1,10 +0,0 @@ -Name: zerocopy -URL: https://crates.io/crates/zerocopy -Version: 0.7.35 -Revision: 727de668608f2d16e151c42e344d172c0931b1e9 -License: Apache-2.0 -License File: //third_party/rust/chromium_crates_io/vendor/zerocopy-0.7.35/LICENSE-APACHE -Shipped: yes -Security Critical: yes - -Description: Utilities for zero-copy parsing and serialization
diff --git a/third_party/rust/zerocopy_derive/v0_7/BUILD.gn b/third_party/rust/zerocopy_derive/v0_7/BUILD.gn deleted file mode 100644 index 28ef3a10..0000000 --- a/third_party/rust/zerocopy_derive/v0_7/BUILD.gn +++ /dev/null
@@ -1,49 +0,0 @@ -# Copyright 2023 The Chromium Authors -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -# @generated from third_party/rust/chromium_crates_io/BUILD.gn.hbs by -# tools/crates/gnrt. -# Do not edit! - -import("//build/rust/cargo_crate.gni") - -cargo_crate("lib") { - crate_name = "zerocopy_derive" - epoch = "0.7" - crate_type = "proc-macro" - crate_root = "//third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/src/lib.rs" - sources = [ - "//third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/src/ext.rs", - "//third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/src/lib.rs", - "//third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/src/repr.rs", - ] - inputs = [] - - build_native_rust_unit_tests = false - edition = "2018" - cargo_pkg_version = "0.7.35" - cargo_pkg_authors = "Joshua Liebow-Feeser <joshlf@google.com>" - cargo_pkg_name = "zerocopy-derive" - cargo_pkg_description = "Custom derive for traits from the zerocopy crate" - library_configs -= [ "//build/config/coverage:default_coverage" ] - library_configs -= [ "//build/config/compiler:chromium_code" ] - library_configs += [ "//build/config/compiler:no_chromium_code" ] - executable_configs -= [ "//build/config/compiler:chromium_code" ] - executable_configs += [ "//build/config/compiler:no_chromium_code" ] - proc_macro_configs -= [ "//build/config/compiler:chromium_code" ] - proc_macro_configs += [ "//build/config/compiler:no_chromium_code" ] - deps = [ - "//third_party/rust/proc_macro2/v1:lib", - "//third_party/rust/quote/v1:lib", - "//third_party/rust/syn/v2:lib", - ] - rustflags = [ - "--cap-lints=allow", # Suppress all warnings in crates.io crates - ] - - # Only for usage from third-party crates. Add the crate to - # //third_party/rust/chromium_crates_io/Cargo.toml to use - # it from first-party code. - visibility = [ "//third_party/rust/*" ] -}
diff --git a/third_party/rust/zerocopy_derive/v0_7/README.chromium b/third_party/rust/zerocopy_derive/v0_7/README.chromium deleted file mode 100644 index 554b8b2..0000000 --- a/third_party/rust/zerocopy_derive/v0_7/README.chromium +++ /dev/null
@@ -1,10 +0,0 @@ -Name: zerocopy-derive -URL: https://crates.io/crates/zerocopy-derive -Version: 0.7.35 -Revision: 727de668608f2d16e151c42e344d172c0931b1e9 -License: Apache-2.0 -License File: //third_party/rust/chromium_crates_io/vendor/zerocopy-derive-0.7.35/LICENSE-APACHE -Shipped: yes -Security Critical: yes - -Description: Custom derive for traits from the zerocopy crate
diff --git a/third_party/skia b/third_party/skia index 22f5a70..1e80d35 160000 --- a/third_party/skia +++ b/third_party/skia
@@ -1 +1 @@ -Subproject commit 22f5a70db6b391890418db99f8b00f7a9be48b5f +Subproject commit 1e80d35a4d444ebea76749d1399ef8bd8ea7cabf
diff --git a/third_party/webrtc b/third_party/webrtc index 03d202c..f145333 160000 --- a/third_party/webrtc +++ b/third_party/webrtc
@@ -1 +1 @@ -Subproject commit 03d202cd0fcc5dfaa030dac5178629db3f1ab931 +Subproject commit f14533349fc3ebcbf82ac8a371abef69ec4acdd8
diff --git a/tools/metrics/actions/actions.xml b/tools/metrics/actions/actions.xml index 7ce36fb..219caec 100644 --- a/tools/metrics/actions/actions.xml +++ b/tools/metrics/actions/actions.xml
@@ -12286,6 +12286,54 @@ </description> </action> +<action name="Glic.Settings.Geolocation.Disabled"> + <owner>tommasin@chromium.org</owner> + <owner>erikchen@chromium.org</owner> + <description> + Logged if the user disables geolocation in glic settings. + </description> +</action> + +<action name="Glic.Settings.Geolocation.Enabled"> + <owner>tommasin@chromium.org</owner> + <owner>erikchen@chromium.org</owner> + <description> + Logged if the user enables geolocation in glic settings. + </description> +</action> + +<action name="Glic.Settings.Microphone.Disabled"> + <owner>tommasin@chromium.org</owner> + <owner>erikchen@chromium.org</owner> + <description> + Logged if the user disables microphone in glic settings. + </description> +</action> + +<action name="Glic.Settings.Microphone.Enabled"> + <owner>tommasin@chromium.org</owner> + <owner>erikchen@chromium.org</owner> + <description> + Logged if the user enables microphone in glic settings. + </description> +</action> + +<action name="Glic.Settings.TabContext.Disabled"> + <owner>tommasin@chromium.org</owner> + <owner>erikchen@chromium.org</owner> + <description> + Logged if the user disables tab context in glic settings. + </description> +</action> + +<action name="Glic.Settings.TabContext.Enabled"> + <owner>tommasin@chromium.org</owner> + <owner>erikchen@chromium.org</owner> + <description> + Logged if the user enables tab context in glic settings. + </description> +</action> + <action name="Glic.Unpinned"> <owner>charlesmeng@chromium.org</owner> <owner>erikchen@chromium.org</owner> @@ -12294,6 +12342,38 @@ </description> </action> +<action name="GlicLocationPermissionDisabled"> + <owner>tommasin@chromium.org</owner> + <owner>erikchen@chromium.org</owner> + <description> + Tracks when glic location permission is disabled from the web client. + </description> +</action> + +<action name="GlicLocationPermissionEnabled"> + <owner>tommasin@chromium.org</owner> + <owner>erikchen@chromium.org</owner> + <description> + Tracks when glic location permission is enabled from the web client. + </description> +</action> + +<action name="GlicMicrophonePermissionDisabled"> + <owner>tommasin@chromium.org</owner> + <owner>erikchen@chromium.org</owner> + <description> + Tracks when glic microphone permission is disabled from the web client. + </description> +</action> + +<action name="GlicMicrophonePermissionEnabled"> + <owner>tommasin@chromium.org</owner> + <owner>erikchen@chromium.org</owner> + <description> + Tracks when glic microphone permission is enabled from the web client. + </description> +</action> + <action name="GlicOsEntrypoint.ContextMenuSelection.CloseGlic"> <owner>agale@chromium.org</owner> <owner>erikchen@chromium.org</owner> @@ -12435,14 +12515,16 @@ <owner>erikchen@chromium.org</owner> <owner>pauladedeji@google.com</owner> <description> - Tracks when glic tab context permission is disabled. + Tracks when glic tab context permission is disabled from the web client. </description> </action> <action name="GlicTabContextPermissionEnabled"> <owner>erikchen@chromium.org</owner> <owner>pauladedeji@google.com</owner> - <description>Tracks when glic tab context permission is enabled.</description> + <description> + Tracks when glic tab context permission is enabled from the web client. + </description> </action> <action name="GlicWebClientSessionEnd"> @@ -24164,6 +24246,23 @@ <description>User opened the app menu.</description> </action> +<action name="MobileMenuShow.OverviewModeMenu"> + <owner>ckitagawa@chromium.org</owner> + <description> + User opened the app menu in overview mode (AKA the hub or tab switcher). + </description> +</action> + +<action name="MobileMenuShow.PageMenu"> + <owner>ckitagawa@chromium.org</owner> + <description>User opened the app menu on a tab.</description> +</action> + +<action name="MobileMenuShow.TabletEmptyModeMenu"> + <owner>ckitagawa@chromium.org</owner> + <description>User opened the app menu in the empty tablet mode.</description> +</action> + <action name="MobileMenuSiteInformation"> <owner>gambard@chromium.org</owner> <description>User pressed 'Site Information' in the app menu.</description> @@ -31572,6 +31671,14 @@ <description>Cookies subpage opened from PageInfo.</description> </action> +<action name="PageInfo.CookiesSubpage.RwsSiteSettingsOpened"> + <owner>mjenn@google.com</owner> + <owner>koilos@google.com</owner> + <description> + Opened the RWS site settings page for a website from PageInfo. + </description> +</action> + <action name="PageInfo.CookiesSubpage.SettingsLinkClicked"> <owner>zsalata@google.com</owner> <owner>olesiamarukhno@google.com</owner>
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml index 7324463..d53b944 100644 --- a/tools/metrics/histograms/enums.xml +++ b/tools/metrics/histograms/enums.xml
@@ -11422,6 +11422,8 @@ <int value="-1077752943" label="enable-password-generation"/> <int value="-1077534880" label="OmniboxDynamicMaxAutocomplete:enabled"/> <int value="-1077006912" label="ReadAnythingOmniboxIcon:disabled"/> + <int value="-1076662984" + label="AccessibilityManifestV3SwitchAccess:disabled"/> <int value="-1076661289" label="WebIdentityDigitalCredentialsCreation:disabled"/> <int value="-1075156797" label="enable-brotli"/> @@ -17478,6 +17480,7 @@ <int value="1291790140" label="FastPairSubsequentPairingUX:enabled"/> <int value="1291966558" label="ScrollAnchoring:disabled"/> <int value="1292091029" label="OmniboxOneClickUnelide:disabled"/> + <int value="1292453125" label="AccessibilityManifestV3SwitchAccess:enabled"/> <int value="1292482533" label="EnableTabMuting:disabled"/> <int value="1292763218" label="SystemTrayUnified:disabled"/> <int value="1293262425" label="PasswordGenerationSoftNudge:enabled"/>
diff --git a/tools/metrics/histograms/metadata/android/enums.xml b/tools/metrics/histograms/metadata/android/enums.xml index 2f194378..12b2170 100644 --- a/tools/metrics/histograms/metadata/android/enums.xml +++ b/tools/metrics/histograms/metadata/android/enums.xml
@@ -1154,6 +1154,7 @@ <int value="57" label="CollaborationRemoved"/> <int value="58" label="CctAccountMismatchNotice"/> <int value="59" label="PromptHatsClearBrowsingData"/> + <int value="60" label="OsAdvancedProtectionSettingChangedMessage"/> </enum> <!-- LINT.ThenChange(//components/messages/android/message_enums.h:MessageIdentifier) -->
diff --git a/tools/metrics/histograms/metadata/android/histograms.xml b/tools/metrics/histograms/metadata/android/histograms.xml index 662ffc5..22c2ff690 100644 --- a/tools/metrics/histograms/metadata/android/histograms.xml +++ b/tools/metrics/histograms/metadata/android/histograms.xml
@@ -177,6 +177,7 @@ <variant name=".NearOomReduction"/> <variant name=".NotificationBlocked"/> <variant name=".OfferNotification"/> + <variant name=".OsAdvancedProtectionSettingChangedMessage"/> <variant name=".PermissionBlocked"/> <variant name=".PermissionUpdate"/> <variant name=".PopupBlocked"/>
diff --git a/tools/metrics/histograms/metadata/content/histograms.xml b/tools/metrics/histograms/metadata/content/histograms.xml index 73e38cd..e7142b59 100644 --- a/tools/metrics/histograms/metadata/content/histograms.xml +++ b/tools/metrics/histograms/metadata/content/histograms.xml
@@ -823,6 +823,8 @@ <variant name="javascript-jit" summary="JavaScript JIT"/> <variant name="javascript-optimizer" summary="JavaScript Optimizer"/> <variant name="keygen" summary="Keygen exceptions"/> + <variant name="local-network-access" + summary="Local network access exceptions"/> <variant name="media-engagement" summary="Media engagement exceptions"/> <variant name="media-stream-camera" summary="Camera exceptions"/> <variant name="media-stream-mic" summary="Microphone exceptions"/>
diff --git a/tools/metrics/histograms/metadata/histogram_suffixes_list.xml b/tools/metrics/histograms/metadata/histogram_suffixes_list.xml index 6dd46e3c..abe6be29 100644 --- a/tools/metrics/histograms/metadata/histogram_suffixes_list.xml +++ b/tools/metrics/histograms/metadata/histogram_suffixes_list.xml
@@ -1894,6 +1894,7 @@ <suffix name="KeyboardAndPointerLock" label="Keyboard and pointer lock permission"/> <suffix name="KeyboardLock" label="Keyboard lock permission"/> + <suffix name="LocalNetworkAccess" label="Local network access permission"/> <suffix name="MidiSysEx" label="Midi SysEx permission"/> <suffix name="MultipleDownload" label="Multiple downloads permission"/> <suffix name="Nfc" label="NFC permission"/> @@ -1934,6 +1935,8 @@ label="Keyboard and pointer lock permission"/> <suffix name="KeyboardLock" label="Keyboard lock permission"/> <suffix name="LocalFonts" label="Local fonts permission actions"/> + <suffix name="LocalNetworkAccess" + label="Local network access permission actions"/> <suffix name="MidiSysEx" label="Midi SysEx permsision actions"/> <suffix name="Nfc" label="Nfc permsision actions"/> <suffix name="Notifications" label="Notification permission actions"/>
diff --git a/tools/metrics/histograms/metadata/sharing/histograms.xml b/tools/metrics/histograms/metadata/sharing/histograms.xml index 0829ca4a..d06b6c18 100644 --- a/tools/metrics/histograms/metadata/sharing/histograms.xml +++ b/tools/metrics/histograms/metadata/sharing/histograms.xml
@@ -286,7 +286,7 @@ <histogram name="Sharing.ScrollCapture.BitmapGeneratorStatus" enum="SharingScrollCaptureBitmapGenerationStatus" - expires_after="2025-04-01"> + expires_after="2025-10-01"> <owner>ckitagawa@chromium.org</owner> <owner>src/components/paint_preview/OWNERS</owner> <summary> @@ -298,7 +298,7 @@ </histogram> <histogram name="Sharing.ScrollCapture.SuccessfulCaptureDuration" units="ms" - expires_after="2025-04-01"> + expires_after="2025-10-01"> <owner>ckitagawa@chromium.org</owner> <owner>src/components/paint_preview/OWNERS</owner> <summary>
diff --git a/tools/metrics/histograms/metadata/tab/histograms.xml b/tools/metrics/histograms/metadata/tab/histograms.xml index 592d95c4..53f6f503 100644 --- a/tools/metrics/histograms/metadata/tab/histograms.xml +++ b/tools/metrics/histograms/metadata/tab/histograms.xml
@@ -1481,7 +1481,7 @@ </histogram> <histogram name="TabGroups.Sync.TabGroupTitleLength" units="characters" - expires_after="2025-04-06"> + expires_after="2025-10-06"> <owner>shaktisahu@chromium.org</owner> <owner>clank-tab-dev@google.com</owner> <summary>
diff --git a/tools/perf/core/perfetto_binary_roller/binary_deps.json b/tools/perf/core/perfetto_binary_roller/binary_deps.json index 86ef8c2d..a04b8c3 100644 --- a/tools/perf/core/perfetto_binary_roller/binary_deps.json +++ b/tools/perf/core/perfetto_binary_roller/binary_deps.json
@@ -5,8 +5,8 @@ "full_remote_path": "perfetto-luci-artifacts/v49.0/linux-arm64/trace_processor_shell" }, "win": { - "hash": "db377bc8d7d8ec6e6f7d5cb4c72061e484101b97", - "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/win/aa832d5cc108f65aae0251a89a59fe0668930e3f/trace_processor_shell.exe" + "hash": "c0c257891632fccd87ff6b867144e89a74c21b27", + "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/win/7da1b1676f326e67cc3eb38774daf3154f876fd0/trace_processor_shell.exe" }, "linux_arm": { "hash": "a15d8362d80cfd7cd8d785cf6afc22586de688cd", @@ -21,8 +21,8 @@ "full_remote_path": "perfetto-luci-artifacts/v49.0/mac-arm64/trace_processor_shell" }, "linux": { - "hash": "23d2fbea450ae7b34904845181c052c9e57cd959", - "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/linux/020d559ba65bf2d9e7477046a752fdb459c640c6/trace_processor_shell" + "hash": "55e8195dc0ceaa80e37076a5c2bc06b20e7ca8f6", + "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/linux/d5ee2fb614866ffe5950d4f06e99ac692bfd1445/trace_processor_shell" } }, "power_profile.sql": {
diff --git a/ui/accessibility/accessibility_features.cc b/ui/accessibility/accessibility_features.cc index 2c6a520..e41c8b6 100644 --- a/ui/accessibility/accessibility_features.cc +++ b/ui/accessibility/accessibility_features.cc
@@ -299,6 +299,14 @@ ::features::kAccessibilityManifestV3EnhancedNetworkTts); } +BASE_FEATURE(kAccessibilityManifestV3SwitchAccess, + "AccessibilityManifestV3SwitchAccess", + base::FEATURE_DISABLED_BY_DEFAULT); +bool IsAccessibilityManifestV3EnabledForSwitchAccess() { + return base::FeatureList::IsEnabled( + ::features::kAccessibilityManifestV3SwitchAccess); +} + #endif // BUILDFLAG(IS_CHROMEOS) BASE_FEATURE(kAccessibilityOnScreenMode,
diff --git a/ui/accessibility/accessibility_features.h b/ui/accessibility/accessibility_features.h index 2713bf34..06334e14 100644 --- a/ui/accessibility/accessibility_features.h +++ b/ui/accessibility/accessibility_features.h
@@ -219,6 +219,9 @@ AX_BASE_EXPORT BASE_DECLARE_FEATURE(kAccessibilityManifestV3EnhancedNetworkTts); AX_BASE_EXPORT bool IsAccessibilityManifestV3EnabledForEnhancedNetworkTts(); +AX_BASE_EXPORT BASE_DECLARE_FEATURE(kAccessibilityManifestV3SwitchAccess); +AX_BASE_EXPORT bool IsAccessibilityManifestV3EnabledForSwitchAccess(); + #endif // BUILDFLAG(IS_CHROMEOS) #if BUILDFLAG(IS_ANDROID)
diff --git a/ui/accessibility/ax_enum_util.cc b/ui/accessibility/ax_enum_util.cc index 960fd15..d3319d85 100644 --- a/ui/accessibility/ax_enum_util.cc +++ b/ui/accessibility/ax_enum_util.cc
@@ -1937,8 +1937,8 @@ return "none"; case ax::mojom::StringListAttribute::kAriaNotificationAnnouncements: return "ariaNotificationAnnouncements"; - case ax::mojom::StringListAttribute::kAriaNotificationIds: - return "ariaNotificationIds"; + case ax::mojom::StringListAttribute::kAriaNotificationTypes: + return "ariaNotificationTypes"; case ax::mojom::StringListAttribute::kCustomActionDescriptions: return "customActionDescriptions"; }
diff --git a/ui/accessibility/ax_enums.mojom b/ui/accessibility/ax_enums.mojom index 59edaf7..8348577 100644 --- a/ui/accessibility/ax_enums.mojom +++ b/ui/accessibility/ax_enums.mojom
@@ -1020,7 +1020,7 @@ enum StringListAttribute { [Default]kNone = 0, [MinVersion=1] kAriaNotificationAnnouncements = 2, - [MinVersion=1] kAriaNotificationIds = 3, + [MinVersion=1] kAriaNotificationTypes = 3, // Descriptions for custom actions. This must be aligned with // custom_action_ids. kCustomActionDescriptions = 1,
diff --git a/ui/accessibility/ax_node_data.cc b/ui/accessibility/ax_node_data.cc index 3d1e7d8..b81a762 100644 --- a/ui/accessibility/ax_node_data.cc +++ b/ui/accessibility/ax_node_data.cc
@@ -1965,8 +1965,8 @@ result += " aria_notification_announcements=" + base::JoinString(values, ","); break; - case ax::mojom::StringListAttribute::kAriaNotificationIds: - result += " aria_notification_ids=" + base::JoinString(values, ","); + case ax::mojom::StringListAttribute::kAriaNotificationTypes: + result += " aria_notification_types=" + base::JoinString(values, ","); break; case ax::mojom::StringListAttribute::kCustomActionDescriptions: result +=
diff --git a/ui/accessibility/platform/ax_platform_node_textchildprovider_win_unittest.cc b/ui/accessibility/platform/ax_platform_node_textchildprovider_win_unittest.cc index d461ee53..6d369cf8 100644 --- a/ui/accessibility/platform/ax_platform_node_textchildprovider_win_unittest.cc +++ b/ui/accessibility/platform/ax_platform_node_textchildprovider_win_unittest.cc
@@ -2,13 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "ui/accessibility/platform/ax_platform_node_win_unittest.h" +#include "ui/accessibility/platform/ax_platform_node_textchildprovider_win.h" +#include "base/compiler_specific.h" #include "base/win/scoped_bstr.h" #include "ui/accessibility/platform/ax_fragment_root_win.h" -#include "ui/accessibility/platform/ax_platform_node_textchildprovider_win.h" #include "ui/accessibility/platform/ax_platform_node_textprovider_win.h" #include "ui/accessibility/platform/ax_platform_node_textrangeprovider_win.h" +#include "ui/accessibility/platform/ax_platform_node_win_unittest.h" #include "ui/accessibility/test_ax_tree_update.h" using Microsoft::WRL::ComPtr; @@ -287,7 +288,7 @@ base::win::ScopedBstr text_content; EXPECT_HRESULT_SUCCEEDED( text_range_provider->GetText(-1, text_content.Receive())); - EXPECT_EQ(0, wcscmp(text_content.Get(), L"text child of text.")); + EXPECT_EQ(0, UNSAFE_TODO(wcscmp(text_content.Get(), L"text child of text."))); ComPtr<IRawElementProviderSimple> enclosing_element; text_range_provider->GetEnclosingElement(&enclosing_element); @@ -334,7 +335,8 @@ base::win::ScopedBstr text_content; EXPECT_HRESULT_SUCCEEDED( text_range_provider->GetText(-1, text_content.Receive())); - EXPECT_EQ(0, wcscmp(text_content.Get(), L"text child of nontext.")); + EXPECT_EQ(0, + UNSAFE_TODO(wcscmp(text_content.Get(), L"text child of nontext."))); ComPtr<IRawElementProviderSimple> enclosing_element; text_range_provider->GetEnclosingElement(&enclosing_element); @@ -357,7 +359,7 @@ base::win::ScopedBstr text_content; EXPECT_HRESULT_SUCCEEDED( text_range_provider->GetText(-1, text_content.Receive())); - EXPECT_EQ(0, wcscmp(text_content.Get(), L"text child of text.")); + EXPECT_EQ(0, UNSAFE_TODO(wcscmp(text_content.Get(), L"text child of text."))); ComPtr<IRawElementProviderSimple> enclosing_element; text_range_provider->GetEnclosingElement(&enclosing_element);
diff --git a/ui/accessibility/platform/ax_platform_node_textprovider_win_unittest.cc b/ui/accessibility/platform/ax_platform_node_textprovider_win_unittest.cc index 2fa56e7e..7efcd28 100644 --- a/ui/accessibility/platform/ax_platform_node_textprovider_win_unittest.cc +++ b/ui/accessibility/platform/ax_platform_node_textprovider_win_unittest.cc
@@ -2,22 +2,23 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "base/memory/raw_ptr.h" -#include "ui/accessibility/platform/ax_platform_node_win_unittest.h" - -#include <UIAutomationClient.h> -#include <UIAutomationCoreApi.h> +#include "ui/accessibility/platform/ax_platform_node_textprovider_win.h" #include <vector> +#include "base/compiler_specific.h" +#include "base/memory/raw_ptr.h" #include "base/win/scoped_bstr.h" #include "base/win/scoped_safearray.h" #include "ui/accessibility/ax_action_data.h" #include "ui/accessibility/platform/ax_fragment_root_win.h" -#include "ui/accessibility/platform/ax_platform_node_textprovider_win.h" #include "ui/accessibility/platform/ax_platform_node_textrangeprovider_win.h" +#include "ui/accessibility/platform/ax_platform_node_win_unittest.h" #include "ui/accessibility/platform/test_ax_node_wrapper.h" +#include <UIAutomationClient.h> +#include <UIAutomationCoreApi.h> + using Microsoft::WRL::ComPtr; namespace ui { @@ -103,7 +104,7 @@ base::win::ScopedBstr text_content; EXPECT_HRESULT_SUCCEEDED( text_range_provider->GetText(-1, text_content.Receive())); - EXPECT_EQ(0, wcscmp(text_content.Get(), L"")); + EXPECT_EQ(0, UNSAFE_TODO(wcscmp(text_content.Get(), L""))); ComPtr<AXPlatformNodeTextRangeProviderWin> actual_range; text_range_provider->QueryInterface(IID_PPV_ARGS(&actual_range)); @@ -121,7 +122,7 @@ SetOwner(owner, text_range_provider.Get()); EXPECT_HRESULT_SUCCEEDED( text_range_provider->GetText(-1, text_content.Receive())); - EXPECT_EQ(0, wcscmp(text_content.Get(), L"")); + EXPECT_EQ(0, UNSAFE_TODO(wcscmp(text_content.Get(), L""))); text_range_provider->QueryInterface(IID_PPV_ARGS(&actual_range)); EXPECT_EQ(*GetStart(actual_range.Get()), *expected_start); EXPECT_EQ(*GetEnd(actual_range.Get()), *expected_end); @@ -134,7 +135,7 @@ SetOwner(owner, text_range_provider.Get()); EXPECT_HRESULT_SUCCEEDED( text_range_provider->GetText(-1, text_content.Receive())); - EXPECT_EQ(0, wcscmp(text_content.Get(), L"")); + EXPECT_EQ(0, UNSAFE_TODO(wcscmp(text_content.Get(), L""))); text_range_provider->QueryInterface(IID_PPV_ARGS(&actual_range)); expected_start = text2_platform_node->GetDelegate()->CreateTextPositionAt(0); expected_end = expected_start->Clone(); @@ -179,7 +180,7 @@ base::win::ScopedBstr text_content; EXPECT_HRESULT_SUCCEEDED( text_range_provider->GetText(-1, text_content.Receive())); - EXPECT_EQ(0, wcscmp(text_content.Get(), L"some-text")); + EXPECT_EQ(0, UNSAFE_TODO(wcscmp(text_content.Get(), L"some-text"))); // Now test that the reverse relation doesn't return a valid // ITextRangeProvider, and instead returns E_INVALIDARG. @@ -200,7 +201,7 @@ base::win::ScopedBstr empty_text_content; EXPECT_HRESULT_SUCCEEDED( text_range_provider->GetText(-1, empty_text_content.Receive())); - EXPECT_EQ(0, wcscmp(empty_text_content.Get(), L"")); + EXPECT_EQ(0, UNSAFE_TODO(wcscmp(empty_text_content.Get(), L""))); // Test that passing in an object from a different instance of // IRawElementProviderSimple than that of the valid text provider @@ -519,7 +520,7 @@ base::win::ScopedBstr text_content; EXPECT_HRESULT_SUCCEEDED( text_range_provider->GetText(-1, text_content.Receive())); - EXPECT_EQ(0, wcscmp(text_content.Get(), L"some")); + EXPECT_EQ(0, UNSAFE_TODO(wcscmp(text_content.Get(), L"some"))); text_content.Reset(); selections.Reset(); text_range_provider.Reset(); @@ -545,7 +546,7 @@ EXPECT_HRESULT_SUCCEEDED( text_range_provider->GetText(-1, text_content.Receive())); - EXPECT_EQ(0, wcscmp(text_content.Get(), L"some")); + EXPECT_EQ(0, UNSAFE_TODO(wcscmp(text_content.Get(), L"some"))); text_content.Reset(); selections.Reset(); text_range_provider.Reset(); @@ -608,7 +609,8 @@ SetOwner(owner, text_range_provider.Get()); EXPECT_HRESULT_SUCCEEDED( text_range_provider->GetText(-1, text_content.Receive())); - EXPECT_EQ(0, wcscmp(text_content.Get(), L"some texttextbox text")); + EXPECT_EQ(0, + UNSAFE_TODO(wcscmp(text_content.Get(), L"some texttextbox text"))); text_content.Reset(); selections.Reset(); text_range_provider.Reset(); @@ -633,7 +635,7 @@ SetOwner(owner, text_range_provider.Get()); EXPECT_HRESULT_SUCCEEDED( text_range_provider->GetText(-1, text_content.Receive())); - EXPECT_EQ(0, wcscmp(text_content.Get(), L"")); + EXPECT_EQ(0, UNSAFE_TODO(wcscmp(text_content.Get(), L""))); text_content.Reset(); selections.Reset(); text_range_provider.Reset(); @@ -657,7 +659,7 @@ SetOwner(owner, text_range_provider.Get()); EXPECT_HRESULT_SUCCEEDED( text_range_provider->GetText(-1, text_content.Receive())); - EXPECT_EQ(0, wcscmp(text_content.Get(), L"text")); + EXPECT_EQ(0, UNSAFE_TODO(wcscmp(text_content.Get(), L"text"))); text_content.Reset(); selections.Reset(); text_range_provider.Reset(); @@ -756,7 +758,7 @@ base::win::ScopedBstr text_content; EXPECT_HRESULT_SUCCEEDED( text_range_provider->GetText(-1, text_content.Receive())); - EXPECT_EQ(0, wcscmp(text_content.Get(), L"aaa")); + EXPECT_EQ(0, UNSAFE_TODO(wcscmp(text_content.Get(), L"aaa"))); selections.Reset(); text_range_provider.Reset(); @@ -779,7 +781,7 @@ EXPECT_HRESULT_SUCCEEDED( text_range_provider->GetText(-1, text_content.Receive())); - EXPECT_EQ(0, wcscmp(text_content.Get(), L"aa")); + EXPECT_EQ(0, UNSAFE_TODO(wcscmp(text_content.Get(), L"aa"))); } TEST_F(AXPlatformNodeTextProviderTest, ITextProviderGetActiveComposition) {
diff --git a/ui/accessibility/platform/browser_accessibility_manager.cc b/ui/accessibility/platform/browser_accessibility_manager.cc index c61890b..72ba6a8 100644 --- a/ui/accessibility/platform/browser_accessibility_manager.cc +++ b/ui/accessibility/platform/browser_accessibility_manager.cc
@@ -241,24 +241,23 @@ ax::mojom::StringListAttribute::kAriaNotificationAnnouncements); const auto& priority_properties = node_data.GetIntListAttribute( ax::mojom::IntListAttribute::kAriaNotificationPriorityProperties); - const std::vector<std::string> notification_ids = - node_data.GetStringListAttribute( - ax::mojom::StringListAttribute::kAriaNotificationIds); const std::vector<std::int32_t> interrupt_properties = node_data.GetIntListAttribute( ax::mojom::IntListAttribute::kAriaNotificationInterruptProperties); + const std::vector<std::string> types = node_data.GetStringListAttribute( + ax::mojom::StringListAttribute::kAriaNotificationTypes); DCHECK_EQ(announcements.size(), priority_properties.size()); - DCHECK_EQ(announcements.size(), notification_ids.size()); DCHECK_EQ(announcements.size(), interrupt_properties.size()); + DCHECK_EQ(announcements.size(), types.size()); for (std::size_t i = 0; i < announcements.size(); ++i) { FireAriaNotificationEvent(wrapper, announcements[i], static_cast<ax::mojom::AriaNotificationPriority>( priority_properties[i]), - notification_ids[i], static_cast<ax::mojom::AriaNotificationInterrupt>( - interrupt_properties[i])); + interrupt_properties[i]), + types[i]); } }
diff --git a/ui/accessibility/platform/browser_accessibility_manager.h b/ui/accessibility/platform/browser_accessibility_manager.h index 0983d23b..d2dd7dd4 100644 --- a/ui/accessibility/platform/browser_accessibility_manager.h +++ b/ui/accessibility/platform/browser_accessibility_manager.h
@@ -141,8 +141,8 @@ BrowserAccessibility* node, const std::string& announcement, ax::mojom::AriaNotificationPriority priority_property, - const std::string& notification_id, - ax::mojom::AriaNotificationInterrupt interrupt_property) {} + ax::mojom::AriaNotificationInterrupt interrupt_property, + const std::string& type) {} virtual void FireBlinkEvent(ax::mojom::Event event_type, BrowserAccessibility* node,
diff --git a/ui/accessibility/platform/browser_accessibility_manager_auralinux.cc b/ui/accessibility/platform/browser_accessibility_manager_auralinux.cc index f75e109..152dd321 100644 --- a/ui/accessibility/platform/browser_accessibility_manager_auralinux.cc +++ b/ui/accessibility/platform/browser_accessibility_manager_auralinux.cc
@@ -406,8 +406,8 @@ BrowserAccessibility* node, const std::string& announcement, ax::mojom::AriaNotificationPriority priority_property, - const std::string& notification_id, - ax::mojom::AriaNotificationInterrupt interrupt_property) { + ax::mojom::AriaNotificationInterrupt interrupt_property, + const std::string& type) { DCHECK(node); // Only newer Atk versions support the notification signal type.
diff --git a/ui/accessibility/platform/browser_accessibility_manager_auralinux.h b/ui/accessibility/platform/browser_accessibility_manager_auralinux.h index 939ec2e..5196f37 100644 --- a/ui/accessibility/platform/browser_accessibility_manager_auralinux.h +++ b/ui/accessibility/platform/browser_accessibility_manager_auralinux.h
@@ -54,8 +54,8 @@ BrowserAccessibility* node, const std::string& announcement, ax::mojom::AriaNotificationPriority priority_property, - const std::string& notification_id, - ax::mojom::AriaNotificationInterrupt interrupt_property) override; + ax::mojom::AriaNotificationInterrupt interrupt_property, + const std::string& type) override; void FireSelectedEvent(BrowserAccessibility* node); void FireEnabledChangedEvent(BrowserAccessibility* node);
diff --git a/ui/accessibility/platform/browser_accessibility_manager_mac.h b/ui/accessibility/platform/browser_accessibility_manager_mac.h index 2070c28..e2656dd 100644 --- a/ui/accessibility/platform/browser_accessibility_manager_mac.h +++ b/ui/accessibility/platform/browser_accessibility_manager_mac.h
@@ -57,8 +57,8 @@ BrowserAccessibility* node, const std::string& announcement, ax::mojom::AriaNotificationPriority priority_property, - const std::string& notification_id, - ax::mojom::AriaNotificationInterrupt interrupt_property) override; + ax::mojom::AriaNotificationInterrupt interrupt_property, + const std::string& type) override; bool OnAccessibilityEvents(const AXUpdatesAndEvents& details) override;
diff --git a/ui/accessibility/platform/browser_accessibility_manager_mac.mm b/ui/accessibility/platform/browser_accessibility_manager_mac.mm index c642b2c..71c78a4 100644 --- a/ui/accessibility/platform/browser_accessibility_manager_mac.mm +++ b/ui/accessibility/platform/browser_accessibility_manager_mac.mm
@@ -440,8 +440,8 @@ BrowserAccessibility* node, const std::string& announcement, ax::mojom::AriaNotificationPriority priority_property, - const std::string& notification_id, - ax::mojom::AriaNotificationInterrupt interrupt_property) { + ax::mojom::AriaNotificationInterrupt interrupt_property, + const std::string& type) { DCHECK(node); auto* root_manager = GetManagerForRootFrame();
diff --git a/ui/accessibility/platform/browser_accessibility_manager_win.cc b/ui/accessibility/platform/browser_accessibility_manager_win.cc index db836ff..1198758 100644 --- a/ui/accessibility/platform/browser_accessibility_manager_win.cc +++ b/ui/accessibility/platform/browser_accessibility_manager_win.cc
@@ -136,8 +136,8 @@ BrowserAccessibility* node, const std::string& announcement, ax::mojom::AriaNotificationPriority priority_property, - const std::string& notification_id, - ax::mojom::AriaNotificationInterrupt interrupt_property) { + ax::mojom::AriaNotificationInterrupt interrupt_property, + const std::string& type) { DCHECK(node); if (!AXPlatform::GetInstance().IsUiaProviderEnabled()) { return; @@ -193,13 +193,11 @@ }; const base::win::ScopedBstr announcement_bstr(base::UTF8ToWide(announcement)); - const base::win::ScopedBstr notification_id_bstr( - base::UTF8ToWide(notification_id)); + const base::win::ScopedBstr type_bstr(base::UTF8ToWide(type)); uia_raise_notification_event_func(provider, NotificationKind_ActionCompleted, MapPropertiesToUiaNotificationProcessing(), - announcement_bstr.Get(), - notification_id_bstr.Get()); + announcement_bstr.Get(), type_bstr.Get()); } void BrowserAccessibilityManagerWin::FireFocusEvent(AXNode* node) {
diff --git a/ui/accessibility/platform/browser_accessibility_manager_win.h b/ui/accessibility/platform/browser_accessibility_manager_win.h index c2f14ba..e569530 100644 --- a/ui/accessibility/platform/browser_accessibility_manager_win.h +++ b/ui/accessibility/platform/browser_accessibility_manager_win.h
@@ -59,8 +59,8 @@ BrowserAccessibility* node, const std::string& announcement, ax::mojom::AriaNotificationPriority priority_property, - const std::string& notification_id, - ax::mojom::AriaNotificationInterrupt interrupt_property) override; + ax::mojom::AriaNotificationInterrupt interrupt_property, + const std::string& type) override; void FireFocusEvent(AXNode* node) override; void FireBlinkEvent(ax::mojom::Event event_type,
diff --git a/ui/android/java/res/values/one_off_colors.xml b/ui/android/java/res/values/one_off_colors.xml index b664834..fca6b82c 100644 --- a/ui/android/java/res/values/one_off_colors.xml +++ b/ui/android/java/res/values/one_off_colors.xml
@@ -53,4 +53,8 @@ <!-- Colors used in Google Pay icon --> <color name="google_pay_icon_grey_dark">#3C4043</color> + + <!-- Colors used in New Tab Page. --> + <color name="custom_tile_background_color_placeholder">#28E84800</color> + </resources>
diff --git a/ui/base/dragdrop/os_exchange_data_win_unittest.cc b/ui/base/dragdrop/os_exchange_data_win_unittest.cc index 721884e..ba8df9bf 100644 --- a/ui/base/dragdrop/os_exchange_data_win_unittest.cc +++ b/ui/base/dragdrop/os_exchange_data_win_unittest.cc
@@ -8,6 +8,7 @@ #include <memory> +#include "base/compiler_specific.h" #include "base/containers/contains.h" #include "base/files/file_util.h" #include "base/functional/bind.h" @@ -198,7 +199,7 @@ HGLOBAL glob = GlobalAlloc(GPTR, sizeof(wchar_t) * (input.size() + 1)); base::win::ScopedHGlobal<wchar_t*> global_lock(glob); wchar_t* buffer_handle = global_lock.data(); - wcscpy_s(buffer_handle, input.size() + 1, input.c_str()); + UNSAFE_TODO(wcscpy_s(buffer_handle, input.size() + 1, input.c_str())); medium.hGlobal = glob; medium.pUnkForRelease = NULL; EXPECT_EQ(S_OK, com_data->SetData(&format_etc, &medium, TRUE)); @@ -233,7 +234,7 @@ HGLOBAL glob = GlobalAlloc(GPTR, sizeof(wchar_t) * (input.size() + 1)); base::win::ScopedHGlobal<wchar_t*> global_lock(glob); wchar_t* buffer_handle = global_lock.data(); - wcscpy_s(buffer_handle, input.size() + 1, input.c_str()); + UNSAFE_TODO(wcscpy_s(buffer_handle, input.size() + 1, input.c_str())); medium.hGlobal = glob; medium.pUnkForRelease = NULL; EXPECT_EQ(S_OK, com_data->SetData(&format_etc, &medium, TRUE)); @@ -243,7 +244,7 @@ HGLOBAL glob = GlobalAlloc(GPTR, sizeof(wchar_t) * (input2.size() + 1)); base::win::ScopedHGlobal<wchar_t*> global_lock(glob); wchar_t* buffer_handle = global_lock.data(); - wcscpy_s(buffer_handle, input2.size() + 1, input2.c_str()); + UNSAFE_TODO(wcscpy_s(buffer_handle, input2.size() + 1, input2.c_str())); medium.hGlobal = glob; medium.pUnkForRelease = NULL; EXPECT_EQ(S_OK, com_data->SetData(&format_etc, &medium, TRUE));
diff --git a/ui/gl/dcomp_presenter_unittest.cc b/ui/gl/dcomp_presenter_unittest.cc index 5e4fd3d..b306de2 100644 --- a/ui/gl/dcomp_presenter_unittest.cc +++ b/ui/gl/dcomp_presenter_unittest.cc
@@ -10,6 +10,7 @@ #include <limits> #include <memory> +#include "base/compiler_specific.h" #include "base/containers/flat_set.h" #include "base/containers/span.h" #include "base/functional/callback_helpers.h" @@ -114,7 +115,8 @@ std::vector<char> image_data(size.width() * size.height() * 3 / 2); // Y, U, and V should all be 160. Output color should be pink. - memset(&image_data[0], 160, size.width() * size.height() * 3 / 2); + UNSAFE_TODO( + memset(&image_data[0], 160, size.width() * size.height() * 3 / 2)); D3D11_SUBRESOURCE_DATA data = {}; data.pSysMem = (const void*)&image_data[0];
diff --git a/ui/gl/gl_implementation.cc b/ui/gl/gl_implementation.cc index 0f325907..ed2c9697 100644 --- a/ui/gl/gl_implementation.cc +++ b/ui/gl/gl_implementation.cc
@@ -254,6 +254,10 @@ void SetGLImplementationCommandLineSwitches( const GLImplementationParts& implementation, base::CommandLine* command_line) { + // Avoid duplicating the GL implementation switches. Multiples are not + // handled. + command_line->RemoveSwitch(switches::kUseGL); + command_line->RemoveSwitch(switches::kUseANGLE); command_line->AppendSwitchASCII( switches::kUseGL, gl::GetGLImplementationGLName(implementation)); command_line->AppendSwitchASCII( @@ -266,6 +270,11 @@ } void SetSoftwareWebGLCommandLineSwitches(base::CommandLine* command_line) { + // Avoid duplicating the GL implementation switches. Multiples are not + // handled. + command_line->RemoveSwitch(switches::kUseGL); + command_line->RemoveSwitch(switches::kUseANGLE); + #if BUILDFLAG(IS_WIN) if (base::FeatureList::IsEnabled(features::kAllowD3D11WarpFallback)) { command_line->AppendSwitchASCII(switches::kUseGL, @@ -281,6 +290,14 @@ kANGLEImplementationSwiftShaderForWebGLName); } +GL_EXPORT bool HasRequestedSoftwareGLImplementationFromCommandLine( + const base::CommandLine* command_line) { + std::optional<GLImplementationParts> requested_impl = + GetRequestedGLImplementationFromCommandLine(command_line); + return requested_impl.has_value() && + IsSoftwareGLImplementation(requested_impl.value()); +} + std::optional<GLImplementationParts> GetRequestedGLImplementationFromCommandLine( const base::CommandLine* command_line) {
diff --git a/ui/gl/gl_implementation.h b/ui/gl/gl_implementation.h index f3bd65a3..aa86d4c 100644 --- a/ui/gl/gl_implementation.h +++ b/ui/gl/gl_implementation.h
@@ -180,6 +180,12 @@ GL_EXPORT void SetSoftwareWebGLCommandLineSwitches( base::CommandLine* command_line); +// Check if there is a requested software GL implementation in the command line +// arguments. Used to avoid requesting multiple times or overriding specific +// user requests. +GL_EXPORT bool HasRequestedSoftwareGLImplementationFromCommandLine( + const base::CommandLine* command_line); + // Return requested GL implementation by checking commandline. If there isn't // gl related argument, nullopt is returned. GL_EXPORT std::optional<GLImplementationParts>
diff --git a/ui/gl/init/gl_display_initializer.cc b/ui/gl/init/gl_display_initializer.cc index 3c348ada..5c81113 100644 --- a/ui/gl/init/gl_display_initializer.cc +++ b/ui/gl/init/gl_display_initializer.cc
@@ -45,12 +45,6 @@ bool default_angle_metal = base::FeatureList::IsEnabled(features::kDefaultANGLEMetal); bool default_angle_vulkan = features::IsDefaultANGLEVulkan(); - const char* default_software_renderer = kANGLEImplementationSwiftShaderName; -#if BUILDFLAG(IS_WIN) - if (base::FeatureList::IsEnabled(features::kAllowD3D11WarpFallback)) { - default_software_renderer = kANGLEImplementationD3D11WarpName; - } -#endif // If we're already requesting software GL, make sure we don't fallback to the // GPU @@ -59,7 +53,8 @@ std::string requested_renderer = force_software_gl - ? default_software_renderer + ? std::string( + GetGLImplementationANGLEName(GetGLImplementationParts())) : command_line->GetSwitchValueASCII(switches::kUseANGLE); bool use_angle_default =
diff --git a/ui/gl/test/gl_test_helper.cc b/ui/gl/test/gl_test_helper.cc index 8bee93fa..53938339a 100644 --- a/ui/gl/test/gl_test_helper.cc +++ b/ui/gl/test/gl_test_helper.cc
@@ -7,9 +7,9 @@ #include <memory> #include <string> -#include "testing/gtest/include/gtest/gtest.h" - +#include "base/compiler_specific.h" #include "base/containers/heap_array.h" +#include "testing/gtest/include/gtest/gtest.h" #include "ui/gl/gl_surface_egl.h" #include "ui/gl/init/gl_factory.h" @@ -128,7 +128,8 @@ SkISize::Make(size.width(), size.height()), SkColorInfo(SkColorType::kBGRA_8888_SkColorType, SkAlphaType::kPremul_SkAlphaType, nullptr)))); - memcpy(sk_bitmap.getAddr(0, 0), bits, sk_bitmap.computeByteSize()); + UNSAFE_TODO( + memcpy(sk_bitmap.getAddr(0, 0), bits, sk_bitmap.computeByteSize())); return sk_bitmap; }
diff --git a/ui/views/win/hwnd_message_handler.cc b/ui/views/win/hwnd_message_handler.cc index d6e5e4d6..a0e6a63f 100644 --- a/ui/views/win/hwnd_message_handler.cc +++ b/ui/views/win/hwnd_message_handler.cc
@@ -15,6 +15,7 @@ #include <utility> #include "base/auto_reset.h" +#include "base/compiler_specific.h" #include "base/containers/heap_array.h" #include "base/debug/gdi_debug_util_win.h" #include "base/functional/bind.h" @@ -3579,7 +3580,8 @@ ::ClientToScreen(hwnd(), &mouse_location); POINT cursor_pos = {0}; ::GetCursorPos(&cursor_pos); - return memcmp(&cursor_pos, &mouse_location, sizeof(POINT)) == 0; + return UNSAFE_TODO(memcmp(&cursor_pos, &mouse_location, sizeof(POINT))) == + 0; } return false; }
diff --git a/ui/views/win/pen_event_processor_unittest.cc b/ui/views/win/pen_event_processor_unittest.cc index 51f29f9..5c04735 100644 --- a/ui/views/win/pen_event_processor_unittest.cc +++ b/ui/views/win/pen_event_processor_unittest.cc
@@ -7,6 +7,7 @@ #include <combaseapi.h> #include <windows.devices.input.h> +#include "base/compiler_specific.h" #include "base/test/scoped_feature_list.h" #include "base/test/task_environment.h" #include "base/win/scoped_winrt_initializer.h" @@ -65,7 +66,7 @@ /*direct_manipulation_enabled*/ false); POINTER_PEN_INFO pen_info; - memset(&pen_info, 0, sizeof(POINTER_PEN_INFO)); + UNSAFE_TODO(memset(&pen_info, 0, sizeof(POINTER_PEN_INFO))); gfx::Point point(100, 100); std::unique_ptr<ui::Event> event = @@ -119,7 +120,7 @@ /*direct_manipulation_enabled*/ true); POINTER_PEN_INFO pen_info; - memset(&pen_info, 0, sizeof(POINTER_PEN_INFO)); + UNSAFE_TODO(memset(&pen_info, 0, sizeof(POINTER_PEN_INFO))); gfx::Point point(100, 100); // Set up the modifier state that shift is down so we can test @@ -127,7 +128,7 @@ BYTE restore_key_state[256]; GetKeyboardState(restore_key_state); BYTE shift_key_state[256]; - memset(shift_key_state, 0, sizeof(shift_key_state)); + UNSAFE_TODO(memset(shift_key_state, 0, sizeof(shift_key_state))); // Mask high order bit on indicating it is down. // See MSDN GetKeyState(). shift_key_state[VK_SHIFT] |= 0x80; @@ -184,7 +185,7 @@ /*direct_manipulation_enabled*/ true); POINTER_PEN_INFO pen_info; - memset(&pen_info, 0, sizeof(POINTER_PEN_INFO)); + UNSAFE_TODO(memset(&pen_info, 0, sizeof(POINTER_PEN_INFO))); gfx::Point point(100, 100); pen_info.pointerInfo.pointerFlags = @@ -202,7 +203,7 @@ /*direct_manipulation_enabled*/ true); POINTER_PEN_INFO pen_info; - memset(&pen_info, 0, sizeof(POINTER_PEN_INFO)); + UNSAFE_TODO(memset(&pen_info, 0, sizeof(POINTER_PEN_INFO))); gfx::Point point(100, 100); pen_info.pointerInfo.pointerFlags = POINTER_FLAG_FIRSTBUTTON; @@ -219,7 +220,7 @@ /*direct_manipulation_enabled*/ true); POINTER_PEN_INFO pen_info; - memset(&pen_info, 0, sizeof(POINTER_PEN_INFO)); + UNSAFE_TODO(memset(&pen_info, 0, sizeof(POINTER_PEN_INFO))); gfx::Point point(100, 100); pen_info.pointerInfo.pointerFlags = @@ -249,7 +250,7 @@ /*direct_manipulation_enabled*/ true); POINTER_PEN_INFO pen_info; - memset(&pen_info, 0, sizeof(POINTER_PEN_INFO)); + UNSAFE_TODO(memset(&pen_info, 0, sizeof(POINTER_PEN_INFO))); gfx::Point point(100, 100); pen_info.pointerInfo.pointerFlags = POINTER_FLAG_FIRSTBUTTON; @@ -282,7 +283,7 @@ /*direct_manipulation_enabled*/ true); POINTER_PEN_INFO pen_info; - memset(&pen_info, 0, sizeof(POINTER_PEN_INFO)); + UNSAFE_TODO(memset(&pen_info, 0, sizeof(POINTER_PEN_INFO))); gfx::Point point(100, 100); pen_info.pointerInfo.pointerFlags = @@ -316,7 +317,7 @@ std::array<POINTER_PEN_INFO, 3> pen_info; for (auto& i : pen_info) { - memset(&i, 0, sizeof(POINTER_PEN_INFO)); + UNSAFE_TODO(memset(&i, 0, sizeof(POINTER_PEN_INFO))); } gfx::Point point(100, 100); @@ -354,7 +355,7 @@ /*direct_manipulation_enabled=*/true); const uint32_t pointer_id = 1; POINTER_PEN_INFO pen_info; - memset(&pen_info, 0, sizeof(POINTER_PEN_INFO)); + UNSAFE_TODO(memset(&pen_info, 0, sizeof(POINTER_PEN_INFO))); pen_info.pointerInfo.pointerFlags = POINTER_FLAG_INCONTACT | POINTER_FLAG_FIRSTBUTTON; pen_info.pointerInfo.ButtonChangeType = POINTER_CHANGE_FIRSTBUTTON_DOWN;
diff --git a/v8 b/v8 index f96f20a..570c6a0 160000 --- a/v8 +++ b/v8
@@ -1 +1 @@ -Subproject commit f96f20ad4151649e8ecc9f12ac2ccfd9cb1cc226 +Subproject commit 570c6a0c527c3df6a3413051a06128c2699b235d